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 
2767       // If the src element is zero/undef then all the output elements will be -
2768       // only demanded elements are guaranteed to be correct.
2769       for (unsigned i = 0; i != NumSrcElts; ++i) {
2770         if (SrcDemandedElts[i]) {
2771           if (SrcZero[i])
2772             KnownZero.setBits(i * Scale, (i + 1) * Scale);
2773           if (SrcUndef[i])
2774             KnownUndef.setBits(i * Scale, (i + 1) * Scale);
2775         }
2776       }
2777     }
2778 
2779     // Bitcast from 'small element' src vector to 'large element' vector, we
2780     // demand all smaller source elements covered by the larger demanded element
2781     // of this vector.
2782     if ((NumSrcElts % NumElts) == 0) {
2783       unsigned Scale = NumSrcElts / NumElts;
2784       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2785       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2786                                      TLO, Depth + 1))
2787         return true;
2788 
2789       // If all the src elements covering an output element are zero/undef, then
2790       // the output element will be as well, assuming it was demanded.
2791       for (unsigned i = 0; i != NumElts; ++i) {
2792         if (DemandedElts[i]) {
2793           if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
2794             KnownZero.setBit(i);
2795           if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
2796             KnownUndef.setBit(i);
2797         }
2798       }
2799     }
2800     break;
2801   }
2802   case ISD::BUILD_VECTOR: {
2803     // Check all elements and simplify any unused elements with UNDEF.
2804     if (!DemandedElts.isAllOnes()) {
2805       // Don't simplify BROADCASTS.
2806       if (llvm::any_of(Op->op_values(),
2807                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
2808         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
2809         bool Updated = false;
2810         for (unsigned i = 0; i != NumElts; ++i) {
2811           if (!DemandedElts[i] && !Ops[i].isUndef()) {
2812             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
2813             KnownUndef.setBit(i);
2814             Updated = true;
2815           }
2816         }
2817         if (Updated)
2818           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
2819       }
2820     }
2821     for (unsigned i = 0; i != NumElts; ++i) {
2822       SDValue SrcOp = Op.getOperand(i);
2823       if (SrcOp.isUndef()) {
2824         KnownUndef.setBit(i);
2825       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
2826                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
2827         KnownZero.setBit(i);
2828       }
2829     }
2830     break;
2831   }
2832   case ISD::CONCAT_VECTORS: {
2833     EVT SubVT = Op.getOperand(0).getValueType();
2834     unsigned NumSubVecs = Op.getNumOperands();
2835     unsigned NumSubElts = SubVT.getVectorNumElements();
2836     for (unsigned i = 0; i != NumSubVecs; ++i) {
2837       SDValue SubOp = Op.getOperand(i);
2838       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
2839       APInt SubUndef, SubZero;
2840       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
2841                                      Depth + 1))
2842         return true;
2843       KnownUndef.insertBits(SubUndef, i * NumSubElts);
2844       KnownZero.insertBits(SubZero, i * NumSubElts);
2845     }
2846     break;
2847   }
2848   case ISD::INSERT_SUBVECTOR: {
2849     // Demand any elements from the subvector and the remainder from the src its
2850     // inserted into.
2851     SDValue Src = Op.getOperand(0);
2852     SDValue Sub = Op.getOperand(1);
2853     uint64_t Idx = Op.getConstantOperandVal(2);
2854     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2855     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2856     APInt DemandedSrcElts = DemandedElts;
2857     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2858 
2859     APInt SubUndef, SubZero;
2860     if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
2861                                    Depth + 1))
2862       return true;
2863 
2864     // If none of the src operand elements are demanded, replace it with undef.
2865     if (!DemandedSrcElts && !Src.isUndef())
2866       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
2867                                                TLO.DAG.getUNDEF(VT), Sub,
2868                                                Op.getOperand(2)));
2869 
2870     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
2871                                    TLO, Depth + 1))
2872       return true;
2873     KnownUndef.insertBits(SubUndef, Idx);
2874     KnownZero.insertBits(SubZero, Idx);
2875 
2876     // Attempt to avoid multi-use ops if we don't need anything from them.
2877     if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
2878       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
2879           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
2880       SDValue NewSub = SimplifyMultipleUseDemandedVectorElts(
2881           Sub, DemandedSubElts, TLO.DAG, Depth + 1);
2882       if (NewSrc || NewSub) {
2883         NewSrc = NewSrc ? NewSrc : Src;
2884         NewSub = NewSub ? NewSub : Sub;
2885         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
2886                                         NewSub, Op.getOperand(2));
2887         return TLO.CombineTo(Op, NewOp);
2888       }
2889     }
2890     break;
2891   }
2892   case ISD::EXTRACT_SUBVECTOR: {
2893     // Offset the demanded elts by the subvector index.
2894     SDValue Src = Op.getOperand(0);
2895     if (Src.getValueType().isScalableVector())
2896       break;
2897     uint64_t Idx = Op.getConstantOperandVal(1);
2898     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2899     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2900 
2901     APInt SrcUndef, SrcZero;
2902     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
2903                                    Depth + 1))
2904       return true;
2905     KnownUndef = SrcUndef.extractBits(NumElts, Idx);
2906     KnownZero = SrcZero.extractBits(NumElts, Idx);
2907 
2908     // Attempt to avoid multi-use ops if we don't need anything from them.
2909     if (!DemandedElts.isAllOnes()) {
2910       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
2911           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
2912       if (NewSrc) {
2913         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
2914                                         Op.getOperand(1));
2915         return TLO.CombineTo(Op, NewOp);
2916       }
2917     }
2918     break;
2919   }
2920   case ISD::INSERT_VECTOR_ELT: {
2921     SDValue Vec = Op.getOperand(0);
2922     SDValue Scl = Op.getOperand(1);
2923     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2924 
2925     // For a legal, constant insertion index, if we don't need this insertion
2926     // then strip it, else remove it from the demanded elts.
2927     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
2928       unsigned Idx = CIdx->getZExtValue();
2929       if (!DemandedElts[Idx])
2930         return TLO.CombineTo(Op, Vec);
2931 
2932       APInt DemandedVecElts(DemandedElts);
2933       DemandedVecElts.clearBit(Idx);
2934       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
2935                                      KnownZero, TLO, Depth + 1))
2936         return true;
2937 
2938       KnownUndef.setBitVal(Idx, Scl.isUndef());
2939 
2940       KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
2941       break;
2942     }
2943 
2944     APInt VecUndef, VecZero;
2945     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
2946                                    Depth + 1))
2947       return true;
2948     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
2949     break;
2950   }
2951   case ISD::VSELECT: {
2952     // Try to transform the select condition based on the current demanded
2953     // elements.
2954     // TODO: If a condition element is undef, we can choose from one arm of the
2955     //       select (and if one arm is undef, then we can propagate that to the
2956     //       result).
2957     // TODO - add support for constant vselect masks (see IR version of this).
2958     APInt UnusedUndef, UnusedZero;
2959     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef,
2960                                    UnusedZero, TLO, Depth + 1))
2961       return true;
2962 
2963     // See if we can simplify either vselect operand.
2964     APInt DemandedLHS(DemandedElts);
2965     APInt DemandedRHS(DemandedElts);
2966     APInt UndefLHS, ZeroLHS;
2967     APInt UndefRHS, ZeroRHS;
2968     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS,
2969                                    ZeroLHS, TLO, Depth + 1))
2970       return true;
2971     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS,
2972                                    ZeroRHS, TLO, Depth + 1))
2973       return true;
2974 
2975     KnownUndef = UndefLHS & UndefRHS;
2976     KnownZero = ZeroLHS & ZeroRHS;
2977     break;
2978   }
2979   case ISD::VECTOR_SHUFFLE: {
2980     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
2981 
2982     // Collect demanded elements from shuffle operands..
2983     APInt DemandedLHS(NumElts, 0);
2984     APInt DemandedRHS(NumElts, 0);
2985     for (unsigned i = 0; i != NumElts; ++i) {
2986       int M = ShuffleMask[i];
2987       if (M < 0 || !DemandedElts[i])
2988         continue;
2989       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
2990       if (M < (int)NumElts)
2991         DemandedLHS.setBit(M);
2992       else
2993         DemandedRHS.setBit(M - NumElts);
2994     }
2995 
2996     // See if we can simplify either shuffle operand.
2997     APInt UndefLHS, ZeroLHS;
2998     APInt UndefRHS, ZeroRHS;
2999     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS,
3000                                    ZeroLHS, TLO, Depth + 1))
3001       return true;
3002     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS,
3003                                    ZeroRHS, TLO, Depth + 1))
3004       return true;
3005 
3006     // Simplify mask using undef elements from LHS/RHS.
3007     bool Updated = false;
3008     bool IdentityLHS = true, IdentityRHS = true;
3009     SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end());
3010     for (unsigned i = 0; i != NumElts; ++i) {
3011       int &M = NewMask[i];
3012       if (M < 0)
3013         continue;
3014       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
3015           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
3016         Updated = true;
3017         M = -1;
3018       }
3019       IdentityLHS &= (M < 0) || (M == (int)i);
3020       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
3021     }
3022 
3023     // Update legal shuffle masks based on demanded elements if it won't reduce
3024     // to Identity which can cause premature removal of the shuffle mask.
3025     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
3026       SDValue LegalShuffle =
3027           buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1),
3028                                   NewMask, TLO.DAG);
3029       if (LegalShuffle)
3030         return TLO.CombineTo(Op, LegalShuffle);
3031     }
3032 
3033     // Propagate undef/zero elements from LHS/RHS.
3034     for (unsigned i = 0; i != NumElts; ++i) {
3035       int M = ShuffleMask[i];
3036       if (M < 0) {
3037         KnownUndef.setBit(i);
3038       } else if (M < (int)NumElts) {
3039         if (UndefLHS[M])
3040           KnownUndef.setBit(i);
3041         if (ZeroLHS[M])
3042           KnownZero.setBit(i);
3043       } else {
3044         if (UndefRHS[M - NumElts])
3045           KnownUndef.setBit(i);
3046         if (ZeroRHS[M - NumElts])
3047           KnownZero.setBit(i);
3048       }
3049     }
3050     break;
3051   }
3052   case ISD::ANY_EXTEND_VECTOR_INREG:
3053   case ISD::SIGN_EXTEND_VECTOR_INREG:
3054   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3055     APInt SrcUndef, SrcZero;
3056     SDValue Src = Op.getOperand(0);
3057     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3058     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
3059     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3060                                    Depth + 1))
3061       return true;
3062     KnownZero = SrcZero.zextOrTrunc(NumElts);
3063     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
3064 
3065     if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
3066         Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
3067         DemandedSrcElts == 1) {
3068       // aext - if we just need the bottom element then we can bitcast.
3069       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
3070     }
3071 
3072     if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
3073       // zext(undef) upper bits are guaranteed to be zero.
3074       if (DemandedElts.isSubsetOf(KnownUndef))
3075         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3076       KnownUndef.clearAllBits();
3077 
3078       // zext - if we just need the bottom element then we can mask:
3079       // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
3080       if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
3081           Op->isOnlyUserOf(Src.getNode()) &&
3082           Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
3083         SDLoc DL(Op);
3084         EVT SrcVT = Src.getValueType();
3085         EVT SrcSVT = SrcVT.getScalarType();
3086         SmallVector<SDValue> MaskElts;
3087         MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
3088         MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
3089         SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
3090         if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
3091                 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
3092           Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
3093           return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
3094         }
3095       }
3096     }
3097     break;
3098   }
3099 
3100   // TODO: There are more binop opcodes that could be handled here - MIN,
3101   // MAX, saturated math, etc.
3102   case ISD::ADD: {
3103     SDValue Op0 = Op.getOperand(0);
3104     SDValue Op1 = Op.getOperand(1);
3105     if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
3106       APInt UndefLHS, ZeroLHS;
3107       if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3108                                      Depth + 1, /*AssumeSingleUse*/ true))
3109         return true;
3110     }
3111     LLVM_FALLTHROUGH;
3112   }
3113   case ISD::OR:
3114   case ISD::XOR:
3115   case ISD::SUB:
3116   case ISD::FADD:
3117   case ISD::FSUB:
3118   case ISD::FMUL:
3119   case ISD::FDIV:
3120   case ISD::FREM: {
3121     SDValue Op0 = Op.getOperand(0);
3122     SDValue Op1 = Op.getOperand(1);
3123 
3124     APInt UndefRHS, ZeroRHS;
3125     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3126                                    Depth + 1))
3127       return true;
3128     APInt UndefLHS, ZeroLHS;
3129     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3130                                    Depth + 1))
3131       return true;
3132 
3133     KnownZero = ZeroLHS & ZeroRHS;
3134     KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
3135 
3136     // Attempt to avoid multi-use ops if we don't need anything from them.
3137     // TODO - use KnownUndef to relax the demandedelts?
3138     if (!DemandedElts.isAllOnes())
3139       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3140         return true;
3141     break;
3142   }
3143   case ISD::SHL:
3144   case ISD::SRL:
3145   case ISD::SRA:
3146   case ISD::ROTL:
3147   case ISD::ROTR: {
3148     SDValue Op0 = Op.getOperand(0);
3149     SDValue Op1 = Op.getOperand(1);
3150 
3151     APInt UndefRHS, ZeroRHS;
3152     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3153                                    Depth + 1))
3154       return true;
3155     APInt UndefLHS, ZeroLHS;
3156     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3157                                    Depth + 1))
3158       return true;
3159 
3160     KnownZero = ZeroLHS;
3161     KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
3162 
3163     // Attempt to avoid multi-use ops if we don't need anything from them.
3164     // TODO - use KnownUndef to relax the demandedelts?
3165     if (!DemandedElts.isAllOnes())
3166       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3167         return true;
3168     break;
3169   }
3170   case ISD::MUL:
3171   case ISD::AND: {
3172     SDValue Op0 = Op.getOperand(0);
3173     SDValue Op1 = Op.getOperand(1);
3174 
3175     APInt SrcUndef, SrcZero;
3176     if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
3177                                    Depth + 1))
3178       return true;
3179     if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
3180                                    TLO, Depth + 1))
3181       return true;
3182 
3183     // If either side has a zero element, then the result element is zero, even
3184     // if the other is an UNDEF.
3185     // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
3186     // and then handle 'and' nodes with the rest of the binop opcodes.
3187     KnownZero |= SrcZero;
3188     KnownUndef &= SrcUndef;
3189     KnownUndef &= ~KnownZero;
3190 
3191     // Attempt to avoid multi-use ops if we don't need anything from them.
3192     // TODO - use KnownUndef to relax the demandedelts?
3193     if (!DemandedElts.isAllOnes())
3194       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3195         return true;
3196     break;
3197   }
3198   case ISD::TRUNCATE:
3199   case ISD::SIGN_EXTEND:
3200   case ISD::ZERO_EXTEND:
3201     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
3202                                    KnownZero, TLO, Depth + 1))
3203       return true;
3204 
3205     if (Op.getOpcode() == ISD::ZERO_EXTEND) {
3206       // zext(undef) upper bits are guaranteed to be zero.
3207       if (DemandedElts.isSubsetOf(KnownUndef))
3208         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3209       KnownUndef.clearAllBits();
3210     }
3211     break;
3212   default: {
3213     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
3214       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
3215                                                   KnownZero, TLO, Depth))
3216         return true;
3217     } else {
3218       KnownBits Known;
3219       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
3220       if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
3221                                TLO, Depth, AssumeSingleUse))
3222         return true;
3223     }
3224     break;
3225   }
3226   }
3227   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
3228 
3229   // Constant fold all undef cases.
3230   // TODO: Handle zero cases as well.
3231   if (DemandedElts.isSubsetOf(KnownUndef))
3232     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3233 
3234   return false;
3235 }
3236 
3237 /// Determine which of the bits specified in Mask are known to be either zero or
3238 /// one and return them in the Known.
3239 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
3240                                                    KnownBits &Known,
3241                                                    const APInt &DemandedElts,
3242                                                    const SelectionDAG &DAG,
3243                                                    unsigned Depth) const {
3244   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3245           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3246           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3247           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3248          "Should use MaskedValueIsZero if you don't know whether Op"
3249          " is a target node!");
3250   Known.resetAll();
3251 }
3252 
3253 void TargetLowering::computeKnownBitsForTargetInstr(
3254     GISelKnownBits &Analysis, Register R, KnownBits &Known,
3255     const APInt &DemandedElts, const MachineRegisterInfo &MRI,
3256     unsigned Depth) const {
3257   Known.resetAll();
3258 }
3259 
3260 void TargetLowering::computeKnownBitsForFrameIndex(
3261   const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const {
3262   // The low bits are known zero if the pointer is aligned.
3263   Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx)));
3264 }
3265 
3266 Align TargetLowering::computeKnownAlignForTargetInstr(
3267   GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI,
3268   unsigned Depth) const {
3269   return Align(1);
3270 }
3271 
3272 /// This method can be implemented by targets that want to expose additional
3273 /// information about sign bits to the DAG Combiner.
3274 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
3275                                                          const APInt &,
3276                                                          const SelectionDAG &,
3277                                                          unsigned Depth) const {
3278   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3279           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3280           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3281           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3282          "Should use ComputeNumSignBits if you don't know whether Op"
3283          " is a target node!");
3284   return 1;
3285 }
3286 
3287 unsigned TargetLowering::computeNumSignBitsForTargetInstr(
3288   GISelKnownBits &Analysis, Register R, const APInt &DemandedElts,
3289   const MachineRegisterInfo &MRI, unsigned Depth) const {
3290   return 1;
3291 }
3292 
3293 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
3294     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
3295     TargetLoweringOpt &TLO, unsigned Depth) const {
3296   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3297           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3298           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3299           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3300          "Should use SimplifyDemandedVectorElts if you don't know whether Op"
3301          " is a target node!");
3302   return false;
3303 }
3304 
3305 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
3306     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3307     KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
3308   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3309           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3310           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3311           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3312          "Should use SimplifyDemandedBits if you don't know whether Op"
3313          " is a target node!");
3314   computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
3315   return false;
3316 }
3317 
3318 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
3319     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3320     SelectionDAG &DAG, unsigned Depth) const {
3321   assert(
3322       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3323        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3324        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3325        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3326       "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
3327       " is a target node!");
3328   return SDValue();
3329 }
3330 
3331 SDValue
3332 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
3333                                         SDValue N1, MutableArrayRef<int> Mask,
3334                                         SelectionDAG &DAG) const {
3335   bool LegalMask = isShuffleMaskLegal(Mask, VT);
3336   if (!LegalMask) {
3337     std::swap(N0, N1);
3338     ShuffleVectorSDNode::commuteMask(Mask);
3339     LegalMask = isShuffleMaskLegal(Mask, VT);
3340   }
3341 
3342   if (!LegalMask)
3343     return SDValue();
3344 
3345   return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
3346 }
3347 
3348 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const {
3349   return nullptr;
3350 }
3351 
3352 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
3353     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
3354     bool PoisonOnly, unsigned Depth) const {
3355   assert(
3356       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3357        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3358        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3359        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3360       "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
3361       " is a target node!");
3362   return false;
3363 }
3364 
3365 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
3366                                                   const SelectionDAG &DAG,
3367                                                   bool SNaN,
3368                                                   unsigned Depth) const {
3369   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3370           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3371           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3372           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3373          "Should use isKnownNeverNaN if you don't know whether Op"
3374          " is a target node!");
3375   return false;
3376 }
3377 
3378 bool TargetLowering::isSplatValueForTargetNode(SDValue Op,
3379                                                const APInt &DemandedElts,
3380                                                APInt &UndefElts,
3381                                                unsigned Depth) const {
3382   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3383           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3384           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3385           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3386          "Should use isSplatValue if you don't know whether Op"
3387          " is a target node!");
3388   return false;
3389 }
3390 
3391 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
3392 // work with truncating build vectors and vectors with elements of less than
3393 // 8 bits.
3394 bool TargetLowering::isConstTrueVal(SDValue N) const {
3395   if (!N)
3396     return false;
3397 
3398   unsigned EltWidth;
3399   APInt CVal;
3400   if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
3401                                                /*AllowTruncation=*/true)) {
3402     CVal = CN->getAPIntValue();
3403     EltWidth = N.getValueType().getScalarSizeInBits();
3404   } else
3405     return false;
3406 
3407   // If this is a truncating splat, truncate the splat value.
3408   // Otherwise, we may fail to match the expected values below.
3409   if (EltWidth < CVal.getBitWidth())
3410     CVal = CVal.trunc(EltWidth);
3411 
3412   switch (getBooleanContents(N.getValueType())) {
3413   case UndefinedBooleanContent:
3414     return CVal[0];
3415   case ZeroOrOneBooleanContent:
3416     return CVal.isOne();
3417   case ZeroOrNegativeOneBooleanContent:
3418     return CVal.isAllOnes();
3419   }
3420 
3421   llvm_unreachable("Invalid boolean contents");
3422 }
3423 
3424 bool TargetLowering::isConstFalseVal(SDValue N) const {
3425   if (!N)
3426     return false;
3427 
3428   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
3429   if (!CN) {
3430     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
3431     if (!BV)
3432       return false;
3433 
3434     // Only interested in constant splats, we don't care about undef
3435     // elements in identifying boolean constants and getConstantSplatNode
3436     // returns NULL if all ops are undef;
3437     CN = BV->getConstantSplatNode();
3438     if (!CN)
3439       return false;
3440   }
3441 
3442   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
3443     return !CN->getAPIntValue()[0];
3444 
3445   return CN->isZero();
3446 }
3447 
3448 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
3449                                        bool SExt) const {
3450   if (VT == MVT::i1)
3451     return N->isOne();
3452 
3453   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
3454   switch (Cnt) {
3455   case TargetLowering::ZeroOrOneBooleanContent:
3456     // An extended value of 1 is always true, unless its original type is i1,
3457     // in which case it will be sign extended to -1.
3458     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
3459   case TargetLowering::UndefinedBooleanContent:
3460   case TargetLowering::ZeroOrNegativeOneBooleanContent:
3461     return N->isAllOnes() && SExt;
3462   }
3463   llvm_unreachable("Unexpected enumeration.");
3464 }
3465 
3466 /// This helper function of SimplifySetCC tries to optimize the comparison when
3467 /// either operand of the SetCC node is a bitwise-and instruction.
3468 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3469                                          ISD::CondCode Cond, const SDLoc &DL,
3470                                          DAGCombinerInfo &DCI) const {
3471   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
3472     std::swap(N0, N1);
3473 
3474   SelectionDAG &DAG = DCI.DAG;
3475   EVT OpVT = N0.getValueType();
3476   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
3477       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
3478     return SDValue();
3479 
3480   // (X & Y) != 0 --> zextOrTrunc(X & Y)
3481   // iff everything but LSB is known zero:
3482   if (Cond == ISD::SETNE && isNullConstant(N1) &&
3483       (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent ||
3484        getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) {
3485     unsigned NumEltBits = OpVT.getScalarSizeInBits();
3486     APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
3487     if (DAG.MaskedValueIsZero(N0, UpperBits))
3488       return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
3489   }
3490 
3491   // Match these patterns in any of their permutations:
3492   // (X & Y) == Y
3493   // (X & Y) != Y
3494   SDValue X, Y;
3495   if (N0.getOperand(0) == N1) {
3496     X = N0.getOperand(1);
3497     Y = N0.getOperand(0);
3498   } else if (N0.getOperand(1) == N1) {
3499     X = N0.getOperand(0);
3500     Y = N0.getOperand(1);
3501   } else {
3502     return SDValue();
3503   }
3504 
3505   SDValue Zero = DAG.getConstant(0, DL, OpVT);
3506   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
3507     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
3508     // Note that where Y is variable and is known to have at most one bit set
3509     // (for example, if it is Z & 1) we cannot do this; the expressions are not
3510     // equivalent when Y == 0.
3511     assert(OpVT.isInteger());
3512     Cond = ISD::getSetCCInverse(Cond, OpVT);
3513     if (DCI.isBeforeLegalizeOps() ||
3514         isCondCodeLegal(Cond, N0.getSimpleValueType()))
3515       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
3516   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
3517     // If the target supports an 'and-not' or 'and-complement' logic operation,
3518     // try to use that to make a comparison operation more efficient.
3519     // But don't do this transform if the mask is a single bit because there are
3520     // more efficient ways to deal with that case (for example, 'bt' on x86 or
3521     // 'rlwinm' on PPC).
3522 
3523     // Bail out if the compare operand that we want to turn into a zero is
3524     // already a zero (otherwise, infinite loop).
3525     auto *YConst = dyn_cast<ConstantSDNode>(Y);
3526     if (YConst && YConst->isZero())
3527       return SDValue();
3528 
3529     // Transform this into: ~X & Y == 0.
3530     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
3531     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
3532     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
3533   }
3534 
3535   return SDValue();
3536 }
3537 
3538 /// There are multiple IR patterns that could be checking whether certain
3539 /// truncation of a signed number would be lossy or not. The pattern which is
3540 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
3541 /// We are looking for the following pattern: (KeptBits is a constant)
3542 ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
3543 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
3544 /// KeptBits also can't be 1, that would have been folded to  %x dstcond 0
3545 /// We will unfold it into the natural trunc+sext pattern:
3546 ///   ((%x << C) a>> C) dstcond %x
3547 /// Where  C = bitwidth(x) - KeptBits  and  C u< bitwidth(x)
3548 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
3549     EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
3550     const SDLoc &DL) const {
3551   // We must be comparing with a constant.
3552   ConstantSDNode *C1;
3553   if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
3554     return SDValue();
3555 
3556   // N0 should be:  add %x, (1 << (KeptBits-1))
3557   if (N0->getOpcode() != ISD::ADD)
3558     return SDValue();
3559 
3560   // And we must be 'add'ing a constant.
3561   ConstantSDNode *C01;
3562   if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
3563     return SDValue();
3564 
3565   SDValue X = N0->getOperand(0);
3566   EVT XVT = X.getValueType();
3567 
3568   // Validate constants ...
3569 
3570   APInt I1 = C1->getAPIntValue();
3571 
3572   ISD::CondCode NewCond;
3573   if (Cond == ISD::CondCode::SETULT) {
3574     NewCond = ISD::CondCode::SETEQ;
3575   } else if (Cond == ISD::CondCode::SETULE) {
3576     NewCond = ISD::CondCode::SETEQ;
3577     // But need to 'canonicalize' the constant.
3578     I1 += 1;
3579   } else if (Cond == ISD::CondCode::SETUGT) {
3580     NewCond = ISD::CondCode::SETNE;
3581     // But need to 'canonicalize' the constant.
3582     I1 += 1;
3583   } else if (Cond == ISD::CondCode::SETUGE) {
3584     NewCond = ISD::CondCode::SETNE;
3585   } else
3586     return SDValue();
3587 
3588   APInt I01 = C01->getAPIntValue();
3589 
3590   auto checkConstants = [&I1, &I01]() -> bool {
3591     // Both of them must be power-of-two, and the constant from setcc is bigger.
3592     return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
3593   };
3594 
3595   if (checkConstants()) {
3596     // Great, e.g. got  icmp ult i16 (add i16 %x, 128), 256
3597   } else {
3598     // What if we invert constants? (and the target predicate)
3599     I1.negate();
3600     I01.negate();
3601     assert(XVT.isInteger());
3602     NewCond = getSetCCInverse(NewCond, XVT);
3603     if (!checkConstants())
3604       return SDValue();
3605     // Great, e.g. got  icmp uge i16 (add i16 %x, -128), -256
3606   }
3607 
3608   // They are power-of-two, so which bit is set?
3609   const unsigned KeptBits = I1.logBase2();
3610   const unsigned KeptBitsMinusOne = I01.logBase2();
3611 
3612   // Magic!
3613   if (KeptBits != (KeptBitsMinusOne + 1))
3614     return SDValue();
3615   assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
3616 
3617   // We don't want to do this in every single case.
3618   SelectionDAG &DAG = DCI.DAG;
3619   if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
3620           XVT, KeptBits))
3621     return SDValue();
3622 
3623   const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits;
3624   assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable");
3625 
3626   // Unfold into:  ((%x << C) a>> C) cond %x
3627   // Where 'cond' will be either 'eq' or 'ne'.
3628   SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT);
3629   SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt);
3630   SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt);
3631   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond);
3632 
3633   return T2;
3634 }
3635 
3636 // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
3637 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
3638     EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
3639     DAGCombinerInfo &DCI, const SDLoc &DL) const {
3640   assert(isConstOrConstSplat(N1C) &&
3641          isConstOrConstSplat(N1C)->getAPIntValue().isZero() &&
3642          "Should be a comparison with 0.");
3643   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3644          "Valid only for [in]equality comparisons.");
3645 
3646   unsigned NewShiftOpcode;
3647   SDValue X, C, Y;
3648 
3649   SelectionDAG &DAG = DCI.DAG;
3650   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3651 
3652   // Look for '(C l>>/<< Y)'.
3653   auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) {
3654     // The shift should be one-use.
3655     if (!V.hasOneUse())
3656       return false;
3657     unsigned OldShiftOpcode = V.getOpcode();
3658     switch (OldShiftOpcode) {
3659     case ISD::SHL:
3660       NewShiftOpcode = ISD::SRL;
3661       break;
3662     case ISD::SRL:
3663       NewShiftOpcode = ISD::SHL;
3664       break;
3665     default:
3666       return false; // must be a logical shift.
3667     }
3668     // We should be shifting a constant.
3669     // FIXME: best to use isConstantOrConstantVector().
3670     C = V.getOperand(0);
3671     ConstantSDNode *CC =
3672         isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3673     if (!CC)
3674       return false;
3675     Y = V.getOperand(1);
3676 
3677     ConstantSDNode *XC =
3678         isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3679     return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
3680         X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
3681   };
3682 
3683   // LHS of comparison should be an one-use 'and'.
3684   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
3685     return SDValue();
3686 
3687   X = N0.getOperand(0);
3688   SDValue Mask = N0.getOperand(1);
3689 
3690   // 'and' is commutative!
3691   if (!Match(Mask)) {
3692     std::swap(X, Mask);
3693     if (!Match(Mask))
3694       return SDValue();
3695   }
3696 
3697   EVT VT = X.getValueType();
3698 
3699   // Produce:
3700   // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
3701   SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
3702   SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
3703   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
3704   return T2;
3705 }
3706 
3707 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
3708 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
3709 /// handle the commuted versions of these patterns.
3710 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
3711                                            ISD::CondCode Cond, const SDLoc &DL,
3712                                            DAGCombinerInfo &DCI) const {
3713   unsigned BOpcode = N0.getOpcode();
3714   assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
3715          "Unexpected binop");
3716   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
3717 
3718   // (X + Y) == X --> Y == 0
3719   // (X - Y) == X --> Y == 0
3720   // (X ^ Y) == X --> Y == 0
3721   SelectionDAG &DAG = DCI.DAG;
3722   EVT OpVT = N0.getValueType();
3723   SDValue X = N0.getOperand(0);
3724   SDValue Y = N0.getOperand(1);
3725   if (X == N1)
3726     return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
3727 
3728   if (Y != N1)
3729     return SDValue();
3730 
3731   // (X + Y) == Y --> X == 0
3732   // (X ^ Y) == Y --> X == 0
3733   if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
3734     return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
3735 
3736   // The shift would not be valid if the operands are boolean (i1).
3737   if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
3738     return SDValue();
3739 
3740   // (X - Y) == Y --> X == Y << 1
3741   EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(),
3742                                  !DCI.isBeforeLegalize());
3743   SDValue One = DAG.getConstant(1, DL, ShiftVT);
3744   SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
3745   if (!DCI.isCalledByLegalizer())
3746     DCI.AddToWorklist(YShl1.getNode());
3747   return DAG.getSetCC(DL, VT, X, YShl1, Cond);
3748 }
3749 
3750 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT,
3751                                       SDValue N0, const APInt &C1,
3752                                       ISD::CondCode Cond, const SDLoc &dl,
3753                                       SelectionDAG &DAG) {
3754   // Look through truncs that don't change the value of a ctpop.
3755   // FIXME: Add vector support? Need to be careful with setcc result type below.
3756   SDValue CTPOP = N0;
3757   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
3758       N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits()))
3759     CTPOP = N0.getOperand(0);
3760 
3761   if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
3762     return SDValue();
3763 
3764   EVT CTVT = CTPOP.getValueType();
3765   SDValue CTOp = CTPOP.getOperand(0);
3766 
3767   // If this is a vector CTPOP, keep the CTPOP if it is legal.
3768   // TODO: Should we check if CTPOP is legal(or custom) for scalars?
3769   if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT))
3770     return SDValue();
3771 
3772   // (ctpop x) u< 2 -> (x & x-1) == 0
3773   // (ctpop x) u> 1 -> (x & x-1) != 0
3774   if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
3775     unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
3776     if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
3777       return SDValue();
3778     if (C1 == 0 && (Cond == ISD::SETULT))
3779       return SDValue(); // This is handled elsewhere.
3780 
3781     unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
3782 
3783     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3784     SDValue Result = CTOp;
3785     for (unsigned i = 0; i < Passes; i++) {
3786       SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
3787       Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
3788     }
3789     ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
3790     return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
3791   }
3792 
3793   // If ctpop is not supported, expand a power-of-2 comparison based on it.
3794   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
3795     // For scalars, keep CTPOP if it is legal or custom.
3796     if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT))
3797       return SDValue();
3798     // This is based on X86's custom lowering for CTPOP which produces more
3799     // instructions than the expansion here.
3800 
3801     // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0)
3802     // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0)
3803     SDValue Zero = DAG.getConstant(0, dl, CTVT);
3804     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3805     assert(CTVT.isInteger());
3806     ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT);
3807     SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
3808     SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
3809     SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond);
3810     SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
3811     unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR;
3812     return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS);
3813   }
3814 
3815   return SDValue();
3816 }
3817 
3818 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1,
3819                                    ISD::CondCode Cond, const SDLoc &dl,
3820                                    SelectionDAG &DAG) {
3821   if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
3822     return SDValue();
3823 
3824   auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
3825   if (!C1 || !(C1->isZero() || C1->isAllOnes()))
3826     return SDValue();
3827 
3828   auto getRotateSource = [](SDValue X) {
3829     if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
3830       return X.getOperand(0);
3831     return SDValue();
3832   };
3833 
3834   // Peek through a rotated value compared against 0 or -1:
3835   // (rot X, Y) == 0/-1 --> X == 0/-1
3836   // (rot X, Y) != 0/-1 --> X != 0/-1
3837   if (SDValue R = getRotateSource(N0))
3838     return DAG.getSetCC(dl, VT, R, N1, Cond);
3839 
3840   // Peek through an 'or' of a rotated value compared against 0:
3841   // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
3842   // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
3843   //
3844   // TODO: Add the 'and' with -1 sibling.
3845   // TODO: Recurse through a series of 'or' ops to find the rotate.
3846   EVT OpVT = N0.getValueType();
3847   if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
3848     if (SDValue R = getRotateSource(N0.getOperand(0))) {
3849       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
3850       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
3851     }
3852     if (SDValue R = getRotateSource(N0.getOperand(1))) {
3853       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
3854       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
3855     }
3856   }
3857 
3858   return SDValue();
3859 }
3860 
3861 /// Try to simplify a setcc built with the specified operands and cc. If it is
3862 /// unable to simplify it, return a null SDValue.
3863 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
3864                                       ISD::CondCode Cond, bool foldBooleans,
3865                                       DAGCombinerInfo &DCI,
3866                                       const SDLoc &dl) const {
3867   SelectionDAG &DAG = DCI.DAG;
3868   const DataLayout &Layout = DAG.getDataLayout();
3869   EVT OpVT = N0.getValueType();
3870 
3871   // Constant fold or commute setcc.
3872   if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
3873     return Fold;
3874 
3875   // Ensure that the constant occurs on the RHS and fold constant comparisons.
3876   // TODO: Handle non-splat vector constants. All undef causes trouble.
3877   // FIXME: We can't yet fold constant scalable vector splats, so avoid an
3878   // infinite loop here when we encounter one.
3879   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
3880   if (isConstOrConstSplat(N0) &&
3881       (!OpVT.isScalableVector() || !isConstOrConstSplat(N1)) &&
3882       (DCI.isBeforeLegalizeOps() ||
3883        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
3884     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
3885 
3886   // If we have a subtract with the same 2 non-constant operands as this setcc
3887   // -- but in reverse order -- then try to commute the operands of this setcc
3888   // to match. A matching pair of setcc (cmp) and sub may be combined into 1
3889   // instruction on some targets.
3890   if (!isConstOrConstSplat(N0) && !isConstOrConstSplat(N1) &&
3891       (DCI.isBeforeLegalizeOps() ||
3892        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
3893       DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
3894       !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
3895     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
3896 
3897   if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
3898     return V;
3899 
3900   if (auto *N1C = isConstOrConstSplat(N1)) {
3901     const APInt &C1 = N1C->getAPIntValue();
3902 
3903     // Optimize some CTPOP cases.
3904     if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
3905       return V;
3906 
3907     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
3908     // equality comparison, then we're just comparing whether X itself is
3909     // zero.
3910     if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
3911         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
3912         isPowerOf2_32(N0.getScalarValueSizeInBits())) {
3913       if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
3914         if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3915             ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
3916           if ((C1 == 0) == (Cond == ISD::SETEQ)) {
3917             // (srl (ctlz x), 5) == 0  -> X != 0
3918             // (srl (ctlz x), 5) != 1  -> X != 0
3919             Cond = ISD::SETNE;
3920           } else {
3921             // (srl (ctlz x), 5) != 0  -> X == 0
3922             // (srl (ctlz x), 5) == 1  -> X == 0
3923             Cond = ISD::SETEQ;
3924           }
3925           SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
3926           return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
3927                               Cond);
3928         }
3929       }
3930     }
3931   }
3932 
3933   // FIXME: Support vectors.
3934   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
3935     const APInt &C1 = N1C->getAPIntValue();
3936 
3937     // (zext x) == C --> x == (trunc C)
3938     // (sext x) == C --> x == (trunc C)
3939     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3940         DCI.isBeforeLegalize() && N0->hasOneUse()) {
3941       unsigned MinBits = N0.getValueSizeInBits();
3942       SDValue PreExt;
3943       bool Signed = false;
3944       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
3945         // ZExt
3946         MinBits = N0->getOperand(0).getValueSizeInBits();
3947         PreExt = N0->getOperand(0);
3948       } else if (N0->getOpcode() == ISD::AND) {
3949         // DAGCombine turns costly ZExts into ANDs
3950         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
3951           if ((C->getAPIntValue()+1).isPowerOf2()) {
3952             MinBits = C->getAPIntValue().countTrailingOnes();
3953             PreExt = N0->getOperand(0);
3954           }
3955       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
3956         // SExt
3957         MinBits = N0->getOperand(0).getValueSizeInBits();
3958         PreExt = N0->getOperand(0);
3959         Signed = true;
3960       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
3961         // ZEXTLOAD / SEXTLOAD
3962         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
3963           MinBits = LN0->getMemoryVT().getSizeInBits();
3964           PreExt = N0;
3965         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
3966           Signed = true;
3967           MinBits = LN0->getMemoryVT().getSizeInBits();
3968           PreExt = N0;
3969         }
3970       }
3971 
3972       // Figure out how many bits we need to preserve this constant.
3973       unsigned ReqdBits = Signed ? C1.getMinSignedBits() : C1.getActiveBits();
3974 
3975       // Make sure we're not losing bits from the constant.
3976       if (MinBits > 0 &&
3977           MinBits < C1.getBitWidth() &&
3978           MinBits >= ReqdBits) {
3979         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
3980         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
3981           // Will get folded away.
3982           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
3983           if (MinBits == 1 && C1 == 1)
3984             // Invert the condition.
3985             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
3986                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3987           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
3988           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
3989         }
3990 
3991         // If truncating the setcc operands is not desirable, we can still
3992         // simplify the expression in some cases:
3993         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
3994         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
3995         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
3996         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
3997         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
3998         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
3999         SDValue TopSetCC = N0->getOperand(0);
4000         unsigned N0Opc = N0->getOpcode();
4001         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
4002         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
4003             TopSetCC.getOpcode() == ISD::SETCC &&
4004             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
4005             (isConstFalseVal(N1) ||
4006              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
4007 
4008           bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
4009                          (!N1C->isZero() && Cond == ISD::SETNE);
4010 
4011           if (!Inverse)
4012             return TopSetCC;
4013 
4014           ISD::CondCode InvCond = ISD::getSetCCInverse(
4015               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
4016               TopSetCC.getOperand(0).getValueType());
4017           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
4018                                       TopSetCC.getOperand(1),
4019                                       InvCond);
4020         }
4021       }
4022     }
4023 
4024     // If the LHS is '(and load, const)', the RHS is 0, the test is for
4025     // equality or unsigned, and all 1 bits of the const are in the same
4026     // partial word, see if we can shorten the load.
4027     if (DCI.isBeforeLegalize() &&
4028         !ISD::isSignedIntSetCC(Cond) &&
4029         N0.getOpcode() == ISD::AND && C1 == 0 &&
4030         N0.getNode()->hasOneUse() &&
4031         isa<LoadSDNode>(N0.getOperand(0)) &&
4032         N0.getOperand(0).getNode()->hasOneUse() &&
4033         isa<ConstantSDNode>(N0.getOperand(1))) {
4034       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
4035       APInt bestMask;
4036       unsigned bestWidth = 0, bestOffset = 0;
4037       if (Lod->isSimple() && Lod->isUnindexed()) {
4038         unsigned origWidth = N0.getValueSizeInBits();
4039         unsigned maskWidth = origWidth;
4040         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
4041         // 8 bits, but have to be careful...
4042         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
4043           origWidth = Lod->getMemoryVT().getSizeInBits();
4044         const APInt &Mask = N0.getConstantOperandAPInt(1);
4045         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
4046           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
4047           for (unsigned offset=0; offset<origWidth/width; offset++) {
4048             if (Mask.isSubsetOf(newMask)) {
4049               if (Layout.isLittleEndian())
4050                 bestOffset = (uint64_t)offset * (width/8);
4051               else
4052                 bestOffset = (origWidth/width - offset - 1) * (width/8);
4053               bestMask = Mask.lshr(offset * (width/8) * 8);
4054               bestWidth = width;
4055               break;
4056             }
4057             newMask <<= width;
4058           }
4059         }
4060       }
4061       if (bestWidth) {
4062         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
4063         if (newVT.isRound() &&
4064             shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
4065           SDValue Ptr = Lod->getBasePtr();
4066           if (bestOffset != 0)
4067             Ptr =
4068                 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl);
4069           SDValue NewLoad =
4070               DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
4071                           Lod->getPointerInfo().getWithOffset(bestOffset),
4072                           Lod->getOriginalAlign());
4073           return DAG.getSetCC(dl, VT,
4074                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
4075                                       DAG.getConstant(bestMask.trunc(bestWidth),
4076                                                       dl, newVT)),
4077                               DAG.getConstant(0LL, dl, newVT), Cond);
4078         }
4079       }
4080     }
4081 
4082     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
4083     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
4084       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
4085 
4086       // If the comparison constant has bits in the upper part, the
4087       // zero-extended value could never match.
4088       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
4089                                               C1.getBitWidth() - InSize))) {
4090         switch (Cond) {
4091         case ISD::SETUGT:
4092         case ISD::SETUGE:
4093         case ISD::SETEQ:
4094           return DAG.getConstant(0, dl, VT);
4095         case ISD::SETULT:
4096         case ISD::SETULE:
4097         case ISD::SETNE:
4098           return DAG.getConstant(1, dl, VT);
4099         case ISD::SETGT:
4100         case ISD::SETGE:
4101           // True if the sign bit of C1 is set.
4102           return DAG.getConstant(C1.isNegative(), dl, VT);
4103         case ISD::SETLT:
4104         case ISD::SETLE:
4105           // True if the sign bit of C1 isn't set.
4106           return DAG.getConstant(C1.isNonNegative(), dl, VT);
4107         default:
4108           break;
4109         }
4110       }
4111 
4112       // Otherwise, we can perform the comparison with the low bits.
4113       switch (Cond) {
4114       case ISD::SETEQ:
4115       case ISD::SETNE:
4116       case ISD::SETUGT:
4117       case ISD::SETUGE:
4118       case ISD::SETULT:
4119       case ISD::SETULE: {
4120         EVT newVT = N0.getOperand(0).getValueType();
4121         if (DCI.isBeforeLegalizeOps() ||
4122             (isOperationLegal(ISD::SETCC, newVT) &&
4123              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
4124           EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
4125           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
4126 
4127           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
4128                                           NewConst, Cond);
4129           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
4130         }
4131         break;
4132       }
4133       default:
4134         break; // todo, be more careful with signed comparisons
4135       }
4136     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4137                (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4138                !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(),
4139                                       OpVT)) {
4140       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
4141       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
4142       EVT ExtDstTy = N0.getValueType();
4143       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
4144 
4145       // If the constant doesn't fit into the number of bits for the source of
4146       // the sign extension, it is impossible for both sides to be equal.
4147       if (C1.getMinSignedBits() > ExtSrcTyBits)
4148         return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
4149 
4150       assert(ExtDstTy == N0.getOperand(0).getValueType() &&
4151              ExtDstTy != ExtSrcTy && "Unexpected types!");
4152       APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
4153       SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
4154                                    DAG.getConstant(Imm, dl, ExtDstTy));
4155       if (!DCI.isCalledByLegalizer())
4156         DCI.AddToWorklist(ZextOp.getNode());
4157       // Otherwise, make this a use of a zext.
4158       return DAG.getSetCC(dl, VT, ZextOp,
4159                           DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
4160     } else if ((N1C->isZero() || N1C->isOne()) &&
4161                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4162       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
4163       if (N0.getOpcode() == ISD::SETCC &&
4164           isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
4165           (N0.getValueType() == MVT::i1 ||
4166            getBooleanContents(N0.getOperand(0).getValueType()) ==
4167                        ZeroOrOneBooleanContent)) {
4168         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
4169         if (TrueWhenTrue)
4170           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
4171         // Invert the condition.
4172         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4173         CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType());
4174         if (DCI.isBeforeLegalizeOps() ||
4175             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
4176           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
4177       }
4178 
4179       if ((N0.getOpcode() == ISD::XOR ||
4180            (N0.getOpcode() == ISD::AND &&
4181             N0.getOperand(0).getOpcode() == ISD::XOR &&
4182             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
4183           isOneConstant(N0.getOperand(1))) {
4184         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
4185         // can only do this if the top bits are known zero.
4186         unsigned BitWidth = N0.getValueSizeInBits();
4187         if (DAG.MaskedValueIsZero(N0,
4188                                   APInt::getHighBitsSet(BitWidth,
4189                                                         BitWidth-1))) {
4190           // Okay, get the un-inverted input value.
4191           SDValue Val;
4192           if (N0.getOpcode() == ISD::XOR) {
4193             Val = N0.getOperand(0);
4194           } else {
4195             assert(N0.getOpcode() == ISD::AND &&
4196                     N0.getOperand(0).getOpcode() == ISD::XOR);
4197             // ((X^1)&1)^1 -> X & 1
4198             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
4199                               N0.getOperand(0).getOperand(0),
4200                               N0.getOperand(1));
4201           }
4202 
4203           return DAG.getSetCC(dl, VT, Val, N1,
4204                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4205         }
4206       } else if (N1C->isOne()) {
4207         SDValue Op0 = N0;
4208         if (Op0.getOpcode() == ISD::TRUNCATE)
4209           Op0 = Op0.getOperand(0);
4210 
4211         if ((Op0.getOpcode() == ISD::XOR) &&
4212             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
4213             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
4214           SDValue XorLHS = Op0.getOperand(0);
4215           SDValue XorRHS = Op0.getOperand(1);
4216           // Ensure that the input setccs return an i1 type or 0/1 value.
4217           if (Op0.getValueType() == MVT::i1 ||
4218               (getBooleanContents(XorLHS.getOperand(0).getValueType()) ==
4219                       ZeroOrOneBooleanContent &&
4220                getBooleanContents(XorRHS.getOperand(0).getValueType()) ==
4221                         ZeroOrOneBooleanContent)) {
4222             // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
4223             Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
4224             return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
4225           }
4226         }
4227         if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
4228           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
4229           if (Op0.getValueType().bitsGT(VT))
4230             Op0 = DAG.getNode(ISD::AND, dl, VT,
4231                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
4232                           DAG.getConstant(1, dl, VT));
4233           else if (Op0.getValueType().bitsLT(VT))
4234             Op0 = DAG.getNode(ISD::AND, dl, VT,
4235                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
4236                         DAG.getConstant(1, dl, VT));
4237 
4238           return DAG.getSetCC(dl, VT, Op0,
4239                               DAG.getConstant(0, dl, Op0.getValueType()),
4240                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4241         }
4242         if (Op0.getOpcode() == ISD::AssertZext &&
4243             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
4244           return DAG.getSetCC(dl, VT, Op0,
4245                               DAG.getConstant(0, dl, Op0.getValueType()),
4246                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4247       }
4248     }
4249 
4250     // Given:
4251     //   icmp eq/ne (urem %x, %y), 0
4252     // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
4253     //   icmp eq/ne %x, 0
4254     if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
4255         (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4256       KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
4257       KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
4258       if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
4259         return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4260     }
4261 
4262     // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
4263     //  and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
4264     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4265         N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) &&
4266         N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
4267         N1C && N1C->isAllOnes()) {
4268       return DAG.getSetCC(dl, VT, N0.getOperand(0),
4269                           DAG.getConstant(0, dl, OpVT),
4270                           Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE);
4271     }
4272 
4273     if (SDValue V =
4274             optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
4275       return V;
4276   }
4277 
4278   // These simplifications apply to splat vectors as well.
4279   // TODO: Handle more splat vector cases.
4280   if (auto *N1C = isConstOrConstSplat(N1)) {
4281     const APInt &C1 = N1C->getAPIntValue();
4282 
4283     APInt MinVal, MaxVal;
4284     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
4285     if (ISD::isSignedIntSetCC(Cond)) {
4286       MinVal = APInt::getSignedMinValue(OperandBitSize);
4287       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
4288     } else {
4289       MinVal = APInt::getMinValue(OperandBitSize);
4290       MaxVal = APInt::getMaxValue(OperandBitSize);
4291     }
4292 
4293     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
4294     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
4295       // X >= MIN --> true
4296       if (C1 == MinVal)
4297         return DAG.getBoolConstant(true, dl, VT, OpVT);
4298 
4299       if (!VT.isVector()) { // TODO: Support this for vectors.
4300         // X >= C0 --> X > (C0 - 1)
4301         APInt C = C1 - 1;
4302         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
4303         if ((DCI.isBeforeLegalizeOps() ||
4304              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4305             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4306                                   isLegalICmpImmediate(C.getSExtValue())))) {
4307           return DAG.getSetCC(dl, VT, N0,
4308                               DAG.getConstant(C, dl, N1.getValueType()),
4309                               NewCC);
4310         }
4311       }
4312     }
4313 
4314     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
4315       // X <= MAX --> true
4316       if (C1 == MaxVal)
4317         return DAG.getBoolConstant(true, dl, VT, OpVT);
4318 
4319       // X <= C0 --> X < (C0 + 1)
4320       if (!VT.isVector()) { // TODO: Support this for vectors.
4321         APInt C = C1 + 1;
4322         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
4323         if ((DCI.isBeforeLegalizeOps() ||
4324              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4325             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4326                                   isLegalICmpImmediate(C.getSExtValue())))) {
4327           return DAG.getSetCC(dl, VT, N0,
4328                               DAG.getConstant(C, dl, N1.getValueType()),
4329                               NewCC);
4330         }
4331       }
4332     }
4333 
4334     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
4335       if (C1 == MinVal)
4336         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
4337 
4338       // TODO: Support this for vectors after legalize ops.
4339       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4340         // Canonicalize setlt X, Max --> setne X, Max
4341         if (C1 == MaxVal)
4342           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4343 
4344         // If we have setult X, 1, turn it into seteq X, 0
4345         if (C1 == MinVal+1)
4346           return DAG.getSetCC(dl, VT, N0,
4347                               DAG.getConstant(MinVal, dl, N0.getValueType()),
4348                               ISD::SETEQ);
4349       }
4350     }
4351 
4352     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
4353       if (C1 == MaxVal)
4354         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
4355 
4356       // TODO: Support this for vectors after legalize ops.
4357       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4358         // Canonicalize setgt X, Min --> setne X, Min
4359         if (C1 == MinVal)
4360           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4361 
4362         // If we have setugt X, Max-1, turn it into seteq X, Max
4363         if (C1 == MaxVal-1)
4364           return DAG.getSetCC(dl, VT, N0,
4365                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
4366                               ISD::SETEQ);
4367       }
4368     }
4369 
4370     if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
4371       // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
4372       if (C1.isZero())
4373         if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
4374                 VT, N0, N1, Cond, DCI, dl))
4375           return CC;
4376 
4377       // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
4378       // For example, when high 32-bits of i64 X are known clear:
4379       // all bits clear: (X | (Y<<32)) ==  0 --> (X | Y) ==  0
4380       // all bits set:   (X | (Y<<32)) == -1 --> (X & Y) == -1
4381       bool CmpZero = N1C->getAPIntValue().isZero();
4382       bool CmpNegOne = N1C->getAPIntValue().isAllOnes();
4383       if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
4384         // Match or(lo,shl(hi,bw/2)) pattern.
4385         auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
4386           unsigned EltBits = V.getScalarValueSizeInBits();
4387           if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
4388             return false;
4389           SDValue LHS = V.getOperand(0);
4390           SDValue RHS = V.getOperand(1);
4391           APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
4392           // Unshifted element must have zero upperbits.
4393           if (RHS.getOpcode() == ISD::SHL &&
4394               isa<ConstantSDNode>(RHS.getOperand(1)) &&
4395               RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4396               DAG.MaskedValueIsZero(LHS, HiBits)) {
4397             Lo = LHS;
4398             Hi = RHS.getOperand(0);
4399             return true;
4400           }
4401           if (LHS.getOpcode() == ISD::SHL &&
4402               isa<ConstantSDNode>(LHS.getOperand(1)) &&
4403               LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4404               DAG.MaskedValueIsZero(RHS, HiBits)) {
4405             Lo = RHS;
4406             Hi = LHS.getOperand(0);
4407             return true;
4408           }
4409           return false;
4410         };
4411 
4412         auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
4413           unsigned EltBits = N0.getScalarValueSizeInBits();
4414           unsigned HalfBits = EltBits / 2;
4415           APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
4416           SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
4417           SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
4418           SDValue NewN0 =
4419               DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
4420           SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
4421           return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
4422         };
4423 
4424         SDValue Lo, Hi;
4425         if (IsConcat(N0, Lo, Hi))
4426           return MergeConcat(Lo, Hi);
4427 
4428         if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
4429           SDValue Lo0, Lo1, Hi0, Hi1;
4430           if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
4431               IsConcat(N0.getOperand(1), Lo1, Hi1)) {
4432             return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
4433                                DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
4434           }
4435         }
4436       }
4437     }
4438 
4439     // If we have "setcc X, C0", check to see if we can shrink the immediate
4440     // by changing cc.
4441     // TODO: Support this for vectors after legalize ops.
4442     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4443       // SETUGT X, SINTMAX  -> SETLT X, 0
4444       // SETUGE X, SINTMIN -> SETLT X, 0
4445       if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
4446           (Cond == ISD::SETUGE && C1.isMinSignedValue()))
4447         return DAG.getSetCC(dl, VT, N0,
4448                             DAG.getConstant(0, dl, N1.getValueType()),
4449                             ISD::SETLT);
4450 
4451       // SETULT X, SINTMIN  -> SETGT X, -1
4452       // SETULE X, SINTMAX  -> SETGT X, -1
4453       if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
4454           (Cond == ISD::SETULE && C1.isMaxSignedValue()))
4455         return DAG.getSetCC(dl, VT, N0,
4456                             DAG.getAllOnesConstant(dl, N1.getValueType()),
4457                             ISD::SETGT);
4458     }
4459   }
4460 
4461   // Back to non-vector simplifications.
4462   // TODO: Can we do these for vector splats?
4463   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4464     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4465     const APInt &C1 = N1C->getAPIntValue();
4466     EVT ShValTy = N0.getValueType();
4467 
4468     // Fold bit comparisons when we can. This will result in an
4469     // incorrect value when boolean false is negative one, unless
4470     // the bitsize is 1 in which case the false value is the same
4471     // in practice regardless of the representation.
4472     if ((VT.getSizeInBits() == 1 ||
4473          getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) &&
4474         (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4475         (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
4476         N0.getOpcode() == ISD::AND) {
4477       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4478         EVT ShiftTy =
4479             getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4480         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
4481           // Perform the xform if the AND RHS is a single bit.
4482           unsigned ShCt = AndRHS->getAPIntValue().logBase2();
4483           if (AndRHS->getAPIntValue().isPowerOf2() &&
4484               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4485             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4486                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4487                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4488           }
4489         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
4490           // (X & 8) == 8  -->  (X & 8) >> 3
4491           // Perform the xform if C1 is a single bit.
4492           unsigned ShCt = C1.logBase2();
4493           if (C1.isPowerOf2() &&
4494               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4495             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4496                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4497                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4498           }
4499         }
4500       }
4501     }
4502 
4503     if (C1.getMinSignedBits() <= 64 &&
4504         !isLegalICmpImmediate(C1.getSExtValue())) {
4505       EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4506       // (X & -256) == 256 -> (X >> 8) == 1
4507       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4508           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
4509         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4510           const APInt &AndRHSC = AndRHS->getAPIntValue();
4511           if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) {
4512             unsigned ShiftBits = AndRHSC.countTrailingZeros();
4513             if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4514               SDValue Shift =
4515                 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0),
4516                             DAG.getConstant(ShiftBits, dl, ShiftTy));
4517               SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy);
4518               return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
4519             }
4520           }
4521         }
4522       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
4523                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
4524         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
4525         // X <  0x100000000 -> (X >> 32) <  1
4526         // X >= 0x100000000 -> (X >> 32) >= 1
4527         // X <= 0x0ffffffff -> (X >> 32) <  1
4528         // X >  0x0ffffffff -> (X >> 32) >= 1
4529         unsigned ShiftBits;
4530         APInt NewC = C1;
4531         ISD::CondCode NewCond = Cond;
4532         if (AdjOne) {
4533           ShiftBits = C1.countTrailingOnes();
4534           NewC = NewC + 1;
4535           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4536         } else {
4537           ShiftBits = C1.countTrailingZeros();
4538         }
4539         NewC.lshrInPlace(ShiftBits);
4540         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
4541             isLegalICmpImmediate(NewC.getSExtValue()) &&
4542             !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4543           SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4544                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
4545           SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
4546           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
4547         }
4548       }
4549     }
4550   }
4551 
4552   if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
4553     auto *CFP = cast<ConstantFPSDNode>(N1);
4554     assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
4555 
4556     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
4557     // constant if knowing that the operand is non-nan is enough.  We prefer to
4558     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
4559     // materialize 0.0.
4560     if (Cond == ISD::SETO || Cond == ISD::SETUO)
4561       return DAG.getSetCC(dl, VT, N0, N0, Cond);
4562 
4563     // setcc (fneg x), C -> setcc swap(pred) x, -C
4564     if (N0.getOpcode() == ISD::FNEG) {
4565       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
4566       if (DCI.isBeforeLegalizeOps() ||
4567           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
4568         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
4569         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
4570       }
4571     }
4572 
4573     // If the condition is not legal, see if we can find an equivalent one
4574     // which is legal.
4575     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
4576       // If the comparison was an awkward floating-point == or != and one of
4577       // the comparison operands is infinity or negative infinity, convert the
4578       // condition to a less-awkward <= or >=.
4579       if (CFP->getValueAPF().isInfinity()) {
4580         bool IsNegInf = CFP->getValueAPF().isNegative();
4581         ISD::CondCode NewCond = ISD::SETCC_INVALID;
4582         switch (Cond) {
4583         case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
4584         case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
4585         case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
4586         case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
4587         default: break;
4588         }
4589         if (NewCond != ISD::SETCC_INVALID &&
4590             isCondCodeLegal(NewCond, N0.getSimpleValueType()))
4591           return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4592       }
4593     }
4594   }
4595 
4596   if (N0 == N1) {
4597     // The sext(setcc()) => setcc() optimization relies on the appropriate
4598     // constant being emitted.
4599     assert(!N0.getValueType().isInteger() &&
4600            "Integer types should be handled by FoldSetCC");
4601 
4602     bool EqTrue = ISD::isTrueWhenEqual(Cond);
4603     unsigned UOF = ISD::getUnorderedFlavor(Cond);
4604     if (UOF == 2) // FP operators that are undefined on NaNs.
4605       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4606     if (UOF == unsigned(EqTrue))
4607       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4608     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
4609     // if it is not already.
4610     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
4611     if (NewCond != Cond &&
4612         (DCI.isBeforeLegalizeOps() ||
4613                             isCondCodeLegal(NewCond, N0.getSimpleValueType())))
4614       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4615   }
4616 
4617   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4618       N0.getValueType().isInteger()) {
4619     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
4620         N0.getOpcode() == ISD::XOR) {
4621       // Simplify (X+Y) == (X+Z) -->  Y == Z
4622       if (N0.getOpcode() == N1.getOpcode()) {
4623         if (N0.getOperand(0) == N1.getOperand(0))
4624           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
4625         if (N0.getOperand(1) == N1.getOperand(1))
4626           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
4627         if (isCommutativeBinOp(N0.getOpcode())) {
4628           // If X op Y == Y op X, try other combinations.
4629           if (N0.getOperand(0) == N1.getOperand(1))
4630             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
4631                                 Cond);
4632           if (N0.getOperand(1) == N1.getOperand(0))
4633             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
4634                                 Cond);
4635         }
4636       }
4637 
4638       // If RHS is a legal immediate value for a compare instruction, we need
4639       // to be careful about increasing register pressure needlessly.
4640       bool LegalRHSImm = false;
4641 
4642       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
4643         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4644           // Turn (X+C1) == C2 --> X == C2-C1
4645           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
4646             return DAG.getSetCC(dl, VT, N0.getOperand(0),
4647                                 DAG.getConstant(RHSC->getAPIntValue()-
4648                                                 LHSR->getAPIntValue(),
4649                                 dl, N0.getValueType()), Cond);
4650           }
4651 
4652           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
4653           if (N0.getOpcode() == ISD::XOR)
4654             // If we know that all of the inverted bits are zero, don't bother
4655             // performing the inversion.
4656             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
4657               return
4658                 DAG.getSetCC(dl, VT, N0.getOperand(0),
4659                              DAG.getConstant(LHSR->getAPIntValue() ^
4660                                                RHSC->getAPIntValue(),
4661                                              dl, N0.getValueType()),
4662                              Cond);
4663         }
4664 
4665         // Turn (C1-X) == C2 --> X == C1-C2
4666         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
4667           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
4668             return
4669               DAG.getSetCC(dl, VT, N0.getOperand(1),
4670                            DAG.getConstant(SUBC->getAPIntValue() -
4671                                              RHSC->getAPIntValue(),
4672                                            dl, N0.getValueType()),
4673                            Cond);
4674           }
4675         }
4676 
4677         // Could RHSC fold directly into a compare?
4678         if (RHSC->getValueType(0).getSizeInBits() <= 64)
4679           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
4680       }
4681 
4682       // (X+Y) == X --> Y == 0 and similar folds.
4683       // Don't do this if X is an immediate that can fold into a cmp
4684       // instruction and X+Y has other uses. It could be an induction variable
4685       // chain, and the transform would increase register pressure.
4686       if (!LegalRHSImm || N0.hasOneUse())
4687         if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
4688           return V;
4689     }
4690 
4691     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
4692         N1.getOpcode() == ISD::XOR)
4693       if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
4694         return V;
4695 
4696     if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
4697       return V;
4698   }
4699 
4700   // Fold remainder of division by a constant.
4701   if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
4702       N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4703     AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4704 
4705     // When division is cheap or optimizing for minimum size,
4706     // fall through to DIVREM creation by skipping this fold.
4707     if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
4708       if (N0.getOpcode() == ISD::UREM) {
4709         if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
4710           return Folded;
4711       } else if (N0.getOpcode() == ISD::SREM) {
4712         if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
4713           return Folded;
4714       }
4715     }
4716   }
4717 
4718   // Fold away ALL boolean setcc's.
4719   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
4720     SDValue Temp;
4721     switch (Cond) {
4722     default: llvm_unreachable("Unknown integer setcc!");
4723     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
4724       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4725       N0 = DAG.getNOT(dl, Temp, OpVT);
4726       if (!DCI.isCalledByLegalizer())
4727         DCI.AddToWorklist(Temp.getNode());
4728       break;
4729     case ISD::SETNE:  // X != Y   -->  (X^Y)
4730       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4731       break;
4732     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
4733     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
4734       Temp = DAG.getNOT(dl, N0, OpVT);
4735       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
4736       if (!DCI.isCalledByLegalizer())
4737         DCI.AddToWorklist(Temp.getNode());
4738       break;
4739     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
4740     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
4741       Temp = DAG.getNOT(dl, N1, OpVT);
4742       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
4743       if (!DCI.isCalledByLegalizer())
4744         DCI.AddToWorklist(Temp.getNode());
4745       break;
4746     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
4747     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
4748       Temp = DAG.getNOT(dl, N0, OpVT);
4749       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
4750       if (!DCI.isCalledByLegalizer())
4751         DCI.AddToWorklist(Temp.getNode());
4752       break;
4753     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
4754     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
4755       Temp = DAG.getNOT(dl, N1, OpVT);
4756       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
4757       break;
4758     }
4759     if (VT.getScalarType() != MVT::i1) {
4760       if (!DCI.isCalledByLegalizer())
4761         DCI.AddToWorklist(N0.getNode());
4762       // FIXME: If running after legalize, we probably can't do this.
4763       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
4764       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
4765     }
4766     return N0;
4767   }
4768 
4769   // Could not fold it.
4770   return SDValue();
4771 }
4772 
4773 /// Returns true (and the GlobalValue and the offset) if the node is a
4774 /// GlobalAddress + offset.
4775 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA,
4776                                     int64_t &Offset) const {
4777 
4778   SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
4779 
4780   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
4781     GA = GASD->getGlobal();
4782     Offset += GASD->getOffset();
4783     return true;
4784   }
4785 
4786   if (N->getOpcode() == ISD::ADD) {
4787     SDValue N1 = N->getOperand(0);
4788     SDValue N2 = N->getOperand(1);
4789     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
4790       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
4791         Offset += V->getSExtValue();
4792         return true;
4793       }
4794     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
4795       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
4796         Offset += V->getSExtValue();
4797         return true;
4798       }
4799     }
4800   }
4801 
4802   return false;
4803 }
4804 
4805 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
4806                                           DAGCombinerInfo &DCI) const {
4807   // Default implementation: no optimization.
4808   return SDValue();
4809 }
4810 
4811 //===----------------------------------------------------------------------===//
4812 //  Inline Assembler Implementation Methods
4813 //===----------------------------------------------------------------------===//
4814 
4815 TargetLowering::ConstraintType
4816 TargetLowering::getConstraintType(StringRef Constraint) const {
4817   unsigned S = Constraint.size();
4818 
4819   if (S == 1) {
4820     switch (Constraint[0]) {
4821     default: break;
4822     case 'r':
4823       return C_RegisterClass;
4824     case 'm': // memory
4825     case 'o': // offsetable
4826     case 'V': // not offsetable
4827       return C_Memory;
4828     case 'n': // Simple Integer
4829     case 'E': // Floating Point Constant
4830     case 'F': // Floating Point Constant
4831       return C_Immediate;
4832     case 'i': // Simple Integer or Relocatable Constant
4833     case 's': // Relocatable Constant
4834     case 'p': // Address.
4835     case 'X': // Allow ANY value.
4836     case 'I': // Target registers.
4837     case 'J':
4838     case 'K':
4839     case 'L':
4840     case 'M':
4841     case 'N':
4842     case 'O':
4843     case 'P':
4844     case '<':
4845     case '>':
4846       return C_Other;
4847     }
4848   }
4849 
4850   if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
4851     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
4852       return C_Memory;
4853     return C_Register;
4854   }
4855   return C_Unknown;
4856 }
4857 
4858 /// Try to replace an X constraint, which matches anything, with another that
4859 /// has more specific requirements based on the type of the corresponding
4860 /// operand.
4861 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4862   if (ConstraintVT.isInteger())
4863     return "r";
4864   if (ConstraintVT.isFloatingPoint())
4865     return "f"; // works for many targets
4866   return nullptr;
4867 }
4868 
4869 SDValue TargetLowering::LowerAsmOutputForConstraint(
4870     SDValue &Chain, SDValue &Flag, const SDLoc &DL,
4871     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
4872   return SDValue();
4873 }
4874 
4875 /// Lower the specified operand into the Ops vector.
4876 /// If it is invalid, don't add anything to Ops.
4877 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4878                                                   std::string &Constraint,
4879                                                   std::vector<SDValue> &Ops,
4880                                                   SelectionDAG &DAG) const {
4881 
4882   if (Constraint.length() > 1) return;
4883 
4884   char ConstraintLetter = Constraint[0];
4885   switch (ConstraintLetter) {
4886   default: break;
4887   case 'X':    // Allows any operand
4888   case 'i':    // Simple Integer or Relocatable Constant
4889   case 'n':    // Simple Integer
4890   case 's': {  // Relocatable Constant
4891 
4892     ConstantSDNode *C;
4893     uint64_t Offset = 0;
4894 
4895     // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
4896     // etc., since getelementpointer is variadic. We can't use
4897     // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
4898     // while in this case the GA may be furthest from the root node which is
4899     // likely an ISD::ADD.
4900     while (true) {
4901       if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
4902         // gcc prints these as sign extended.  Sign extend value to 64 bits
4903         // now; without this it would get ZExt'd later in
4904         // ScheduleDAGSDNodes::EmitNode, which is very generic.
4905         bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
4906         BooleanContent BCont = getBooleanContents(MVT::i64);
4907         ISD::NodeType ExtOpc =
4908             IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
4909         int64_t ExtVal =
4910             ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
4911         Ops.push_back(
4912             DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
4913         return;
4914       }
4915       if (ConstraintLetter != 'n') {
4916         if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
4917           Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
4918                                                    GA->getValueType(0),
4919                                                    Offset + GA->getOffset()));
4920           return;
4921         }
4922         if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
4923           Ops.push_back(DAG.getTargetBlockAddress(
4924               BA->getBlockAddress(), BA->getValueType(0),
4925               Offset + BA->getOffset(), BA->getTargetFlags()));
4926           return;
4927         }
4928         if (isa<BasicBlockSDNode>(Op)) {
4929           Ops.push_back(Op);
4930           return;
4931         }
4932       }
4933       const unsigned OpCode = Op.getOpcode();
4934       if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
4935         if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
4936           Op = Op.getOperand(1);
4937         // Subtraction is not commutative.
4938         else if (OpCode == ISD::ADD &&
4939                  (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
4940           Op = Op.getOperand(0);
4941         else
4942           return;
4943         Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
4944         continue;
4945       }
4946       return;
4947     }
4948     break;
4949   }
4950   }
4951 }
4952 
4953 std::pair<unsigned, const TargetRegisterClass *>
4954 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
4955                                              StringRef Constraint,
4956                                              MVT VT) const {
4957   if (Constraint.empty() || Constraint[0] != '{')
4958     return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
4959   assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
4960 
4961   // Remove the braces from around the name.
4962   StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
4963 
4964   std::pair<unsigned, const TargetRegisterClass *> R =
4965       std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
4966 
4967   // Figure out which register class contains this reg.
4968   for (const TargetRegisterClass *RC : RI->regclasses()) {
4969     // If none of the value types for this register class are valid, we
4970     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
4971     if (!isLegalRC(*RI, *RC))
4972       continue;
4973 
4974     for (const MCPhysReg &PR : *RC) {
4975       if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
4976         std::pair<unsigned, const TargetRegisterClass *> S =
4977             std::make_pair(PR, RC);
4978 
4979         // If this register class has the requested value type, return it,
4980         // otherwise keep searching and return the first class found
4981         // if no other is found which explicitly has the requested type.
4982         if (RI->isTypeLegalForClass(*RC, VT))
4983           return S;
4984         if (!R.second)
4985           R = S;
4986       }
4987     }
4988   }
4989 
4990   return R;
4991 }
4992 
4993 //===----------------------------------------------------------------------===//
4994 // Constraint Selection.
4995 
4996 /// Return true of this is an input operand that is a matching constraint like
4997 /// "4".
4998 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
4999   assert(!ConstraintCode.empty() && "No known constraint!");
5000   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
5001 }
5002 
5003 /// If this is an input matching constraint, this method returns the output
5004 /// operand it matches.
5005 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
5006   assert(!ConstraintCode.empty() && "No known constraint!");
5007   return atoi(ConstraintCode.c_str());
5008 }
5009 
5010 /// Split up the constraint string from the inline assembly value into the
5011 /// specific constraints and their prefixes, and also tie in the associated
5012 /// operand values.
5013 /// If this returns an empty vector, and if the constraint string itself
5014 /// isn't empty, there was an error parsing.
5015 TargetLowering::AsmOperandInfoVector
5016 TargetLowering::ParseConstraints(const DataLayout &DL,
5017                                  const TargetRegisterInfo *TRI,
5018                                  const CallBase &Call) const {
5019   /// Information about all of the constraints.
5020   AsmOperandInfoVector ConstraintOperands;
5021   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
5022   unsigned maCount = 0; // Largest number of multiple alternative constraints.
5023 
5024   // Do a prepass over the constraints, canonicalizing them, and building up the
5025   // ConstraintOperands list.
5026   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5027   unsigned ResNo = 0; // ResNo - The result number of the next output.
5028 
5029   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
5030     ConstraintOperands.emplace_back(std::move(CI));
5031     AsmOperandInfo &OpInfo = ConstraintOperands.back();
5032 
5033     // Update multiple alternative constraint count.
5034     if (OpInfo.multipleAlternatives.size() > maCount)
5035       maCount = OpInfo.multipleAlternatives.size();
5036 
5037     OpInfo.ConstraintVT = MVT::Other;
5038 
5039     // Compute the value type for each operand.
5040     switch (OpInfo.Type) {
5041     case InlineAsm::isOutput:
5042       // Indirect outputs just consume an argument.
5043       if (OpInfo.isIndirect) {
5044         OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5045         break;
5046       }
5047 
5048       // The return value of the call is this value.  As such, there is no
5049       // corresponding argument.
5050       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
5051       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
5052         OpInfo.ConstraintVT =
5053             getSimpleValueType(DL, STy->getElementType(ResNo));
5054       } else {
5055         assert(ResNo == 0 && "Asm only has one result!");
5056         OpInfo.ConstraintVT =
5057             getAsmOperandValueType(DL, Call.getType()).getSimpleVT();
5058       }
5059       ++ResNo;
5060       break;
5061     case InlineAsm::isInput:
5062       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5063       break;
5064     case InlineAsm::isClobber:
5065       // Nothing to do.
5066       break;
5067     }
5068 
5069     if (OpInfo.CallOperandVal) {
5070       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
5071       if (OpInfo.isIndirect) {
5072         OpTy = Call.getParamElementType(ArgNo);
5073         assert(OpTy && "Indirect operand must have elementtype attribute");
5074       }
5075 
5076       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5077       if (StructType *STy = dyn_cast<StructType>(OpTy))
5078         if (STy->getNumElements() == 1)
5079           OpTy = STy->getElementType(0);
5080 
5081       // If OpTy is not a single value, it may be a struct/union that we
5082       // can tile with integers.
5083       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5084         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
5085         switch (BitSize) {
5086         default: break;
5087         case 1:
5088         case 8:
5089         case 16:
5090         case 32:
5091         case 64:
5092         case 128:
5093           OpInfo.ConstraintVT =
5094               MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
5095           break;
5096         }
5097       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
5098         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
5099         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
5100       } else {
5101         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
5102       }
5103 
5104       ArgNo++;
5105     }
5106   }
5107 
5108   // If we have multiple alternative constraints, select the best alternative.
5109   if (!ConstraintOperands.empty()) {
5110     if (maCount) {
5111       unsigned bestMAIndex = 0;
5112       int bestWeight = -1;
5113       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
5114       int weight = -1;
5115       unsigned maIndex;
5116       // Compute the sums of the weights for each alternative, keeping track
5117       // of the best (highest weight) one so far.
5118       for (maIndex = 0; maIndex < maCount; ++maIndex) {
5119         int weightSum = 0;
5120         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5121              cIndex != eIndex; ++cIndex) {
5122           AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5123           if (OpInfo.Type == InlineAsm::isClobber)
5124             continue;
5125 
5126           // If this is an output operand with a matching input operand,
5127           // look up the matching input. If their types mismatch, e.g. one
5128           // is an integer, the other is floating point, or their sizes are
5129           // different, flag it as an maCantMatch.
5130           if (OpInfo.hasMatchingInput()) {
5131             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5132             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5133               if ((OpInfo.ConstraintVT.isInteger() !=
5134                    Input.ConstraintVT.isInteger()) ||
5135                   (OpInfo.ConstraintVT.getSizeInBits() !=
5136                    Input.ConstraintVT.getSizeInBits())) {
5137                 weightSum = -1; // Can't match.
5138                 break;
5139               }
5140             }
5141           }
5142           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
5143           if (weight == -1) {
5144             weightSum = -1;
5145             break;
5146           }
5147           weightSum += weight;
5148         }
5149         // Update best.
5150         if (weightSum > bestWeight) {
5151           bestWeight = weightSum;
5152           bestMAIndex = maIndex;
5153         }
5154       }
5155 
5156       // Now select chosen alternative in each constraint.
5157       for (AsmOperandInfo &cInfo : ConstraintOperands)
5158         if (cInfo.Type != InlineAsm::isClobber)
5159           cInfo.selectAlternative(bestMAIndex);
5160     }
5161   }
5162 
5163   // Check and hook up tied operands, choose constraint code to use.
5164   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5165        cIndex != eIndex; ++cIndex) {
5166     AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5167 
5168     // If this is an output operand with a matching input operand, look up the
5169     // matching input. If their types mismatch, e.g. one is an integer, the
5170     // other is floating point, or their sizes are different, flag it as an
5171     // error.
5172     if (OpInfo.hasMatchingInput()) {
5173       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5174 
5175       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5176         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
5177             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
5178                                          OpInfo.ConstraintVT);
5179         std::pair<unsigned, const TargetRegisterClass *> InputRC =
5180             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
5181                                          Input.ConstraintVT);
5182         if ((OpInfo.ConstraintVT.isInteger() !=
5183              Input.ConstraintVT.isInteger()) ||
5184             (MatchRC.second != InputRC.second)) {
5185           report_fatal_error("Unsupported asm: input constraint"
5186                              " with a matching output constraint of"
5187                              " incompatible type!");
5188         }
5189       }
5190     }
5191   }
5192 
5193   return ConstraintOperands;
5194 }
5195 
5196 /// Return an integer indicating how general CT is.
5197 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
5198   switch (CT) {
5199   case TargetLowering::C_Immediate:
5200   case TargetLowering::C_Other:
5201   case TargetLowering::C_Unknown:
5202     return 0;
5203   case TargetLowering::C_Register:
5204     return 1;
5205   case TargetLowering::C_RegisterClass:
5206     return 2;
5207   case TargetLowering::C_Memory:
5208     return 3;
5209   }
5210   llvm_unreachable("Invalid constraint type");
5211 }
5212 
5213 /// Examine constraint type and operand type and determine a weight value.
5214 /// This object must already have been set up with the operand type
5215 /// and the current alternative constraint selected.
5216 TargetLowering::ConstraintWeight
5217   TargetLowering::getMultipleConstraintMatchWeight(
5218     AsmOperandInfo &info, int maIndex) const {
5219   InlineAsm::ConstraintCodeVector *rCodes;
5220   if (maIndex >= (int)info.multipleAlternatives.size())
5221     rCodes = &info.Codes;
5222   else
5223     rCodes = &info.multipleAlternatives[maIndex].Codes;
5224   ConstraintWeight BestWeight = CW_Invalid;
5225 
5226   // Loop over the options, keeping track of the most general one.
5227   for (const std::string &rCode : *rCodes) {
5228     ConstraintWeight weight =
5229         getSingleConstraintMatchWeight(info, rCode.c_str());
5230     if (weight > BestWeight)
5231       BestWeight = weight;
5232   }
5233 
5234   return BestWeight;
5235 }
5236 
5237 /// Examine constraint type and operand type and determine a weight value.
5238 /// This object must already have been set up with the operand type
5239 /// and the current alternative constraint selected.
5240 TargetLowering::ConstraintWeight
5241   TargetLowering::getSingleConstraintMatchWeight(
5242     AsmOperandInfo &info, const char *constraint) const {
5243   ConstraintWeight weight = CW_Invalid;
5244   Value *CallOperandVal = info.CallOperandVal;
5245     // If we don't have a value, we can't do a match,
5246     // but allow it at the lowest weight.
5247   if (!CallOperandVal)
5248     return CW_Default;
5249   // Look at the constraint type.
5250   switch (*constraint) {
5251     case 'i': // immediate integer.
5252     case 'n': // immediate integer with a known value.
5253       if (isa<ConstantInt>(CallOperandVal))
5254         weight = CW_Constant;
5255       break;
5256     case 's': // non-explicit intregal immediate.
5257       if (isa<GlobalValue>(CallOperandVal))
5258         weight = CW_Constant;
5259       break;
5260     case 'E': // immediate float if host format.
5261     case 'F': // immediate float.
5262       if (isa<ConstantFP>(CallOperandVal))
5263         weight = CW_Constant;
5264       break;
5265     case '<': // memory operand with autodecrement.
5266     case '>': // memory operand with autoincrement.
5267     case 'm': // memory operand.
5268     case 'o': // offsettable memory operand
5269     case 'V': // non-offsettable memory operand
5270       weight = CW_Memory;
5271       break;
5272     case 'r': // general register.
5273     case 'g': // general register, memory operand or immediate integer.
5274               // note: Clang converts "g" to "imr".
5275       if (CallOperandVal->getType()->isIntegerTy())
5276         weight = CW_Register;
5277       break;
5278     case 'X': // any operand.
5279   default:
5280     weight = CW_Default;
5281     break;
5282   }
5283   return weight;
5284 }
5285 
5286 /// If there are multiple different constraints that we could pick for this
5287 /// operand (e.g. "imr") try to pick the 'best' one.
5288 /// This is somewhat tricky: constraints fall into four classes:
5289 ///    Other         -> immediates and magic values
5290 ///    Register      -> one specific register
5291 ///    RegisterClass -> a group of regs
5292 ///    Memory        -> memory
5293 /// Ideally, we would pick the most specific constraint possible: if we have
5294 /// something that fits into a register, we would pick it.  The problem here
5295 /// is that if we have something that could either be in a register or in
5296 /// memory that use of the register could cause selection of *other*
5297 /// operands to fail: they might only succeed if we pick memory.  Because of
5298 /// this the heuristic we use is:
5299 ///
5300 ///  1) If there is an 'other' constraint, and if the operand is valid for
5301 ///     that constraint, use it.  This makes us take advantage of 'i'
5302 ///     constraints when available.
5303 ///  2) Otherwise, pick the most general constraint present.  This prefers
5304 ///     'm' over 'r', for example.
5305 ///
5306 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
5307                              const TargetLowering &TLI,
5308                              SDValue Op, SelectionDAG *DAG) {
5309   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
5310   unsigned BestIdx = 0;
5311   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
5312   int BestGenerality = -1;
5313 
5314   // Loop over the options, keeping track of the most general one.
5315   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
5316     TargetLowering::ConstraintType CType =
5317       TLI.getConstraintType(OpInfo.Codes[i]);
5318 
5319     // Indirect 'other' or 'immediate' constraints are not allowed.
5320     if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
5321                                CType == TargetLowering::C_Register ||
5322                                CType == TargetLowering::C_RegisterClass))
5323       continue;
5324 
5325     // If this is an 'other' or 'immediate' constraint, see if the operand is
5326     // valid for it. For example, on X86 we might have an 'rI' constraint. If
5327     // the operand is an integer in the range [0..31] we want to use I (saving a
5328     // load of a register), otherwise we must use 'r'.
5329     if ((CType == TargetLowering::C_Other ||
5330          CType == TargetLowering::C_Immediate) && Op.getNode()) {
5331       assert(OpInfo.Codes[i].size() == 1 &&
5332              "Unhandled multi-letter 'other' constraint");
5333       std::vector<SDValue> ResultOps;
5334       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
5335                                        ResultOps, *DAG);
5336       if (!ResultOps.empty()) {
5337         BestType = CType;
5338         BestIdx = i;
5339         break;
5340       }
5341     }
5342 
5343     // Things with matching constraints can only be registers, per gcc
5344     // documentation.  This mainly affects "g" constraints.
5345     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
5346       continue;
5347 
5348     // This constraint letter is more general than the previous one, use it.
5349     int Generality = getConstraintGenerality(CType);
5350     if (Generality > BestGenerality) {
5351       BestType = CType;
5352       BestIdx = i;
5353       BestGenerality = Generality;
5354     }
5355   }
5356 
5357   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
5358   OpInfo.ConstraintType = BestType;
5359 }
5360 
5361 /// Determines the constraint code and constraint type to use for the specific
5362 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
5363 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
5364                                             SDValue Op,
5365                                             SelectionDAG *DAG) const {
5366   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
5367 
5368   // Single-letter constraints ('r') are very common.
5369   if (OpInfo.Codes.size() == 1) {
5370     OpInfo.ConstraintCode = OpInfo.Codes[0];
5371     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5372   } else {
5373     ChooseConstraint(OpInfo, *this, Op, DAG);
5374   }
5375 
5376   // 'X' matches anything.
5377   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
5378     // Constants are handled elsewhere.  For Functions, the type here is the
5379     // type of the result, which is not what we want to look at; leave them
5380     // alone.
5381     Value *v = OpInfo.CallOperandVal;
5382     if (isa<ConstantInt>(v) || isa<Function>(v)) {
5383       return;
5384     }
5385 
5386     if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
5387       OpInfo.ConstraintCode = "i";
5388       return;
5389     }
5390 
5391     // Otherwise, try to resolve it to something we know about by looking at
5392     // the actual operand type.
5393     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
5394       OpInfo.ConstraintCode = Repl;
5395       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5396     }
5397   }
5398 }
5399 
5400 /// Given an exact SDIV by a constant, create a multiplication
5401 /// with the multiplicative inverse of the constant.
5402 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N,
5403                               const SDLoc &dl, SelectionDAG &DAG,
5404                               SmallVectorImpl<SDNode *> &Created) {
5405   SDValue Op0 = N->getOperand(0);
5406   SDValue Op1 = N->getOperand(1);
5407   EVT VT = N->getValueType(0);
5408   EVT SVT = VT.getScalarType();
5409   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
5410   EVT ShSVT = ShVT.getScalarType();
5411 
5412   bool UseSRA = false;
5413   SmallVector<SDValue, 16> Shifts, Factors;
5414 
5415   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5416     if (C->isZero())
5417       return false;
5418     APInt Divisor = C->getAPIntValue();
5419     unsigned Shift = Divisor.countTrailingZeros();
5420     if (Shift) {
5421       Divisor.ashrInPlace(Shift);
5422       UseSRA = true;
5423     }
5424     // Calculate the multiplicative inverse, using Newton's method.
5425     APInt t;
5426     APInt Factor = Divisor;
5427     while ((t = Divisor * Factor) != 1)
5428       Factor *= APInt(Divisor.getBitWidth(), 2) - t;
5429     Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
5430     Factors.push_back(DAG.getConstant(Factor, dl, SVT));
5431     return true;
5432   };
5433 
5434   // Collect all magic values from the build vector.
5435   if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
5436     return SDValue();
5437 
5438   SDValue Shift, Factor;
5439   if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
5440     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5441     Factor = DAG.getBuildVector(VT, dl, Factors);
5442   } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
5443     assert(Shifts.size() == 1 && Factors.size() == 1 &&
5444            "Expected matchUnaryPredicate to return one element for scalable "
5445            "vectors");
5446     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5447     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5448   } else {
5449     assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
5450     Shift = Shifts[0];
5451     Factor = Factors[0];
5452   }
5453 
5454   SDValue Res = Op0;
5455 
5456   // Shift the value upfront if it is even, so the LSB is one.
5457   if (UseSRA) {
5458     // TODO: For UDIV use SRL instead of SRA.
5459     SDNodeFlags Flags;
5460     Flags.setExact(true);
5461     Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
5462     Created.push_back(Res.getNode());
5463   }
5464 
5465   return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
5466 }
5467 
5468 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
5469                               SelectionDAG &DAG,
5470                               SmallVectorImpl<SDNode *> &Created) const {
5471   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5472   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5473   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
5474     return SDValue(N, 0); // Lower SDIV as SDIV
5475   return SDValue();
5476 }
5477 
5478 /// Given an ISD::SDIV node expressing a divide by constant,
5479 /// return a DAG expression to select that will generate the same value by
5480 /// multiplying by a magic number.
5481 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5482 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
5483                                   bool IsAfterLegalization,
5484                                   SmallVectorImpl<SDNode *> &Created) const {
5485   SDLoc dl(N);
5486   EVT VT = N->getValueType(0);
5487   EVT SVT = VT.getScalarType();
5488   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5489   EVT ShSVT = ShVT.getScalarType();
5490   unsigned EltBits = VT.getScalarSizeInBits();
5491   EVT MulVT;
5492 
5493   // Check to see if we can do this.
5494   // FIXME: We should be more aggressive here.
5495   if (!isTypeLegal(VT)) {
5496     // Limit this to simple scalars for now.
5497     if (VT.isVector() || !VT.isSimple())
5498       return SDValue();
5499 
5500     // If this type will be promoted to a large enough type with a legal
5501     // multiply operation, we can go ahead and do this transform.
5502     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5503       return SDValue();
5504 
5505     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5506     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5507         !isOperationLegal(ISD::MUL, MulVT))
5508       return SDValue();
5509   }
5510 
5511   // If the sdiv has an 'exact' bit we can use a simpler lowering.
5512   if (N->getFlags().hasExact())
5513     return BuildExactSDIV(*this, N, dl, DAG, Created);
5514 
5515   SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
5516 
5517   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5518     if (C->isZero())
5519       return false;
5520 
5521     const APInt &Divisor = C->getAPIntValue();
5522     SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor);
5523     int NumeratorFactor = 0;
5524     int ShiftMask = -1;
5525 
5526     if (Divisor.isOne() || Divisor.isAllOnes()) {
5527       // If d is +1/-1, we just multiply the numerator by +1/-1.
5528       NumeratorFactor = Divisor.getSExtValue();
5529       magics.Magic = 0;
5530       magics.ShiftAmount = 0;
5531       ShiftMask = 0;
5532     } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
5533       // If d > 0 and m < 0, add the numerator.
5534       NumeratorFactor = 1;
5535     } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
5536       // If d < 0 and m > 0, subtract the numerator.
5537       NumeratorFactor = -1;
5538     }
5539 
5540     MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT));
5541     Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
5542     Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
5543     ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
5544     return true;
5545   };
5546 
5547   SDValue N0 = N->getOperand(0);
5548   SDValue N1 = N->getOperand(1);
5549 
5550   // Collect the shifts / magic values from each element.
5551   if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
5552     return SDValue();
5553 
5554   SDValue MagicFactor, Factor, Shift, ShiftMask;
5555   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5556     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5557     Factor = DAG.getBuildVector(VT, dl, Factors);
5558     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5559     ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
5560   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5561     assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
5562            Shifts.size() == 1 && ShiftMasks.size() == 1 &&
5563            "Expected matchUnaryPredicate to return one element for scalable "
5564            "vectors");
5565     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5566     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5567     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5568     ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
5569   } else {
5570     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5571     MagicFactor = MagicFactors[0];
5572     Factor = Factors[0];
5573     Shift = Shifts[0];
5574     ShiftMask = ShiftMasks[0];
5575   }
5576 
5577   // Multiply the numerator (operand 0) by the magic value.
5578   // FIXME: We should support doing a MUL in a wider type.
5579   auto GetMULHS = [&](SDValue X, SDValue Y) {
5580     // If the type isn't legal, use a wider mul of the the type calculated
5581     // earlier.
5582     if (!isTypeLegal(VT)) {
5583       X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
5584       Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
5585       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5586       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5587                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5588       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5589     }
5590 
5591     if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization))
5592       return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
5593     if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) {
5594       SDValue LoHi =
5595           DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5596       return SDValue(LoHi.getNode(), 1);
5597     }
5598     return SDValue();
5599   };
5600 
5601   SDValue Q = GetMULHS(N0, MagicFactor);
5602   if (!Q)
5603     return SDValue();
5604 
5605   Created.push_back(Q.getNode());
5606 
5607   // (Optionally) Add/subtract the numerator using Factor.
5608   Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
5609   Created.push_back(Factor.getNode());
5610   Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
5611   Created.push_back(Q.getNode());
5612 
5613   // Shift right algebraic by shift value.
5614   Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
5615   Created.push_back(Q.getNode());
5616 
5617   // Extract the sign bit, mask it and add it to the quotient.
5618   SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
5619   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
5620   Created.push_back(T.getNode());
5621   T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
5622   Created.push_back(T.getNode());
5623   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
5624 }
5625 
5626 /// Given an ISD::UDIV node expressing a divide by constant,
5627 /// return a DAG expression to select that will generate the same value by
5628 /// multiplying by a magic number.
5629 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5630 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
5631                                   bool IsAfterLegalization,
5632                                   SmallVectorImpl<SDNode *> &Created) const {
5633   SDLoc dl(N);
5634   EVT VT = N->getValueType(0);
5635   EVT SVT = VT.getScalarType();
5636   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5637   EVT ShSVT = ShVT.getScalarType();
5638   unsigned EltBits = VT.getScalarSizeInBits();
5639   EVT MulVT;
5640 
5641   // Check to see if we can do this.
5642   // FIXME: We should be more aggressive here.
5643   if (!isTypeLegal(VT)) {
5644     // Limit this to simple scalars for now.
5645     if (VT.isVector() || !VT.isSimple())
5646       return SDValue();
5647 
5648     // If this type will be promoted to a large enough type with a legal
5649     // multiply operation, we can go ahead and do this transform.
5650     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5651       return SDValue();
5652 
5653     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5654     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5655         !isOperationLegal(ISD::MUL, MulVT))
5656       return SDValue();
5657   }
5658 
5659   bool UseNPQ = false;
5660   SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
5661 
5662   auto BuildUDIVPattern = [&](ConstantSDNode *C) {
5663     if (C->isZero())
5664       return false;
5665     // FIXME: We should use a narrower constant when the upper
5666     // bits are known to be zero.
5667     const APInt& Divisor = C->getAPIntValue();
5668     UnsignedDivisonByConstantInfo magics = UnsignedDivisonByConstantInfo::get(Divisor);
5669     unsigned PreShift = 0, PostShift = 0;
5670 
5671     // If the divisor is even, we can avoid using the expensive fixup by
5672     // shifting the divided value upfront.
5673     if (magics.IsAdd != 0 && !Divisor[0]) {
5674       PreShift = Divisor.countTrailingZeros();
5675       // Get magic number for the shifted divisor.
5676       magics = UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift);
5677       assert(magics.IsAdd == 0 && "Should use cheap fixup now");
5678     }
5679 
5680     APInt Magic = magics.Magic;
5681 
5682     unsigned SelNPQ;
5683     if (magics.IsAdd == 0 || Divisor.isOne()) {
5684       assert(magics.ShiftAmount < Divisor.getBitWidth() &&
5685              "We shouldn't generate an undefined shift!");
5686       PostShift = magics.ShiftAmount;
5687       SelNPQ = false;
5688     } else {
5689       PostShift = magics.ShiftAmount - 1;
5690       SelNPQ = true;
5691     }
5692 
5693     PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT));
5694     MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT));
5695     NPQFactors.push_back(
5696         DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
5697                                : APInt::getZero(EltBits),
5698                         dl, SVT));
5699     PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT));
5700     UseNPQ |= SelNPQ;
5701     return true;
5702   };
5703 
5704   SDValue N0 = N->getOperand(0);
5705   SDValue N1 = N->getOperand(1);
5706 
5707   // Collect the shifts/magic values from each element.
5708   if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
5709     return SDValue();
5710 
5711   SDValue PreShift, PostShift, MagicFactor, NPQFactor;
5712   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5713     PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
5714     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5715     NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
5716     PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
5717   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5718     assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
5719            NPQFactors.size() == 1 && PostShifts.size() == 1 &&
5720            "Expected matchUnaryPredicate to return one for scalable vectors");
5721     PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
5722     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5723     NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
5724     PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
5725   } else {
5726     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5727     PreShift = PreShifts[0];
5728     MagicFactor = MagicFactors[0];
5729     PostShift = PostShifts[0];
5730   }
5731 
5732   SDValue Q = N0;
5733   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
5734   Created.push_back(Q.getNode());
5735 
5736   // FIXME: We should support doing a MUL in a wider type.
5737   auto GetMULHU = [&](SDValue X, SDValue Y) {
5738     // If the type isn't legal, use a wider mul of the the type calculated
5739     // earlier.
5740     if (!isTypeLegal(VT)) {
5741       X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
5742       Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
5743       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5744       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5745                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5746       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5747     }
5748 
5749     if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization))
5750       return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
5751     if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) {
5752       SDValue LoHi =
5753           DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5754       return SDValue(LoHi.getNode(), 1);
5755     }
5756     return SDValue(); // No mulhu or equivalent
5757   };
5758 
5759   // Multiply the numerator (operand 0) by the magic value.
5760   Q = GetMULHU(Q, MagicFactor);
5761   if (!Q)
5762     return SDValue();
5763 
5764   Created.push_back(Q.getNode());
5765 
5766   if (UseNPQ) {
5767     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
5768     Created.push_back(NPQ.getNode());
5769 
5770     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
5771     // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
5772     if (VT.isVector())
5773       NPQ = GetMULHU(NPQ, NPQFactor);
5774     else
5775       NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
5776 
5777     Created.push_back(NPQ.getNode());
5778 
5779     Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
5780     Created.push_back(Q.getNode());
5781   }
5782 
5783   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
5784   Created.push_back(Q.getNode());
5785 
5786   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5787 
5788   SDValue One = DAG.getConstant(1, dl, VT);
5789   SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
5790   return DAG.getSelect(dl, VT, IsOne, N0, Q);
5791 }
5792 
5793 /// If all values in Values that *don't* match the predicate are same 'splat'
5794 /// value, then replace all values with that splat value.
5795 /// Else, if AlternativeReplacement was provided, then replace all values that
5796 /// do match predicate with AlternativeReplacement value.
5797 static void
5798 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values,
5799                           std::function<bool(SDValue)> Predicate,
5800                           SDValue AlternativeReplacement = SDValue()) {
5801   SDValue Replacement;
5802   // Is there a value for which the Predicate does *NOT* match? What is it?
5803   auto SplatValue = llvm::find_if_not(Values, Predicate);
5804   if (SplatValue != Values.end()) {
5805     // Does Values consist only of SplatValue's and values matching Predicate?
5806     if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
5807           return Value == *SplatValue || Predicate(Value);
5808         })) // Then we shall replace values matching predicate with SplatValue.
5809       Replacement = *SplatValue;
5810   }
5811   if (!Replacement) {
5812     // Oops, we did not find the "baseline" splat value.
5813     if (!AlternativeReplacement)
5814       return; // Nothing to do.
5815     // Let's replace with provided value then.
5816     Replacement = AlternativeReplacement;
5817   }
5818   std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
5819 }
5820 
5821 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
5822 /// where the divisor is constant and the comparison target is zero,
5823 /// return a DAG expression that will generate the same comparison result
5824 /// using only multiplications, additions and shifts/rotations.
5825 /// Ref: "Hacker's Delight" 10-17.
5826 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
5827                                         SDValue CompTargetNode,
5828                                         ISD::CondCode Cond,
5829                                         DAGCombinerInfo &DCI,
5830                                         const SDLoc &DL) const {
5831   SmallVector<SDNode *, 5> Built;
5832   if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
5833                                          DCI, DL, Built)) {
5834     for (SDNode *N : Built)
5835       DCI.AddToWorklist(N);
5836     return Folded;
5837   }
5838 
5839   return SDValue();
5840 }
5841 
5842 SDValue
5843 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
5844                                   SDValue CompTargetNode, ISD::CondCode Cond,
5845                                   DAGCombinerInfo &DCI, const SDLoc &DL,
5846                                   SmallVectorImpl<SDNode *> &Created) const {
5847   // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
5848   // - D must be constant, with D = D0 * 2^K where D0 is odd
5849   // - P is the multiplicative inverse of D0 modulo 2^W
5850   // - Q = floor(((2^W) - 1) / D)
5851   // where W is the width of the common type of N and D.
5852   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5853          "Only applicable for (in)equality comparisons.");
5854 
5855   SelectionDAG &DAG = DCI.DAG;
5856 
5857   EVT VT = REMNode.getValueType();
5858   EVT SVT = VT.getScalarType();
5859   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
5860   EVT ShSVT = ShVT.getScalarType();
5861 
5862   // If MUL is unavailable, we cannot proceed in any case.
5863   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
5864     return SDValue();
5865 
5866   bool ComparingWithAllZeros = true;
5867   bool AllComparisonsWithNonZerosAreTautological = true;
5868   bool HadTautologicalLanes = false;
5869   bool AllLanesAreTautological = true;
5870   bool HadEvenDivisor = false;
5871   bool AllDivisorsArePowerOfTwo = true;
5872   bool HadTautologicalInvertedLanes = false;
5873   SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts;
5874 
5875   auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
5876     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
5877     if (CDiv->isZero())
5878       return false;
5879 
5880     const APInt &D = CDiv->getAPIntValue();
5881     const APInt &Cmp = CCmp->getAPIntValue();
5882 
5883     ComparingWithAllZeros &= Cmp.isZero();
5884 
5885     // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
5886     // if C2 is not less than C1, the comparison is always false.
5887     // But we will only be able to produce the comparison that will give the
5888     // opposive tautological answer. So this lane would need to be fixed up.
5889     bool TautologicalInvertedLane = D.ule(Cmp);
5890     HadTautologicalInvertedLanes |= TautologicalInvertedLane;
5891 
5892     // If all lanes are tautological (either all divisors are ones, or divisor
5893     // is not greater than the constant we are comparing with),
5894     // we will prefer to avoid the fold.
5895     bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
5896     HadTautologicalLanes |= TautologicalLane;
5897     AllLanesAreTautological &= TautologicalLane;
5898 
5899     // If we are comparing with non-zero, we need'll need  to subtract said
5900     // comparison value from the LHS. But there is no point in doing that if
5901     // every lane where we are comparing with non-zero is tautological..
5902     if (!Cmp.isZero())
5903       AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
5904 
5905     // Decompose D into D0 * 2^K
5906     unsigned K = D.countTrailingZeros();
5907     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
5908     APInt D0 = D.lshr(K);
5909 
5910     // D is even if it has trailing zeros.
5911     HadEvenDivisor |= (K != 0);
5912     // D is a power-of-two if D0 is one.
5913     // If all divisors are power-of-two, we will prefer to avoid the fold.
5914     AllDivisorsArePowerOfTwo &= D0.isOne();
5915 
5916     // P = inv(D0, 2^W)
5917     // 2^W requires W + 1 bits, so we have to extend and then truncate.
5918     unsigned W = D.getBitWidth();
5919     APInt P = D0.zext(W + 1)
5920                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
5921                   .trunc(W);
5922     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
5923     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
5924 
5925     // Q = floor((2^W - 1) u/ D)
5926     // R = ((2^W - 1) u% D)
5927     APInt Q, R;
5928     APInt::udivrem(APInt::getAllOnes(W), D, Q, R);
5929 
5930     // If we are comparing with zero, then that comparison constant is okay,
5931     // else it may need to be one less than that.
5932     if (Cmp.ugt(R))
5933       Q -= 1;
5934 
5935     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
5936            "We are expecting that K is always less than all-ones for ShSVT");
5937 
5938     // If the lane is tautological the result can be constant-folded.
5939     if (TautologicalLane) {
5940       // Set P and K amount to a bogus values so we can try to splat them.
5941       P = 0;
5942       K = -1;
5943       // And ensure that comparison constant is tautological,
5944       // it will always compare true/false.
5945       Q = -1;
5946     }
5947 
5948     PAmts.push_back(DAG.getConstant(P, DL, SVT));
5949     KAmts.push_back(
5950         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
5951     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
5952     return true;
5953   };
5954 
5955   SDValue N = REMNode.getOperand(0);
5956   SDValue D = REMNode.getOperand(1);
5957 
5958   // Collect the values from each element.
5959   if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
5960     return SDValue();
5961 
5962   // If all lanes are tautological, the result can be constant-folded.
5963   if (AllLanesAreTautological)
5964     return SDValue();
5965 
5966   // If this is a urem by a powers-of-two, avoid the fold since it can be
5967   // best implemented as a bit test.
5968   if (AllDivisorsArePowerOfTwo)
5969     return SDValue();
5970 
5971   SDValue PVal, KVal, QVal;
5972   if (D.getOpcode() == ISD::BUILD_VECTOR) {
5973     if (HadTautologicalLanes) {
5974       // Try to turn PAmts into a splat, since we don't care about the values
5975       // that are currently '0'. If we can't, just keep '0'`s.
5976       turnVectorIntoSplatVector(PAmts, isNullConstant);
5977       // Try to turn KAmts into a splat, since we don't care about the values
5978       // that are currently '-1'. If we can't, change them to '0'`s.
5979       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
5980                                 DAG.getConstant(0, DL, ShSVT));
5981     }
5982 
5983     PVal = DAG.getBuildVector(VT, DL, PAmts);
5984     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
5985     QVal = DAG.getBuildVector(VT, DL, QAmts);
5986   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
5987     assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
5988            "Expected matchBinaryPredicate to return one element for "
5989            "SPLAT_VECTORs");
5990     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
5991     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
5992     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
5993   } else {
5994     PVal = PAmts[0];
5995     KVal = KAmts[0];
5996     QVal = QAmts[0];
5997   }
5998 
5999   if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
6000     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
6001       return SDValue(); // FIXME: Could/should use `ISD::ADD`?
6002     assert(CompTargetNode.getValueType() == N.getValueType() &&
6003            "Expecting that the types on LHS and RHS of comparisons match.");
6004     N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
6005   }
6006 
6007   // (mul N, P)
6008   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6009   Created.push_back(Op0.getNode());
6010 
6011   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6012   // divisors as a performance improvement, since rotating by 0 is a no-op.
6013   if (HadEvenDivisor) {
6014     // We need ROTR to do this.
6015     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6016       return SDValue();
6017     // UREM: (rotr (mul N, P), K)
6018     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6019     Created.push_back(Op0.getNode());
6020   }
6021 
6022   // UREM: (setule/setugt (rotr (mul N, P), K), Q)
6023   SDValue NewCC =
6024       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6025                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6026   if (!HadTautologicalInvertedLanes)
6027     return NewCC;
6028 
6029   // If any lanes previously compared always-false, the NewCC will give
6030   // always-true result for them, so we need to fixup those lanes.
6031   // Or the other way around for inequality predicate.
6032   assert(VT.isVector() && "Can/should only get here for vectors.");
6033   Created.push_back(NewCC.getNode());
6034 
6035   // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
6036   // if C2 is not less than C1, the comparison is always false.
6037   // But we have produced the comparison that will give the
6038   // opposive tautological answer. So these lanes would need to be fixed up.
6039   SDValue TautologicalInvertedChannels =
6040       DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
6041   Created.push_back(TautologicalInvertedChannels.getNode());
6042 
6043   // NOTE: we avoid letting illegal types through even if we're before legalize
6044   // ops – legalization has a hard time producing good code for this.
6045   if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
6046     // If we have a vector select, let's replace the comparison results in the
6047     // affected lanes with the correct tautological result.
6048     SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
6049                                               DL, SETCCVT, SETCCVT);
6050     return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
6051                        Replacement, NewCC);
6052   }
6053 
6054   // Else, we can just invert the comparison result in the appropriate lanes.
6055   //
6056   // NOTE: see the note above VSELECT above.
6057   if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
6058     return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
6059                        TautologicalInvertedChannels);
6060 
6061   return SDValue(); // Don't know how to lower.
6062 }
6063 
6064 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
6065 /// where the divisor is constant and the comparison target is zero,
6066 /// return a DAG expression that will generate the same comparison result
6067 /// using only multiplications, additions and shifts/rotations.
6068 /// Ref: "Hacker's Delight" 10-17.
6069 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
6070                                         SDValue CompTargetNode,
6071                                         ISD::CondCode Cond,
6072                                         DAGCombinerInfo &DCI,
6073                                         const SDLoc &DL) const {
6074   SmallVector<SDNode *, 7> Built;
6075   if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
6076                                          DCI, DL, Built)) {
6077     assert(Built.size() <= 7 && "Max size prediction failed.");
6078     for (SDNode *N : Built)
6079       DCI.AddToWorklist(N);
6080     return Folded;
6081   }
6082 
6083   return SDValue();
6084 }
6085 
6086 SDValue
6087 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
6088                                   SDValue CompTargetNode, ISD::CondCode Cond,
6089                                   DAGCombinerInfo &DCI, const SDLoc &DL,
6090                                   SmallVectorImpl<SDNode *> &Created) const {
6091   // Fold:
6092   //   (seteq/ne (srem N, D), 0)
6093   // To:
6094   //   (setule/ugt (rotr (add (mul N, P), A), K), Q)
6095   //
6096   // - D must be constant, with D = D0 * 2^K where D0 is odd
6097   // - P is the multiplicative inverse of D0 modulo 2^W
6098   // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
6099   // - Q = floor((2 * A) / (2^K))
6100   // where W is the width of the common type of N and D.
6101   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6102          "Only applicable for (in)equality comparisons.");
6103 
6104   SelectionDAG &DAG = DCI.DAG;
6105 
6106   EVT VT = REMNode.getValueType();
6107   EVT SVT = VT.getScalarType();
6108   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
6109   EVT ShSVT = ShVT.getScalarType();
6110 
6111   // If we are after ops legalization, and MUL is unavailable, we can not
6112   // proceed.
6113   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
6114     return SDValue();
6115 
6116   // TODO: Could support comparing with non-zero too.
6117   ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
6118   if (!CompTarget || !CompTarget->isZero())
6119     return SDValue();
6120 
6121   bool HadIntMinDivisor = false;
6122   bool HadOneDivisor = false;
6123   bool AllDivisorsAreOnes = true;
6124   bool HadEvenDivisor = false;
6125   bool NeedToApplyOffset = false;
6126   bool AllDivisorsArePowerOfTwo = true;
6127   SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
6128 
6129   auto BuildSREMPattern = [&](ConstantSDNode *C) {
6130     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
6131     if (C->isZero())
6132       return false;
6133 
6134     // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
6135 
6136     // WARNING: this fold is only valid for positive divisors!
6137     APInt D = C->getAPIntValue();
6138     if (D.isNegative())
6139       D.negate(); //  `rem %X, -C` is equivalent to `rem %X, C`
6140 
6141     HadIntMinDivisor |= D.isMinSignedValue();
6142 
6143     // If all divisors are ones, we will prefer to avoid the fold.
6144     HadOneDivisor |= D.isOne();
6145     AllDivisorsAreOnes &= D.isOne();
6146 
6147     // Decompose D into D0 * 2^K
6148     unsigned K = D.countTrailingZeros();
6149     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
6150     APInt D0 = D.lshr(K);
6151 
6152     if (!D.isMinSignedValue()) {
6153       // D is even if it has trailing zeros; unless it's INT_MIN, in which case
6154       // we don't care about this lane in this fold, we'll special-handle it.
6155       HadEvenDivisor |= (K != 0);
6156     }
6157 
6158     // D is a power-of-two if D0 is one. This includes INT_MIN.
6159     // If all divisors are power-of-two, we will prefer to avoid the fold.
6160     AllDivisorsArePowerOfTwo &= D0.isOne();
6161 
6162     // P = inv(D0, 2^W)
6163     // 2^W requires W + 1 bits, so we have to extend and then truncate.
6164     unsigned W = D.getBitWidth();
6165     APInt P = D0.zext(W + 1)
6166                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
6167                   .trunc(W);
6168     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
6169     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
6170 
6171     // A = floor((2^(W - 1) - 1) / D0) & -2^K
6172     APInt A = APInt::getSignedMaxValue(W).udiv(D0);
6173     A.clearLowBits(K);
6174 
6175     if (!D.isMinSignedValue()) {
6176       // If divisor INT_MIN, then we don't care about this lane in this fold,
6177       // we'll special-handle it.
6178       NeedToApplyOffset |= A != 0;
6179     }
6180 
6181     // Q = floor((2 * A) / (2^K))
6182     APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
6183 
6184     assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) &&
6185            "We are expecting that A is always less than all-ones for SVT");
6186     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
6187            "We are expecting that K is always less than all-ones for ShSVT");
6188 
6189     // If the divisor is 1 the result can be constant-folded. Likewise, we
6190     // don't care about INT_MIN lanes, those can be set to undef if appropriate.
6191     if (D.isOne()) {
6192       // Set P, A and K to a bogus values so we can try to splat them.
6193       P = 0;
6194       A = -1;
6195       K = -1;
6196 
6197       // x ?% 1 == 0  <-->  true  <-->  x u<= -1
6198       Q = -1;
6199     }
6200 
6201     PAmts.push_back(DAG.getConstant(P, DL, SVT));
6202     AAmts.push_back(DAG.getConstant(A, DL, SVT));
6203     KAmts.push_back(
6204         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
6205     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
6206     return true;
6207   };
6208 
6209   SDValue N = REMNode.getOperand(0);
6210   SDValue D = REMNode.getOperand(1);
6211 
6212   // Collect the values from each element.
6213   if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
6214     return SDValue();
6215 
6216   // If this is a srem by a one, avoid the fold since it can be constant-folded.
6217   if (AllDivisorsAreOnes)
6218     return SDValue();
6219 
6220   // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
6221   // since it can be best implemented as a bit test.
6222   if (AllDivisorsArePowerOfTwo)
6223     return SDValue();
6224 
6225   SDValue PVal, AVal, KVal, QVal;
6226   if (D.getOpcode() == ISD::BUILD_VECTOR) {
6227     if (HadOneDivisor) {
6228       // Try to turn PAmts into a splat, since we don't care about the values
6229       // that are currently '0'. If we can't, just keep '0'`s.
6230       turnVectorIntoSplatVector(PAmts, isNullConstant);
6231       // Try to turn AAmts into a splat, since we don't care about the
6232       // values that are currently '-1'. If we can't, change them to '0'`s.
6233       turnVectorIntoSplatVector(AAmts, isAllOnesConstant,
6234                                 DAG.getConstant(0, DL, SVT));
6235       // Try to turn KAmts into a splat, since we don't care about the values
6236       // that are currently '-1'. If we can't, change them to '0'`s.
6237       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
6238                                 DAG.getConstant(0, DL, ShSVT));
6239     }
6240 
6241     PVal = DAG.getBuildVector(VT, DL, PAmts);
6242     AVal = DAG.getBuildVector(VT, DL, AAmts);
6243     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
6244     QVal = DAG.getBuildVector(VT, DL, QAmts);
6245   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
6246     assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
6247            QAmts.size() == 1 &&
6248            "Expected matchUnaryPredicate to return one element for scalable "
6249            "vectors");
6250     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
6251     AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
6252     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6253     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6254   } else {
6255     assert(isa<ConstantSDNode>(D) && "Expected a constant");
6256     PVal = PAmts[0];
6257     AVal = AAmts[0];
6258     KVal = KAmts[0];
6259     QVal = QAmts[0];
6260   }
6261 
6262   // (mul N, P)
6263   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6264   Created.push_back(Op0.getNode());
6265 
6266   if (NeedToApplyOffset) {
6267     // We need ADD to do this.
6268     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
6269       return SDValue();
6270 
6271     // (add (mul N, P), A)
6272     Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
6273     Created.push_back(Op0.getNode());
6274   }
6275 
6276   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6277   // divisors as a performance improvement, since rotating by 0 is a no-op.
6278   if (HadEvenDivisor) {
6279     // We need ROTR to do this.
6280     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6281       return SDValue();
6282     // SREM: (rotr (add (mul N, P), A), K)
6283     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6284     Created.push_back(Op0.getNode());
6285   }
6286 
6287   // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
6288   SDValue Fold =
6289       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6290                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6291 
6292   // If we didn't have lanes with INT_MIN divisor, then we're done.
6293   if (!HadIntMinDivisor)
6294     return Fold;
6295 
6296   // That fold is only valid for positive divisors. Which effectively means,
6297   // it is invalid for INT_MIN divisors. So if we have such a lane,
6298   // we must fix-up results for said lanes.
6299   assert(VT.isVector() && "Can/should only get here for vectors.");
6300 
6301   // NOTE: we avoid letting illegal types through even if we're before legalize
6302   // ops – legalization has a hard time producing good code for the code that
6303   // follows.
6304   if (!isOperationLegalOrCustom(ISD::SETEQ, VT) ||
6305       !isOperationLegalOrCustom(ISD::AND, VT) ||
6306       !isOperationLegalOrCustom(Cond, VT) ||
6307       !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT))
6308     return SDValue();
6309 
6310   Created.push_back(Fold.getNode());
6311 
6312   SDValue IntMin = DAG.getConstant(
6313       APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT);
6314   SDValue IntMax = DAG.getConstant(
6315       APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT);
6316   SDValue Zero =
6317       DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT);
6318 
6319   // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded.
6320   SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ);
6321   Created.push_back(DivisorIsIntMin.getNode());
6322 
6323   // (N s% INT_MIN) ==/!= 0  <-->  (N & INT_MAX) ==/!= 0
6324   SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax);
6325   Created.push_back(Masked.getNode());
6326   SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond);
6327   Created.push_back(MaskedIsZero.getNode());
6328 
6329   // To produce final result we need to blend 2 vectors: 'SetCC' and
6330   // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick
6331   // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is
6332   // constant-folded, select can get lowered to a shuffle with constant mask.
6333   SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin,
6334                                 MaskedIsZero, Fold);
6335 
6336   return Blended;
6337 }
6338 
6339 bool TargetLowering::
6340 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
6341   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
6342     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
6343                                 "be a constant integer");
6344     return true;
6345   }
6346 
6347   return false;
6348 }
6349 
6350 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
6351                                          const DenormalMode &Mode) const {
6352   SDLoc DL(Op);
6353   EVT VT = Op.getValueType();
6354   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6355   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6356   // Testing it with denormal inputs to avoid wrong estimate.
6357   if (Mode.Input == DenormalMode::IEEE) {
6358     // This is specifically a check for the handling of denormal inputs,
6359     // not the result.
6360 
6361     // Test = fabs(X) < SmallestNormal
6362     const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
6363     APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
6364     SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
6365     SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
6366     return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
6367   }
6368   // Test = X == 0.0
6369   return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
6370 }
6371 
6372 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
6373                                              bool LegalOps, bool OptForSize,
6374                                              NegatibleCost &Cost,
6375                                              unsigned Depth) const {
6376   // fneg is removable even if it has multiple uses.
6377   if (Op.getOpcode() == ISD::FNEG) {
6378     Cost = NegatibleCost::Cheaper;
6379     return Op.getOperand(0);
6380   }
6381 
6382   // Don't recurse exponentially.
6383   if (Depth > SelectionDAG::MaxRecursionDepth)
6384     return SDValue();
6385 
6386   // Pre-increment recursion depth for use in recursive calls.
6387   ++Depth;
6388   const SDNodeFlags Flags = Op->getFlags();
6389   const TargetOptions &Options = DAG.getTarget().Options;
6390   EVT VT = Op.getValueType();
6391   unsigned Opcode = Op.getOpcode();
6392 
6393   // Don't allow anything with multiple uses unless we know it is free.
6394   if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
6395     bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
6396                         isFPExtFree(VT, Op.getOperand(0).getValueType());
6397     if (!IsFreeExtend)
6398       return SDValue();
6399   }
6400 
6401   auto RemoveDeadNode = [&](SDValue N) {
6402     if (N && N.getNode()->use_empty())
6403       DAG.RemoveDeadNode(N.getNode());
6404   };
6405 
6406   SDLoc DL(Op);
6407 
6408   // Because getNegatedExpression can delete nodes we need a handle to keep
6409   // temporary nodes alive in case the recursion manages to create an identical
6410   // node.
6411   std::list<HandleSDNode> Handles;
6412 
6413   switch (Opcode) {
6414   case ISD::ConstantFP: {
6415     // Don't invert constant FP values after legalization unless the target says
6416     // the negated constant is legal.
6417     bool IsOpLegal =
6418         isOperationLegal(ISD::ConstantFP, VT) ||
6419         isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
6420                      OptForSize);
6421 
6422     if (LegalOps && !IsOpLegal)
6423       break;
6424 
6425     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
6426     V.changeSign();
6427     SDValue CFP = DAG.getConstantFP(V, DL, VT);
6428 
6429     // If we already have the use of the negated floating constant, it is free
6430     // to negate it even it has multiple uses.
6431     if (!Op.hasOneUse() && CFP.use_empty())
6432       break;
6433     Cost = NegatibleCost::Neutral;
6434     return CFP;
6435   }
6436   case ISD::BUILD_VECTOR: {
6437     // Only permit BUILD_VECTOR of constants.
6438     if (llvm::any_of(Op->op_values(), [&](SDValue N) {
6439           return !N.isUndef() && !isa<ConstantFPSDNode>(N);
6440         }))
6441       break;
6442 
6443     bool IsOpLegal =
6444         (isOperationLegal(ISD::ConstantFP, VT) &&
6445          isOperationLegal(ISD::BUILD_VECTOR, VT)) ||
6446         llvm::all_of(Op->op_values(), [&](SDValue N) {
6447           return N.isUndef() ||
6448                  isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
6449                               OptForSize);
6450         });
6451 
6452     if (LegalOps && !IsOpLegal)
6453       break;
6454 
6455     SmallVector<SDValue, 4> Ops;
6456     for (SDValue C : Op->op_values()) {
6457       if (C.isUndef()) {
6458         Ops.push_back(C);
6459         continue;
6460       }
6461       APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
6462       V.changeSign();
6463       Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
6464     }
6465     Cost = NegatibleCost::Neutral;
6466     return DAG.getBuildVector(VT, DL, Ops);
6467   }
6468   case ISD::FADD: {
6469     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6470       break;
6471 
6472     // After operation legalization, it might not be legal to create new FSUBs.
6473     if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
6474       break;
6475     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6476 
6477     // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
6478     NegatibleCost CostX = NegatibleCost::Expensive;
6479     SDValue NegX =
6480         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6481     // Prevent this node from being deleted by the next call.
6482     if (NegX)
6483       Handles.emplace_back(NegX);
6484 
6485     // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
6486     NegatibleCost CostY = NegatibleCost::Expensive;
6487     SDValue NegY =
6488         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6489 
6490     // We're done with the handles.
6491     Handles.clear();
6492 
6493     // Negate the X if its cost is less or equal than Y.
6494     if (NegX && (CostX <= CostY)) {
6495       Cost = CostX;
6496       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
6497       if (NegY != N)
6498         RemoveDeadNode(NegY);
6499       return N;
6500     }
6501 
6502     // Negate the Y if it is not expensive.
6503     if (NegY) {
6504       Cost = CostY;
6505       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
6506       if (NegX != N)
6507         RemoveDeadNode(NegX);
6508       return N;
6509     }
6510     break;
6511   }
6512   case ISD::FSUB: {
6513     // We can't turn -(A-B) into B-A when we honor signed zeros.
6514     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6515       break;
6516 
6517     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6518     // fold (fneg (fsub 0, Y)) -> Y
6519     if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
6520       if (C->isZero()) {
6521         Cost = NegatibleCost::Cheaper;
6522         return Y;
6523       }
6524 
6525     // fold (fneg (fsub X, Y)) -> (fsub Y, X)
6526     Cost = NegatibleCost::Neutral;
6527     return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
6528   }
6529   case ISD::FMUL:
6530   case ISD::FDIV: {
6531     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6532 
6533     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
6534     NegatibleCost CostX = NegatibleCost::Expensive;
6535     SDValue NegX =
6536         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6537     // Prevent this node from being deleted by the next call.
6538     if (NegX)
6539       Handles.emplace_back(NegX);
6540 
6541     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
6542     NegatibleCost CostY = NegatibleCost::Expensive;
6543     SDValue NegY =
6544         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6545 
6546     // We're done with the handles.
6547     Handles.clear();
6548 
6549     // Negate the X if its cost is less or equal than Y.
6550     if (NegX && (CostX <= CostY)) {
6551       Cost = CostX;
6552       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
6553       if (NegY != N)
6554         RemoveDeadNode(NegY);
6555       return N;
6556     }
6557 
6558     // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
6559     if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
6560       if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
6561         break;
6562 
6563     // Negate the Y if it is not expensive.
6564     if (NegY) {
6565       Cost = CostY;
6566       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
6567       if (NegX != N)
6568         RemoveDeadNode(NegX);
6569       return N;
6570     }
6571     break;
6572   }
6573   case ISD::FMA:
6574   case ISD::FMAD: {
6575     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6576       break;
6577 
6578     SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
6579     NegatibleCost CostZ = NegatibleCost::Expensive;
6580     SDValue NegZ =
6581         getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
6582     // Give up if fail to negate the Z.
6583     if (!NegZ)
6584       break;
6585 
6586     // Prevent this node from being deleted by the next two calls.
6587     Handles.emplace_back(NegZ);
6588 
6589     // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
6590     NegatibleCost CostX = NegatibleCost::Expensive;
6591     SDValue NegX =
6592         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6593     // Prevent this node from being deleted by the next call.
6594     if (NegX)
6595       Handles.emplace_back(NegX);
6596 
6597     // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
6598     NegatibleCost CostY = NegatibleCost::Expensive;
6599     SDValue NegY =
6600         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6601 
6602     // We're done with the handles.
6603     Handles.clear();
6604 
6605     // Negate the X if its cost is less or equal than Y.
6606     if (NegX && (CostX <= CostY)) {
6607       Cost = std::min(CostX, CostZ);
6608       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
6609       if (NegY != N)
6610         RemoveDeadNode(NegY);
6611       return N;
6612     }
6613 
6614     // Negate the Y if it is not expensive.
6615     if (NegY) {
6616       Cost = std::min(CostY, CostZ);
6617       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
6618       if (NegX != N)
6619         RemoveDeadNode(NegX);
6620       return N;
6621     }
6622     break;
6623   }
6624 
6625   case ISD::FP_EXTEND:
6626   case ISD::FSIN:
6627     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6628                                             OptForSize, Cost, Depth))
6629       return DAG.getNode(Opcode, DL, VT, NegV);
6630     break;
6631   case ISD::FP_ROUND:
6632     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6633                                             OptForSize, Cost, Depth))
6634       return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
6635     break;
6636   }
6637 
6638   return SDValue();
6639 }
6640 
6641 //===----------------------------------------------------------------------===//
6642 // Legalization Utilities
6643 //===----------------------------------------------------------------------===//
6644 
6645 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
6646                                     SDValue LHS, SDValue RHS,
6647                                     SmallVectorImpl<SDValue> &Result,
6648                                     EVT HiLoVT, SelectionDAG &DAG,
6649                                     MulExpansionKind Kind, SDValue LL,
6650                                     SDValue LH, SDValue RL, SDValue RH) const {
6651   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
6652          Opcode == ISD::SMUL_LOHI);
6653 
6654   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
6655                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
6656   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
6657                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
6658   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6659                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
6660   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6661                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
6662 
6663   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
6664     return false;
6665 
6666   unsigned OuterBitSize = VT.getScalarSizeInBits();
6667   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
6668 
6669   // LL, LH, RL, and RH must be either all NULL or all set to a value.
6670   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
6671          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
6672 
6673   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
6674   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
6675                           bool Signed) -> bool {
6676     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
6677       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
6678       Hi = SDValue(Lo.getNode(), 1);
6679       return true;
6680     }
6681     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
6682       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
6683       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
6684       return true;
6685     }
6686     return false;
6687   };
6688 
6689   SDValue Lo, Hi;
6690 
6691   if (!LL.getNode() && !RL.getNode() &&
6692       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6693     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
6694     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
6695   }
6696 
6697   if (!LL.getNode())
6698     return false;
6699 
6700   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
6701   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
6702       DAG.MaskedValueIsZero(RHS, HighMask)) {
6703     // The inputs are both zero-extended.
6704     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
6705       Result.push_back(Lo);
6706       Result.push_back(Hi);
6707       if (Opcode != ISD::MUL) {
6708         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6709         Result.push_back(Zero);
6710         Result.push_back(Zero);
6711       }
6712       return true;
6713     }
6714   }
6715 
6716   if (!VT.isVector() && Opcode == ISD::MUL &&
6717       DAG.ComputeNumSignBits(LHS) > InnerBitSize &&
6718       DAG.ComputeNumSignBits(RHS) > InnerBitSize) {
6719     // The input values are both sign-extended.
6720     // TODO non-MUL case?
6721     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
6722       Result.push_back(Lo);
6723       Result.push_back(Hi);
6724       return true;
6725     }
6726   }
6727 
6728   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
6729   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
6730   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
6731 
6732   if (!LH.getNode() && !RH.getNode() &&
6733       isOperationLegalOrCustom(ISD::SRL, VT) &&
6734       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6735     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
6736     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
6737     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
6738     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
6739   }
6740 
6741   if (!LH.getNode())
6742     return false;
6743 
6744   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
6745     return false;
6746 
6747   Result.push_back(Lo);
6748 
6749   if (Opcode == ISD::MUL) {
6750     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
6751     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
6752     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
6753     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
6754     Result.push_back(Hi);
6755     return true;
6756   }
6757 
6758   // Compute the full width result.
6759   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
6760     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
6761     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6762     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
6763     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
6764   };
6765 
6766   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6767   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
6768     return false;
6769 
6770   // This is effectively the add part of a multiply-add of half-sized operands,
6771   // so it cannot overflow.
6772   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6773 
6774   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
6775     return false;
6776 
6777   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6778   EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6779 
6780   bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
6781                   isOperationLegalOrCustom(ISD::ADDE, VT));
6782   if (UseGlue)
6783     Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
6784                        Merge(Lo, Hi));
6785   else
6786     Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next,
6787                        Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
6788 
6789   SDValue Carry = Next.getValue(1);
6790   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6791   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
6792 
6793   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
6794     return false;
6795 
6796   if (UseGlue)
6797     Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
6798                      Carry);
6799   else
6800     Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
6801                      Zero, Carry);
6802 
6803   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6804 
6805   if (Opcode == ISD::SMUL_LOHI) {
6806     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6807                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
6808     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
6809 
6810     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6811                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
6812     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
6813   }
6814 
6815   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6816   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
6817   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6818   return true;
6819 }
6820 
6821 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
6822                                SelectionDAG &DAG, MulExpansionKind Kind,
6823                                SDValue LL, SDValue LH, SDValue RL,
6824                                SDValue RH) const {
6825   SmallVector<SDValue, 2> Result;
6826   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
6827                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
6828                            DAG, Kind, LL, LH, RL, RH);
6829   if (Ok) {
6830     assert(Result.size() == 2);
6831     Lo = Result[0];
6832     Hi = Result[1];
6833   }
6834   return Ok;
6835 }
6836 
6837 // Check that (every element of) Z is undef or not an exact multiple of BW.
6838 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
6839   return ISD::matchUnaryPredicate(
6840       Z,
6841       [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
6842       true);
6843 }
6844 
6845 SDValue TargetLowering::expandFunnelShift(SDNode *Node,
6846                                           SelectionDAG &DAG) const {
6847   EVT VT = Node->getValueType(0);
6848 
6849   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
6850                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
6851                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
6852                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
6853     return SDValue();
6854 
6855   SDValue X = Node->getOperand(0);
6856   SDValue Y = Node->getOperand(1);
6857   SDValue Z = Node->getOperand(2);
6858 
6859   unsigned BW = VT.getScalarSizeInBits();
6860   bool IsFSHL = Node->getOpcode() == ISD::FSHL;
6861   SDLoc DL(SDValue(Node, 0));
6862 
6863   EVT ShVT = Z.getValueType();
6864 
6865   // If a funnel shift in the other direction is more supported, use it.
6866   unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
6867   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
6868       isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
6869     if (isNonZeroModBitWidthOrUndef(Z, BW)) {
6870       // fshl X, Y, Z -> fshr X, Y, -Z
6871       // fshr X, Y, Z -> fshl X, Y, -Z
6872       SDValue Zero = DAG.getConstant(0, DL, ShVT);
6873       Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z);
6874     } else {
6875       // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
6876       // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
6877       SDValue One = DAG.getConstant(1, DL, ShVT);
6878       if (IsFSHL) {
6879         Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
6880         X = DAG.getNode(ISD::SRL, DL, VT, X, One);
6881       } else {
6882         X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
6883         Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
6884       }
6885       Z = DAG.getNOT(DL, Z, ShVT);
6886     }
6887     return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
6888   }
6889 
6890   SDValue ShX, ShY;
6891   SDValue ShAmt, InvShAmt;
6892   if (isNonZeroModBitWidthOrUndef(Z, BW)) {
6893     // fshl: X << C | Y >> (BW - C)
6894     // fshr: X << (BW - C) | Y >> C
6895     // where C = Z % BW is not zero
6896     SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
6897     ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
6898     InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
6899     ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
6900     ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6901   } else {
6902     // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
6903     // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
6904     SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
6905     if (isPowerOf2_32(BW)) {
6906       // Z % BW -> Z & (BW - 1)
6907       ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
6908       // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
6909       InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
6910     } else {
6911       SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
6912       ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
6913       InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
6914     }
6915 
6916     SDValue One = DAG.getConstant(1, DL, ShVT);
6917     if (IsFSHL) {
6918       ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
6919       SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
6920       ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
6921     } else {
6922       SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
6923       ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
6924       ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
6925     }
6926   }
6927   return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
6928 }
6929 
6930 // TODO: Merge with expandFunnelShift.
6931 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps,
6932                                   SelectionDAG &DAG) const {
6933   EVT VT = Node->getValueType(0);
6934   unsigned EltSizeInBits = VT.getScalarSizeInBits();
6935   bool IsLeft = Node->getOpcode() == ISD::ROTL;
6936   SDValue Op0 = Node->getOperand(0);
6937   SDValue Op1 = Node->getOperand(1);
6938   SDLoc DL(SDValue(Node, 0));
6939 
6940   EVT ShVT = Op1.getValueType();
6941   SDValue Zero = DAG.getConstant(0, DL, ShVT);
6942 
6943   // If a rotate in the other direction is more supported, use it.
6944   unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
6945   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
6946       isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
6947     SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
6948     return DAG.getNode(RevRot, DL, VT, Op0, Sub);
6949   }
6950 
6951   if (!AllowVectorOps && VT.isVector() &&
6952       (!isOperationLegalOrCustom(ISD::SHL, VT) ||
6953        !isOperationLegalOrCustom(ISD::SRL, VT) ||
6954        !isOperationLegalOrCustom(ISD::SUB, VT) ||
6955        !isOperationLegalOrCustomOrPromote(ISD::OR, VT) ||
6956        !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
6957     return SDValue();
6958 
6959   unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
6960   unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
6961   SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
6962   SDValue ShVal;
6963   SDValue HsVal;
6964   if (isPowerOf2_32(EltSizeInBits)) {
6965     // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
6966     // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
6967     SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
6968     SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
6969     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
6970     SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
6971     HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
6972   } else {
6973     // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
6974     // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
6975     SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
6976     SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
6977     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
6978     SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
6979     SDValue One = DAG.getConstant(1, DL, ShVT);
6980     HsVal =
6981         DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
6982   }
6983   return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
6984 }
6985 
6986 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi,
6987                                       SelectionDAG &DAG) const {
6988   assert(Node->getNumOperands() == 3 && "Not a double-shift!");
6989   EVT VT = Node->getValueType(0);
6990   unsigned VTBits = VT.getScalarSizeInBits();
6991   assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
6992 
6993   bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
6994   bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
6995   SDValue ShOpLo = Node->getOperand(0);
6996   SDValue ShOpHi = Node->getOperand(1);
6997   SDValue ShAmt = Node->getOperand(2);
6998   EVT ShAmtVT = ShAmt.getValueType();
6999   EVT ShAmtCCVT =
7000       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
7001   SDLoc dl(Node);
7002 
7003   // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
7004   // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
7005   // away during isel.
7006   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
7007                                   DAG.getConstant(VTBits - 1, dl, ShAmtVT));
7008   SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7009                                      DAG.getConstant(VTBits - 1, dl, ShAmtVT))
7010                        : DAG.getConstant(0, dl, VT);
7011 
7012   SDValue Tmp2, Tmp3;
7013   if (IsSHL) {
7014     Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
7015     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
7016   } else {
7017     Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
7018     Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
7019   }
7020 
7021   // If the shift amount is larger or equal than the width of a part we don't
7022   // use the result from the FSHL/FSHR. Insert a test and select the appropriate
7023   // values for large shift amounts.
7024   SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
7025                                 DAG.getConstant(VTBits, dl, ShAmtVT));
7026   SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
7027                               DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
7028 
7029   if (IsSHL) {
7030     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
7031     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
7032   } else {
7033     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
7034     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
7035   }
7036 }
7037 
7038 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
7039                                       SelectionDAG &DAG) const {
7040   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
7041   SDValue Src = Node->getOperand(OpNo);
7042   EVT SrcVT = Src.getValueType();
7043   EVT DstVT = Node->getValueType(0);
7044   SDLoc dl(SDValue(Node, 0));
7045 
7046   // FIXME: Only f32 to i64 conversions are supported.
7047   if (SrcVT != MVT::f32 || DstVT != MVT::i64)
7048     return false;
7049 
7050   if (Node->isStrictFPOpcode())
7051     // When a NaN is converted to an integer a trap is allowed. We can't
7052     // use this expansion here because it would eliminate that trap. Other
7053     // traps are also allowed and cannot be eliminated. See
7054     // IEEE 754-2008 sec 5.8.
7055     return false;
7056 
7057   // Expand f32 -> i64 conversion
7058   // This algorithm comes from compiler-rt's implementation of fixsfdi:
7059   // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
7060   unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
7061   EVT IntVT = SrcVT.changeTypeToInteger();
7062   EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
7063 
7064   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
7065   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
7066   SDValue Bias = DAG.getConstant(127, dl, IntVT);
7067   SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
7068   SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
7069   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
7070 
7071   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
7072 
7073   SDValue ExponentBits = DAG.getNode(
7074       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
7075       DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
7076   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
7077 
7078   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
7079                              DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
7080                              DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
7081   Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
7082 
7083   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
7084                           DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
7085                           DAG.getConstant(0x00800000, dl, IntVT));
7086 
7087   R = DAG.getZExtOrTrunc(R, dl, DstVT);
7088 
7089   R = DAG.getSelectCC(
7090       dl, Exponent, ExponentLoBit,
7091       DAG.getNode(ISD::SHL, dl, DstVT, R,
7092                   DAG.getZExtOrTrunc(
7093                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
7094                       dl, IntShVT)),
7095       DAG.getNode(ISD::SRL, dl, DstVT, R,
7096                   DAG.getZExtOrTrunc(
7097                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
7098                       dl, IntShVT)),
7099       ISD::SETGT);
7100 
7101   SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
7102                             DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
7103 
7104   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
7105                            DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
7106   return true;
7107 }
7108 
7109 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result,
7110                                       SDValue &Chain,
7111                                       SelectionDAG &DAG) const {
7112   SDLoc dl(SDValue(Node, 0));
7113   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
7114   SDValue Src = Node->getOperand(OpNo);
7115 
7116   EVT SrcVT = Src.getValueType();
7117   EVT DstVT = Node->getValueType(0);
7118   EVT SetCCVT =
7119       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
7120   EVT DstSetCCVT =
7121       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
7122 
7123   // Only expand vector types if we have the appropriate vector bit operations.
7124   unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
7125                                                    ISD::FP_TO_SINT;
7126   if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
7127                            !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT)))
7128     return false;
7129 
7130   // If the maximum float value is smaller then the signed integer range,
7131   // the destination signmask can't be represented by the float, so we can
7132   // just use FP_TO_SINT directly.
7133   const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT);
7134   APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
7135   APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
7136   if (APFloat::opOverflow &
7137       APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
7138     if (Node->isStrictFPOpcode()) {
7139       Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
7140                            { Node->getOperand(0), Src });
7141       Chain = Result.getValue(1);
7142     } else
7143       Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
7144     return true;
7145   }
7146 
7147   // Don't expand it if there isn't cheap fsub instruction.
7148   if (!isOperationLegalOrCustom(
7149           Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
7150     return false;
7151 
7152   SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
7153   SDValue Sel;
7154 
7155   if (Node->isStrictFPOpcode()) {
7156     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
7157                        Node->getOperand(0), /*IsSignaling*/ true);
7158     Chain = Sel.getValue(1);
7159   } else {
7160     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
7161   }
7162 
7163   bool Strict = Node->isStrictFPOpcode() ||
7164                 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
7165 
7166   if (Strict) {
7167     // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
7168     // signmask then offset (the result of which should be fully representable).
7169     // Sel = Src < 0x8000000000000000
7170     // FltOfs = select Sel, 0, 0x8000000000000000
7171     // IntOfs = select Sel, 0, 0x8000000000000000
7172     // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
7173 
7174     // TODO: Should any fast-math-flags be set for the FSUB?
7175     SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
7176                                    DAG.getConstantFP(0.0, dl, SrcVT), Cst);
7177     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
7178     SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
7179                                    DAG.getConstant(0, dl, DstVT),
7180                                    DAG.getConstant(SignMask, dl, DstVT));
7181     SDValue SInt;
7182     if (Node->isStrictFPOpcode()) {
7183       SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
7184                                 { Chain, Src, FltOfs });
7185       SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
7186                          { Val.getValue(1), Val });
7187       Chain = SInt.getValue(1);
7188     } else {
7189       SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
7190       SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
7191     }
7192     Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
7193   } else {
7194     // Expand based on maximum range of FP_TO_SINT:
7195     // True = fp_to_sint(Src)
7196     // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
7197     // Result = select (Src < 0x8000000000000000), True, False
7198 
7199     SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
7200     // TODO: Should any fast-math-flags be set for the FSUB?
7201     SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
7202                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
7203     False = DAG.getNode(ISD::XOR, dl, DstVT, False,
7204                         DAG.getConstant(SignMask, dl, DstVT));
7205     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
7206     Result = DAG.getSelect(dl, DstVT, Sel, True, False);
7207   }
7208   return true;
7209 }
7210 
7211 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result,
7212                                       SDValue &Chain,
7213                                       SelectionDAG &DAG) const {
7214   // This transform is not correct for converting 0 when rounding mode is set
7215   // to round toward negative infinity which will produce -0.0. So disable under
7216   // strictfp.
7217   if (Node->isStrictFPOpcode())
7218     return false;
7219 
7220   SDValue Src = Node->getOperand(0);
7221   EVT SrcVT = Src.getValueType();
7222   EVT DstVT = Node->getValueType(0);
7223 
7224   if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
7225     return false;
7226 
7227   // Only expand vector types if we have the appropriate vector bit operations.
7228   if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
7229                            !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
7230                            !isOperationLegalOrCustom(ISD::FSUB, DstVT) ||
7231                            !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
7232                            !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
7233     return false;
7234 
7235   SDLoc dl(SDValue(Node, 0));
7236   EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout());
7237 
7238   // Implementation of unsigned i64 to f64 following the algorithm in
7239   // __floatundidf in compiler_rt.  This implementation performs rounding
7240   // correctly in all rounding modes with the exception of converting 0
7241   // when rounding toward negative infinity. In that case the fsub will produce
7242   // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect.
7243   SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
7244   SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
7245       BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT);
7246   SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
7247   SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
7248   SDValue HiShift = DAG.getConstant(32, dl, ShiftVT);
7249 
7250   SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
7251   SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
7252   SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
7253   SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
7254   SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
7255   SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
7256   SDValue HiSub =
7257       DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
7258   Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
7259   return true;
7260 }
7261 
7262 SDValue
7263 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node,
7264                                                SelectionDAG &DAG) const {
7265   unsigned Opcode = Node->getOpcode();
7266   assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
7267           Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
7268          "Wrong opcode");
7269 
7270   if (Node->getFlags().hasNoNaNs()) {
7271     ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
7272     SDValue Op1 = Node->getOperand(0);
7273     SDValue Op2 = Node->getOperand(1);
7274     SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred);
7275     // Copy FMF flags, but always set the no-signed-zeros flag
7276     // as this is implied by the FMINNUM/FMAXNUM semantics.
7277     SDNodeFlags Flags = Node->getFlags();
7278     Flags.setNoSignedZeros(true);
7279     SelCC->setFlags(Flags);
7280     return SelCC;
7281   }
7282 
7283   return SDValue();
7284 }
7285 
7286 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node,
7287                                               SelectionDAG &DAG) const {
7288   SDLoc dl(Node);
7289   unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ?
7290     ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
7291   EVT VT = Node->getValueType(0);
7292 
7293   if (VT.isScalableVector())
7294     report_fatal_error(
7295         "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
7296 
7297   if (isOperationLegalOrCustom(NewOp, VT)) {
7298     SDValue Quiet0 = Node->getOperand(0);
7299     SDValue Quiet1 = Node->getOperand(1);
7300 
7301     if (!Node->getFlags().hasNoNaNs()) {
7302       // Insert canonicalizes if it's possible we need to quiet to get correct
7303       // sNaN behavior.
7304       if (!DAG.isKnownNeverSNaN(Quiet0)) {
7305         Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
7306                              Node->getFlags());
7307       }
7308       if (!DAG.isKnownNeverSNaN(Quiet1)) {
7309         Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
7310                              Node->getFlags());
7311       }
7312     }
7313 
7314     return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
7315   }
7316 
7317   // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
7318   // instead if there are no NaNs.
7319   if (Node->getFlags().hasNoNaNs()) {
7320     unsigned IEEE2018Op =
7321         Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
7322     if (isOperationLegalOrCustom(IEEE2018Op, VT)) {
7323       return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
7324                          Node->getOperand(1), Node->getFlags());
7325     }
7326   }
7327 
7328   if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG))
7329     return SelCC;
7330 
7331   return SDValue();
7332 }
7333 
7334 // Only expand vector types if we have the appropriate vector bit operations.
7335 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
7336   assert(VT.isVector() && "Expected vector type");
7337   unsigned Len = VT.getScalarSizeInBits();
7338   return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
7339          TLI.isOperationLegalOrCustom(ISD::SUB, VT) &&
7340          TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
7341          (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
7342          TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT);
7343 }
7344 
7345 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const {
7346   SDLoc dl(Node);
7347   EVT VT = Node->getValueType(0);
7348   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7349   SDValue Op = Node->getOperand(0);
7350   unsigned Len = VT.getScalarSizeInBits();
7351   assert(VT.isInteger() && "CTPOP not implemented for this type.");
7352 
7353   // TODO: Add support for irregular type lengths.
7354   if (!(Len <= 128 && Len % 8 == 0))
7355     return SDValue();
7356 
7357   // Only expand vector types if we have the appropriate vector bit operations.
7358   if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
7359     return SDValue();
7360 
7361   // This is the "best" algorithm from
7362   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
7363   SDValue Mask55 =
7364       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
7365   SDValue Mask33 =
7366       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
7367   SDValue Mask0F =
7368       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
7369   SDValue Mask01 =
7370       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
7371 
7372   // v = v - ((v >> 1) & 0x55555555...)
7373   Op = DAG.getNode(ISD::SUB, dl, VT, Op,
7374                    DAG.getNode(ISD::AND, dl, VT,
7375                                DAG.getNode(ISD::SRL, dl, VT, Op,
7376                                            DAG.getConstant(1, dl, ShVT)),
7377                                Mask55));
7378   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
7379   Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
7380                    DAG.getNode(ISD::AND, dl, VT,
7381                                DAG.getNode(ISD::SRL, dl, VT, Op,
7382                                            DAG.getConstant(2, dl, ShVT)),
7383                                Mask33));
7384   // v = (v + (v >> 4)) & 0x0F0F0F0F...
7385   Op = DAG.getNode(ISD::AND, dl, VT,
7386                    DAG.getNode(ISD::ADD, dl, VT, Op,
7387                                DAG.getNode(ISD::SRL, dl, VT, Op,
7388                                            DAG.getConstant(4, dl, ShVT))),
7389                    Mask0F);
7390   // v = (v * 0x01010101...) >> (Len - 8)
7391   if (Len > 8)
7392     Op =
7393         DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
7394                     DAG.getConstant(Len - 8, dl, ShVT));
7395 
7396   return Op;
7397 }
7398 
7399 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const {
7400   SDLoc dl(Node);
7401   EVT VT = Node->getValueType(0);
7402   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7403   SDValue Op = Node->getOperand(0);
7404   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7405 
7406   // If the non-ZERO_UNDEF version is supported we can use that instead.
7407   if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
7408       isOperationLegalOrCustom(ISD::CTLZ, VT))
7409     return DAG.getNode(ISD::CTLZ, dl, VT, Op);
7410 
7411   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7412   if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
7413     EVT SetCCVT =
7414         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7415     SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
7416     SDValue Zero = DAG.getConstant(0, dl, VT);
7417     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7418     return DAG.getSelect(dl, VT, SrcIsZero,
7419                          DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
7420   }
7421 
7422   // Only expand vector types if we have the appropriate vector bit operations.
7423   // This includes the operations needed to expand CTPOP if it isn't supported.
7424   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7425                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
7426                          !canExpandVectorCTPOP(*this, VT)) ||
7427                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
7428                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
7429     return SDValue();
7430 
7431   // for now, we do this:
7432   // x = x | (x >> 1);
7433   // x = x | (x >> 2);
7434   // ...
7435   // x = x | (x >>16);
7436   // x = x | (x >>32); // for 64-bit input
7437   // return popcount(~x);
7438   //
7439   // Ref: "Hacker's Delight" by Henry Warren
7440   for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) {
7441     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
7442     Op = DAG.getNode(ISD::OR, dl, VT, Op,
7443                      DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
7444   }
7445   Op = DAG.getNOT(dl, Op, VT);
7446   return DAG.getNode(ISD::CTPOP, dl, VT, Op);
7447 }
7448 
7449 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const {
7450   SDLoc dl(Node);
7451   EVT VT = Node->getValueType(0);
7452   SDValue Op = Node->getOperand(0);
7453   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7454 
7455   // If the non-ZERO_UNDEF version is supported we can use that instead.
7456   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
7457       isOperationLegalOrCustom(ISD::CTTZ, VT))
7458     return DAG.getNode(ISD::CTTZ, dl, VT, Op);
7459 
7460   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7461   if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) {
7462     EVT SetCCVT =
7463         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7464     SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op);
7465     SDValue Zero = DAG.getConstant(0, dl, VT);
7466     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7467     return DAG.getSelect(dl, VT, SrcIsZero,
7468                          DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
7469   }
7470 
7471   // Only expand vector types if we have the appropriate vector bit operations.
7472   // This includes the operations needed to expand CTPOP if it isn't supported.
7473   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7474                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
7475                          !isOperationLegalOrCustom(ISD::CTLZ, VT) &&
7476                          !canExpandVectorCTPOP(*this, VT)) ||
7477                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
7478                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
7479                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
7480     return SDValue();
7481 
7482   // for now, we use: { return popcount(~x & (x - 1)); }
7483   // unless the target has ctlz but not ctpop, in which case we use:
7484   // { return 32 - nlz(~x & (x-1)); }
7485   // Ref: "Hacker's Delight" by Henry Warren
7486   SDValue Tmp = DAG.getNode(
7487       ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
7488       DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
7489 
7490   // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
7491   if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) {
7492     return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
7493                        DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
7494   }
7495 
7496   return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
7497 }
7498 
7499 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG,
7500                                   bool IsNegative) const {
7501   SDLoc dl(N);
7502   EVT VT = N->getValueType(0);
7503   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7504   SDValue Op = N->getOperand(0);
7505 
7506   // abs(x) -> smax(x,sub(0,x))
7507   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7508       isOperationLegal(ISD::SMAX, VT)) {
7509     SDValue Zero = DAG.getConstant(0, dl, VT);
7510     return DAG.getNode(ISD::SMAX, dl, VT, Op,
7511                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7512   }
7513 
7514   // abs(x) -> umin(x,sub(0,x))
7515   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7516       isOperationLegal(ISD::UMIN, VT)) {
7517     SDValue Zero = DAG.getConstant(0, dl, VT);
7518     return DAG.getNode(ISD::UMIN, dl, VT, Op,
7519                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7520   }
7521 
7522   // 0 - abs(x) -> smin(x, sub(0,x))
7523   if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
7524       isOperationLegal(ISD::SMIN, VT)) {
7525     SDValue Zero = DAG.getConstant(0, dl, VT);
7526     return DAG.getNode(ISD::SMIN, dl, VT, Op,
7527                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7528   }
7529 
7530   // Only expand vector types if we have the appropriate vector operations.
7531   if (VT.isVector() &&
7532       (!isOperationLegalOrCustom(ISD::SRA, VT) ||
7533        (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
7534        (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
7535        !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
7536     return SDValue();
7537 
7538   SDValue Shift =
7539       DAG.getNode(ISD::SRA, dl, VT, Op,
7540                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT));
7541   SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
7542 
7543   // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
7544   if (!IsNegative)
7545     return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
7546 
7547   // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
7548   return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
7549 }
7550 
7551 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const {
7552   SDLoc dl(N);
7553   EVT VT = N->getValueType(0);
7554   SDValue Op = N->getOperand(0);
7555 
7556   if (!VT.isSimple())
7557     return SDValue();
7558 
7559   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
7560   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
7561   switch (VT.getSimpleVT().getScalarType().SimpleTy) {
7562   default:
7563     return SDValue();
7564   case MVT::i16:
7565     // Use a rotate by 8. This can be further expanded if necessary.
7566     return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7567   case MVT::i32:
7568     Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7569     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7570     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7571     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7572     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
7573                        DAG.getConstant(0xFF0000, dl, VT));
7574     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
7575     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
7576     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
7577     return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
7578   case MVT::i64:
7579     Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
7580     Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
7581     Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7582     Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7583     Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7584     Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7585     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
7586     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
7587     Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7,
7588                        DAG.getConstant(255ULL<<48, dl, VT));
7589     Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6,
7590                        DAG.getConstant(255ULL<<40, dl, VT));
7591     Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5,
7592                        DAG.getConstant(255ULL<<32, dl, VT));
7593     Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
7594                        DAG.getConstant(255ULL<<24, dl, VT));
7595     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
7596                        DAG.getConstant(255ULL<<16, dl, VT));
7597     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
7598                        DAG.getConstant(255ULL<<8 , dl, VT));
7599     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
7600     Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
7601     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
7602     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
7603     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
7604     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
7605     return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
7606   }
7607 }
7608 
7609 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const {
7610   SDLoc dl(N);
7611   EVT VT = N->getValueType(0);
7612   SDValue Op = N->getOperand(0);
7613   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
7614   unsigned Sz = VT.getScalarSizeInBits();
7615 
7616   SDValue Tmp, Tmp2, Tmp3;
7617 
7618   // If we can, perform BSWAP first and then the mask+swap the i4, then i2
7619   // and finally the i1 pairs.
7620   // TODO: We can easily support i4/i2 legal types if any target ever does.
7621   if (Sz >= 8 && isPowerOf2_32(Sz)) {
7622     // Create the masks - repeating the pattern every byte.
7623     APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
7624     APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
7625     APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
7626 
7627     // BSWAP if the type is wider than a single byte.
7628     Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
7629 
7630     // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
7631     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
7632     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
7633     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
7634     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
7635     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7636 
7637     // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
7638     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
7639     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
7640     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
7641     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
7642     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7643 
7644     // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
7645     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
7646     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
7647     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
7648     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
7649     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7650     return Tmp;
7651   }
7652 
7653   Tmp = DAG.getConstant(0, dl, VT);
7654   for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
7655     if (I < J)
7656       Tmp2 =
7657           DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
7658     else
7659       Tmp2 =
7660           DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
7661 
7662     APInt Shift(Sz, 1);
7663     Shift <<= J;
7664     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
7665     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
7666   }
7667 
7668   return Tmp;
7669 }
7670 
7671 std::pair<SDValue, SDValue>
7672 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
7673                                     SelectionDAG &DAG) const {
7674   SDLoc SL(LD);
7675   SDValue Chain = LD->getChain();
7676   SDValue BasePTR = LD->getBasePtr();
7677   EVT SrcVT = LD->getMemoryVT();
7678   EVT DstVT = LD->getValueType(0);
7679   ISD::LoadExtType ExtType = LD->getExtensionType();
7680 
7681   if (SrcVT.isScalableVector())
7682     report_fatal_error("Cannot scalarize scalable vector loads");
7683 
7684   unsigned NumElem = SrcVT.getVectorNumElements();
7685 
7686   EVT SrcEltVT = SrcVT.getScalarType();
7687   EVT DstEltVT = DstVT.getScalarType();
7688 
7689   // A vector must always be stored in memory as-is, i.e. without any padding
7690   // between the elements, since various code depend on it, e.g. in the
7691   // handling of a bitcast of a vector type to int, which may be done with a
7692   // vector store followed by an integer load. A vector that does not have
7693   // elements that are byte-sized must therefore be stored as an integer
7694   // built out of the extracted vector elements.
7695   if (!SrcEltVT.isByteSized()) {
7696     unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
7697     EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
7698 
7699     unsigned NumSrcBits = SrcVT.getSizeInBits();
7700     EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
7701 
7702     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
7703     SDValue SrcEltBitMask = DAG.getConstant(
7704         APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
7705 
7706     // Load the whole vector and avoid masking off the top bits as it makes
7707     // the codegen worse.
7708     SDValue Load =
7709         DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR,
7710                        LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(),
7711                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
7712 
7713     SmallVector<SDValue, 8> Vals;
7714     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7715       unsigned ShiftIntoIdx =
7716           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
7717       SDValue ShiftAmount =
7718           DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(),
7719                                      LoadVT, SL, /*LegalTypes=*/false);
7720       SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
7721       SDValue Elt =
7722           DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
7723       SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
7724 
7725       if (ExtType != ISD::NON_EXTLOAD) {
7726         unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
7727         Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
7728       }
7729 
7730       Vals.push_back(Scalar);
7731     }
7732 
7733     SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
7734     return std::make_pair(Value, Load.getValue(1));
7735   }
7736 
7737   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
7738   assert(SrcEltVT.isByteSized());
7739 
7740   SmallVector<SDValue, 8> Vals;
7741   SmallVector<SDValue, 8> LoadChains;
7742 
7743   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7744     SDValue ScalarLoad =
7745         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
7746                        LD->getPointerInfo().getWithOffset(Idx * Stride),
7747                        SrcEltVT, LD->getOriginalAlign(),
7748                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
7749 
7750     BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride));
7751 
7752     Vals.push_back(ScalarLoad.getValue(0));
7753     LoadChains.push_back(ScalarLoad.getValue(1));
7754   }
7755 
7756   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
7757   SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
7758 
7759   return std::make_pair(Value, NewChain);
7760 }
7761 
7762 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
7763                                              SelectionDAG &DAG) const {
7764   SDLoc SL(ST);
7765 
7766   SDValue Chain = ST->getChain();
7767   SDValue BasePtr = ST->getBasePtr();
7768   SDValue Value = ST->getValue();
7769   EVT StVT = ST->getMemoryVT();
7770 
7771   if (StVT.isScalableVector())
7772     report_fatal_error("Cannot scalarize scalable vector stores");
7773 
7774   // The type of the data we want to save
7775   EVT RegVT = Value.getValueType();
7776   EVT RegSclVT = RegVT.getScalarType();
7777 
7778   // The type of data as saved in memory.
7779   EVT MemSclVT = StVT.getScalarType();
7780 
7781   unsigned NumElem = StVT.getVectorNumElements();
7782 
7783   // A vector must always be stored in memory as-is, i.e. without any padding
7784   // between the elements, since various code depend on it, e.g. in the
7785   // handling of a bitcast of a vector type to int, which may be done with a
7786   // vector store followed by an integer load. A vector that does not have
7787   // elements that are byte-sized must therefore be stored as an integer
7788   // built out of the extracted vector elements.
7789   if (!MemSclVT.isByteSized()) {
7790     unsigned NumBits = StVT.getSizeInBits();
7791     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
7792 
7793     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
7794 
7795     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7796       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
7797                                 DAG.getVectorIdxConstant(Idx, SL));
7798       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
7799       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
7800       unsigned ShiftIntoIdx =
7801           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
7802       SDValue ShiftAmount =
7803           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
7804       SDValue ShiftedElt =
7805           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
7806       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
7807     }
7808 
7809     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
7810                         ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
7811                         ST->getAAInfo());
7812   }
7813 
7814   // Store Stride in bytes
7815   unsigned Stride = MemSclVT.getSizeInBits() / 8;
7816   assert(Stride && "Zero stride!");
7817   // Extract each of the elements from the original vector and save them into
7818   // memory individually.
7819   SmallVector<SDValue, 8> Stores;
7820   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7821     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
7822                               DAG.getVectorIdxConstant(Idx, SL));
7823 
7824     SDValue Ptr =
7825         DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride));
7826 
7827     // This scalar TruncStore may be illegal, but we legalize it later.
7828     SDValue Store = DAG.getTruncStore(
7829         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
7830         MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
7831         ST->getAAInfo());
7832 
7833     Stores.push_back(Store);
7834   }
7835 
7836   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
7837 }
7838 
7839 std::pair<SDValue, SDValue>
7840 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
7841   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
7842          "unaligned indexed loads not implemented!");
7843   SDValue Chain = LD->getChain();
7844   SDValue Ptr = LD->getBasePtr();
7845   EVT VT = LD->getValueType(0);
7846   EVT LoadedVT = LD->getMemoryVT();
7847   SDLoc dl(LD);
7848   auto &MF = DAG.getMachineFunction();
7849 
7850   if (VT.isFloatingPoint() || VT.isVector()) {
7851     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
7852     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
7853       if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
7854           LoadedVT.isVector()) {
7855         // Scalarize the load and let the individual components be handled.
7856         return scalarizeVectorLoad(LD, DAG);
7857       }
7858 
7859       // Expand to a (misaligned) integer load of the same size,
7860       // then bitconvert to floating point or vector.
7861       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
7862                                     LD->getMemOperand());
7863       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
7864       if (LoadedVT != VT)
7865         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
7866                              ISD::ANY_EXTEND, dl, VT, Result);
7867 
7868       return std::make_pair(Result, newLoad.getValue(1));
7869     }
7870 
7871     // Copy the value to a (aligned) stack slot using (unaligned) integer
7872     // loads and stores, then do a (aligned) load from the stack slot.
7873     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
7874     unsigned LoadedBytes = LoadedVT.getStoreSize();
7875     unsigned RegBytes = RegVT.getSizeInBits() / 8;
7876     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
7877 
7878     // Make sure the stack slot is also aligned for the register type.
7879     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
7880     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
7881     SmallVector<SDValue, 8> Stores;
7882     SDValue StackPtr = StackBase;
7883     unsigned Offset = 0;
7884 
7885     EVT PtrVT = Ptr.getValueType();
7886     EVT StackPtrVT = StackPtr.getValueType();
7887 
7888     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
7889     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
7890 
7891     // Do all but one copies using the full register width.
7892     for (unsigned i = 1; i < NumRegs; i++) {
7893       // Load one integer register's worth from the original location.
7894       SDValue Load = DAG.getLoad(
7895           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
7896           LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
7897           LD->getAAInfo());
7898       // Follow the load with a store to the stack slot.  Remember the store.
7899       Stores.push_back(DAG.getStore(
7900           Load.getValue(1), dl, Load, StackPtr,
7901           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
7902       // Increment the pointers.
7903       Offset += RegBytes;
7904 
7905       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
7906       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
7907     }
7908 
7909     // The last copy may be partial.  Do an extending load.
7910     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
7911                                   8 * (LoadedBytes - Offset));
7912     SDValue Load =
7913         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
7914                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
7915                        LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
7916                        LD->getAAInfo());
7917     // Follow the load with a store to the stack slot.  Remember the store.
7918     // On big-endian machines this requires a truncating store to ensure
7919     // that the bits end up in the right place.
7920     Stores.push_back(DAG.getTruncStore(
7921         Load.getValue(1), dl, Load, StackPtr,
7922         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
7923 
7924     // The order of the stores doesn't matter - say it with a TokenFactor.
7925     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7926 
7927     // Finally, perform the original load only redirected to the stack slot.
7928     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
7929                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
7930                           LoadedVT);
7931 
7932     // Callers expect a MERGE_VALUES node.
7933     return std::make_pair(Load, TF);
7934   }
7935 
7936   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
7937          "Unaligned load of unsupported type.");
7938 
7939   // Compute the new VT that is half the size of the old one.  This is an
7940   // integer MVT.
7941   unsigned NumBits = LoadedVT.getSizeInBits();
7942   EVT NewLoadedVT;
7943   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
7944   NumBits >>= 1;
7945 
7946   Align Alignment = LD->getOriginalAlign();
7947   unsigned IncrementSize = NumBits / 8;
7948   ISD::LoadExtType HiExtType = LD->getExtensionType();
7949 
7950   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
7951   if (HiExtType == ISD::NON_EXTLOAD)
7952     HiExtType = ISD::ZEXTLOAD;
7953 
7954   // Load the value in two parts
7955   SDValue Lo, Hi;
7956   if (DAG.getDataLayout().isLittleEndian()) {
7957     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
7958                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7959                         LD->getAAInfo());
7960 
7961     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
7962     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
7963                         LD->getPointerInfo().getWithOffset(IncrementSize),
7964                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7965                         LD->getAAInfo());
7966   } else {
7967     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
7968                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7969                         LD->getAAInfo());
7970 
7971     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
7972     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
7973                         LD->getPointerInfo().getWithOffset(IncrementSize),
7974                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7975                         LD->getAAInfo());
7976   }
7977 
7978   // aggregate the two parts
7979   SDValue ShiftAmount =
7980       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
7981                                                     DAG.getDataLayout()));
7982   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
7983   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
7984 
7985   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
7986                              Hi.getValue(1));
7987 
7988   return std::make_pair(Result, TF);
7989 }
7990 
7991 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
7992                                              SelectionDAG &DAG) const {
7993   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
7994          "unaligned indexed stores not implemented!");
7995   SDValue Chain = ST->getChain();
7996   SDValue Ptr = ST->getBasePtr();
7997   SDValue Val = ST->getValue();
7998   EVT VT = Val.getValueType();
7999   Align Alignment = ST->getOriginalAlign();
8000   auto &MF = DAG.getMachineFunction();
8001   EVT StoreMemVT = ST->getMemoryVT();
8002 
8003   SDLoc dl(ST);
8004   if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
8005     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8006     if (isTypeLegal(intVT)) {
8007       if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
8008           StoreMemVT.isVector()) {
8009         // Scalarize the store and let the individual components be handled.
8010         SDValue Result = scalarizeVectorStore(ST, DAG);
8011         return Result;
8012       }
8013       // Expand to a bitconvert of the value to the integer type of the
8014       // same size, then a (misaligned) int store.
8015       // FIXME: Does not handle truncating floating point stores!
8016       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
8017       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
8018                             Alignment, ST->getMemOperand()->getFlags());
8019       return Result;
8020     }
8021     // Do a (aligned) store to a stack slot, then copy from the stack slot
8022     // to the final destination using (unaligned) integer loads and stores.
8023     MVT RegVT = getRegisterType(
8024         *DAG.getContext(),
8025         EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
8026     EVT PtrVT = Ptr.getValueType();
8027     unsigned StoredBytes = StoreMemVT.getStoreSize();
8028     unsigned RegBytes = RegVT.getSizeInBits() / 8;
8029     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
8030 
8031     // Make sure the stack slot is also aligned for the register type.
8032     SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
8033     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
8034 
8035     // Perform the original store, only redirected to the stack slot.
8036     SDValue Store = DAG.getTruncStore(
8037         Chain, dl, Val, StackPtr,
8038         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
8039 
8040     EVT StackPtrVT = StackPtr.getValueType();
8041 
8042     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
8043     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
8044     SmallVector<SDValue, 8> Stores;
8045     unsigned Offset = 0;
8046 
8047     // Do all but one copies using the full register width.
8048     for (unsigned i = 1; i < NumRegs; i++) {
8049       // Load one integer register's worth from the stack slot.
8050       SDValue Load = DAG.getLoad(
8051           RegVT, dl, Store, StackPtr,
8052           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
8053       // Store it to the final location.  Remember the store.
8054       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
8055                                     ST->getPointerInfo().getWithOffset(Offset),
8056                                     ST->getOriginalAlign(),
8057                                     ST->getMemOperand()->getFlags()));
8058       // Increment the pointers.
8059       Offset += RegBytes;
8060       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
8061       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
8062     }
8063 
8064     // The last store may be partial.  Do a truncating store.  On big-endian
8065     // machines this requires an extending load from the stack slot to ensure
8066     // that the bits are in the right place.
8067     EVT LoadMemVT =
8068         EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
8069 
8070     // Load from the stack slot.
8071     SDValue Load = DAG.getExtLoad(
8072         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
8073         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
8074 
8075     Stores.push_back(
8076         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
8077                           ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
8078                           ST->getOriginalAlign(),
8079                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
8080     // The order of the stores doesn't matter - say it with a TokenFactor.
8081     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8082     return Result;
8083   }
8084 
8085   assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
8086          "Unaligned store of unknown type.");
8087   // Get the half-size VT
8088   EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
8089   unsigned NumBits = NewStoredVT.getFixedSizeInBits();
8090   unsigned IncrementSize = NumBits / 8;
8091 
8092   // Divide the stored value in two parts.
8093   SDValue ShiftAmount = DAG.getConstant(
8094       NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout()));
8095   SDValue Lo = Val;
8096   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
8097 
8098   // Store the two parts
8099   SDValue Store1, Store2;
8100   Store1 = DAG.getTruncStore(Chain, dl,
8101                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
8102                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
8103                              ST->getMemOperand()->getFlags());
8104 
8105   Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
8106   Store2 = DAG.getTruncStore(
8107       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
8108       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
8109       ST->getMemOperand()->getFlags(), ST->getAAInfo());
8110 
8111   SDValue Result =
8112       DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
8113   return Result;
8114 }
8115 
8116 SDValue
8117 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
8118                                        const SDLoc &DL, EVT DataVT,
8119                                        SelectionDAG &DAG,
8120                                        bool IsCompressedMemory) const {
8121   SDValue Increment;
8122   EVT AddrVT = Addr.getValueType();
8123   EVT MaskVT = Mask.getValueType();
8124   assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
8125          "Incompatible types of Data and Mask");
8126   if (IsCompressedMemory) {
8127     if (DataVT.isScalableVector())
8128       report_fatal_error(
8129           "Cannot currently handle compressed memory with scalable vectors");
8130     // Incrementing the pointer according to number of '1's in the mask.
8131     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
8132     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
8133     if (MaskIntVT.getSizeInBits() < 32) {
8134       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
8135       MaskIntVT = MVT::i32;
8136     }
8137 
8138     // Count '1's with POPCNT.
8139     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
8140     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
8141     // Scale is an element size in bytes.
8142     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
8143                                     AddrVT);
8144     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
8145   } else if (DataVT.isScalableVector()) {
8146     Increment = DAG.getVScale(DL, AddrVT,
8147                               APInt(AddrVT.getFixedSizeInBits(),
8148                                     DataVT.getStoreSize().getKnownMinSize()));
8149   } else
8150     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
8151 
8152   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
8153 }
8154 
8155 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx,
8156                                        EVT VecVT, const SDLoc &dl,
8157                                        ElementCount SubEC) {
8158   assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
8159          "Cannot index a scalable vector within a fixed-width vector");
8160 
8161   unsigned NElts = VecVT.getVectorMinNumElements();
8162   unsigned NumSubElts = SubEC.getKnownMinValue();
8163   EVT IdxVT = Idx.getValueType();
8164 
8165   if (VecVT.isScalableVector() && !SubEC.isScalable()) {
8166     // If this is a constant index and we know the value plus the number of the
8167     // elements in the subvector minus one is less than the minimum number of
8168     // elements then it's safe to return Idx.
8169     if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
8170       if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
8171         return Idx;
8172     SDValue VS =
8173         DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
8174     unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
8175     SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
8176                               DAG.getConstant(NumSubElts, dl, IdxVT));
8177     return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
8178   }
8179   if (isPowerOf2_32(NElts) && NumSubElts == 1) {
8180     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts));
8181     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
8182                        DAG.getConstant(Imm, dl, IdxVT));
8183   }
8184   unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
8185   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
8186                      DAG.getConstant(MaxIndex, dl, IdxVT));
8187 }
8188 
8189 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
8190                                                 SDValue VecPtr, EVT VecVT,
8191                                                 SDValue Index) const {
8192   return getVectorSubVecPointer(
8193       DAG, VecPtr, VecVT,
8194       EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1),
8195       Index);
8196 }
8197 
8198 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG,
8199                                                SDValue VecPtr, EVT VecVT,
8200                                                EVT SubVecVT,
8201                                                SDValue Index) const {
8202   SDLoc dl(Index);
8203   // Make sure the index type is big enough to compute in.
8204   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
8205 
8206   EVT EltVT = VecVT.getVectorElementType();
8207 
8208   // Calculate the element offset and add it to the pointer.
8209   unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
8210   assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
8211          "Converting bits to bytes lost precision");
8212   assert(SubVecVT.getVectorElementType() == EltVT &&
8213          "Sub-vector must be a vector with matching element type");
8214   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
8215                                   SubVecVT.getVectorElementCount());
8216 
8217   EVT IdxVT = Index.getValueType();
8218   if (SubVecVT.isScalableVector())
8219     Index =
8220         DAG.getNode(ISD::MUL, dl, IdxVT, Index,
8221                     DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
8222 
8223   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
8224                       DAG.getConstant(EltSize, dl, IdxVT));
8225   return DAG.getMemBasePlusOffset(VecPtr, Index, dl);
8226 }
8227 
8228 //===----------------------------------------------------------------------===//
8229 // Implementation of Emulated TLS Model
8230 //===----------------------------------------------------------------------===//
8231 
8232 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
8233                                                 SelectionDAG &DAG) const {
8234   // Access to address of TLS varialbe xyz is lowered to a function call:
8235   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
8236   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8237   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
8238   SDLoc dl(GA);
8239 
8240   ArgListTy Args;
8241   ArgListEntry Entry;
8242   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
8243   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
8244   StringRef EmuTlsVarName(NameString);
8245   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
8246   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
8247   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
8248   Entry.Ty = VoidPtrType;
8249   Args.push_back(Entry);
8250 
8251   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
8252 
8253   TargetLowering::CallLoweringInfo CLI(DAG);
8254   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
8255   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
8256   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8257 
8258   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8259   // At last for X86 targets, maybe good for other targets too?
8260   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8261   MFI.setAdjustsStack(true); // Is this only for X86 target?
8262   MFI.setHasCalls(true);
8263 
8264   assert((GA->getOffset() == 0) &&
8265          "Emulated TLS must have zero offset in GlobalAddressSDNode");
8266   return CallResult.first;
8267 }
8268 
8269 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
8270                                                 SelectionDAG &DAG) const {
8271   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
8272   if (!isCtlzFast())
8273     return SDValue();
8274   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8275   SDLoc dl(Op);
8276   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8277     if (C->isZero() && CC == ISD::SETEQ) {
8278       EVT VT = Op.getOperand(0).getValueType();
8279       SDValue Zext = Op.getOperand(0);
8280       if (VT.bitsLT(MVT::i32)) {
8281         VT = MVT::i32;
8282         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
8283       }
8284       unsigned Log2b = Log2_32(VT.getSizeInBits());
8285       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
8286       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
8287                                 DAG.getConstant(Log2b, dl, MVT::i32));
8288       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
8289     }
8290   }
8291   return SDValue();
8292 }
8293 
8294 // Convert redundant addressing modes (e.g. scaling is redundant
8295 // when accessing bytes).
8296 ISD::MemIndexType
8297 TargetLowering::getCanonicalIndexType(ISD::MemIndexType IndexType, EVT MemVT,
8298                                       SDValue Offsets) const {
8299   bool IsScaledIndex =
8300       (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::UNSIGNED_SCALED);
8301   bool IsSignedIndex =
8302       (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::SIGNED_UNSCALED);
8303 
8304   // Scaling is unimportant for bytes, canonicalize to unscaled.
8305   if (IsScaledIndex && MemVT.getScalarType() == MVT::i8)
8306     return IsSignedIndex ? ISD::SIGNED_UNSCALED : ISD::UNSIGNED_UNSCALED;
8307 
8308   return IndexType;
8309 }
8310 
8311 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const {
8312   SDValue Op0 = Node->getOperand(0);
8313   SDValue Op1 = Node->getOperand(1);
8314   EVT VT = Op0.getValueType();
8315   unsigned Opcode = Node->getOpcode();
8316   SDLoc DL(Node);
8317 
8318   // umin(x,y) -> sub(x,usubsat(x,y))
8319   if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
8320       isOperationLegal(ISD::USUBSAT, VT)) {
8321     return DAG.getNode(ISD::SUB, DL, VT, Op0,
8322                        DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
8323   }
8324 
8325   // umax(x,y) -> add(x,usubsat(y,x))
8326   if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
8327       isOperationLegal(ISD::USUBSAT, VT)) {
8328     return DAG.getNode(ISD::ADD, DL, VT, Op0,
8329                        DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
8330   }
8331 
8332   // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
8333   ISD::CondCode CC;
8334   switch (Opcode) {
8335   default: llvm_unreachable("How did we get here?");
8336   case ISD::SMAX: CC = ISD::SETGT; break;
8337   case ISD::SMIN: CC = ISD::SETLT; break;
8338   case ISD::UMAX: CC = ISD::SETUGT; break;
8339   case ISD::UMIN: CC = ISD::SETULT; break;
8340   }
8341 
8342   // FIXME: Should really try to split the vector in case it's legal on a
8343   // subvector.
8344   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
8345     return DAG.UnrollVectorOp(Node);
8346 
8347   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8348   SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
8349   return DAG.getSelect(DL, VT, Cond, Op0, Op1);
8350 }
8351 
8352 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const {
8353   unsigned Opcode = Node->getOpcode();
8354   SDValue LHS = Node->getOperand(0);
8355   SDValue RHS = Node->getOperand(1);
8356   EVT VT = LHS.getValueType();
8357   SDLoc dl(Node);
8358 
8359   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
8360   assert(VT.isInteger() && "Expected operands to be integers");
8361 
8362   // usub.sat(a, b) -> umax(a, b) - b
8363   if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
8364     SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
8365     return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
8366   }
8367 
8368   // uadd.sat(a, b) -> umin(a, ~b) + b
8369   if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
8370     SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
8371     SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
8372     return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
8373   }
8374 
8375   unsigned OverflowOp;
8376   switch (Opcode) {
8377   case ISD::SADDSAT:
8378     OverflowOp = ISD::SADDO;
8379     break;
8380   case ISD::UADDSAT:
8381     OverflowOp = ISD::UADDO;
8382     break;
8383   case ISD::SSUBSAT:
8384     OverflowOp = ISD::SSUBO;
8385     break;
8386   case ISD::USUBSAT:
8387     OverflowOp = ISD::USUBO;
8388     break;
8389   default:
8390     llvm_unreachable("Expected method to receive signed or unsigned saturation "
8391                      "addition or subtraction node.");
8392   }
8393 
8394   // FIXME: Should really try to split the vector in case it's legal on a
8395   // subvector.
8396   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
8397     return DAG.UnrollVectorOp(Node);
8398 
8399   unsigned BitWidth = LHS.getScalarValueSizeInBits();
8400   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8401   SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8402   SDValue SumDiff = Result.getValue(0);
8403   SDValue Overflow = Result.getValue(1);
8404   SDValue Zero = DAG.getConstant(0, dl, VT);
8405   SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
8406 
8407   if (Opcode == ISD::UADDSAT) {
8408     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
8409       // (LHS + RHS) | OverflowMask
8410       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
8411       return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
8412     }
8413     // Overflow ? 0xffff.... : (LHS + RHS)
8414     return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
8415   }
8416 
8417   if (Opcode == ISD::USUBSAT) {
8418     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
8419       // (LHS - RHS) & ~OverflowMask
8420       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
8421       SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
8422       return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
8423     }
8424     // Overflow ? 0 : (LHS - RHS)
8425     return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
8426   }
8427 
8428   // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
8429   APInt MinVal = APInt::getSignedMinValue(BitWidth);
8430   SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8431   SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
8432                               DAG.getConstant(BitWidth - 1, dl, VT));
8433   Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
8434   return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
8435 }
8436 
8437 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const {
8438   unsigned Opcode = Node->getOpcode();
8439   bool IsSigned = Opcode == ISD::SSHLSAT;
8440   SDValue LHS = Node->getOperand(0);
8441   SDValue RHS = Node->getOperand(1);
8442   EVT VT = LHS.getValueType();
8443   SDLoc dl(Node);
8444 
8445   assert((Node->getOpcode() == ISD::SSHLSAT ||
8446           Node->getOpcode() == ISD::USHLSAT) &&
8447           "Expected a SHLSAT opcode");
8448   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
8449   assert(VT.isInteger() && "Expected operands to be integers");
8450 
8451   // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
8452 
8453   unsigned BW = VT.getScalarSizeInBits();
8454   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
8455   SDValue Orig =
8456       DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
8457 
8458   SDValue SatVal;
8459   if (IsSigned) {
8460     SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
8461     SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
8462     SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT),
8463                              SatMin, SatMax, ISD::SETLT);
8464   } else {
8465     SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
8466   }
8467   Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE);
8468 
8469   return Result;
8470 }
8471 
8472 SDValue
8473 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const {
8474   assert((Node->getOpcode() == ISD::SMULFIX ||
8475           Node->getOpcode() == ISD::UMULFIX ||
8476           Node->getOpcode() == ISD::SMULFIXSAT ||
8477           Node->getOpcode() == ISD::UMULFIXSAT) &&
8478          "Expected a fixed point multiplication opcode");
8479 
8480   SDLoc dl(Node);
8481   SDValue LHS = Node->getOperand(0);
8482   SDValue RHS = Node->getOperand(1);
8483   EVT VT = LHS.getValueType();
8484   unsigned Scale = Node->getConstantOperandVal(2);
8485   bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
8486                      Node->getOpcode() == ISD::UMULFIXSAT);
8487   bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
8488                  Node->getOpcode() == ISD::SMULFIXSAT);
8489   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8490   unsigned VTSize = VT.getScalarSizeInBits();
8491 
8492   if (!Scale) {
8493     // [us]mul.fix(a, b, 0) -> mul(a, b)
8494     if (!Saturating) {
8495       if (isOperationLegalOrCustom(ISD::MUL, VT))
8496         return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8497     } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
8498       SDValue Result =
8499           DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8500       SDValue Product = Result.getValue(0);
8501       SDValue Overflow = Result.getValue(1);
8502       SDValue Zero = DAG.getConstant(0, dl, VT);
8503 
8504       APInt MinVal = APInt::getSignedMinValue(VTSize);
8505       APInt MaxVal = APInt::getSignedMaxValue(VTSize);
8506       SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8507       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8508       // Xor the inputs, if resulting sign bit is 0 the product will be
8509       // positive, else negative.
8510       SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
8511       SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
8512       Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
8513       return DAG.getSelect(dl, VT, Overflow, Result, Product);
8514     } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
8515       SDValue Result =
8516           DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8517       SDValue Product = Result.getValue(0);
8518       SDValue Overflow = Result.getValue(1);
8519 
8520       APInt MaxVal = APInt::getMaxValue(VTSize);
8521       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8522       return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
8523     }
8524   }
8525 
8526   assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
8527          "Expected scale to be less than the number of bits if signed or at "
8528          "most the number of bits if unsigned.");
8529   assert(LHS.getValueType() == RHS.getValueType() &&
8530          "Expected both operands to be the same type");
8531 
8532   // Get the upper and lower bits of the result.
8533   SDValue Lo, Hi;
8534   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
8535   unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
8536   if (isOperationLegalOrCustom(LoHiOp, VT)) {
8537     SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
8538     Lo = Result.getValue(0);
8539     Hi = Result.getValue(1);
8540   } else if (isOperationLegalOrCustom(HiOp, VT)) {
8541     Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8542     Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
8543   } else if (VT.isVector()) {
8544     return SDValue();
8545   } else {
8546     report_fatal_error("Unable to expand fixed point multiplication.");
8547   }
8548 
8549   if (Scale == VTSize)
8550     // Result is just the top half since we'd be shifting by the width of the
8551     // operand. Overflow impossible so this works for both UMULFIX and
8552     // UMULFIXSAT.
8553     return Hi;
8554 
8555   // The result will need to be shifted right by the scale since both operands
8556   // are scaled. The result is given to us in 2 halves, so we only want part of
8557   // both in the result.
8558   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
8559   SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
8560                                DAG.getConstant(Scale, dl, ShiftTy));
8561   if (!Saturating)
8562     return Result;
8563 
8564   if (!Signed) {
8565     // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
8566     // widened multiplication) aren't all zeroes.
8567 
8568     // Saturate to max if ((Hi >> Scale) != 0),
8569     // which is the same as if (Hi > ((1 << Scale) - 1))
8570     APInt MaxVal = APInt::getMaxValue(VTSize);
8571     SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale),
8572                                       dl, VT);
8573     Result = DAG.getSelectCC(dl, Hi, LowMask,
8574                              DAG.getConstant(MaxVal, dl, VT), Result,
8575                              ISD::SETUGT);
8576 
8577     return Result;
8578   }
8579 
8580   // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
8581   // widened multiplication) aren't all ones or all zeroes.
8582 
8583   SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
8584   SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
8585 
8586   if (Scale == 0) {
8587     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
8588                                DAG.getConstant(VTSize - 1, dl, ShiftTy));
8589     SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
8590     // Saturated to SatMin if wide product is negative, and SatMax if wide
8591     // product is positive ...
8592     SDValue Zero = DAG.getConstant(0, dl, VT);
8593     SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax,
8594                                                ISD::SETLT);
8595     // ... but only if we overflowed.
8596     return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
8597   }
8598 
8599   //  We handled Scale==0 above so all the bits to examine is in Hi.
8600 
8601   // Saturate to max if ((Hi >> (Scale - 1)) > 0),
8602   // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
8603   SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1),
8604                                     dl, VT);
8605   Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT);
8606   // Saturate to min if (Hi >> (Scale - 1)) < -1),
8607   // which is the same as if (HI < (-1 << (Scale - 1))
8608   SDValue HighMask =
8609       DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1),
8610                       dl, VT);
8611   Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT);
8612   return Result;
8613 }
8614 
8615 SDValue
8616 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
8617                                     SDValue LHS, SDValue RHS,
8618                                     unsigned Scale, SelectionDAG &DAG) const {
8619   assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
8620           Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
8621          "Expected a fixed point division opcode");
8622 
8623   EVT VT = LHS.getValueType();
8624   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
8625   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
8626   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8627 
8628   // If there is enough room in the type to upscale the LHS or downscale the
8629   // RHS before the division, we can perform it in this type without having to
8630   // resize. For signed operations, the LHS headroom is the number of
8631   // redundant sign bits, and for unsigned ones it is the number of zeroes.
8632   // The headroom for the RHS is the number of trailing zeroes.
8633   unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
8634                             : DAG.computeKnownBits(LHS).countMinLeadingZeros();
8635   unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
8636 
8637   // For signed saturating operations, we need to be able to detect true integer
8638   // division overflow; that is, when you have MIN / -EPS. However, this
8639   // is undefined behavior and if we emit divisions that could take such
8640   // values it may cause undesired behavior (arithmetic exceptions on x86, for
8641   // example).
8642   // Avoid this by requiring an extra bit so that we never get this case.
8643   // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
8644   // signed saturating division, we need to emit a whopping 32-bit division.
8645   if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
8646     return SDValue();
8647 
8648   unsigned LHSShift = std::min(LHSLead, Scale);
8649   unsigned RHSShift = Scale - LHSShift;
8650 
8651   // At this point, we know that if we shift the LHS up by LHSShift and the
8652   // RHS down by RHSShift, we can emit a regular division with a final scaling
8653   // factor of Scale.
8654 
8655   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
8656   if (LHSShift)
8657     LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
8658                       DAG.getConstant(LHSShift, dl, ShiftTy));
8659   if (RHSShift)
8660     RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
8661                       DAG.getConstant(RHSShift, dl, ShiftTy));
8662 
8663   SDValue Quot;
8664   if (Signed) {
8665     // For signed operations, if the resulting quotient is negative and the
8666     // remainder is nonzero, subtract 1 from the quotient to round towards
8667     // negative infinity.
8668     SDValue Rem;
8669     // FIXME: Ideally we would always produce an SDIVREM here, but if the
8670     // type isn't legal, SDIVREM cannot be expanded. There is no reason why
8671     // we couldn't just form a libcall, but the type legalizer doesn't do it.
8672     if (isTypeLegal(VT) &&
8673         isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
8674       Quot = DAG.getNode(ISD::SDIVREM, dl,
8675                          DAG.getVTList(VT, VT),
8676                          LHS, RHS);
8677       Rem = Quot.getValue(1);
8678       Quot = Quot.getValue(0);
8679     } else {
8680       Quot = DAG.getNode(ISD::SDIV, dl, VT,
8681                          LHS, RHS);
8682       Rem = DAG.getNode(ISD::SREM, dl, VT,
8683                         LHS, RHS);
8684     }
8685     SDValue Zero = DAG.getConstant(0, dl, VT);
8686     SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
8687     SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
8688     SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
8689     SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
8690     SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
8691                                DAG.getConstant(1, dl, VT));
8692     Quot = DAG.getSelect(dl, VT,
8693                          DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
8694                          Sub1, Quot);
8695   } else
8696     Quot = DAG.getNode(ISD::UDIV, dl, VT,
8697                        LHS, RHS);
8698 
8699   return Quot;
8700 }
8701 
8702 void TargetLowering::expandUADDSUBO(
8703     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
8704   SDLoc dl(Node);
8705   SDValue LHS = Node->getOperand(0);
8706   SDValue RHS = Node->getOperand(1);
8707   bool IsAdd = Node->getOpcode() == ISD::UADDO;
8708 
8709   // If ADD/SUBCARRY is legal, use that instead.
8710   unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY;
8711   if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
8712     SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
8713     SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
8714                                     { LHS, RHS, CarryIn });
8715     Result = SDValue(NodeCarry.getNode(), 0);
8716     Overflow = SDValue(NodeCarry.getNode(), 1);
8717     return;
8718   }
8719 
8720   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
8721                             LHS.getValueType(), LHS, RHS);
8722 
8723   EVT ResultType = Node->getValueType(1);
8724   EVT SetCCType = getSetCCResultType(
8725       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
8726   ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
8727   SDValue SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
8728   Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
8729 }
8730 
8731 void TargetLowering::expandSADDSUBO(
8732     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
8733   SDLoc dl(Node);
8734   SDValue LHS = Node->getOperand(0);
8735   SDValue RHS = Node->getOperand(1);
8736   bool IsAdd = Node->getOpcode() == ISD::SADDO;
8737 
8738   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
8739                             LHS.getValueType(), LHS, RHS);
8740 
8741   EVT ResultType = Node->getValueType(1);
8742   EVT OType = getSetCCResultType(
8743       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
8744 
8745   // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
8746   unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
8747   if (isOperationLegal(OpcSat, LHS.getValueType())) {
8748     SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
8749     SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
8750     Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
8751     return;
8752   }
8753 
8754   SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
8755 
8756   // For an addition, the result should be less than one of the operands (LHS)
8757   // if and only if the other operand (RHS) is negative, otherwise there will
8758   // be overflow.
8759   // For a subtraction, the result should be less than one of the operands
8760   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
8761   // otherwise there will be overflow.
8762   SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
8763   SDValue ConditionRHS =
8764       DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT);
8765 
8766   Overflow = DAG.getBoolExtOrTrunc(
8767       DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl,
8768       ResultType, ResultType);
8769 }
8770 
8771 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result,
8772                                 SDValue &Overflow, SelectionDAG &DAG) const {
8773   SDLoc dl(Node);
8774   EVT VT = Node->getValueType(0);
8775   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8776   SDValue LHS = Node->getOperand(0);
8777   SDValue RHS = Node->getOperand(1);
8778   bool isSigned = Node->getOpcode() == ISD::SMULO;
8779 
8780   // For power-of-two multiplications we can use a simpler shift expansion.
8781   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
8782     const APInt &C = RHSC->getAPIntValue();
8783     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
8784     if (C.isPowerOf2()) {
8785       // smulo(x, signed_min) is same as umulo(x, signed_min).
8786       bool UseArithShift = isSigned && !C.isMinSignedValue();
8787       EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout());
8788       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy);
8789       Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
8790       Overflow = DAG.getSetCC(dl, SetCCVT,
8791           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
8792                       dl, VT, Result, ShiftAmt),
8793           LHS, ISD::SETNE);
8794       return true;
8795     }
8796   }
8797 
8798   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2);
8799   if (VT.isVector())
8800     WideVT =
8801         EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount());
8802 
8803   SDValue BottomHalf;
8804   SDValue TopHalf;
8805   static const unsigned Ops[2][3] =
8806       { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
8807         { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
8808   if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
8809     BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8810     TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
8811   } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
8812     BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
8813                              RHS);
8814     TopHalf = BottomHalf.getValue(1);
8815   } else if (isTypeLegal(WideVT)) {
8816     LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
8817     RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
8818     SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
8819     BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
8820     SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl,
8821         getShiftAmountTy(WideVT, DAG.getDataLayout()));
8822     TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
8823                           DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
8824   } else {
8825     if (VT.isVector())
8826       return false;
8827 
8828     // We can fall back to a libcall with an illegal type for the MUL if we
8829     // have a libcall big enough.
8830     // Also, we can fall back to a division in some cases, but that's a big
8831     // performance hit in the general case.
8832     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
8833     if (WideVT == MVT::i16)
8834       LC = RTLIB::MUL_I16;
8835     else if (WideVT == MVT::i32)
8836       LC = RTLIB::MUL_I32;
8837     else if (WideVT == MVT::i64)
8838       LC = RTLIB::MUL_I64;
8839     else if (WideVT == MVT::i128)
8840       LC = RTLIB::MUL_I128;
8841     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
8842 
8843     SDValue HiLHS;
8844     SDValue HiRHS;
8845     if (isSigned) {
8846       // The high part is obtained by SRA'ing all but one of the bits of low
8847       // part.
8848       unsigned LoSize = VT.getFixedSizeInBits();
8849       HiLHS =
8850           DAG.getNode(ISD::SRA, dl, VT, LHS,
8851                       DAG.getConstant(LoSize - 1, dl,
8852                                       getPointerTy(DAG.getDataLayout())));
8853       HiRHS =
8854           DAG.getNode(ISD::SRA, dl, VT, RHS,
8855                       DAG.getConstant(LoSize - 1, dl,
8856                                       getPointerTy(DAG.getDataLayout())));
8857     } else {
8858         HiLHS = DAG.getConstant(0, dl, VT);
8859         HiRHS = DAG.getConstant(0, dl, VT);
8860     }
8861 
8862     // Here we're passing the 2 arguments explicitly as 4 arguments that are
8863     // pre-lowered to the correct types. This all depends upon WideVT not
8864     // being a legal type for the architecture and thus has to be split to
8865     // two arguments.
8866     SDValue Ret;
8867     TargetLowering::MakeLibCallOptions CallOptions;
8868     CallOptions.setSExt(isSigned);
8869     CallOptions.setIsPostTypeLegalization(true);
8870     if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) {
8871       // Halves of WideVT are packed into registers in different order
8872       // depending on platform endianness. This is usually handled by
8873       // the C calling convention, but we can't defer to it in
8874       // the legalizer.
8875       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
8876       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
8877     } else {
8878       SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
8879       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
8880     }
8881     assert(Ret.getOpcode() == ISD::MERGE_VALUES &&
8882            "Ret value is a collection of constituent nodes holding result.");
8883     if (DAG.getDataLayout().isLittleEndian()) {
8884       // Same as above.
8885       BottomHalf = Ret.getOperand(0);
8886       TopHalf = Ret.getOperand(1);
8887     } else {
8888       BottomHalf = Ret.getOperand(1);
8889       TopHalf = Ret.getOperand(0);
8890     }
8891   }
8892 
8893   Result = BottomHalf;
8894   if (isSigned) {
8895     SDValue ShiftAmt = DAG.getConstant(
8896         VT.getScalarSizeInBits() - 1, dl,
8897         getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
8898     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
8899     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
8900   } else {
8901     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
8902                             DAG.getConstant(0, dl, VT), ISD::SETNE);
8903   }
8904 
8905   // Truncate the result if SetCC returns a larger type than needed.
8906   EVT RType = Node->getValueType(1);
8907   if (RType.bitsLT(Overflow.getValueType()))
8908     Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
8909 
8910   assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
8911          "Unexpected result type for S/UMULO legalization");
8912   return true;
8913 }
8914 
8915 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const {
8916   SDLoc dl(Node);
8917   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
8918   SDValue Op = Node->getOperand(0);
8919   EVT VT = Op.getValueType();
8920 
8921   if (VT.isScalableVector())
8922     report_fatal_error(
8923         "Expanding reductions for scalable vectors is undefined.");
8924 
8925   // Try to use a shuffle reduction for power of two vectors.
8926   if (VT.isPow2VectorType()) {
8927     while (VT.getVectorNumElements() > 1) {
8928       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
8929       if (!isOperationLegalOrCustom(BaseOpcode, HalfVT))
8930         break;
8931 
8932       SDValue Lo, Hi;
8933       std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
8934       Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi);
8935       VT = HalfVT;
8936     }
8937   }
8938 
8939   EVT EltVT = VT.getVectorElementType();
8940   unsigned NumElts = VT.getVectorNumElements();
8941 
8942   SmallVector<SDValue, 8> Ops;
8943   DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
8944 
8945   SDValue Res = Ops[0];
8946   for (unsigned i = 1; i < NumElts; i++)
8947     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags());
8948 
8949   // Result type may be wider than element type.
8950   if (EltVT != Node->getValueType(0))
8951     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
8952   return Res;
8953 }
8954 
8955 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const {
8956   SDLoc dl(Node);
8957   SDValue AccOp = Node->getOperand(0);
8958   SDValue VecOp = Node->getOperand(1);
8959   SDNodeFlags Flags = Node->getFlags();
8960 
8961   EVT VT = VecOp.getValueType();
8962   EVT EltVT = VT.getVectorElementType();
8963 
8964   if (VT.isScalableVector())
8965     report_fatal_error(
8966         "Expanding reductions for scalable vectors is undefined.");
8967 
8968   unsigned NumElts = VT.getVectorNumElements();
8969 
8970   SmallVector<SDValue, 8> Ops;
8971   DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
8972 
8973   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
8974 
8975   SDValue Res = AccOp;
8976   for (unsigned i = 0; i < NumElts; i++)
8977     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
8978 
8979   return Res;
8980 }
8981 
8982 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result,
8983                                SelectionDAG &DAG) const {
8984   EVT VT = Node->getValueType(0);
8985   SDLoc dl(Node);
8986   bool isSigned = Node->getOpcode() == ISD::SREM;
8987   unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
8988   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
8989   SDValue Dividend = Node->getOperand(0);
8990   SDValue Divisor = Node->getOperand(1);
8991   if (isOperationLegalOrCustom(DivRemOpc, VT)) {
8992     SDVTList VTs = DAG.getVTList(VT, VT);
8993     Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
8994     return true;
8995   }
8996   if (isOperationLegalOrCustom(DivOpc, VT)) {
8997     // X % Y -> X-X/Y*Y
8998     SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
8999     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
9000     Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
9001     return true;
9002   }
9003   return false;
9004 }
9005 
9006 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node,
9007                                             SelectionDAG &DAG) const {
9008   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
9009   SDLoc dl(SDValue(Node, 0));
9010   SDValue Src = Node->getOperand(0);
9011 
9012   // DstVT is the result type, while SatVT is the size to which we saturate
9013   EVT SrcVT = Src.getValueType();
9014   EVT DstVT = Node->getValueType(0);
9015 
9016   EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9017   unsigned SatWidth = SatVT.getScalarSizeInBits();
9018   unsigned DstWidth = DstVT.getScalarSizeInBits();
9019   assert(SatWidth <= DstWidth &&
9020          "Expected saturation width smaller than result width");
9021 
9022   // Determine minimum and maximum integer values and their corresponding
9023   // floating-point values.
9024   APInt MinInt, MaxInt;
9025   if (IsSigned) {
9026     MinInt = APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth);
9027     MaxInt = APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth);
9028   } else {
9029     MinInt = APInt::getMinValue(SatWidth).zextOrSelf(DstWidth);
9030     MaxInt = APInt::getMaxValue(SatWidth).zextOrSelf(DstWidth);
9031   }
9032 
9033   // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as
9034   // libcall emission cannot handle this. Large result types will fail.
9035   if (SrcVT == MVT::f16) {
9036     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
9037     SrcVT = Src.getValueType();
9038   }
9039 
9040   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
9041   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
9042 
9043   APFloat::opStatus MinStatus =
9044       MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
9045   APFloat::opStatus MaxStatus =
9046       MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
9047   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
9048                              !(MaxStatus & APFloat::opStatus::opInexact);
9049 
9050   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
9051   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
9052 
9053   // If the integer bounds are exactly representable as floats and min/max are
9054   // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
9055   // of comparisons and selects.
9056   bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) &&
9057                      isOperationLegal(ISD::FMAXNUM, SrcVT);
9058   if (AreExactFloatBounds && MinMaxLegal) {
9059     SDValue Clamped = Src;
9060 
9061     // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat.
9062     Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode);
9063     // Clamp by MaxFloat from above. NaN cannot occur.
9064     Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode);
9065     // Convert clamped value to integer.
9066     SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
9067                                   dl, DstVT, Clamped);
9068 
9069     // In the unsigned case we're done, because we mapped NaN to MinFloat,
9070     // which will cast to zero.
9071     if (!IsSigned)
9072       return FpToInt;
9073 
9074     // Otherwise, select 0 if Src is NaN.
9075     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
9076     return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt,
9077                            ISD::CondCode::SETUO);
9078   }
9079 
9080   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
9081   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
9082 
9083   // Result of direct conversion. The assumption here is that the operation is
9084   // non-trapping and it's fine to apply it to an out-of-range value if we
9085   // select it away later.
9086   SDValue FpToInt =
9087       DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
9088 
9089   SDValue Select = FpToInt;
9090 
9091   // If Src ULT MinFloat, select MinInt. In particular, this also selects
9092   // MinInt if Src is NaN.
9093   Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select,
9094                            ISD::CondCode::SETULT);
9095   // If Src OGT MaxFloat, select MaxInt.
9096   Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select,
9097                            ISD::CondCode::SETOGT);
9098 
9099   // In the unsigned case we are done, because we mapped NaN to MinInt, which
9100   // is already zero.
9101   if (!IsSigned)
9102     return Select;
9103 
9104   // Otherwise, select 0 if Src is NaN.
9105   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
9106   return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
9107 }
9108 
9109 SDValue TargetLowering::expandVectorSplice(SDNode *Node,
9110                                            SelectionDAG &DAG) const {
9111   assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!");
9112   assert(Node->getValueType(0).isScalableVector() &&
9113          "Fixed length vector types expected to use SHUFFLE_VECTOR!");
9114 
9115   EVT VT = Node->getValueType(0);
9116   SDValue V1 = Node->getOperand(0);
9117   SDValue V2 = Node->getOperand(1);
9118   int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue();
9119   SDLoc DL(Node);
9120 
9121   // Expand through memory thusly:
9122   //  Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
9123   //  Store V1, Ptr
9124   //  Store V2, Ptr + sizeof(V1)
9125   //  If (Imm < 0)
9126   //    TrailingElts = -Imm
9127   //    Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt))
9128   //  else
9129   //    Ptr = Ptr + (Imm * sizeof(VT.Elt))
9130   //  Res = Load Ptr
9131 
9132   Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
9133 
9134   EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
9135                                VT.getVectorElementCount() * 2);
9136   SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
9137   EVT PtrVT = StackPtr.getValueType();
9138   auto &MF = DAG.getMachineFunction();
9139   auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
9140   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
9141 
9142   // Store the lo part of CONCAT_VECTORS(V1, V2)
9143   SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo);
9144   // Store the hi part of CONCAT_VECTORS(V1, V2)
9145   SDValue OffsetToV2 = DAG.getVScale(
9146       DL, PtrVT,
9147       APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
9148   SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2);
9149   SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo);
9150 
9151   if (Imm >= 0) {
9152     // Load back the required element. getVectorElementPointer takes care of
9153     // clamping the index if it's out-of-bounds.
9154     StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2));
9155     // Load the spliced result
9156     return DAG.getLoad(VT, DL, StoreV2, StackPtr,
9157                        MachinePointerInfo::getUnknownStack(MF));
9158   }
9159 
9160   uint64_t TrailingElts = -Imm;
9161 
9162   // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2.
9163   TypeSize EltByteSize = VT.getVectorElementType().getStoreSize();
9164   SDValue TrailingBytes =
9165       DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT);
9166 
9167   if (TrailingElts > VT.getVectorMinNumElements()) {
9168     SDValue VLBytes = DAG.getVScale(
9169         DL, PtrVT,
9170         APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
9171     TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes);
9172   }
9173 
9174   // Calculate the start address of the spliced result.
9175   StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
9176 
9177   // Load the spliced result
9178   return DAG.getLoad(VT, DL, StoreV2, StackPtr2,
9179                      MachinePointerInfo::getUnknownStack(MF));
9180 }
9181 
9182 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT,
9183                                            SDValue &LHS, SDValue &RHS,
9184                                            SDValue &CC, bool &NeedInvert,
9185                                            const SDLoc &dl, SDValue &Chain,
9186                                            bool IsSignaling) const {
9187   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9188   MVT OpVT = LHS.getSimpleValueType();
9189   ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
9190   NeedInvert = false;
9191   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
9192   default:
9193     llvm_unreachable("Unknown condition code action!");
9194   case TargetLowering::Legal:
9195     // Nothing to do.
9196     break;
9197   case TargetLowering::Expand: {
9198     ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
9199     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9200       std::swap(LHS, RHS);
9201       CC = DAG.getCondCode(InvCC);
9202       return true;
9203     }
9204     // Swapping operands didn't work. Try inverting the condition.
9205     bool NeedSwap = false;
9206     InvCC = getSetCCInverse(CCCode, OpVT);
9207     if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9208       // If inverting the condition is not enough, try swapping operands
9209       // on top of it.
9210       InvCC = ISD::getSetCCSwappedOperands(InvCC);
9211       NeedSwap = true;
9212     }
9213     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9214       CC = DAG.getCondCode(InvCC);
9215       NeedInvert = true;
9216       if (NeedSwap)
9217         std::swap(LHS, RHS);
9218       return true;
9219     }
9220 
9221     ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
9222     unsigned Opc = 0;
9223     switch (CCCode) {
9224     default:
9225       llvm_unreachable("Don't know how to expand this condition!");
9226     case ISD::SETUO:
9227       if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) {
9228         CC1 = ISD::SETUNE;
9229         CC2 = ISD::SETUNE;
9230         Opc = ISD::OR;
9231         break;
9232       }
9233       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
9234              "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
9235       NeedInvert = true;
9236       LLVM_FALLTHROUGH;
9237     case ISD::SETO:
9238       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
9239              "If SETO is expanded, SETOEQ must be legal!");
9240       CC1 = ISD::SETOEQ;
9241       CC2 = ISD::SETOEQ;
9242       Opc = ISD::AND;
9243       break;
9244     case ISD::SETONE:
9245     case ISD::SETUEQ:
9246       // If the SETUO or SETO CC isn't legal, we might be able to use
9247       // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
9248       // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
9249       // the operands.
9250       CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
9251       if (!TLI.isCondCodeLegal(CC2, OpVT) &&
9252           (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) ||
9253            TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) {
9254         CC1 = ISD::SETOGT;
9255         CC2 = ISD::SETOLT;
9256         Opc = ISD::OR;
9257         NeedInvert = ((unsigned)CCCode & 0x8U);
9258         break;
9259       }
9260       LLVM_FALLTHROUGH;
9261     case ISD::SETOEQ:
9262     case ISD::SETOGT:
9263     case ISD::SETOGE:
9264     case ISD::SETOLT:
9265     case ISD::SETOLE:
9266     case ISD::SETUNE:
9267     case ISD::SETUGT:
9268     case ISD::SETUGE:
9269     case ISD::SETULT:
9270     case ISD::SETULE:
9271       // If we are floating point, assign and break, otherwise fall through.
9272       if (!OpVT.isInteger()) {
9273         // We can use the 4th bit to tell if we are the unordered
9274         // or ordered version of the opcode.
9275         CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
9276         Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
9277         CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
9278         break;
9279       }
9280       // Fallthrough if we are unsigned integer.
9281       LLVM_FALLTHROUGH;
9282     case ISD::SETLE:
9283     case ISD::SETGT:
9284     case ISD::SETGE:
9285     case ISD::SETLT:
9286     case ISD::SETNE:
9287     case ISD::SETEQ:
9288       // If all combinations of inverting the condition and swapping operands
9289       // didn't work then we have no means to expand the condition.
9290       llvm_unreachable("Don't know how to expand this condition!");
9291     }
9292 
9293     SDValue SetCC1, SetCC2;
9294     if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
9295       // If we aren't the ordered or unorder operation,
9296       // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
9297       SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
9298       SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
9299     } else {
9300       // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
9301       SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
9302       SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
9303     }
9304     if (Chain)
9305       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
9306                           SetCC2.getValue(1));
9307     LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
9308     RHS = SDValue();
9309     CC = SDValue();
9310     return true;
9311   }
9312   }
9313   return false;
9314 }
9315