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/CodeGen/TargetSubtargetInfo.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/KnownBits.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include <cctype>
35 using namespace llvm;
36 
37 /// NOTE: The TargetMachine owns TLOF.
38 TargetLowering::TargetLowering(const TargetMachine &tm)
39     : TargetLoweringBase(tm) {}
40 
41 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
42   return nullptr;
43 }
44 
45 bool TargetLowering::isPositionIndependent() const {
46   return getTargetMachine().isPositionIndependent();
47 }
48 
49 /// Check whether a given call node is in tail position within its function. If
50 /// so, it sets Chain to the input chain of the tail call.
51 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
52                                           SDValue &Chain) const {
53   const Function &F = DAG.getMachineFunction().getFunction();
54 
55   // First, check if tail calls have been disabled in this function.
56   if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
57     return false;
58 
59   // Conservatively require the attributes of the call to match those of
60   // the return. Ignore following attributes because they don't affect the
61   // call sequence.
62   AttrBuilder CallerAttrs(F.getAttributes(), AttributeList::ReturnIndex);
63   for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable,
64                            Attribute::DereferenceableOrNull, Attribute::NoAlias,
65                            Attribute::NonNull})
66     CallerAttrs.removeAttribute(Attr);
67 
68   if (CallerAttrs.hasAttributes())
69     return false;
70 
71   // It's not safe to eliminate the sign / zero extension of the return value.
72   if (CallerAttrs.contains(Attribute::ZExt) ||
73       CallerAttrs.contains(Attribute::SExt))
74     return false;
75 
76   // Check if the only use is a function return node.
77   return isUsedByReturnOnly(Node, Chain);
78 }
79 
80 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
81     const uint32_t *CallerPreservedMask,
82     const SmallVectorImpl<CCValAssign> &ArgLocs,
83     const SmallVectorImpl<SDValue> &OutVals) const {
84   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
85     const CCValAssign &ArgLoc = ArgLocs[I];
86     if (!ArgLoc.isRegLoc())
87       continue;
88     MCRegister Reg = ArgLoc.getLocReg();
89     // Only look at callee saved registers.
90     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
91       continue;
92     // Check that we pass the value used for the caller.
93     // (We look for a CopyFromReg reading a virtual register that is used
94     //  for the function live-in value of register Reg)
95     SDValue Value = OutVals[I];
96     if (Value->getOpcode() != ISD::CopyFromReg)
97       return false;
98     Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
99     if (MRI.getLiveInPhysReg(ArgReg) != Reg)
100       return false;
101   }
102   return true;
103 }
104 
105 /// Set CallLoweringInfo attribute flags based on a call instruction
106 /// and called function attributes.
107 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call,
108                                                      unsigned ArgIdx) {
109   IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt);
110   IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt);
111   IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg);
112   IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet);
113   IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest);
114   IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal);
115   IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated);
116   IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca);
117   IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned);
118   IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
119   IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError);
120   Alignment = Call->getParamStackAlign(ArgIdx);
121   ByValType = nullptr;
122   if (IsByVal) {
123     ByValType = Call->getParamByValType(ArgIdx);
124     if (!Alignment)
125       Alignment = Call->getParamAlign(ArgIdx);
126   }
127   PreallocatedType = nullptr;
128   if (IsPreallocated)
129     PreallocatedType = Call->getParamPreallocatedType(ArgIdx);
130 }
131 
132 /// Generate a libcall taking the given operands as arguments and returning a
133 /// result of type RetVT.
134 std::pair<SDValue, SDValue>
135 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
136                             ArrayRef<SDValue> Ops,
137                             MakeLibCallOptions CallOptions,
138                             const SDLoc &dl,
139                             SDValue InChain) const {
140   if (!InChain)
141     InChain = DAG.getEntryNode();
142 
143   TargetLowering::ArgListTy Args;
144   Args.reserve(Ops.size());
145 
146   TargetLowering::ArgListEntry Entry;
147   for (unsigned i = 0; i < Ops.size(); ++i) {
148     SDValue NewOp = Ops[i];
149     Entry.Node = NewOp;
150     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
151     Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(),
152                                                  CallOptions.IsSExt);
153     Entry.IsZExt = !Entry.IsSExt;
154 
155     if (CallOptions.IsSoften &&
156         !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) {
157       Entry.IsSExt = Entry.IsZExt = false;
158     }
159     Args.push_back(Entry);
160   }
161 
162   if (LC == RTLIB::UNKNOWN_LIBCALL)
163     report_fatal_error("Unsupported library call operation!");
164   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
165                                          getPointerTy(DAG.getDataLayout()));
166 
167   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
168   TargetLowering::CallLoweringInfo CLI(DAG);
169   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt);
170   bool zeroExtend = !signExtend;
171 
172   if (CallOptions.IsSoften &&
173       !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) {
174     signExtend = zeroExtend = false;
175   }
176 
177   CLI.setDebugLoc(dl)
178       .setChain(InChain)
179       .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
180       .setNoReturn(CallOptions.DoesNotReturn)
181       .setDiscardResult(!CallOptions.IsReturnValueUsed)
182       .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization)
183       .setSExtResult(signExtend)
184       .setZExtResult(zeroExtend);
185   return LowerCallTo(CLI);
186 }
187 
188 bool TargetLowering::findOptimalMemOpLowering(
189     std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS,
190     unsigned SrcAS, const AttributeList &FuncAttributes) const {
191   if (Op.isMemcpyWithFixedDstAlign() && Op.getSrcAlign() < Op.getDstAlign())
192     return false;
193 
194   EVT VT = getOptimalMemOpType(Op, FuncAttributes);
195 
196   if (VT == MVT::Other) {
197     // Use the largest integer type whose alignment constraints are satisfied.
198     // We only need to check DstAlign here as SrcAlign is always greater or
199     // equal to DstAlign (or zero).
200     VT = MVT::i64;
201     if (Op.isFixedDstAlign())
202       while (Op.getDstAlign() < (VT.getSizeInBits() / 8) &&
203              !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign()))
204         VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
205     assert(VT.isInteger());
206 
207     // Find the largest legal integer type.
208     MVT LVT = MVT::i64;
209     while (!isTypeLegal(LVT))
210       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
211     assert(LVT.isInteger());
212 
213     // If the type we've chosen is larger than the largest legal integer type
214     // then use that instead.
215     if (VT.bitsGT(LVT))
216       VT = LVT;
217   }
218 
219   unsigned NumMemOps = 0;
220   uint64_t Size = Op.size();
221   while (Size) {
222     unsigned VTSize = VT.getSizeInBits() / 8;
223     while (VTSize > Size) {
224       // For now, only use non-vector load / store's for the left-over pieces.
225       EVT NewVT = VT;
226       unsigned NewVTSize;
227 
228       bool Found = false;
229       if (VT.isVector() || VT.isFloatingPoint()) {
230         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
231         if (isOperationLegalOrCustom(ISD::STORE, NewVT) &&
232             isSafeMemOpType(NewVT.getSimpleVT()))
233           Found = true;
234         else if (NewVT == MVT::i64 &&
235                  isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
236                  isSafeMemOpType(MVT::f64)) {
237           // i64 is usually not legal on 32-bit targets, but f64 may be.
238           NewVT = MVT::f64;
239           Found = true;
240         }
241       }
242 
243       if (!Found) {
244         do {
245           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
246           if (NewVT == MVT::i8)
247             break;
248         } while (!isSafeMemOpType(NewVT.getSimpleVT()));
249       }
250       NewVTSize = NewVT.getSizeInBits() / 8;
251 
252       // If the new VT cannot cover all of the remaining bits, then consider
253       // issuing a (or a pair of) unaligned and overlapping load / store.
254       bool Fast;
255       if (NumMemOps && Op.allowOverlap() && NewVTSize < Size &&
256           allowsMisalignedMemoryAccesses(
257               VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
258               MachineMemOperand::MONone, &Fast) &&
259           Fast)
260         VTSize = Size;
261       else {
262         VT = NewVT;
263         VTSize = NewVTSize;
264       }
265     }
266 
267     if (++NumMemOps > Limit)
268       return false;
269 
270     MemOps.push_back(VT);
271     Size -= VTSize;
272   }
273 
274   return true;
275 }
276 
277 /// Soften the operands of a comparison. This code is shared among BR_CC,
278 /// SELECT_CC, and SETCC handlers.
279 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
280                                          SDValue &NewLHS, SDValue &NewRHS,
281                                          ISD::CondCode &CCCode,
282                                          const SDLoc &dl, const SDValue OldLHS,
283                                          const SDValue OldRHS) const {
284   SDValue Chain;
285   return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
286                              OldRHS, Chain);
287 }
288 
289 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
290                                          SDValue &NewLHS, SDValue &NewRHS,
291                                          ISD::CondCode &CCCode,
292                                          const SDLoc &dl, const SDValue OldLHS,
293                                          const SDValue OldRHS,
294                                          SDValue &Chain,
295                                          bool IsSignaling) const {
296   // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
297   // not supporting it. We can update this code when libgcc provides such
298   // functions.
299 
300   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
301          && "Unsupported setcc type!");
302 
303   // Expand into one or more soft-fp libcall(s).
304   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
305   bool ShouldInvertCC = false;
306   switch (CCCode) {
307   case ISD::SETEQ:
308   case ISD::SETOEQ:
309     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
310           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
311           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
312     break;
313   case ISD::SETNE:
314   case ISD::SETUNE:
315     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
316           (VT == MVT::f64) ? RTLIB::UNE_F64 :
317           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
318     break;
319   case ISD::SETGE:
320   case ISD::SETOGE:
321     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
322           (VT == MVT::f64) ? RTLIB::OGE_F64 :
323           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
324     break;
325   case ISD::SETLT:
326   case ISD::SETOLT:
327     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
328           (VT == MVT::f64) ? RTLIB::OLT_F64 :
329           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
330     break;
331   case ISD::SETLE:
332   case ISD::SETOLE:
333     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
334           (VT == MVT::f64) ? RTLIB::OLE_F64 :
335           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
336     break;
337   case ISD::SETGT:
338   case ISD::SETOGT:
339     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
340           (VT == MVT::f64) ? RTLIB::OGT_F64 :
341           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
342     break;
343   case ISD::SETO:
344     ShouldInvertCC = true;
345     LLVM_FALLTHROUGH;
346   case ISD::SETUO:
347     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
348           (VT == MVT::f64) ? RTLIB::UO_F64 :
349           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
350     break;
351   case ISD::SETONE:
352     // SETONE = O && UNE
353     ShouldInvertCC = true;
354     LLVM_FALLTHROUGH;
355   case ISD::SETUEQ:
356     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
357           (VT == MVT::f64) ? RTLIB::UO_F64 :
358           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
359     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
360           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
361           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
362     break;
363   default:
364     // Invert CC for unordered comparisons
365     ShouldInvertCC = true;
366     switch (CCCode) {
367     case ISD::SETULT:
368       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
369             (VT == MVT::f64) ? RTLIB::OGE_F64 :
370             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
371       break;
372     case ISD::SETULE:
373       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
374             (VT == MVT::f64) ? RTLIB::OGT_F64 :
375             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
376       break;
377     case ISD::SETUGT:
378       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
379             (VT == MVT::f64) ? RTLIB::OLE_F64 :
380             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
381       break;
382     case ISD::SETUGE:
383       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
384             (VT == MVT::f64) ? RTLIB::OLT_F64 :
385             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
386       break;
387     default: llvm_unreachable("Do not know how to soften this setcc!");
388     }
389   }
390 
391   // Use the target specific return value for comparions lib calls.
392   EVT RetVT = getCmpLibcallReturnType();
393   SDValue Ops[2] = {NewLHS, NewRHS};
394   TargetLowering::MakeLibCallOptions CallOptions;
395   EVT OpsVT[2] = { OldLHS.getValueType(),
396                    OldRHS.getValueType() };
397   CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true);
398   auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain);
399   NewLHS = Call.first;
400   NewRHS = DAG.getConstant(0, dl, RetVT);
401 
402   CCCode = getCmpLibcallCC(LC1);
403   if (ShouldInvertCC) {
404     assert(RetVT.isInteger());
405     CCCode = getSetCCInverse(CCCode, RetVT);
406   }
407 
408   if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
409     // Update Chain.
410     Chain = Call.second;
411   } else {
412     EVT SetCCVT =
413         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
414     SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
415     auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain);
416     CCCode = getCmpLibcallCC(LC2);
417     if (ShouldInvertCC)
418       CCCode = getSetCCInverse(CCCode, RetVT);
419     NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
420     if (Chain)
421       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
422                           Call2.second);
423     NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
424                          Tmp.getValueType(), Tmp, NewLHS);
425     NewRHS = SDValue();
426   }
427 }
428 
429 /// Return the entry encoding for a jump table in the current function. The
430 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
431 unsigned TargetLowering::getJumpTableEncoding() const {
432   // In non-pic modes, just use the address of a block.
433   if (!isPositionIndependent())
434     return MachineJumpTableInfo::EK_BlockAddress;
435 
436   // In PIC mode, if the target supports a GPRel32 directive, use it.
437   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
438     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
439 
440   // Otherwise, use a label difference.
441   return MachineJumpTableInfo::EK_LabelDifference32;
442 }
443 
444 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
445                                                  SelectionDAG &DAG) const {
446   // If our PIC model is GP relative, use the global offset table as the base.
447   unsigned JTEncoding = getJumpTableEncoding();
448 
449   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
450       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
451     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
452 
453   return Table;
454 }
455 
456 /// This returns the relocation base for the given PIC jumptable, the same as
457 /// getPICJumpTableRelocBase, but as an MCExpr.
458 const MCExpr *
459 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
460                                              unsigned JTI,MCContext &Ctx) const{
461   // The normal PIC reloc base is the label at the start of the jump table.
462   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
463 }
464 
465 bool
466 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
467   const TargetMachine &TM = getTargetMachine();
468   const GlobalValue *GV = GA->getGlobal();
469 
470   // If the address is not even local to this DSO we will have to load it from
471   // a got and then add the offset.
472   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
473     return false;
474 
475   // If the code is position independent we will have to add a base register.
476   if (isPositionIndependent())
477     return false;
478 
479   // Otherwise we can do it.
480   return true;
481 }
482 
483 //===----------------------------------------------------------------------===//
484 //  Optimization Methods
485 //===----------------------------------------------------------------------===//
486 
487 /// If the specified instruction has a constant integer operand and there are
488 /// bits set in that constant that are not demanded, then clear those bits and
489 /// return true.
490 bool TargetLowering::ShrinkDemandedConstant(SDValue Op,
491                                             const APInt &DemandedBits,
492                                             const APInt &DemandedElts,
493                                             TargetLoweringOpt &TLO) const {
494   SDLoc DL(Op);
495   unsigned Opcode = Op.getOpcode();
496 
497   // Do target-specific constant optimization.
498   if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
499     return TLO.New.getNode();
500 
501   // FIXME: ISD::SELECT, ISD::SELECT_CC
502   switch (Opcode) {
503   default:
504     break;
505   case ISD::XOR:
506   case ISD::AND:
507   case ISD::OR: {
508     auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
509     if (!Op1C)
510       return false;
511 
512     // If this is a 'not' op, don't touch it because that's a canonical form.
513     const APInt &C = Op1C->getAPIntValue();
514     if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
515       return false;
516 
517     if (!C.isSubsetOf(DemandedBits)) {
518       EVT VT = Op.getValueType();
519       SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
520       SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
521       return TLO.CombineTo(Op, NewOp);
522     }
523 
524     break;
525   }
526   }
527 
528   return false;
529 }
530 
531 bool TargetLowering::ShrinkDemandedConstant(SDValue Op,
532                                             const APInt &DemandedBits,
533                                             TargetLoweringOpt &TLO) const {
534   EVT VT = Op.getValueType();
535   APInt DemandedElts = VT.isVector()
536                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
537                            : APInt(1, 1);
538   return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
539 }
540 
541 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
542 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
543 /// generalized for targets with other types of implicit widening casts.
544 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
545                                       const APInt &Demanded,
546                                       TargetLoweringOpt &TLO) const {
547   assert(Op.getNumOperands() == 2 &&
548          "ShrinkDemandedOp only supports binary operators!");
549   assert(Op.getNode()->getNumValues() == 1 &&
550          "ShrinkDemandedOp only supports nodes with one result!");
551 
552   SelectionDAG &DAG = TLO.DAG;
553   SDLoc dl(Op);
554 
555   // Early return, as this function cannot handle vector types.
556   if (Op.getValueType().isVector())
557     return false;
558 
559   // Don't do this if the node has another user, which may require the
560   // full value.
561   if (!Op.getNode()->hasOneUse())
562     return false;
563 
564   // Search for the smallest integer type with free casts to and from
565   // Op's type. For expedience, just check power-of-2 integer types.
566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
567   unsigned DemandedSize = Demanded.getActiveBits();
568   unsigned SmallVTBits = DemandedSize;
569   if (!isPowerOf2_32(SmallVTBits))
570     SmallVTBits = NextPowerOf2(SmallVTBits);
571   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
572     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
573     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
574         TLI.isZExtFree(SmallVT, Op.getValueType())) {
575       // We found a type with free casts.
576       SDValue X = DAG.getNode(
577           Op.getOpcode(), dl, SmallVT,
578           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
579           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)));
580       assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
581       SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X);
582       return TLO.CombineTo(Op, Z);
583     }
584   }
585   return false;
586 }
587 
588 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
589                                           DAGCombinerInfo &DCI) const {
590   SelectionDAG &DAG = DCI.DAG;
591   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
592                         !DCI.isBeforeLegalizeOps());
593   KnownBits Known;
594 
595   bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
596   if (Simplified) {
597     DCI.AddToWorklist(Op.getNode());
598     DCI.CommitTargetLoweringOpt(TLO);
599   }
600   return Simplified;
601 }
602 
603 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
604                                           KnownBits &Known,
605                                           TargetLoweringOpt &TLO,
606                                           unsigned Depth,
607                                           bool AssumeSingleUse) const {
608   EVT VT = Op.getValueType();
609 
610   // TODO: We can probably do more work on calculating the known bits and
611   // simplifying the operations for scalable vectors, but for now we just
612   // bail out.
613   if (VT.isScalableVector()) {
614     // Pretend we don't know anything for now.
615     Known = KnownBits(DemandedBits.getBitWidth());
616     return false;
617   }
618 
619   APInt DemandedElts = VT.isVector()
620                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
621                            : APInt(1, 1);
622   return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
623                               AssumeSingleUse);
624 }
625 
626 // TODO: Can we merge SelectionDAG::GetDemandedBits into this?
627 // TODO: Under what circumstances can we create nodes? Constant folding?
628 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
629     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
630     SelectionDAG &DAG, unsigned Depth) const {
631   // Limit search depth.
632   if (Depth >= SelectionDAG::MaxRecursionDepth)
633     return SDValue();
634 
635   // Ignore UNDEFs.
636   if (Op.isUndef())
637     return SDValue();
638 
639   // Not demanding any bits/elts from Op.
640   if (DemandedBits == 0 || DemandedElts == 0)
641     return DAG.getUNDEF(Op.getValueType());
642 
643   unsigned NumElts = DemandedElts.getBitWidth();
644   unsigned BitWidth = DemandedBits.getBitWidth();
645   KnownBits LHSKnown, RHSKnown;
646   switch (Op.getOpcode()) {
647   case ISD::BITCAST: {
648     SDValue Src = peekThroughBitcasts(Op.getOperand(0));
649     EVT SrcVT = Src.getValueType();
650     EVT DstVT = Op.getValueType();
651     if (SrcVT == DstVT)
652       return Src;
653 
654     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
655     unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
656     if (NumSrcEltBits == NumDstEltBits)
657       if (SDValue V = SimplifyMultipleUseDemandedBits(
658               Src, DemandedBits, DemandedElts, DAG, Depth + 1))
659         return DAG.getBitcast(DstVT, V);
660 
661     // TODO - bigendian once we have test coverage.
662     if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0 &&
663         DAG.getDataLayout().isLittleEndian()) {
664       unsigned Scale = NumDstEltBits / NumSrcEltBits;
665       unsigned NumSrcElts = SrcVT.getVectorNumElements();
666       APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
667       APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
668       for (unsigned i = 0; i != Scale; ++i) {
669         unsigned Offset = i * NumSrcEltBits;
670         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset);
671         if (!Sub.isNullValue()) {
672           DemandedSrcBits |= Sub;
673           for (unsigned j = 0; j != NumElts; ++j)
674             if (DemandedElts[j])
675               DemandedSrcElts.setBit((j * Scale) + i);
676         }
677       }
678 
679       if (SDValue V = SimplifyMultipleUseDemandedBits(
680               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
681         return DAG.getBitcast(DstVT, V);
682     }
683 
684     // TODO - bigendian once we have test coverage.
685     if ((NumSrcEltBits % NumDstEltBits) == 0 &&
686         DAG.getDataLayout().isLittleEndian()) {
687       unsigned Scale = NumSrcEltBits / NumDstEltBits;
688       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
689       APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
690       APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
691       for (unsigned i = 0; i != NumElts; ++i)
692         if (DemandedElts[i]) {
693           unsigned Offset = (i % Scale) * NumDstEltBits;
694           DemandedSrcBits.insertBits(DemandedBits, Offset);
695           DemandedSrcElts.setBit(i / Scale);
696         }
697 
698       if (SDValue V = SimplifyMultipleUseDemandedBits(
699               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
700         return DAG.getBitcast(DstVT, V);
701     }
702 
703     break;
704   }
705   case ISD::AND: {
706     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
707     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
708 
709     // If all of the demanded bits are known 1 on one side, return the other.
710     // These bits cannot contribute to the result of the 'and' in this
711     // context.
712     if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
713       return Op.getOperand(0);
714     if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
715       return Op.getOperand(1);
716     break;
717   }
718   case ISD::OR: {
719     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
720     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
721 
722     // If all of the demanded bits are known zero on one side, return the
723     // other.  These bits cannot contribute to the result of the 'or' in this
724     // context.
725     if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
726       return Op.getOperand(0);
727     if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
728       return Op.getOperand(1);
729     break;
730   }
731   case ISD::XOR: {
732     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
733     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
734 
735     // If all of the demanded bits are known zero on one side, return the
736     // other.
737     if (DemandedBits.isSubsetOf(RHSKnown.Zero))
738       return Op.getOperand(0);
739     if (DemandedBits.isSubsetOf(LHSKnown.Zero))
740       return Op.getOperand(1);
741     break;
742   }
743   case ISD::SHL: {
744     // If we are only demanding sign bits then we can use the shift source
745     // directly.
746     if (const APInt *MaxSA =
747             DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
748       SDValue Op0 = Op.getOperand(0);
749       unsigned ShAmt = MaxSA->getZExtValue();
750       unsigned NumSignBits =
751           DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
752       unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
753       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
754         return Op0;
755     }
756     break;
757   }
758   case ISD::SETCC: {
759     SDValue Op0 = Op.getOperand(0);
760     SDValue Op1 = Op.getOperand(1);
761     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
762     // If (1) we only need the sign-bit, (2) the setcc operands are the same
763     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
764     // -1, we may be able to bypass the setcc.
765     if (DemandedBits.isSignMask() &&
766         Op0.getScalarValueSizeInBits() == BitWidth &&
767         getBooleanContents(Op0.getValueType()) ==
768             BooleanContent::ZeroOrNegativeOneBooleanContent) {
769       // If we're testing X < 0, then this compare isn't needed - just use X!
770       // FIXME: We're limiting to integer types here, but this should also work
771       // if we don't care about FP signed-zero. The use of SETLT with FP means
772       // that we don't care about NaNs.
773       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
774           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
775         return Op0;
776     }
777     break;
778   }
779   case ISD::SIGN_EXTEND_INREG: {
780     // If none of the extended bits are demanded, eliminate the sextinreg.
781     SDValue Op0 = Op.getOperand(0);
782     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
783     unsigned ExBits = ExVT.getScalarSizeInBits();
784     if (DemandedBits.getActiveBits() <= ExBits)
785       return Op0;
786     // If the input is already sign extended, just drop the extension.
787     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
788     if (NumSignBits >= (BitWidth - ExBits + 1))
789       return Op0;
790     break;
791   }
792   case ISD::ANY_EXTEND_VECTOR_INREG:
793   case ISD::SIGN_EXTEND_VECTOR_INREG:
794   case ISD::ZERO_EXTEND_VECTOR_INREG: {
795     // If we only want the lowest element and none of extended bits, then we can
796     // return the bitcasted source vector.
797     SDValue Src = Op.getOperand(0);
798     EVT SrcVT = Src.getValueType();
799     EVT DstVT = Op.getValueType();
800     if (DemandedElts == 1 && DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
801         DAG.getDataLayout().isLittleEndian() &&
802         DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
803       return DAG.getBitcast(DstVT, Src);
804     }
805     break;
806   }
807   case ISD::INSERT_VECTOR_ELT: {
808     // If we don't demand the inserted element, return the base vector.
809     SDValue Vec = Op.getOperand(0);
810     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
811     EVT VecVT = Vec.getValueType();
812     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
813         !DemandedElts[CIdx->getZExtValue()])
814       return Vec;
815     break;
816   }
817   case ISD::INSERT_SUBVECTOR: {
818     // If we don't demand the inserted subvector, return the base vector.
819     SDValue Vec = Op.getOperand(0);
820     SDValue Sub = Op.getOperand(1);
821     uint64_t Idx = Op.getConstantOperandVal(2);
822     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
823     if (DemandedElts.extractBits(NumSubElts, Idx) == 0)
824       return Vec;
825     break;
826   }
827   case ISD::VECTOR_SHUFFLE: {
828     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
829 
830     // If all the demanded elts are from one operand and are inline,
831     // then we can use the operand directly.
832     bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
833     for (unsigned i = 0; i != NumElts; ++i) {
834       int M = ShuffleMask[i];
835       if (M < 0 || !DemandedElts[i])
836         continue;
837       AllUndef = false;
838       IdentityLHS &= (M == (int)i);
839       IdentityRHS &= ((M - NumElts) == i);
840     }
841 
842     if (AllUndef)
843       return DAG.getUNDEF(Op.getValueType());
844     if (IdentityLHS)
845       return Op.getOperand(0);
846     if (IdentityRHS)
847       return Op.getOperand(1);
848     break;
849   }
850   default:
851     if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
852       if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode(
853               Op, DemandedBits, DemandedElts, DAG, Depth))
854         return V;
855     break;
856   }
857   return SDValue();
858 }
859 
860 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
861     SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG,
862     unsigned Depth) const {
863   EVT VT = Op.getValueType();
864   APInt DemandedElts = VT.isVector()
865                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
866                            : APInt(1, 1);
867   return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
868                                          Depth);
869 }
870 
871 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts(
872     SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
873     unsigned Depth) const {
874   APInt DemandedBits = APInt::getAllOnesValue(Op.getScalarValueSizeInBits());
875   return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
876                                          Depth);
877 }
878 
879 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the
880 /// result of Op are ever used downstream. If we can use this information to
881 /// simplify Op, create a new simplified DAG node and return true, returning the
882 /// original and new nodes in Old and New. Otherwise, analyze the expression and
883 /// return a mask of Known bits for the expression (used to simplify the
884 /// caller).  The Known bits may only be accurate for those bits in the
885 /// OriginalDemandedBits and OriginalDemandedElts.
886 bool TargetLowering::SimplifyDemandedBits(
887     SDValue Op, const APInt &OriginalDemandedBits,
888     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
889     unsigned Depth, bool AssumeSingleUse) const {
890   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
891   assert(Op.getScalarValueSizeInBits() == BitWidth &&
892          "Mask size mismatches value type size!");
893 
894   // Don't know anything.
895   Known = KnownBits(BitWidth);
896 
897   // TODO: We can probably do more work on calculating the known bits and
898   // simplifying the operations for scalable vectors, but for now we just
899   // bail out.
900   if (Op.getValueType().isScalableVector())
901     return false;
902 
903   unsigned NumElts = OriginalDemandedElts.getBitWidth();
904   assert((!Op.getValueType().isVector() ||
905           NumElts == Op.getValueType().getVectorNumElements()) &&
906          "Unexpected vector size");
907 
908   APInt DemandedBits = OriginalDemandedBits;
909   APInt DemandedElts = OriginalDemandedElts;
910   SDLoc dl(Op);
911   auto &DL = TLO.DAG.getDataLayout();
912 
913   // Undef operand.
914   if (Op.isUndef())
915     return false;
916 
917   if (Op.getOpcode() == ISD::Constant) {
918     // We know all of the bits for a constant!
919     Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue());
920     return false;
921   }
922 
923   if (Op.getOpcode() == ISD::ConstantFP) {
924     // We know all of the bits for a floating point constant!
925     Known = KnownBits::makeConstant(
926         cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
927     return false;
928   }
929 
930   // Other users may use these bits.
931   EVT VT = Op.getValueType();
932   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
933     if (Depth != 0) {
934       // If not at the root, Just compute the Known bits to
935       // simplify things downstream.
936       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
937       return false;
938     }
939     // If this is the root being simplified, allow it to have multiple uses,
940     // just set the DemandedBits/Elts to all bits.
941     DemandedBits = APInt::getAllOnesValue(BitWidth);
942     DemandedElts = APInt::getAllOnesValue(NumElts);
943   } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
944     // Not demanding any bits/elts from Op.
945     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
946   } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
947     // Limit search depth.
948     return false;
949   }
950 
951   KnownBits Known2;
952   switch (Op.getOpcode()) {
953   case ISD::TargetConstant:
954     llvm_unreachable("Can't simplify this node");
955   case ISD::SCALAR_TO_VECTOR: {
956     if (!DemandedElts[0])
957       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
958 
959     KnownBits SrcKnown;
960     SDValue Src = Op.getOperand(0);
961     unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
962     APInt SrcDemandedBits = DemandedBits.zextOrSelf(SrcBitWidth);
963     if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
964       return true;
965 
966     // Upper elements are undef, so only get the knownbits if we just demand
967     // the bottom element.
968     if (DemandedElts == 1)
969       Known = SrcKnown.anyextOrTrunc(BitWidth);
970     break;
971   }
972   case ISD::BUILD_VECTOR:
973     // Collect the known bits that are shared by every demanded element.
974     // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
975     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
976     return false; // Don't fall through, will infinitely loop.
977   case ISD::LOAD: {
978     auto *LD = cast<LoadSDNode>(Op);
979     if (getTargetConstantFromLoad(LD)) {
980       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
981       return false; // Don't fall through, will infinitely loop.
982     }
983     if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
984       // If this is a ZEXTLoad and we are looking at the loaded value.
985       EVT MemVT = LD->getMemoryVT();
986       unsigned MemBits = MemVT.getScalarSizeInBits();
987       Known.Zero.setBitsFrom(MemBits);
988       return false; // Don't fall through, will infinitely loop.
989     }
990     break;
991   }
992   case ISD::INSERT_VECTOR_ELT: {
993     SDValue Vec = Op.getOperand(0);
994     SDValue Scl = Op.getOperand(1);
995     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
996     EVT VecVT = Vec.getValueType();
997 
998     // If index isn't constant, assume we need all vector elements AND the
999     // inserted element.
1000     APInt DemandedVecElts(DemandedElts);
1001     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1002       unsigned Idx = CIdx->getZExtValue();
1003       DemandedVecElts.clearBit(Idx);
1004 
1005       // Inserted element is not required.
1006       if (!DemandedElts[Idx])
1007         return TLO.CombineTo(Op, Vec);
1008     }
1009 
1010     KnownBits KnownScl;
1011     unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1012     APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1013     if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1014       return true;
1015 
1016     Known = KnownScl.anyextOrTrunc(BitWidth);
1017 
1018     KnownBits KnownVec;
1019     if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1020                              Depth + 1))
1021       return true;
1022 
1023     if (!!DemandedVecElts)
1024       Known = KnownBits::commonBits(Known, KnownVec);
1025 
1026     return false;
1027   }
1028   case ISD::INSERT_SUBVECTOR: {
1029     // Demand any elements from the subvector and the remainder from the src its
1030     // inserted into.
1031     SDValue Src = Op.getOperand(0);
1032     SDValue Sub = Op.getOperand(1);
1033     uint64_t Idx = Op.getConstantOperandVal(2);
1034     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1035     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1036     APInt DemandedSrcElts = DemandedElts;
1037     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
1038 
1039     KnownBits KnownSub, KnownSrc;
1040     if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1041                              Depth + 1))
1042       return true;
1043     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1044                              Depth + 1))
1045       return true;
1046 
1047     Known.Zero.setAllBits();
1048     Known.One.setAllBits();
1049     if (!!DemandedSubElts)
1050       Known = KnownBits::commonBits(Known, KnownSub);
1051     if (!!DemandedSrcElts)
1052       Known = KnownBits::commonBits(Known, KnownSrc);
1053 
1054     // Attempt to avoid multi-use src if we don't need anything from it.
1055     if (!DemandedBits.isAllOnesValue() || !DemandedSubElts.isAllOnesValue() ||
1056         !DemandedSrcElts.isAllOnesValue()) {
1057       SDValue NewSub = SimplifyMultipleUseDemandedBits(
1058           Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1059       SDValue NewSrc = SimplifyMultipleUseDemandedBits(
1060           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1061       if (NewSub || NewSrc) {
1062         NewSub = NewSub ? NewSub : Sub;
1063         NewSrc = NewSrc ? NewSrc : Src;
1064         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1065                                         Op.getOperand(2));
1066         return TLO.CombineTo(Op, NewOp);
1067       }
1068     }
1069     break;
1070   }
1071   case ISD::EXTRACT_SUBVECTOR: {
1072     // Offset the demanded elts by the subvector index.
1073     SDValue Src = Op.getOperand(0);
1074     if (Src.getValueType().isScalableVector())
1075       break;
1076     uint64_t Idx = Op.getConstantOperandVal(1);
1077     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1078     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
1079 
1080     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1081                              Depth + 1))
1082       return true;
1083 
1084     // Attempt to avoid multi-use src if we don't need anything from it.
1085     if (!DemandedBits.isAllOnesValue() || !DemandedSrcElts.isAllOnesValue()) {
1086       SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
1087           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1088       if (DemandedSrc) {
1089         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1090                                         Op.getOperand(1));
1091         return TLO.CombineTo(Op, NewOp);
1092       }
1093     }
1094     break;
1095   }
1096   case ISD::CONCAT_VECTORS: {
1097     Known.Zero.setAllBits();
1098     Known.One.setAllBits();
1099     EVT SubVT = Op.getOperand(0).getValueType();
1100     unsigned NumSubVecs = Op.getNumOperands();
1101     unsigned NumSubElts = SubVT.getVectorNumElements();
1102     for (unsigned i = 0; i != NumSubVecs; ++i) {
1103       APInt DemandedSubElts =
1104           DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1105       if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1106                                Known2, TLO, Depth + 1))
1107         return true;
1108       // Known bits are shared by every demanded subvector element.
1109       if (!!DemandedSubElts)
1110         Known = KnownBits::commonBits(Known, Known2);
1111     }
1112     break;
1113   }
1114   case ISD::VECTOR_SHUFFLE: {
1115     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1116 
1117     // Collect demanded elements from shuffle operands..
1118     APInt DemandedLHS(NumElts, 0);
1119     APInt DemandedRHS(NumElts, 0);
1120     for (unsigned i = 0; i != NumElts; ++i) {
1121       if (!DemandedElts[i])
1122         continue;
1123       int M = ShuffleMask[i];
1124       if (M < 0) {
1125         // For UNDEF elements, we don't know anything about the common state of
1126         // the shuffle result.
1127         DemandedLHS.clearAllBits();
1128         DemandedRHS.clearAllBits();
1129         break;
1130       }
1131       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
1132       if (M < (int)NumElts)
1133         DemandedLHS.setBit(M);
1134       else
1135         DemandedRHS.setBit(M - NumElts);
1136     }
1137 
1138     if (!!DemandedLHS || !!DemandedRHS) {
1139       SDValue Op0 = Op.getOperand(0);
1140       SDValue Op1 = Op.getOperand(1);
1141 
1142       Known.Zero.setAllBits();
1143       Known.One.setAllBits();
1144       if (!!DemandedLHS) {
1145         if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1146                                  Depth + 1))
1147           return true;
1148         Known = KnownBits::commonBits(Known, Known2);
1149       }
1150       if (!!DemandedRHS) {
1151         if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1152                                  Depth + 1))
1153           return true;
1154         Known = KnownBits::commonBits(Known, Known2);
1155       }
1156 
1157       // Attempt to avoid multi-use ops if we don't need anything from them.
1158       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1159           Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1160       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1161           Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1162       if (DemandedOp0 || DemandedOp1) {
1163         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1164         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1165         SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1166         return TLO.CombineTo(Op, NewOp);
1167       }
1168     }
1169     break;
1170   }
1171   case ISD::AND: {
1172     SDValue Op0 = Op.getOperand(0);
1173     SDValue Op1 = Op.getOperand(1);
1174 
1175     // If the RHS is a constant, check to see if the LHS would be zero without
1176     // using the bits from the RHS.  Below, we use knowledge about the RHS to
1177     // simplify the LHS, here we're using information from the LHS to simplify
1178     // the RHS.
1179     if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) {
1180       // Do not increment Depth here; that can cause an infinite loop.
1181       KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1182       // If the LHS already has zeros where RHSC does, this 'and' is dead.
1183       if ((LHSKnown.Zero & DemandedBits) ==
1184           (~RHSC->getAPIntValue() & DemandedBits))
1185         return TLO.CombineTo(Op, Op0);
1186 
1187       // If any of the set bits in the RHS are known zero on the LHS, shrink
1188       // the constant.
1189       if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1190                                  DemandedElts, TLO))
1191         return true;
1192 
1193       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1194       // constant, but if this 'and' is only clearing bits that were just set by
1195       // the xor, then this 'and' can be eliminated by shrinking the mask of
1196       // the xor. For example, for a 32-bit X:
1197       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1198       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1199           LHSKnown.One == ~RHSC->getAPIntValue()) {
1200         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1201         return TLO.CombineTo(Op, Xor);
1202       }
1203     }
1204 
1205     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1206                              Depth + 1))
1207       return true;
1208     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1209     if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1210                              Known2, TLO, Depth + 1))
1211       return true;
1212     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1213 
1214     // Attempt to avoid multi-use ops if we don't need anything from them.
1215     if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1216       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1217           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1218       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1219           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1220       if (DemandedOp0 || DemandedOp1) {
1221         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1222         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1223         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1224         return TLO.CombineTo(Op, NewOp);
1225       }
1226     }
1227 
1228     // If all of the demanded bits are known one on one side, return the other.
1229     // These bits cannot contribute to the result of the 'and'.
1230     if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
1231       return TLO.CombineTo(Op, Op0);
1232     if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1233       return TLO.CombineTo(Op, Op1);
1234     // If all of the demanded bits in the inputs are known zeros, return zero.
1235     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1236       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1237     // If the RHS is a constant, see if we can simplify it.
1238     if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1239                                TLO))
1240       return true;
1241     // If the operation can be done in a smaller type, do so.
1242     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1243       return true;
1244 
1245     Known &= Known2;
1246     break;
1247   }
1248   case ISD::OR: {
1249     SDValue Op0 = Op.getOperand(0);
1250     SDValue Op1 = Op.getOperand(1);
1251 
1252     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1253                              Depth + 1))
1254       return true;
1255     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1256     if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1257                              Known2, TLO, Depth + 1))
1258       return true;
1259     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1260 
1261     // Attempt to avoid multi-use ops if we don't need anything from them.
1262     if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1263       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1264           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1265       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1266           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1267       if (DemandedOp0 || DemandedOp1) {
1268         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1269         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1270         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1271         return TLO.CombineTo(Op, NewOp);
1272       }
1273     }
1274 
1275     // If all of the demanded bits are known zero on one side, return the other.
1276     // These bits cannot contribute to the result of the 'or'.
1277     if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
1278       return TLO.CombineTo(Op, Op0);
1279     if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1280       return TLO.CombineTo(Op, Op1);
1281     // If the RHS is a constant, see if we can simplify it.
1282     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1283       return true;
1284     // If the operation can be done in a smaller type, do so.
1285     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1286       return true;
1287 
1288     Known |= Known2;
1289     break;
1290   }
1291   case ISD::XOR: {
1292     SDValue Op0 = Op.getOperand(0);
1293     SDValue Op1 = Op.getOperand(1);
1294 
1295     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1296                              Depth + 1))
1297       return true;
1298     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1299     if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1300                              Depth + 1))
1301       return true;
1302     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1303 
1304     // Attempt to avoid multi-use ops if we don't need anything from them.
1305     if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1306       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1307           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1308       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1309           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1310       if (DemandedOp0 || DemandedOp1) {
1311         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1312         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1313         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1314         return TLO.CombineTo(Op, NewOp);
1315       }
1316     }
1317 
1318     // If all of the demanded bits are known zero on one side, return the other.
1319     // These bits cannot contribute to the result of the 'xor'.
1320     if (DemandedBits.isSubsetOf(Known.Zero))
1321       return TLO.CombineTo(Op, Op0);
1322     if (DemandedBits.isSubsetOf(Known2.Zero))
1323       return TLO.CombineTo(Op, Op1);
1324     // If the operation can be done in a smaller type, do so.
1325     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1326       return true;
1327 
1328     // If all of the unknown bits are known to be zero on one side or the other
1329     // turn this into an *inclusive* or.
1330     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1331     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1332       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1333 
1334     ConstantSDNode* C = isConstOrConstSplat(Op1, DemandedElts);
1335     if (C) {
1336       // If one side is a constant, and all of the set bits in the constant are
1337       // also known set on the other side, turn this into an AND, as we know
1338       // the bits will be cleared.
1339       //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1340       // NB: it is okay if more bits are known than are requested
1341       if (C->getAPIntValue() == Known2.One) {
1342         SDValue ANDC =
1343             TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1344         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1345       }
1346 
1347       // If the RHS is a constant, see if we can change it. Don't alter a -1
1348       // constant because that's a 'not' op, and that is better for combining
1349       // and codegen.
1350       if (!C->isAllOnesValue() &&
1351           DemandedBits.isSubsetOf(C->getAPIntValue())) {
1352         // We're flipping all demanded bits. Flip the undemanded bits too.
1353         SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1354         return TLO.CombineTo(Op, New);
1355       }
1356     }
1357 
1358     // If we can't turn this into a 'not', try to shrink the constant.
1359     if (!C || !C->isAllOnesValue())
1360       if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1361         return true;
1362 
1363     Known ^= Known2;
1364     break;
1365   }
1366   case ISD::SELECT:
1367     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO,
1368                              Depth + 1))
1369       return true;
1370     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO,
1371                              Depth + 1))
1372       return true;
1373     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1374     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1375 
1376     // If the operands are constants, see if we can simplify them.
1377     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1378       return true;
1379 
1380     // Only known if known in both the LHS and RHS.
1381     Known = KnownBits::commonBits(Known, Known2);
1382     break;
1383   case ISD::SELECT_CC:
1384     if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO,
1385                              Depth + 1))
1386       return true;
1387     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO,
1388                              Depth + 1))
1389       return true;
1390     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1391     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1392 
1393     // If the operands are constants, see if we can simplify them.
1394     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1395       return true;
1396 
1397     // Only known if known in both the LHS and RHS.
1398     Known = KnownBits::commonBits(Known, Known2);
1399     break;
1400   case ISD::SETCC: {
1401     SDValue Op0 = Op.getOperand(0);
1402     SDValue Op1 = Op.getOperand(1);
1403     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1404     // If (1) we only need the sign-bit, (2) the setcc operands are the same
1405     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1406     // -1, we may be able to bypass the setcc.
1407     if (DemandedBits.isSignMask() &&
1408         Op0.getScalarValueSizeInBits() == BitWidth &&
1409         getBooleanContents(Op0.getValueType()) ==
1410             BooleanContent::ZeroOrNegativeOneBooleanContent) {
1411       // If we're testing X < 0, then this compare isn't needed - just use X!
1412       // FIXME: We're limiting to integer types here, but this should also work
1413       // if we don't care about FP signed-zero. The use of SETLT with FP means
1414       // that we don't care about NaNs.
1415       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1416           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
1417         return TLO.CombineTo(Op, Op0);
1418 
1419       // TODO: Should we check for other forms of sign-bit comparisons?
1420       // Examples: X <= -1, X >= 0
1421     }
1422     if (getBooleanContents(Op0.getValueType()) ==
1423             TargetLowering::ZeroOrOneBooleanContent &&
1424         BitWidth > 1)
1425       Known.Zero.setBitsFrom(1);
1426     break;
1427   }
1428   case ISD::SHL: {
1429     SDValue Op0 = Op.getOperand(0);
1430     SDValue Op1 = Op.getOperand(1);
1431     EVT ShiftVT = Op1.getValueType();
1432 
1433     if (const APInt *SA =
1434             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1435       unsigned ShAmt = SA->getZExtValue();
1436       if (ShAmt == 0)
1437         return TLO.CombineTo(Op, Op0);
1438 
1439       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1440       // single shift.  We can do this if the bottom bits (which are shifted
1441       // out) are never demanded.
1442       // TODO - support non-uniform vector amounts.
1443       if (Op0.getOpcode() == ISD::SRL) {
1444         if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
1445           if (const APInt *SA2 =
1446                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1447             unsigned C1 = SA2->getZExtValue();
1448             unsigned Opc = ISD::SHL;
1449             int Diff = ShAmt - C1;
1450             if (Diff < 0) {
1451               Diff = -Diff;
1452               Opc = ISD::SRL;
1453             }
1454             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1455             return TLO.CombineTo(
1456                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1457           }
1458         }
1459       }
1460 
1461       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1462       // are not demanded. This will likely allow the anyext to be folded away.
1463       // TODO - support non-uniform vector amounts.
1464       if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1465         SDValue InnerOp = Op0.getOperand(0);
1466         EVT InnerVT = InnerOp.getValueType();
1467         unsigned InnerBits = InnerVT.getScalarSizeInBits();
1468         if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1469             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1470           EVT ShTy = getShiftAmountTy(InnerVT, DL);
1471           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
1472             ShTy = InnerVT;
1473           SDValue NarrowShl =
1474               TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
1475                               TLO.DAG.getConstant(ShAmt, dl, ShTy));
1476           return TLO.CombineTo(
1477               Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1478         }
1479 
1480         // Repeat the SHL optimization above in cases where an extension
1481         // intervenes: (shl (anyext (shr x, c1)), c2) to
1482         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
1483         // aren't demanded (as above) and that the shifted upper c1 bits of
1484         // x aren't demanded.
1485         // TODO - support non-uniform vector amounts.
1486         if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL &&
1487             InnerOp.hasOneUse()) {
1488           if (const APInt *SA2 =
1489                   TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) {
1490             unsigned InnerShAmt = SA2->getZExtValue();
1491             if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1492                 DemandedBits.getActiveBits() <=
1493                     (InnerBits - InnerShAmt + ShAmt) &&
1494                 DemandedBits.countTrailingZeros() >= ShAmt) {
1495               SDValue NewSA =
1496                   TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
1497               SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1498                                                InnerOp.getOperand(0));
1499               return TLO.CombineTo(
1500                   Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1501             }
1502           }
1503         }
1504       }
1505 
1506       APInt InDemandedMask = DemandedBits.lshr(ShAmt);
1507       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1508                                Depth + 1))
1509         return true;
1510       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1511       Known.Zero <<= ShAmt;
1512       Known.One <<= ShAmt;
1513       // low bits known zero.
1514       Known.Zero.setLowBits(ShAmt);
1515 
1516       // Try shrinking the operation as long as the shift amount will still be
1517       // in range.
1518       if ((ShAmt < DemandedBits.getActiveBits()) &&
1519           ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1520         return true;
1521     }
1522 
1523     // If we are only demanding sign bits then we can use the shift source
1524     // directly.
1525     if (const APInt *MaxSA =
1526             TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
1527       unsigned ShAmt = MaxSA->getZExtValue();
1528       unsigned NumSignBits =
1529           TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1530       unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
1531       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
1532         return TLO.CombineTo(Op, Op0);
1533     }
1534     break;
1535   }
1536   case ISD::SRL: {
1537     SDValue Op0 = Op.getOperand(0);
1538     SDValue Op1 = Op.getOperand(1);
1539     EVT ShiftVT = Op1.getValueType();
1540 
1541     if (const APInt *SA =
1542             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1543       unsigned ShAmt = SA->getZExtValue();
1544       if (ShAmt == 0)
1545         return TLO.CombineTo(Op, Op0);
1546 
1547       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1548       // single shift.  We can do this if the top bits (which are shifted out)
1549       // are never demanded.
1550       // TODO - support non-uniform vector amounts.
1551       if (Op0.getOpcode() == ISD::SHL) {
1552         if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
1553           if (const APInt *SA2 =
1554                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1555             unsigned C1 = SA2->getZExtValue();
1556             unsigned Opc = ISD::SRL;
1557             int Diff = ShAmt - C1;
1558             if (Diff < 0) {
1559               Diff = -Diff;
1560               Opc = ISD::SHL;
1561             }
1562             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1563             return TLO.CombineTo(
1564                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1565           }
1566         }
1567       }
1568 
1569       APInt InDemandedMask = (DemandedBits << ShAmt);
1570 
1571       // If the shift is exact, then it does demand the low bits (and knows that
1572       // they are zero).
1573       if (Op->getFlags().hasExact())
1574         InDemandedMask.setLowBits(ShAmt);
1575 
1576       // Compute the new bits that are at the top now.
1577       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1578                                Depth + 1))
1579         return true;
1580       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1581       Known.Zero.lshrInPlace(ShAmt);
1582       Known.One.lshrInPlace(ShAmt);
1583       // High bits known zero.
1584       Known.Zero.setHighBits(ShAmt);
1585     }
1586     break;
1587   }
1588   case ISD::SRA: {
1589     SDValue Op0 = Op.getOperand(0);
1590     SDValue Op1 = Op.getOperand(1);
1591     EVT ShiftVT = Op1.getValueType();
1592 
1593     // If we only want bits that already match the signbit then we don't need
1594     // to shift.
1595     unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
1596     if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
1597         NumHiDemandedBits)
1598       return TLO.CombineTo(Op, Op0);
1599 
1600     // If this is an arithmetic shift right and only the low-bit is set, we can
1601     // always convert this into a logical shr, even if the shift amount is
1602     // variable.  The low bit of the shift cannot be an input sign bit unless
1603     // the shift amount is >= the size of the datatype, which is undefined.
1604     if (DemandedBits.isOneValue())
1605       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
1606 
1607     if (const APInt *SA =
1608             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1609       unsigned ShAmt = SA->getZExtValue();
1610       if (ShAmt == 0)
1611         return TLO.CombineTo(Op, Op0);
1612 
1613       APInt InDemandedMask = (DemandedBits << ShAmt);
1614 
1615       // If the shift is exact, then it does demand the low bits (and knows that
1616       // they are zero).
1617       if (Op->getFlags().hasExact())
1618         InDemandedMask.setLowBits(ShAmt);
1619 
1620       // If any of the demanded bits are produced by the sign extension, we also
1621       // demand the input sign bit.
1622       if (DemandedBits.countLeadingZeros() < ShAmt)
1623         InDemandedMask.setSignBit();
1624 
1625       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1626                                Depth + 1))
1627         return true;
1628       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1629       Known.Zero.lshrInPlace(ShAmt);
1630       Known.One.lshrInPlace(ShAmt);
1631 
1632       // If the input sign bit is known to be zero, or if none of the top bits
1633       // are demanded, turn this into an unsigned shift right.
1634       if (Known.Zero[BitWidth - ShAmt - 1] ||
1635           DemandedBits.countLeadingZeros() >= ShAmt) {
1636         SDNodeFlags Flags;
1637         Flags.setExact(Op->getFlags().hasExact());
1638         return TLO.CombineTo(
1639             Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
1640       }
1641 
1642       int Log2 = DemandedBits.exactLogBase2();
1643       if (Log2 >= 0) {
1644         // The bit must come from the sign.
1645         SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
1646         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
1647       }
1648 
1649       if (Known.One[BitWidth - ShAmt - 1])
1650         // New bits are known one.
1651         Known.One.setHighBits(ShAmt);
1652 
1653       // Attempt to avoid multi-use ops if we don't need anything from them.
1654       if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1655         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1656             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1657         if (DemandedOp0) {
1658           SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
1659           return TLO.CombineTo(Op, NewOp);
1660         }
1661       }
1662     }
1663     break;
1664   }
1665   case ISD::FSHL:
1666   case ISD::FSHR: {
1667     SDValue Op0 = Op.getOperand(0);
1668     SDValue Op1 = Op.getOperand(1);
1669     SDValue Op2 = Op.getOperand(2);
1670     bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
1671 
1672     if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
1673       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
1674 
1675       // For fshl, 0-shift returns the 1st arg.
1676       // For fshr, 0-shift returns the 2nd arg.
1677       if (Amt == 0) {
1678         if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
1679                                  Known, TLO, Depth + 1))
1680           return true;
1681         break;
1682       }
1683 
1684       // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
1685       // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
1686       APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
1687       APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
1688       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
1689                                Depth + 1))
1690         return true;
1691       if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
1692                                Depth + 1))
1693         return true;
1694 
1695       Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt));
1696       Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt));
1697       Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1698       Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1699       Known.One |= Known2.One;
1700       Known.Zero |= Known2.Zero;
1701     }
1702 
1703     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
1704     if (isPowerOf2_32(BitWidth)) {
1705       APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
1706       if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts,
1707                                Known2, TLO, Depth + 1))
1708         return true;
1709     }
1710     break;
1711   }
1712   case ISD::ROTL:
1713   case ISD::ROTR: {
1714     SDValue Op0 = Op.getOperand(0);
1715     SDValue Op1 = Op.getOperand(1);
1716 
1717     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
1718     if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
1719       return TLO.CombineTo(Op, Op0);
1720 
1721     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
1722     if (isPowerOf2_32(BitWidth)) {
1723       APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
1724       if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
1725                                Depth + 1))
1726         return true;
1727     }
1728     break;
1729   }
1730   case ISD::UMIN: {
1731     // Check if one arg is always less than (or equal) to the other arg.
1732     SDValue Op0 = Op.getOperand(0);
1733     SDValue Op1 = Op.getOperand(1);
1734     KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
1735     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
1736     Known = KnownBits::umin(Known0, Known1);
1737     if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1))
1738       return TLO.CombineTo(Op, IsULE.getValue() ? Op0 : Op1);
1739     if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1))
1740       return TLO.CombineTo(Op, IsULT.getValue() ? Op0 : Op1);
1741     break;
1742   }
1743   case ISD::UMAX: {
1744     // Check if one arg is always greater than (or equal) to the other arg.
1745     SDValue Op0 = Op.getOperand(0);
1746     SDValue Op1 = Op.getOperand(1);
1747     KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
1748     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
1749     Known = KnownBits::umax(Known0, Known1);
1750     if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
1751       return TLO.CombineTo(Op, IsUGE.getValue() ? Op0 : Op1);
1752     if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
1753       return TLO.CombineTo(Op, IsUGT.getValue() ? Op0 : Op1);
1754     break;
1755   }
1756   case ISD::BITREVERSE: {
1757     SDValue Src = Op.getOperand(0);
1758     APInt DemandedSrcBits = DemandedBits.reverseBits();
1759     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
1760                              Depth + 1))
1761       return true;
1762     Known.One = Known2.One.reverseBits();
1763     Known.Zero = Known2.Zero.reverseBits();
1764     break;
1765   }
1766   case ISD::BSWAP: {
1767     SDValue Src = Op.getOperand(0);
1768     APInt DemandedSrcBits = DemandedBits.byteSwap();
1769     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
1770                              Depth + 1))
1771       return true;
1772     Known.One = Known2.One.byteSwap();
1773     Known.Zero = Known2.Zero.byteSwap();
1774     break;
1775   }
1776   case ISD::CTPOP: {
1777     // If only 1 bit is demanded, replace with PARITY as long as we're before
1778     // op legalization.
1779     // FIXME: Limit to scalars for now.
1780     if (DemandedBits.isOneValue() && !TLO.LegalOps && !VT.isVector())
1781       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
1782                                                Op.getOperand(0)));
1783 
1784     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1785     break;
1786   }
1787   case ISD::SIGN_EXTEND_INREG: {
1788     SDValue Op0 = Op.getOperand(0);
1789     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1790     unsigned ExVTBits = ExVT.getScalarSizeInBits();
1791 
1792     // If we only care about the highest bit, don't bother shifting right.
1793     if (DemandedBits.isSignMask()) {
1794       unsigned NumSignBits =
1795           TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1796       bool AlreadySignExtended = NumSignBits >= BitWidth - ExVTBits + 1;
1797       // However if the input is already sign extended we expect the sign
1798       // extension to be dropped altogether later and do not simplify.
1799       if (!AlreadySignExtended) {
1800         // Compute the correct shift amount type, which must be getShiftAmountTy
1801         // for scalar types after legalization.
1802         EVT ShiftAmtTy = VT;
1803         if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
1804           ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
1805 
1806         SDValue ShiftAmt =
1807             TLO.DAG.getConstant(BitWidth - ExVTBits, dl, ShiftAmtTy);
1808         return TLO.CombineTo(Op,
1809                              TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
1810       }
1811     }
1812 
1813     // If none of the extended bits are demanded, eliminate the sextinreg.
1814     if (DemandedBits.getActiveBits() <= ExVTBits)
1815       return TLO.CombineTo(Op, Op0);
1816 
1817     APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
1818 
1819     // Since the sign extended bits are demanded, we know that the sign
1820     // bit is demanded.
1821     InputDemandedBits.setBit(ExVTBits - 1);
1822 
1823     if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1))
1824       return true;
1825     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1826 
1827     // If the sign bit of the input is known set or clear, then we know the
1828     // top bits of the result.
1829 
1830     // If the input sign bit is known zero, convert this into a zero extension.
1831     if (Known.Zero[ExVTBits - 1])
1832       return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
1833 
1834     APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
1835     if (Known.One[ExVTBits - 1]) { // Input sign bit known set
1836       Known.One.setBitsFrom(ExVTBits);
1837       Known.Zero &= Mask;
1838     } else { // Input sign bit unknown
1839       Known.Zero &= Mask;
1840       Known.One &= Mask;
1841     }
1842     break;
1843   }
1844   case ISD::BUILD_PAIR: {
1845     EVT HalfVT = Op.getOperand(0).getValueType();
1846     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
1847 
1848     APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
1849     APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
1850 
1851     KnownBits KnownLo, KnownHi;
1852 
1853     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
1854       return true;
1855 
1856     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
1857       return true;
1858 
1859     Known.Zero = KnownLo.Zero.zext(BitWidth) |
1860                  KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth);
1861 
1862     Known.One = KnownLo.One.zext(BitWidth) |
1863                 KnownHi.One.zext(BitWidth).shl(HalfBitWidth);
1864     break;
1865   }
1866   case ISD::ZERO_EXTEND:
1867   case ISD::ZERO_EXTEND_VECTOR_INREG: {
1868     SDValue Src = Op.getOperand(0);
1869     EVT SrcVT = Src.getValueType();
1870     unsigned InBits = SrcVT.getScalarSizeInBits();
1871     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1872     bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
1873 
1874     // If none of the top bits are demanded, convert this into an any_extend.
1875     if (DemandedBits.getActiveBits() <= InBits) {
1876       // If we only need the non-extended bits of the bottom element
1877       // then we can just bitcast to the result.
1878       if (IsVecInReg && DemandedElts == 1 &&
1879           VT.getSizeInBits() == SrcVT.getSizeInBits() &&
1880           TLO.DAG.getDataLayout().isLittleEndian())
1881         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
1882 
1883       unsigned Opc =
1884           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
1885       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
1886         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
1887     }
1888 
1889     APInt InDemandedBits = DemandedBits.trunc(InBits);
1890     APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
1891     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
1892                              Depth + 1))
1893       return true;
1894     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1895     assert(Known.getBitWidth() == InBits && "Src width has changed?");
1896     Known = Known.zext(BitWidth);
1897 
1898     // Attempt to avoid multi-use ops if we don't need anything from them.
1899     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
1900             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
1901       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
1902     break;
1903   }
1904   case ISD::SIGN_EXTEND:
1905   case ISD::SIGN_EXTEND_VECTOR_INREG: {
1906     SDValue Src = Op.getOperand(0);
1907     EVT SrcVT = Src.getValueType();
1908     unsigned InBits = SrcVT.getScalarSizeInBits();
1909     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1910     bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
1911 
1912     // If none of the top bits are demanded, convert this into an any_extend.
1913     if (DemandedBits.getActiveBits() <= InBits) {
1914       // If we only need the non-extended bits of the bottom element
1915       // then we can just bitcast to the result.
1916       if (IsVecInReg && DemandedElts == 1 &&
1917           VT.getSizeInBits() == SrcVT.getSizeInBits() &&
1918           TLO.DAG.getDataLayout().isLittleEndian())
1919         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
1920 
1921       unsigned Opc =
1922           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
1923       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
1924         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
1925     }
1926 
1927     APInt InDemandedBits = DemandedBits.trunc(InBits);
1928     APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
1929 
1930     // Since some of the sign extended bits are demanded, we know that the sign
1931     // bit is demanded.
1932     InDemandedBits.setBit(InBits - 1);
1933 
1934     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
1935                              Depth + 1))
1936       return true;
1937     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1938     assert(Known.getBitWidth() == InBits && "Src width has changed?");
1939 
1940     // If the sign bit is known one, the top bits match.
1941     Known = Known.sext(BitWidth);
1942 
1943     // If the sign bit is known zero, convert this to a zero extend.
1944     if (Known.isNonNegative()) {
1945       unsigned Opc =
1946           IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND;
1947       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
1948         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
1949     }
1950 
1951     // Attempt to avoid multi-use ops if we don't need anything from them.
1952     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
1953             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
1954       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
1955     break;
1956   }
1957   case ISD::ANY_EXTEND:
1958   case ISD::ANY_EXTEND_VECTOR_INREG: {
1959     SDValue Src = Op.getOperand(0);
1960     EVT SrcVT = Src.getValueType();
1961     unsigned InBits = SrcVT.getScalarSizeInBits();
1962     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1963     bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
1964 
1965     // If we only need the bottom element then we can just bitcast.
1966     // TODO: Handle ANY_EXTEND?
1967     if (IsVecInReg && DemandedElts == 1 &&
1968         VT.getSizeInBits() == SrcVT.getSizeInBits() &&
1969         TLO.DAG.getDataLayout().isLittleEndian())
1970       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
1971 
1972     APInt InDemandedBits = DemandedBits.trunc(InBits);
1973     APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
1974     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
1975                              Depth + 1))
1976       return true;
1977     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1978     assert(Known.getBitWidth() == InBits && "Src width has changed?");
1979     Known = Known.anyext(BitWidth);
1980 
1981     // Attempt to avoid multi-use ops if we don't need anything from them.
1982     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
1983             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
1984       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
1985     break;
1986   }
1987   case ISD::TRUNCATE: {
1988     SDValue Src = Op.getOperand(0);
1989 
1990     // Simplify the input, using demanded bit information, and compute the known
1991     // zero/one bits live out.
1992     unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
1993     APInt TruncMask = DemandedBits.zext(OperandBitWidth);
1994     if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
1995                              Depth + 1))
1996       return true;
1997     Known = Known.trunc(BitWidth);
1998 
1999     // Attempt to avoid multi-use ops if we don't need anything from them.
2000     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2001             Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
2002       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
2003 
2004     // If the input is only used by this truncate, see if we can shrink it based
2005     // on the known demanded bits.
2006     if (Src.getNode()->hasOneUse()) {
2007       switch (Src.getOpcode()) {
2008       default:
2009         break;
2010       case ISD::SRL:
2011         // Shrink SRL by a constant if none of the high bits shifted in are
2012         // demanded.
2013         if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
2014           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2015           // undesirable.
2016           break;
2017 
2018         const APInt *ShAmtC =
2019             TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts);
2020         if (!ShAmtC || ShAmtC->uge(BitWidth))
2021           break;
2022         uint64_t ShVal = ShAmtC->getZExtValue();
2023 
2024         APInt HighBits =
2025             APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
2026         HighBits.lshrInPlace(ShVal);
2027         HighBits = HighBits.trunc(BitWidth);
2028 
2029         if (!(HighBits & DemandedBits)) {
2030           // None of the shifted in bits are needed.  Add a truncate of the
2031           // shift input, then shift it.
2032           SDValue NewShAmt = TLO.DAG.getConstant(
2033               ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes()));
2034           SDValue NewTrunc =
2035               TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
2036           return TLO.CombineTo(
2037               Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
2038         }
2039         break;
2040       }
2041     }
2042 
2043     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2044     break;
2045   }
2046   case ISD::AssertZext: {
2047     // AssertZext demands all of the high bits, plus any of the low bits
2048     // demanded by its users.
2049     EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2050     APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits());
2051     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
2052                              TLO, Depth + 1))
2053       return true;
2054     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2055 
2056     Known.Zero |= ~InMask;
2057     break;
2058   }
2059   case ISD::EXTRACT_VECTOR_ELT: {
2060     SDValue Src = Op.getOperand(0);
2061     SDValue Idx = Op.getOperand(1);
2062     ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
2063     unsigned EltBitWidth = Src.getScalarValueSizeInBits();
2064 
2065     if (SrcEltCnt.isScalable())
2066       return false;
2067 
2068     // Demand the bits from every vector element without a constant index.
2069     unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2070     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
2071     if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
2072       if (CIdx->getAPIntValue().ult(NumSrcElts))
2073         DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
2074 
2075     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2076     // anything about the extended bits.
2077     APInt DemandedSrcBits = DemandedBits;
2078     if (BitWidth > EltBitWidth)
2079       DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
2080 
2081     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
2082                              Depth + 1))
2083       return true;
2084 
2085     // Attempt to avoid multi-use ops if we don't need anything from them.
2086     if (!DemandedSrcBits.isAllOnesValue() ||
2087         !DemandedSrcElts.isAllOnesValue()) {
2088       if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2089               Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2090         SDValue NewOp =
2091             TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2092         return TLO.CombineTo(Op, NewOp);
2093       }
2094     }
2095 
2096     Known = Known2;
2097     if (BitWidth > EltBitWidth)
2098       Known = Known.anyext(BitWidth);
2099     break;
2100   }
2101   case ISD::BITCAST: {
2102     SDValue Src = Op.getOperand(0);
2103     EVT SrcVT = Src.getValueType();
2104     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
2105 
2106     // If this is an FP->Int bitcast and if the sign bit is the only
2107     // thing demanded, turn this into a FGETSIGN.
2108     if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
2109         DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
2110         SrcVT.isFloatingPoint()) {
2111       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT);
2112       bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
2113       if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 &&
2114           SrcVT != MVT::f128) {
2115         // Cannot eliminate/lower SHL for f128 yet.
2116         EVT Ty = OpVTLegal ? VT : MVT::i32;
2117         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
2118         // place.  We expect the SHL to be eliminated by other optimizations.
2119         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src);
2120         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
2121         if (!OpVTLegal && OpVTSizeInBits > 32)
2122           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign);
2123         unsigned ShVal = Op.getValueSizeInBits() - 1;
2124         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT);
2125         return TLO.CombineTo(Op,
2126                              TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
2127       }
2128     }
2129 
2130     // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
2131     // Demand the elt/bit if any of the original elts/bits are demanded.
2132     // TODO - bigendian once we have test coverage.
2133     if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0 &&
2134         TLO.DAG.getDataLayout().isLittleEndian()) {
2135       unsigned Scale = BitWidth / NumSrcEltBits;
2136       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2137       APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
2138       APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
2139       for (unsigned i = 0; i != Scale; ++i) {
2140         unsigned Offset = i * NumSrcEltBits;
2141         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset);
2142         if (!Sub.isNullValue()) {
2143           DemandedSrcBits |= Sub;
2144           for (unsigned j = 0; j != NumElts; ++j)
2145             if (DemandedElts[j])
2146               DemandedSrcElts.setBit((j * Scale) + i);
2147         }
2148       }
2149 
2150       APInt KnownSrcUndef, KnownSrcZero;
2151       if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2152                                      KnownSrcZero, TLO, Depth + 1))
2153         return true;
2154 
2155       KnownBits KnownSrcBits;
2156       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2157                                KnownSrcBits, TLO, Depth + 1))
2158         return true;
2159     } else if ((NumSrcEltBits % BitWidth) == 0 &&
2160                TLO.DAG.getDataLayout().isLittleEndian()) {
2161       unsigned Scale = NumSrcEltBits / BitWidth;
2162       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2163       APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
2164       APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
2165       for (unsigned i = 0; i != NumElts; ++i)
2166         if (DemandedElts[i]) {
2167           unsigned Offset = (i % Scale) * BitWidth;
2168           DemandedSrcBits.insertBits(DemandedBits, Offset);
2169           DemandedSrcElts.setBit(i / Scale);
2170         }
2171 
2172       if (SrcVT.isVector()) {
2173         APInt KnownSrcUndef, KnownSrcZero;
2174         if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2175                                        KnownSrcZero, TLO, Depth + 1))
2176           return true;
2177       }
2178 
2179       KnownBits KnownSrcBits;
2180       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2181                                KnownSrcBits, TLO, Depth + 1))
2182         return true;
2183     }
2184 
2185     // If this is a bitcast, let computeKnownBits handle it.  Only do this on a
2186     // recursive call where Known may be useful to the caller.
2187     if (Depth > 0) {
2188       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2189       return false;
2190     }
2191     break;
2192   }
2193   case ISD::ADD:
2194   case ISD::MUL:
2195   case ISD::SUB: {
2196     // Add, Sub, and Mul don't demand any bits in positions beyond that
2197     // of the highest bit demanded of them.
2198     SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
2199     SDNodeFlags Flags = Op.getNode()->getFlags();
2200     unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros();
2201     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2202     if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO,
2203                              Depth + 1) ||
2204         SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO,
2205                              Depth + 1) ||
2206         // See if the operation should be performed at a smaller bit width.
2207         ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) {
2208       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
2209         // Disable the nsw and nuw flags. We can no longer guarantee that we
2210         // won't wrap after simplification.
2211         Flags.setNoSignedWrap(false);
2212         Flags.setNoUnsignedWrap(false);
2213         SDValue NewOp =
2214             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2215         return TLO.CombineTo(Op, NewOp);
2216       }
2217       return true;
2218     }
2219 
2220     // Attempt to avoid multi-use ops if we don't need anything from them.
2221     if (!LoMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
2222       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
2223           Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2224       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
2225           Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2226       if (DemandedOp0 || DemandedOp1) {
2227         Flags.setNoSignedWrap(false);
2228         Flags.setNoUnsignedWrap(false);
2229         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
2230         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
2231         SDValue NewOp =
2232             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2233         return TLO.CombineTo(Op, NewOp);
2234       }
2235     }
2236 
2237     // If we have a constant operand, we may be able to turn it into -1 if we
2238     // do not demand the high bits. This can make the constant smaller to
2239     // encode, allow more general folding, or match specialized instruction
2240     // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
2241     // is probably not useful (and could be detrimental).
2242     ConstantSDNode *C = isConstOrConstSplat(Op1);
2243     APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
2244     if (C && !C->isAllOnesValue() && !C->isOne() &&
2245         (C->getAPIntValue() | HighMask).isAllOnesValue()) {
2246       SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
2247       // Disable the nsw and nuw flags. We can no longer guarantee that we
2248       // won't wrap after simplification.
2249       Flags.setNoSignedWrap(false);
2250       Flags.setNoUnsignedWrap(false);
2251       SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
2252       return TLO.CombineTo(Op, NewOp);
2253     }
2254 
2255     LLVM_FALLTHROUGH;
2256   }
2257   default:
2258     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2259       if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts,
2260                                             Known, TLO, Depth))
2261         return true;
2262       break;
2263     }
2264 
2265     // Just use computeKnownBits to compute output bits.
2266     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2267     break;
2268   }
2269 
2270   // If we know the value of all of the demanded bits, return this as a
2271   // constant.
2272   if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
2273     // Avoid folding to a constant if any OpaqueConstant is involved.
2274     const SDNode *N = Op.getNode();
2275     for (SDNode *Op :
2276          llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) {
2277       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
2278         if (C->isOpaque())
2279           return false;
2280     }
2281     if (VT.isInteger())
2282       return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
2283     if (VT.isFloatingPoint())
2284       return TLO.CombineTo(
2285           Op,
2286           TLO.DAG.getConstantFP(
2287               APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT));
2288   }
2289 
2290   return false;
2291 }
2292 
2293 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op,
2294                                                 const APInt &DemandedElts,
2295                                                 APInt &KnownUndef,
2296                                                 APInt &KnownZero,
2297                                                 DAGCombinerInfo &DCI) const {
2298   SelectionDAG &DAG = DCI.DAG;
2299   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2300                         !DCI.isBeforeLegalizeOps());
2301 
2302   bool Simplified =
2303       SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
2304   if (Simplified) {
2305     DCI.AddToWorklist(Op.getNode());
2306     DCI.CommitTargetLoweringOpt(TLO);
2307   }
2308 
2309   return Simplified;
2310 }
2311 
2312 /// Given a vector binary operation and known undefined elements for each input
2313 /// operand, compute whether each element of the output is undefined.
2314 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG,
2315                                          const APInt &UndefOp0,
2316                                          const APInt &UndefOp1) {
2317   EVT VT = BO.getValueType();
2318   assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() &&
2319          "Vector binop only");
2320 
2321   EVT EltVT = VT.getVectorElementType();
2322   unsigned NumElts = VT.getVectorNumElements();
2323   assert(UndefOp0.getBitWidth() == NumElts &&
2324          UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
2325 
2326   auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
2327                                    const APInt &UndefVals) {
2328     if (UndefVals[Index])
2329       return DAG.getUNDEF(EltVT);
2330 
2331     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2332       // Try hard to make sure that the getNode() call is not creating temporary
2333       // nodes. Ignore opaque integers because they do not constant fold.
2334       SDValue Elt = BV->getOperand(Index);
2335       auto *C = dyn_cast<ConstantSDNode>(Elt);
2336       if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
2337         return Elt;
2338     }
2339 
2340     return SDValue();
2341   };
2342 
2343   APInt KnownUndef = APInt::getNullValue(NumElts);
2344   for (unsigned i = 0; i != NumElts; ++i) {
2345     // If both inputs for this element are either constant or undef and match
2346     // the element type, compute the constant/undef result for this element of
2347     // the vector.
2348     // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
2349     // not handle FP constants. The code within getNode() should be refactored
2350     // to avoid the danger of creating a bogus temporary node here.
2351     SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
2352     SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
2353     if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
2354       if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
2355         KnownUndef.setBit(i);
2356   }
2357   return KnownUndef;
2358 }
2359 
2360 bool TargetLowering::SimplifyDemandedVectorElts(
2361     SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
2362     APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
2363     bool AssumeSingleUse) const {
2364   EVT VT = Op.getValueType();
2365   unsigned Opcode = Op.getOpcode();
2366   APInt DemandedElts = OriginalDemandedElts;
2367   unsigned NumElts = DemandedElts.getBitWidth();
2368   assert(VT.isVector() && "Expected vector op");
2369 
2370   KnownUndef = KnownZero = APInt::getNullValue(NumElts);
2371 
2372   // TODO: For now we assume we know nothing about scalable vectors.
2373   if (VT.isScalableVector())
2374     return false;
2375 
2376   assert(VT.getVectorNumElements() == NumElts &&
2377          "Mask size mismatches value type element count!");
2378 
2379   // Undef operand.
2380   if (Op.isUndef()) {
2381     KnownUndef.setAllBits();
2382     return false;
2383   }
2384 
2385   // If Op has other users, assume that all elements are needed.
2386   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse)
2387     DemandedElts.setAllBits();
2388 
2389   // Not demanding any elements from Op.
2390   if (DemandedElts == 0) {
2391     KnownUndef.setAllBits();
2392     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2393   }
2394 
2395   // Limit search depth.
2396   if (Depth >= SelectionDAG::MaxRecursionDepth)
2397     return false;
2398 
2399   SDLoc DL(Op);
2400   unsigned EltSizeInBits = VT.getScalarSizeInBits();
2401 
2402   // Helper for demanding the specified elements and all the bits of both binary
2403   // operands.
2404   auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
2405     SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
2406                                                            TLO.DAG, Depth + 1);
2407     SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
2408                                                            TLO.DAG, Depth + 1);
2409     if (NewOp0 || NewOp1) {
2410       SDValue NewOp = TLO.DAG.getNode(
2411           Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1);
2412       return TLO.CombineTo(Op, NewOp);
2413     }
2414     return false;
2415   };
2416 
2417   switch (Opcode) {
2418   case ISD::SCALAR_TO_VECTOR: {
2419     if (!DemandedElts[0]) {
2420       KnownUndef.setAllBits();
2421       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2422     }
2423     KnownUndef.setHighBits(NumElts - 1);
2424     break;
2425   }
2426   case ISD::BITCAST: {
2427     SDValue Src = Op.getOperand(0);
2428     EVT SrcVT = Src.getValueType();
2429 
2430     // We only handle vectors here.
2431     // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
2432     if (!SrcVT.isVector())
2433       break;
2434 
2435     // Fast handling of 'identity' bitcasts.
2436     unsigned NumSrcElts = SrcVT.getVectorNumElements();
2437     if (NumSrcElts == NumElts)
2438       return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
2439                                         KnownZero, TLO, Depth + 1);
2440 
2441     APInt SrcZero, SrcUndef;
2442     APInt SrcDemandedElts = APInt::getNullValue(NumSrcElts);
2443 
2444     // Bitcast from 'large element' src vector to 'small element' vector, we
2445     // must demand a source element if any DemandedElt maps to it.
2446     if ((NumElts % NumSrcElts) == 0) {
2447       unsigned Scale = NumElts / NumSrcElts;
2448       for (unsigned i = 0; i != NumElts; ++i)
2449         if (DemandedElts[i])
2450           SrcDemandedElts.setBit(i / Scale);
2451 
2452       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2453                                      TLO, Depth + 1))
2454         return true;
2455 
2456       // Try calling SimplifyDemandedBits, converting demanded elts to the bits
2457       // of the large element.
2458       // TODO - bigendian once we have test coverage.
2459       if (TLO.DAG.getDataLayout().isLittleEndian()) {
2460         unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
2461         APInt SrcDemandedBits = APInt::getNullValue(SrcEltSizeInBits);
2462         for (unsigned i = 0; i != NumElts; ++i)
2463           if (DemandedElts[i]) {
2464             unsigned Ofs = (i % Scale) * EltSizeInBits;
2465             SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
2466           }
2467 
2468         KnownBits Known;
2469         if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
2470                                  TLO, Depth + 1))
2471           return true;
2472       }
2473 
2474       // If the src element is zero/undef then all the output elements will be -
2475       // only demanded elements are guaranteed to be correct.
2476       for (unsigned i = 0; i != NumSrcElts; ++i) {
2477         if (SrcDemandedElts[i]) {
2478           if (SrcZero[i])
2479             KnownZero.setBits(i * Scale, (i + 1) * Scale);
2480           if (SrcUndef[i])
2481             KnownUndef.setBits(i * Scale, (i + 1) * Scale);
2482         }
2483       }
2484     }
2485 
2486     // Bitcast from 'small element' src vector to 'large element' vector, we
2487     // demand all smaller source elements covered by the larger demanded element
2488     // of this vector.
2489     if ((NumSrcElts % NumElts) == 0) {
2490       unsigned Scale = NumSrcElts / NumElts;
2491       for (unsigned i = 0; i != NumElts; ++i)
2492         if (DemandedElts[i])
2493           SrcDemandedElts.setBits(i * Scale, (i + 1) * Scale);
2494 
2495       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2496                                      TLO, Depth + 1))
2497         return true;
2498 
2499       // If all the src elements covering an output element are zero/undef, then
2500       // the output element will be as well, assuming it was demanded.
2501       for (unsigned i = 0; i != NumElts; ++i) {
2502         if (DemandedElts[i]) {
2503           if (SrcZero.extractBits(Scale, i * Scale).isAllOnesValue())
2504             KnownZero.setBit(i);
2505           if (SrcUndef.extractBits(Scale, i * Scale).isAllOnesValue())
2506             KnownUndef.setBit(i);
2507         }
2508       }
2509     }
2510     break;
2511   }
2512   case ISD::BUILD_VECTOR: {
2513     // Check all elements and simplify any unused elements with UNDEF.
2514     if (!DemandedElts.isAllOnesValue()) {
2515       // Don't simplify BROADCASTS.
2516       if (llvm::any_of(Op->op_values(),
2517                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
2518         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
2519         bool Updated = false;
2520         for (unsigned i = 0; i != NumElts; ++i) {
2521           if (!DemandedElts[i] && !Ops[i].isUndef()) {
2522             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
2523             KnownUndef.setBit(i);
2524             Updated = true;
2525           }
2526         }
2527         if (Updated)
2528           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
2529       }
2530     }
2531     for (unsigned i = 0; i != NumElts; ++i) {
2532       SDValue SrcOp = Op.getOperand(i);
2533       if (SrcOp.isUndef()) {
2534         KnownUndef.setBit(i);
2535       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
2536                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
2537         KnownZero.setBit(i);
2538       }
2539     }
2540     break;
2541   }
2542   case ISD::CONCAT_VECTORS: {
2543     EVT SubVT = Op.getOperand(0).getValueType();
2544     unsigned NumSubVecs = Op.getNumOperands();
2545     unsigned NumSubElts = SubVT.getVectorNumElements();
2546     for (unsigned i = 0; i != NumSubVecs; ++i) {
2547       SDValue SubOp = Op.getOperand(i);
2548       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
2549       APInt SubUndef, SubZero;
2550       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
2551                                      Depth + 1))
2552         return true;
2553       KnownUndef.insertBits(SubUndef, i * NumSubElts);
2554       KnownZero.insertBits(SubZero, i * NumSubElts);
2555     }
2556     break;
2557   }
2558   case ISD::INSERT_SUBVECTOR: {
2559     // Demand any elements from the subvector and the remainder from the src its
2560     // inserted into.
2561     SDValue Src = Op.getOperand(0);
2562     SDValue Sub = Op.getOperand(1);
2563     uint64_t Idx = Op.getConstantOperandVal(2);
2564     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2565     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2566     APInt DemandedSrcElts = DemandedElts;
2567     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
2568 
2569     APInt SubUndef, SubZero;
2570     if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
2571                                    Depth + 1))
2572       return true;
2573 
2574     // If none of the src operand elements are demanded, replace it with undef.
2575     if (!DemandedSrcElts && !Src.isUndef())
2576       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
2577                                                TLO.DAG.getUNDEF(VT), Sub,
2578                                                Op.getOperand(2)));
2579 
2580     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
2581                                    TLO, Depth + 1))
2582       return true;
2583     KnownUndef.insertBits(SubUndef, Idx);
2584     KnownZero.insertBits(SubZero, Idx);
2585 
2586     // Attempt to avoid multi-use ops if we don't need anything from them.
2587     if (!DemandedSrcElts.isAllOnesValue() ||
2588         !DemandedSubElts.isAllOnesValue()) {
2589       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
2590           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
2591       SDValue NewSub = SimplifyMultipleUseDemandedVectorElts(
2592           Sub, DemandedSubElts, TLO.DAG, Depth + 1);
2593       if (NewSrc || NewSub) {
2594         NewSrc = NewSrc ? NewSrc : Src;
2595         NewSub = NewSub ? NewSub : Sub;
2596         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
2597                                         NewSub, Op.getOperand(2));
2598         return TLO.CombineTo(Op, NewOp);
2599       }
2600     }
2601     break;
2602   }
2603   case ISD::EXTRACT_SUBVECTOR: {
2604     // Offset the demanded elts by the subvector index.
2605     SDValue Src = Op.getOperand(0);
2606     if (Src.getValueType().isScalableVector())
2607       break;
2608     uint64_t Idx = Op.getConstantOperandVal(1);
2609     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2610     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2611 
2612     APInt SrcUndef, SrcZero;
2613     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
2614                                    Depth + 1))
2615       return true;
2616     KnownUndef = SrcUndef.extractBits(NumElts, Idx);
2617     KnownZero = SrcZero.extractBits(NumElts, Idx);
2618 
2619     // Attempt to avoid multi-use ops if we don't need anything from them.
2620     if (!DemandedElts.isAllOnesValue()) {
2621       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
2622           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
2623       if (NewSrc) {
2624         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
2625                                         Op.getOperand(1));
2626         return TLO.CombineTo(Op, NewOp);
2627       }
2628     }
2629     break;
2630   }
2631   case ISD::INSERT_VECTOR_ELT: {
2632     SDValue Vec = Op.getOperand(0);
2633     SDValue Scl = Op.getOperand(1);
2634     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2635 
2636     // For a legal, constant insertion index, if we don't need this insertion
2637     // then strip it, else remove it from the demanded elts.
2638     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
2639       unsigned Idx = CIdx->getZExtValue();
2640       if (!DemandedElts[Idx])
2641         return TLO.CombineTo(Op, Vec);
2642 
2643       APInt DemandedVecElts(DemandedElts);
2644       DemandedVecElts.clearBit(Idx);
2645       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
2646                                      KnownZero, TLO, Depth + 1))
2647         return true;
2648 
2649       KnownUndef.setBitVal(Idx, Scl.isUndef());
2650 
2651       KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
2652       break;
2653     }
2654 
2655     APInt VecUndef, VecZero;
2656     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
2657                                    Depth + 1))
2658       return true;
2659     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
2660     break;
2661   }
2662   case ISD::VSELECT: {
2663     // Try to transform the select condition based on the current demanded
2664     // elements.
2665     // TODO: If a condition element is undef, we can choose from one arm of the
2666     //       select (and if one arm is undef, then we can propagate that to the
2667     //       result).
2668     // TODO - add support for constant vselect masks (see IR version of this).
2669     APInt UnusedUndef, UnusedZero;
2670     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef,
2671                                    UnusedZero, TLO, Depth + 1))
2672       return true;
2673 
2674     // See if we can simplify either vselect operand.
2675     APInt DemandedLHS(DemandedElts);
2676     APInt DemandedRHS(DemandedElts);
2677     APInt UndefLHS, ZeroLHS;
2678     APInt UndefRHS, ZeroRHS;
2679     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS,
2680                                    ZeroLHS, TLO, Depth + 1))
2681       return true;
2682     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS,
2683                                    ZeroRHS, TLO, Depth + 1))
2684       return true;
2685 
2686     KnownUndef = UndefLHS & UndefRHS;
2687     KnownZero = ZeroLHS & ZeroRHS;
2688     break;
2689   }
2690   case ISD::VECTOR_SHUFFLE: {
2691     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
2692 
2693     // Collect demanded elements from shuffle operands..
2694     APInt DemandedLHS(NumElts, 0);
2695     APInt DemandedRHS(NumElts, 0);
2696     for (unsigned i = 0; i != NumElts; ++i) {
2697       int M = ShuffleMask[i];
2698       if (M < 0 || !DemandedElts[i])
2699         continue;
2700       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
2701       if (M < (int)NumElts)
2702         DemandedLHS.setBit(M);
2703       else
2704         DemandedRHS.setBit(M - NumElts);
2705     }
2706 
2707     // See if we can simplify either shuffle operand.
2708     APInt UndefLHS, ZeroLHS;
2709     APInt UndefRHS, ZeroRHS;
2710     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS,
2711                                    ZeroLHS, TLO, Depth + 1))
2712       return true;
2713     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS,
2714                                    ZeroRHS, TLO, Depth + 1))
2715       return true;
2716 
2717     // Simplify mask using undef elements from LHS/RHS.
2718     bool Updated = false;
2719     bool IdentityLHS = true, IdentityRHS = true;
2720     SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end());
2721     for (unsigned i = 0; i != NumElts; ++i) {
2722       int &M = NewMask[i];
2723       if (M < 0)
2724         continue;
2725       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
2726           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
2727         Updated = true;
2728         M = -1;
2729       }
2730       IdentityLHS &= (M < 0) || (M == (int)i);
2731       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
2732     }
2733 
2734     // Update legal shuffle masks based on demanded elements if it won't reduce
2735     // to Identity which can cause premature removal of the shuffle mask.
2736     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
2737       SDValue LegalShuffle =
2738           buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1),
2739                                   NewMask, TLO.DAG);
2740       if (LegalShuffle)
2741         return TLO.CombineTo(Op, LegalShuffle);
2742     }
2743 
2744     // Propagate undef/zero elements from LHS/RHS.
2745     for (unsigned i = 0; i != NumElts; ++i) {
2746       int M = ShuffleMask[i];
2747       if (M < 0) {
2748         KnownUndef.setBit(i);
2749       } else if (M < (int)NumElts) {
2750         if (UndefLHS[M])
2751           KnownUndef.setBit(i);
2752         if (ZeroLHS[M])
2753           KnownZero.setBit(i);
2754       } else {
2755         if (UndefRHS[M - NumElts])
2756           KnownUndef.setBit(i);
2757         if (ZeroRHS[M - NumElts])
2758           KnownZero.setBit(i);
2759       }
2760     }
2761     break;
2762   }
2763   case ISD::ANY_EXTEND_VECTOR_INREG:
2764   case ISD::SIGN_EXTEND_VECTOR_INREG:
2765   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2766     APInt SrcUndef, SrcZero;
2767     SDValue Src = Op.getOperand(0);
2768     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2769     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
2770     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
2771                                    Depth + 1))
2772       return true;
2773     KnownZero = SrcZero.zextOrTrunc(NumElts);
2774     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
2775 
2776     if (Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
2777         Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
2778         DemandedSrcElts == 1 && TLO.DAG.getDataLayout().isLittleEndian()) {
2779       // aext - if we just need the bottom element then we can bitcast.
2780       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2781     }
2782 
2783     if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
2784       // zext(undef) upper bits are guaranteed to be zero.
2785       if (DemandedElts.isSubsetOf(KnownUndef))
2786         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
2787       KnownUndef.clearAllBits();
2788     }
2789     break;
2790   }
2791 
2792   // TODO: There are more binop opcodes that could be handled here - MIN,
2793   // MAX, saturated math, etc.
2794   case ISD::OR:
2795   case ISD::XOR:
2796   case ISD::ADD:
2797   case ISD::SUB:
2798   case ISD::FADD:
2799   case ISD::FSUB:
2800   case ISD::FMUL:
2801   case ISD::FDIV:
2802   case ISD::FREM: {
2803     SDValue Op0 = Op.getOperand(0);
2804     SDValue Op1 = Op.getOperand(1);
2805 
2806     APInt UndefRHS, ZeroRHS;
2807     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
2808                                    Depth + 1))
2809       return true;
2810     APInt UndefLHS, ZeroLHS;
2811     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
2812                                    Depth + 1))
2813       return true;
2814 
2815     KnownZero = ZeroLHS & ZeroRHS;
2816     KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
2817 
2818     // Attempt to avoid multi-use ops if we don't need anything from them.
2819     // TODO - use KnownUndef to relax the demandedelts?
2820     if (!DemandedElts.isAllOnesValue())
2821       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
2822         return true;
2823     break;
2824   }
2825   case ISD::SHL:
2826   case ISD::SRL:
2827   case ISD::SRA:
2828   case ISD::ROTL:
2829   case ISD::ROTR: {
2830     SDValue Op0 = Op.getOperand(0);
2831     SDValue Op1 = Op.getOperand(1);
2832 
2833     APInt UndefRHS, ZeroRHS;
2834     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
2835                                    Depth + 1))
2836       return true;
2837     APInt UndefLHS, ZeroLHS;
2838     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
2839                                    Depth + 1))
2840       return true;
2841 
2842     KnownZero = ZeroLHS;
2843     KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
2844 
2845     // Attempt to avoid multi-use ops if we don't need anything from them.
2846     // TODO - use KnownUndef to relax the demandedelts?
2847     if (!DemandedElts.isAllOnesValue())
2848       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
2849         return true;
2850     break;
2851   }
2852   case ISD::MUL:
2853   case ISD::AND: {
2854     SDValue Op0 = Op.getOperand(0);
2855     SDValue Op1 = Op.getOperand(1);
2856 
2857     APInt SrcUndef, SrcZero;
2858     if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
2859                                    Depth + 1))
2860       return true;
2861     if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
2862                                    TLO, Depth + 1))
2863       return true;
2864 
2865     // If either side has a zero element, then the result element is zero, even
2866     // if the other is an UNDEF.
2867     // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
2868     // and then handle 'and' nodes with the rest of the binop opcodes.
2869     KnownZero |= SrcZero;
2870     KnownUndef &= SrcUndef;
2871     KnownUndef &= ~KnownZero;
2872 
2873     // Attempt to avoid multi-use ops if we don't need anything from them.
2874     // TODO - use KnownUndef to relax the demandedelts?
2875     if (!DemandedElts.isAllOnesValue())
2876       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
2877         return true;
2878     break;
2879   }
2880   case ISD::TRUNCATE:
2881   case ISD::SIGN_EXTEND:
2882   case ISD::ZERO_EXTEND:
2883     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
2884                                    KnownZero, TLO, Depth + 1))
2885       return true;
2886 
2887     if (Op.getOpcode() == ISD::ZERO_EXTEND) {
2888       // zext(undef) upper bits are guaranteed to be zero.
2889       if (DemandedElts.isSubsetOf(KnownUndef))
2890         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
2891       KnownUndef.clearAllBits();
2892     }
2893     break;
2894   default: {
2895     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2896       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
2897                                                   KnownZero, TLO, Depth))
2898         return true;
2899     } else {
2900       KnownBits Known;
2901       APInt DemandedBits = APInt::getAllOnesValue(EltSizeInBits);
2902       if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
2903                                TLO, Depth, AssumeSingleUse))
2904         return true;
2905     }
2906     break;
2907   }
2908   }
2909   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
2910 
2911   // Constant fold all undef cases.
2912   // TODO: Handle zero cases as well.
2913   if (DemandedElts.isSubsetOf(KnownUndef))
2914     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2915 
2916   return false;
2917 }
2918 
2919 /// Determine which of the bits specified in Mask are known to be either zero or
2920 /// one and return them in the Known.
2921 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
2922                                                    KnownBits &Known,
2923                                                    const APInt &DemandedElts,
2924                                                    const SelectionDAG &DAG,
2925                                                    unsigned Depth) const {
2926   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2927           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2928           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2929           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2930          "Should use MaskedValueIsZero if you don't know whether Op"
2931          " is a target node!");
2932   Known.resetAll();
2933 }
2934 
2935 void TargetLowering::computeKnownBitsForTargetInstr(
2936     GISelKnownBits &Analysis, Register R, KnownBits &Known,
2937     const APInt &DemandedElts, const MachineRegisterInfo &MRI,
2938     unsigned Depth) const {
2939   Known.resetAll();
2940 }
2941 
2942 void TargetLowering::computeKnownBitsForFrameIndex(
2943   const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const {
2944   // The low bits are known zero if the pointer is aligned.
2945   Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx)));
2946 }
2947 
2948 Align TargetLowering::computeKnownAlignForTargetInstr(
2949   GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI,
2950   unsigned Depth) const {
2951   return Align(1);
2952 }
2953 
2954 /// This method can be implemented by targets that want to expose additional
2955 /// information about sign bits to the DAG Combiner.
2956 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
2957                                                          const APInt &,
2958                                                          const SelectionDAG &,
2959                                                          unsigned Depth) const {
2960   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2961           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2962           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2963           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2964          "Should use ComputeNumSignBits if you don't know whether Op"
2965          " is a target node!");
2966   return 1;
2967 }
2968 
2969 unsigned TargetLowering::computeNumSignBitsForTargetInstr(
2970   GISelKnownBits &Analysis, Register R, const APInt &DemandedElts,
2971   const MachineRegisterInfo &MRI, unsigned Depth) const {
2972   return 1;
2973 }
2974 
2975 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
2976     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
2977     TargetLoweringOpt &TLO, unsigned Depth) const {
2978   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2979           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2980           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2981           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2982          "Should use SimplifyDemandedVectorElts if you don't know whether Op"
2983          " is a target node!");
2984   return false;
2985 }
2986 
2987 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
2988     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
2989     KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
2990   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2991           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2992           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2993           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2994          "Should use SimplifyDemandedBits if you don't know whether Op"
2995          " is a target node!");
2996   computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
2997   return false;
2998 }
2999 
3000 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
3001     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3002     SelectionDAG &DAG, unsigned Depth) const {
3003   assert(
3004       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3005        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3006        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3007        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3008       "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
3009       " is a target node!");
3010   return SDValue();
3011 }
3012 
3013 SDValue
3014 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
3015                                         SDValue N1, MutableArrayRef<int> Mask,
3016                                         SelectionDAG &DAG) const {
3017   bool LegalMask = isShuffleMaskLegal(Mask, VT);
3018   if (!LegalMask) {
3019     std::swap(N0, N1);
3020     ShuffleVectorSDNode::commuteMask(Mask);
3021     LegalMask = isShuffleMaskLegal(Mask, VT);
3022   }
3023 
3024   if (!LegalMask)
3025     return SDValue();
3026 
3027   return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
3028 }
3029 
3030 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const {
3031   return nullptr;
3032 }
3033 
3034 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
3035                                                   const SelectionDAG &DAG,
3036                                                   bool SNaN,
3037                                                   unsigned Depth) const {
3038   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3039           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3040           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3041           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3042          "Should use isKnownNeverNaN if you don't know whether Op"
3043          " is a target node!");
3044   return false;
3045 }
3046 
3047 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
3048 // work with truncating build vectors and vectors with elements of less than
3049 // 8 bits.
3050 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
3051   if (!N)
3052     return false;
3053 
3054   APInt CVal;
3055   if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
3056     CVal = CN->getAPIntValue();
3057   } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) {
3058     auto *CN = BV->getConstantSplatNode();
3059     if (!CN)
3060       return false;
3061 
3062     // If this is a truncating build vector, truncate the splat value.
3063     // Otherwise, we may fail to match the expected values below.
3064     unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits();
3065     CVal = CN->getAPIntValue();
3066     if (BVEltWidth < CVal.getBitWidth())
3067       CVal = CVal.trunc(BVEltWidth);
3068   } else {
3069     return false;
3070   }
3071 
3072   switch (getBooleanContents(N->getValueType(0))) {
3073   case UndefinedBooleanContent:
3074     return CVal[0];
3075   case ZeroOrOneBooleanContent:
3076     return CVal.isOneValue();
3077   case ZeroOrNegativeOneBooleanContent:
3078     return CVal.isAllOnesValue();
3079   }
3080 
3081   llvm_unreachable("Invalid boolean contents");
3082 }
3083 
3084 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
3085   if (!N)
3086     return false;
3087 
3088   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
3089   if (!CN) {
3090     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
3091     if (!BV)
3092       return false;
3093 
3094     // Only interested in constant splats, we don't care about undef
3095     // elements in identifying boolean constants and getConstantSplatNode
3096     // returns NULL if all ops are undef;
3097     CN = BV->getConstantSplatNode();
3098     if (!CN)
3099       return false;
3100   }
3101 
3102   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
3103     return !CN->getAPIntValue()[0];
3104 
3105   return CN->isNullValue();
3106 }
3107 
3108 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
3109                                        bool SExt) const {
3110   if (VT == MVT::i1)
3111     return N->isOne();
3112 
3113   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
3114   switch (Cnt) {
3115   case TargetLowering::ZeroOrOneBooleanContent:
3116     // An extended value of 1 is always true, unless its original type is i1,
3117     // in which case it will be sign extended to -1.
3118     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
3119   case TargetLowering::UndefinedBooleanContent:
3120   case TargetLowering::ZeroOrNegativeOneBooleanContent:
3121     return N->isAllOnesValue() && SExt;
3122   }
3123   llvm_unreachable("Unexpected enumeration.");
3124 }
3125 
3126 /// This helper function of SimplifySetCC tries to optimize the comparison when
3127 /// either operand of the SetCC node is a bitwise-and instruction.
3128 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3129                                          ISD::CondCode Cond, const SDLoc &DL,
3130                                          DAGCombinerInfo &DCI) const {
3131   // Match these patterns in any of their permutations:
3132   // (X & Y) == Y
3133   // (X & Y) != Y
3134   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
3135     std::swap(N0, N1);
3136 
3137   EVT OpVT = N0.getValueType();
3138   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
3139       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
3140     return SDValue();
3141 
3142   SDValue X, Y;
3143   if (N0.getOperand(0) == N1) {
3144     X = N0.getOperand(1);
3145     Y = N0.getOperand(0);
3146   } else if (N0.getOperand(1) == N1) {
3147     X = N0.getOperand(0);
3148     Y = N0.getOperand(1);
3149   } else {
3150     return SDValue();
3151   }
3152 
3153   SelectionDAG &DAG = DCI.DAG;
3154   SDValue Zero = DAG.getConstant(0, DL, OpVT);
3155   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
3156     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
3157     // Note that where Y is variable and is known to have at most one bit set
3158     // (for example, if it is Z & 1) we cannot do this; the expressions are not
3159     // equivalent when Y == 0.
3160     assert(OpVT.isInteger());
3161     Cond = ISD::getSetCCInverse(Cond, OpVT);
3162     if (DCI.isBeforeLegalizeOps() ||
3163         isCondCodeLegal(Cond, N0.getSimpleValueType()))
3164       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
3165   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
3166     // If the target supports an 'and-not' or 'and-complement' logic operation,
3167     // try to use that to make a comparison operation more efficient.
3168     // But don't do this transform if the mask is a single bit because there are
3169     // more efficient ways to deal with that case (for example, 'bt' on x86 or
3170     // 'rlwinm' on PPC).
3171 
3172     // Bail out if the compare operand that we want to turn into a zero is
3173     // already a zero (otherwise, infinite loop).
3174     auto *YConst = dyn_cast<ConstantSDNode>(Y);
3175     if (YConst && YConst->isNullValue())
3176       return SDValue();
3177 
3178     // Transform this into: ~X & Y == 0.
3179     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
3180     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
3181     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
3182   }
3183 
3184   return SDValue();
3185 }
3186 
3187 /// There are multiple IR patterns that could be checking whether certain
3188 /// truncation of a signed number would be lossy or not. The pattern which is
3189 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
3190 /// We are looking for the following pattern: (KeptBits is a constant)
3191 ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
3192 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
3193 /// KeptBits also can't be 1, that would have been folded to  %x dstcond 0
3194 /// We will unfold it into the natural trunc+sext pattern:
3195 ///   ((%x << C) a>> C) dstcond %x
3196 /// Where  C = bitwidth(x) - KeptBits  and  C u< bitwidth(x)
3197 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
3198     EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
3199     const SDLoc &DL) const {
3200   // We must be comparing with a constant.
3201   ConstantSDNode *C1;
3202   if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
3203     return SDValue();
3204 
3205   // N0 should be:  add %x, (1 << (KeptBits-1))
3206   if (N0->getOpcode() != ISD::ADD)
3207     return SDValue();
3208 
3209   // And we must be 'add'ing a constant.
3210   ConstantSDNode *C01;
3211   if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
3212     return SDValue();
3213 
3214   SDValue X = N0->getOperand(0);
3215   EVT XVT = X.getValueType();
3216 
3217   // Validate constants ...
3218 
3219   APInt I1 = C1->getAPIntValue();
3220 
3221   ISD::CondCode NewCond;
3222   if (Cond == ISD::CondCode::SETULT) {
3223     NewCond = ISD::CondCode::SETEQ;
3224   } else if (Cond == ISD::CondCode::SETULE) {
3225     NewCond = ISD::CondCode::SETEQ;
3226     // But need to 'canonicalize' the constant.
3227     I1 += 1;
3228   } else if (Cond == ISD::CondCode::SETUGT) {
3229     NewCond = ISD::CondCode::SETNE;
3230     // But need to 'canonicalize' the constant.
3231     I1 += 1;
3232   } else if (Cond == ISD::CondCode::SETUGE) {
3233     NewCond = ISD::CondCode::SETNE;
3234   } else
3235     return SDValue();
3236 
3237   APInt I01 = C01->getAPIntValue();
3238 
3239   auto checkConstants = [&I1, &I01]() -> bool {
3240     // Both of them must be power-of-two, and the constant from setcc is bigger.
3241     return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
3242   };
3243 
3244   if (checkConstants()) {
3245     // Great, e.g. got  icmp ult i16 (add i16 %x, 128), 256
3246   } else {
3247     // What if we invert constants? (and the target predicate)
3248     I1.negate();
3249     I01.negate();
3250     assert(XVT.isInteger());
3251     NewCond = getSetCCInverse(NewCond, XVT);
3252     if (!checkConstants())
3253       return SDValue();
3254     // Great, e.g. got  icmp uge i16 (add i16 %x, -128), -256
3255   }
3256 
3257   // They are power-of-two, so which bit is set?
3258   const unsigned KeptBits = I1.logBase2();
3259   const unsigned KeptBitsMinusOne = I01.logBase2();
3260 
3261   // Magic!
3262   if (KeptBits != (KeptBitsMinusOne + 1))
3263     return SDValue();
3264   assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
3265 
3266   // We don't want to do this in every single case.
3267   SelectionDAG &DAG = DCI.DAG;
3268   if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
3269           XVT, KeptBits))
3270     return SDValue();
3271 
3272   const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits;
3273   assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable");
3274 
3275   // Unfold into:  ((%x << C) a>> C) cond %x
3276   // Where 'cond' will be either 'eq' or 'ne'.
3277   SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT);
3278   SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt);
3279   SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt);
3280   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond);
3281 
3282   return T2;
3283 }
3284 
3285 // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
3286 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
3287     EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
3288     DAGCombinerInfo &DCI, const SDLoc &DL) const {
3289   assert(isConstOrConstSplat(N1C) &&
3290          isConstOrConstSplat(N1C)->getAPIntValue().isNullValue() &&
3291          "Should be a comparison with 0.");
3292   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3293          "Valid only for [in]equality comparisons.");
3294 
3295   unsigned NewShiftOpcode;
3296   SDValue X, C, Y;
3297 
3298   SelectionDAG &DAG = DCI.DAG;
3299   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3300 
3301   // Look for '(C l>>/<< Y)'.
3302   auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) {
3303     // The shift should be one-use.
3304     if (!V.hasOneUse())
3305       return false;
3306     unsigned OldShiftOpcode = V.getOpcode();
3307     switch (OldShiftOpcode) {
3308     case ISD::SHL:
3309       NewShiftOpcode = ISD::SRL;
3310       break;
3311     case ISD::SRL:
3312       NewShiftOpcode = ISD::SHL;
3313       break;
3314     default:
3315       return false; // must be a logical shift.
3316     }
3317     // We should be shifting a constant.
3318     // FIXME: best to use isConstantOrConstantVector().
3319     C = V.getOperand(0);
3320     ConstantSDNode *CC =
3321         isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3322     if (!CC)
3323       return false;
3324     Y = V.getOperand(1);
3325 
3326     ConstantSDNode *XC =
3327         isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3328     return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
3329         X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
3330   };
3331 
3332   // LHS of comparison should be an one-use 'and'.
3333   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
3334     return SDValue();
3335 
3336   X = N0.getOperand(0);
3337   SDValue Mask = N0.getOperand(1);
3338 
3339   // 'and' is commutative!
3340   if (!Match(Mask)) {
3341     std::swap(X, Mask);
3342     if (!Match(Mask))
3343       return SDValue();
3344   }
3345 
3346   EVT VT = X.getValueType();
3347 
3348   // Produce:
3349   // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
3350   SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
3351   SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
3352   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
3353   return T2;
3354 }
3355 
3356 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
3357 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
3358 /// handle the commuted versions of these patterns.
3359 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
3360                                            ISD::CondCode Cond, const SDLoc &DL,
3361                                            DAGCombinerInfo &DCI) const {
3362   unsigned BOpcode = N0.getOpcode();
3363   assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
3364          "Unexpected binop");
3365   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
3366 
3367   // (X + Y) == X --> Y == 0
3368   // (X - Y) == X --> Y == 0
3369   // (X ^ Y) == X --> Y == 0
3370   SelectionDAG &DAG = DCI.DAG;
3371   EVT OpVT = N0.getValueType();
3372   SDValue X = N0.getOperand(0);
3373   SDValue Y = N0.getOperand(1);
3374   if (X == N1)
3375     return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
3376 
3377   if (Y != N1)
3378     return SDValue();
3379 
3380   // (X + Y) == Y --> X == 0
3381   // (X ^ Y) == Y --> X == 0
3382   if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
3383     return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
3384 
3385   // The shift would not be valid if the operands are boolean (i1).
3386   if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
3387     return SDValue();
3388 
3389   // (X - Y) == Y --> X == Y << 1
3390   EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(),
3391                                  !DCI.isBeforeLegalize());
3392   SDValue One = DAG.getConstant(1, DL, ShiftVT);
3393   SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
3394   if (!DCI.isCalledByLegalizer())
3395     DCI.AddToWorklist(YShl1.getNode());
3396   return DAG.getSetCC(DL, VT, X, YShl1, Cond);
3397 }
3398 
3399 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT,
3400                                       SDValue N0, const APInt &C1,
3401                                       ISD::CondCode Cond, const SDLoc &dl,
3402                                       SelectionDAG &DAG) {
3403   // Look through truncs that don't change the value of a ctpop.
3404   // FIXME: Add vector support? Need to be careful with setcc result type below.
3405   SDValue CTPOP = N0;
3406   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
3407       N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits()))
3408     CTPOP = N0.getOperand(0);
3409 
3410   if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
3411     return SDValue();
3412 
3413   EVT CTVT = CTPOP.getValueType();
3414   SDValue CTOp = CTPOP.getOperand(0);
3415 
3416   // If this is a vector CTPOP, keep the CTPOP if it is legal.
3417   // TODO: Should we check if CTPOP is legal(or custom) for scalars?
3418   if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT))
3419     return SDValue();
3420 
3421   // (ctpop x) u< 2 -> (x & x-1) == 0
3422   // (ctpop x) u> 1 -> (x & x-1) != 0
3423   if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
3424     unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
3425     if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
3426       return SDValue();
3427     if (C1 == 0 && (Cond == ISD::SETULT))
3428       return SDValue(); // This is handled elsewhere.
3429 
3430     unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
3431 
3432     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3433     SDValue Result = CTOp;
3434     for (unsigned i = 0; i < Passes; i++) {
3435       SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
3436       Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
3437     }
3438     ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
3439     return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
3440   }
3441 
3442   // If ctpop is not supported, expand a power-of-2 comparison based on it.
3443   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
3444     // For scalars, keep CTPOP if it is legal or custom.
3445     if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT))
3446       return SDValue();
3447     // This is based on X86's custom lowering for CTPOP which produces more
3448     // instructions than the expansion here.
3449 
3450     // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0)
3451     // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0)
3452     SDValue Zero = DAG.getConstant(0, dl, CTVT);
3453     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3454     assert(CTVT.isInteger());
3455     ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT);
3456     SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
3457     SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
3458     SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond);
3459     SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
3460     unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR;
3461     return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS);
3462   }
3463 
3464   return SDValue();
3465 }
3466 
3467 /// Try to simplify a setcc built with the specified operands and cc. If it is
3468 /// unable to simplify it, return a null SDValue.
3469 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
3470                                       ISD::CondCode Cond, bool foldBooleans,
3471                                       DAGCombinerInfo &DCI,
3472                                       const SDLoc &dl) const {
3473   SelectionDAG &DAG = DCI.DAG;
3474   const DataLayout &Layout = DAG.getDataLayout();
3475   EVT OpVT = N0.getValueType();
3476 
3477   // Constant fold or commute setcc.
3478   if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
3479     return Fold;
3480 
3481   // Ensure that the constant occurs on the RHS and fold constant comparisons.
3482   // TODO: Handle non-splat vector constants. All undef causes trouble.
3483   // FIXME: We can't yet fold constant scalable vector splats, so avoid an
3484   // infinite loop here when we encounter one.
3485   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
3486   if (isConstOrConstSplat(N0) &&
3487       (!OpVT.isScalableVector() || !isConstOrConstSplat(N1)) &&
3488       (DCI.isBeforeLegalizeOps() ||
3489        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
3490     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
3491 
3492   // If we have a subtract with the same 2 non-constant operands as this setcc
3493   // -- but in reverse order -- then try to commute the operands of this setcc
3494   // to match. A matching pair of setcc (cmp) and sub may be combined into 1
3495   // instruction on some targets.
3496   if (!isConstOrConstSplat(N0) && !isConstOrConstSplat(N1) &&
3497       (DCI.isBeforeLegalizeOps() ||
3498        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
3499       DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
3500       !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
3501     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
3502 
3503   if (auto *N1C = isConstOrConstSplat(N1)) {
3504     const APInt &C1 = N1C->getAPIntValue();
3505 
3506     // Optimize some CTPOP cases.
3507     if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
3508       return V;
3509 
3510     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
3511     // equality comparison, then we're just comparing whether X itself is
3512     // zero.
3513     if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) &&
3514         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
3515         isPowerOf2_32(N0.getScalarValueSizeInBits())) {
3516       if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
3517         if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3518             ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
3519           if ((C1 == 0) == (Cond == ISD::SETEQ)) {
3520             // (srl (ctlz x), 5) == 0  -> X != 0
3521             // (srl (ctlz x), 5) != 1  -> X != 0
3522             Cond = ISD::SETNE;
3523           } else {
3524             // (srl (ctlz x), 5) != 0  -> X == 0
3525             // (srl (ctlz x), 5) == 1  -> X == 0
3526             Cond = ISD::SETEQ;
3527           }
3528           SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
3529           return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
3530                               Cond);
3531         }
3532       }
3533     }
3534   }
3535 
3536   // FIXME: Support vectors.
3537   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
3538     const APInt &C1 = N1C->getAPIntValue();
3539 
3540     // (zext x) == C --> x == (trunc C)
3541     // (sext x) == C --> x == (trunc C)
3542     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3543         DCI.isBeforeLegalize() && N0->hasOneUse()) {
3544       unsigned MinBits = N0.getValueSizeInBits();
3545       SDValue PreExt;
3546       bool Signed = false;
3547       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
3548         // ZExt
3549         MinBits = N0->getOperand(0).getValueSizeInBits();
3550         PreExt = N0->getOperand(0);
3551       } else if (N0->getOpcode() == ISD::AND) {
3552         // DAGCombine turns costly ZExts into ANDs
3553         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
3554           if ((C->getAPIntValue()+1).isPowerOf2()) {
3555             MinBits = C->getAPIntValue().countTrailingOnes();
3556             PreExt = N0->getOperand(0);
3557           }
3558       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
3559         // SExt
3560         MinBits = N0->getOperand(0).getValueSizeInBits();
3561         PreExt = N0->getOperand(0);
3562         Signed = true;
3563       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
3564         // ZEXTLOAD / SEXTLOAD
3565         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
3566           MinBits = LN0->getMemoryVT().getSizeInBits();
3567           PreExt = N0;
3568         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
3569           Signed = true;
3570           MinBits = LN0->getMemoryVT().getSizeInBits();
3571           PreExt = N0;
3572         }
3573       }
3574 
3575       // Figure out how many bits we need to preserve this constant.
3576       unsigned ReqdBits = Signed ?
3577         C1.getBitWidth() - C1.getNumSignBits() + 1 :
3578         C1.getActiveBits();
3579 
3580       // Make sure we're not losing bits from the constant.
3581       if (MinBits > 0 &&
3582           MinBits < C1.getBitWidth() &&
3583           MinBits >= ReqdBits) {
3584         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
3585         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
3586           // Will get folded away.
3587           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
3588           if (MinBits == 1 && C1 == 1)
3589             // Invert the condition.
3590             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
3591                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3592           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
3593           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
3594         }
3595 
3596         // If truncating the setcc operands is not desirable, we can still
3597         // simplify the expression in some cases:
3598         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
3599         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
3600         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
3601         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
3602         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
3603         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
3604         SDValue TopSetCC = N0->getOperand(0);
3605         unsigned N0Opc = N0->getOpcode();
3606         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
3607         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
3608             TopSetCC.getOpcode() == ISD::SETCC &&
3609             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
3610             (isConstFalseVal(N1C) ||
3611              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
3612 
3613           bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
3614                          (!N1C->isNullValue() && Cond == ISD::SETNE);
3615 
3616           if (!Inverse)
3617             return TopSetCC;
3618 
3619           ISD::CondCode InvCond = ISD::getSetCCInverse(
3620               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
3621               TopSetCC.getOperand(0).getValueType());
3622           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
3623                                       TopSetCC.getOperand(1),
3624                                       InvCond);
3625         }
3626       }
3627     }
3628 
3629     // If the LHS is '(and load, const)', the RHS is 0, the test is for
3630     // equality or unsigned, and all 1 bits of the const are in the same
3631     // partial word, see if we can shorten the load.
3632     if (DCI.isBeforeLegalize() &&
3633         !ISD::isSignedIntSetCC(Cond) &&
3634         N0.getOpcode() == ISD::AND && C1 == 0 &&
3635         N0.getNode()->hasOneUse() &&
3636         isa<LoadSDNode>(N0.getOperand(0)) &&
3637         N0.getOperand(0).getNode()->hasOneUse() &&
3638         isa<ConstantSDNode>(N0.getOperand(1))) {
3639       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
3640       APInt bestMask;
3641       unsigned bestWidth = 0, bestOffset = 0;
3642       if (Lod->isSimple() && Lod->isUnindexed()) {
3643         unsigned origWidth = N0.getValueSizeInBits();
3644         unsigned maskWidth = origWidth;
3645         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
3646         // 8 bits, but have to be careful...
3647         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
3648           origWidth = Lod->getMemoryVT().getSizeInBits();
3649         const APInt &Mask = N0.getConstantOperandAPInt(1);
3650         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
3651           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
3652           for (unsigned offset=0; offset<origWidth/width; offset++) {
3653             if (Mask.isSubsetOf(newMask)) {
3654               if (Layout.isLittleEndian())
3655                 bestOffset = (uint64_t)offset * (width/8);
3656               else
3657                 bestOffset = (origWidth/width - offset - 1) * (width/8);
3658               bestMask = Mask.lshr(offset * (width/8) * 8);
3659               bestWidth = width;
3660               break;
3661             }
3662             newMask <<= width;
3663           }
3664         }
3665       }
3666       if (bestWidth) {
3667         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
3668         if (newVT.isRound() &&
3669             shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
3670           SDValue Ptr = Lod->getBasePtr();
3671           if (bestOffset != 0)
3672             Ptr =
3673                 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl);
3674           SDValue NewLoad =
3675               DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
3676                           Lod->getPointerInfo().getWithOffset(bestOffset),
3677                           Lod->getOriginalAlign());
3678           return DAG.getSetCC(dl, VT,
3679                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
3680                                       DAG.getConstant(bestMask.trunc(bestWidth),
3681                                                       dl, newVT)),
3682                               DAG.getConstant(0LL, dl, newVT), Cond);
3683         }
3684       }
3685     }
3686 
3687     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
3688     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
3689       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
3690 
3691       // If the comparison constant has bits in the upper part, the
3692       // zero-extended value could never match.
3693       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
3694                                               C1.getBitWidth() - InSize))) {
3695         switch (Cond) {
3696         case ISD::SETUGT:
3697         case ISD::SETUGE:
3698         case ISD::SETEQ:
3699           return DAG.getConstant(0, dl, VT);
3700         case ISD::SETULT:
3701         case ISD::SETULE:
3702         case ISD::SETNE:
3703           return DAG.getConstant(1, dl, VT);
3704         case ISD::SETGT:
3705         case ISD::SETGE:
3706           // True if the sign bit of C1 is set.
3707           return DAG.getConstant(C1.isNegative(), dl, VT);
3708         case ISD::SETLT:
3709         case ISD::SETLE:
3710           // True if the sign bit of C1 isn't set.
3711           return DAG.getConstant(C1.isNonNegative(), dl, VT);
3712         default:
3713           break;
3714         }
3715       }
3716 
3717       // Otherwise, we can perform the comparison with the low bits.
3718       switch (Cond) {
3719       case ISD::SETEQ:
3720       case ISD::SETNE:
3721       case ISD::SETUGT:
3722       case ISD::SETUGE:
3723       case ISD::SETULT:
3724       case ISD::SETULE: {
3725         EVT newVT = N0.getOperand(0).getValueType();
3726         if (DCI.isBeforeLegalizeOps() ||
3727             (isOperationLegal(ISD::SETCC, newVT) &&
3728              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
3729           EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
3730           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
3731 
3732           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
3733                                           NewConst, Cond);
3734           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
3735         }
3736         break;
3737       }
3738       default:
3739         break; // todo, be more careful with signed comparisons
3740       }
3741     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3742                (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3743                !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(),
3744                                       OpVT)) {
3745       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
3746       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
3747       EVT ExtDstTy = N0.getValueType();
3748       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
3749 
3750       // If the constant doesn't fit into the number of bits for the source of
3751       // the sign extension, it is impossible for both sides to be equal.
3752       if (C1.getMinSignedBits() > ExtSrcTyBits)
3753         return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
3754 
3755       assert(ExtDstTy == N0.getOperand(0).getValueType() &&
3756              ExtDstTy != ExtSrcTy && "Unexpected types!");
3757       APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
3758       SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
3759                                    DAG.getConstant(Imm, dl, ExtDstTy));
3760       if (!DCI.isCalledByLegalizer())
3761         DCI.AddToWorklist(ZextOp.getNode());
3762       // Otherwise, make this a use of a zext.
3763       return DAG.getSetCC(dl, VT, ZextOp,
3764                           DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
3765     } else if ((N1C->isNullValue() || N1C->isOne()) &&
3766                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3767       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
3768       if (N0.getOpcode() == ISD::SETCC &&
3769           isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
3770           (N0.getValueType() == MVT::i1 ||
3771            getBooleanContents(N0.getOperand(0).getValueType()) ==
3772                        ZeroOrOneBooleanContent)) {
3773         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
3774         if (TrueWhenTrue)
3775           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
3776         // Invert the condition.
3777         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
3778         CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType());
3779         if (DCI.isBeforeLegalizeOps() ||
3780             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
3781           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
3782       }
3783 
3784       if ((N0.getOpcode() == ISD::XOR ||
3785            (N0.getOpcode() == ISD::AND &&
3786             N0.getOperand(0).getOpcode() == ISD::XOR &&
3787             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
3788           isOneConstant(N0.getOperand(1))) {
3789         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
3790         // can only do this if the top bits are known zero.
3791         unsigned BitWidth = N0.getValueSizeInBits();
3792         if (DAG.MaskedValueIsZero(N0,
3793                                   APInt::getHighBitsSet(BitWidth,
3794                                                         BitWidth-1))) {
3795           // Okay, get the un-inverted input value.
3796           SDValue Val;
3797           if (N0.getOpcode() == ISD::XOR) {
3798             Val = N0.getOperand(0);
3799           } else {
3800             assert(N0.getOpcode() == ISD::AND &&
3801                     N0.getOperand(0).getOpcode() == ISD::XOR);
3802             // ((X^1)&1)^1 -> X & 1
3803             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
3804                               N0.getOperand(0).getOperand(0),
3805                               N0.getOperand(1));
3806           }
3807 
3808           return DAG.getSetCC(dl, VT, Val, N1,
3809                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3810         }
3811       } else if (N1C->isOne()) {
3812         SDValue Op0 = N0;
3813         if (Op0.getOpcode() == ISD::TRUNCATE)
3814           Op0 = Op0.getOperand(0);
3815 
3816         if ((Op0.getOpcode() == ISD::XOR) &&
3817             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
3818             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
3819           SDValue XorLHS = Op0.getOperand(0);
3820           SDValue XorRHS = Op0.getOperand(1);
3821           // Ensure that the input setccs return an i1 type or 0/1 value.
3822           if (Op0.getValueType() == MVT::i1 ||
3823               (getBooleanContents(XorLHS.getOperand(0).getValueType()) ==
3824                       ZeroOrOneBooleanContent &&
3825                getBooleanContents(XorRHS.getOperand(0).getValueType()) ==
3826                         ZeroOrOneBooleanContent)) {
3827             // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
3828             Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
3829             return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
3830           }
3831         }
3832         if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
3833           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
3834           if (Op0.getValueType().bitsGT(VT))
3835             Op0 = DAG.getNode(ISD::AND, dl, VT,
3836                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
3837                           DAG.getConstant(1, dl, VT));
3838           else if (Op0.getValueType().bitsLT(VT))
3839             Op0 = DAG.getNode(ISD::AND, dl, VT,
3840                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
3841                         DAG.getConstant(1, dl, VT));
3842 
3843           return DAG.getSetCC(dl, VT, Op0,
3844                               DAG.getConstant(0, dl, Op0.getValueType()),
3845                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3846         }
3847         if (Op0.getOpcode() == ISD::AssertZext &&
3848             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
3849           return DAG.getSetCC(dl, VT, Op0,
3850                               DAG.getConstant(0, dl, Op0.getValueType()),
3851                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3852       }
3853     }
3854 
3855     // Given:
3856     //   icmp eq/ne (urem %x, %y), 0
3857     // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
3858     //   icmp eq/ne %x, 0
3859     if (N0.getOpcode() == ISD::UREM && N1C->isNullValue() &&
3860         (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3861       KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
3862       KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
3863       if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
3864         return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
3865     }
3866 
3867     if (SDValue V =
3868             optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
3869       return V;
3870   }
3871 
3872   // These simplifications apply to splat vectors as well.
3873   // TODO: Handle more splat vector cases.
3874   if (auto *N1C = isConstOrConstSplat(N1)) {
3875     const APInt &C1 = N1C->getAPIntValue();
3876 
3877     APInt MinVal, MaxVal;
3878     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
3879     if (ISD::isSignedIntSetCC(Cond)) {
3880       MinVal = APInt::getSignedMinValue(OperandBitSize);
3881       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
3882     } else {
3883       MinVal = APInt::getMinValue(OperandBitSize);
3884       MaxVal = APInt::getMaxValue(OperandBitSize);
3885     }
3886 
3887     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
3888     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
3889       // X >= MIN --> true
3890       if (C1 == MinVal)
3891         return DAG.getBoolConstant(true, dl, VT, OpVT);
3892 
3893       if (!VT.isVector()) { // TODO: Support this for vectors.
3894         // X >= C0 --> X > (C0 - 1)
3895         APInt C = C1 - 1;
3896         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
3897         if ((DCI.isBeforeLegalizeOps() ||
3898              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
3899             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
3900                                   isLegalICmpImmediate(C.getSExtValue())))) {
3901           return DAG.getSetCC(dl, VT, N0,
3902                               DAG.getConstant(C, dl, N1.getValueType()),
3903                               NewCC);
3904         }
3905       }
3906     }
3907 
3908     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
3909       // X <= MAX --> true
3910       if (C1 == MaxVal)
3911         return DAG.getBoolConstant(true, dl, VT, OpVT);
3912 
3913       // X <= C0 --> X < (C0 + 1)
3914       if (!VT.isVector()) { // TODO: Support this for vectors.
3915         APInt C = C1 + 1;
3916         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
3917         if ((DCI.isBeforeLegalizeOps() ||
3918              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
3919             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
3920                                   isLegalICmpImmediate(C.getSExtValue())))) {
3921           return DAG.getSetCC(dl, VT, N0,
3922                               DAG.getConstant(C, dl, N1.getValueType()),
3923                               NewCC);
3924         }
3925       }
3926     }
3927 
3928     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
3929       if (C1 == MinVal)
3930         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
3931 
3932       // TODO: Support this for vectors after legalize ops.
3933       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
3934         // Canonicalize setlt X, Max --> setne X, Max
3935         if (C1 == MaxVal)
3936           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
3937 
3938         // If we have setult X, 1, turn it into seteq X, 0
3939         if (C1 == MinVal+1)
3940           return DAG.getSetCC(dl, VT, N0,
3941                               DAG.getConstant(MinVal, dl, N0.getValueType()),
3942                               ISD::SETEQ);
3943       }
3944     }
3945 
3946     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
3947       if (C1 == MaxVal)
3948         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
3949 
3950       // TODO: Support this for vectors after legalize ops.
3951       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
3952         // Canonicalize setgt X, Min --> setne X, Min
3953         if (C1 == MinVal)
3954           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
3955 
3956         // If we have setugt X, Max-1, turn it into seteq X, Max
3957         if (C1 == MaxVal-1)
3958           return DAG.getSetCC(dl, VT, N0,
3959                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
3960                               ISD::SETEQ);
3961       }
3962     }
3963 
3964     if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
3965       // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
3966       if (C1.isNullValue())
3967         if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
3968                 VT, N0, N1, Cond, DCI, dl))
3969           return CC;
3970 
3971       // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
3972       // For example, when high 32-bits of i64 X are known clear:
3973       // all bits clear: (X | (Y<<32)) ==  0 --> (X | Y) ==  0
3974       // all bits set:   (X | (Y<<32)) == -1 --> (X & Y) == -1
3975       bool CmpZero = N1C->getAPIntValue().isNullValue();
3976       bool CmpNegOne = N1C->getAPIntValue().isAllOnesValue();
3977       if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
3978         // Match or(lo,shl(hi,bw/2)) pattern.
3979         auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
3980           unsigned EltBits = V.getScalarValueSizeInBits();
3981           if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
3982             return false;
3983           SDValue LHS = V.getOperand(0);
3984           SDValue RHS = V.getOperand(1);
3985           APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
3986           // Unshifted element must have zero upperbits.
3987           if (RHS.getOpcode() == ISD::SHL &&
3988               isa<ConstantSDNode>(RHS.getOperand(1)) &&
3989               RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
3990               DAG.MaskedValueIsZero(LHS, HiBits)) {
3991             Lo = LHS;
3992             Hi = RHS.getOperand(0);
3993             return true;
3994           }
3995           if (LHS.getOpcode() == ISD::SHL &&
3996               isa<ConstantSDNode>(LHS.getOperand(1)) &&
3997               LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
3998               DAG.MaskedValueIsZero(RHS, HiBits)) {
3999             Lo = RHS;
4000             Hi = LHS.getOperand(0);
4001             return true;
4002           }
4003           return false;
4004         };
4005 
4006         auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
4007           unsigned EltBits = N0.getScalarValueSizeInBits();
4008           unsigned HalfBits = EltBits / 2;
4009           APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
4010           SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
4011           SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
4012           SDValue NewN0 =
4013               DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
4014           SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
4015           return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
4016         };
4017 
4018         SDValue Lo, Hi;
4019         if (IsConcat(N0, Lo, Hi))
4020           return MergeConcat(Lo, Hi);
4021 
4022         if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
4023           SDValue Lo0, Lo1, Hi0, Hi1;
4024           if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
4025               IsConcat(N0.getOperand(1), Lo1, Hi1)) {
4026             return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
4027                                DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
4028           }
4029         }
4030       }
4031     }
4032 
4033     // If we have "setcc X, C0", check to see if we can shrink the immediate
4034     // by changing cc.
4035     // TODO: Support this for vectors after legalize ops.
4036     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4037       // SETUGT X, SINTMAX  -> SETLT X, 0
4038       // SETUGE X, SINTMIN -> SETLT X, 0
4039       if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
4040           (Cond == ISD::SETUGE && C1.isMinSignedValue()))
4041         return DAG.getSetCC(dl, VT, N0,
4042                             DAG.getConstant(0, dl, N1.getValueType()),
4043                             ISD::SETLT);
4044 
4045       // SETULT X, SINTMIN  -> SETGT X, -1
4046       // SETULE X, SINTMAX  -> SETGT X, -1
4047       if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
4048           (Cond == ISD::SETULE && C1.isMaxSignedValue()))
4049         return DAG.getSetCC(dl, VT, N0,
4050                             DAG.getAllOnesConstant(dl, N1.getValueType()),
4051                             ISD::SETGT);
4052     }
4053   }
4054 
4055   // Back to non-vector simplifications.
4056   // TODO: Can we do these for vector splats?
4057   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4058     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4059     const APInt &C1 = N1C->getAPIntValue();
4060     EVT ShValTy = N0.getValueType();
4061 
4062     // Fold bit comparisons when we can. This will result in an
4063     // incorrect value when boolean false is negative one, unless
4064     // the bitsize is 1 in which case the false value is the same
4065     // in practice regardless of the representation.
4066     if ((VT.getSizeInBits() == 1 ||
4067          getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) &&
4068         (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4069         (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
4070         N0.getOpcode() == ISD::AND) {
4071       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4072         EVT ShiftTy =
4073             getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4074         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
4075           // Perform the xform if the AND RHS is a single bit.
4076           unsigned ShCt = AndRHS->getAPIntValue().logBase2();
4077           if (AndRHS->getAPIntValue().isPowerOf2() &&
4078               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4079             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4080                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4081                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4082           }
4083         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
4084           // (X & 8) == 8  -->  (X & 8) >> 3
4085           // Perform the xform if C1 is a single bit.
4086           unsigned ShCt = C1.logBase2();
4087           if (C1.isPowerOf2() &&
4088               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4089             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4090                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4091                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4092           }
4093         }
4094       }
4095     }
4096 
4097     if (C1.getMinSignedBits() <= 64 &&
4098         !isLegalICmpImmediate(C1.getSExtValue())) {
4099       EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4100       // (X & -256) == 256 -> (X >> 8) == 1
4101       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4102           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
4103         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4104           const APInt &AndRHSC = AndRHS->getAPIntValue();
4105           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
4106             unsigned ShiftBits = AndRHSC.countTrailingZeros();
4107             if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4108               SDValue Shift =
4109                 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0),
4110                             DAG.getConstant(ShiftBits, dl, ShiftTy));
4111               SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy);
4112               return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
4113             }
4114           }
4115         }
4116       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
4117                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
4118         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
4119         // X <  0x100000000 -> (X >> 32) <  1
4120         // X >= 0x100000000 -> (X >> 32) >= 1
4121         // X <= 0x0ffffffff -> (X >> 32) <  1
4122         // X >  0x0ffffffff -> (X >> 32) >= 1
4123         unsigned ShiftBits;
4124         APInt NewC = C1;
4125         ISD::CondCode NewCond = Cond;
4126         if (AdjOne) {
4127           ShiftBits = C1.countTrailingOnes();
4128           NewC = NewC + 1;
4129           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4130         } else {
4131           ShiftBits = C1.countTrailingZeros();
4132         }
4133         NewC.lshrInPlace(ShiftBits);
4134         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
4135             isLegalICmpImmediate(NewC.getSExtValue()) &&
4136             !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4137           SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4138                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
4139           SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
4140           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
4141         }
4142       }
4143     }
4144   }
4145 
4146   if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
4147     auto *CFP = cast<ConstantFPSDNode>(N1);
4148     assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
4149 
4150     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
4151     // constant if knowing that the operand is non-nan is enough.  We prefer to
4152     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
4153     // materialize 0.0.
4154     if (Cond == ISD::SETO || Cond == ISD::SETUO)
4155       return DAG.getSetCC(dl, VT, N0, N0, Cond);
4156 
4157     // setcc (fneg x), C -> setcc swap(pred) x, -C
4158     if (N0.getOpcode() == ISD::FNEG) {
4159       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
4160       if (DCI.isBeforeLegalizeOps() ||
4161           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
4162         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
4163         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
4164       }
4165     }
4166 
4167     // If the condition is not legal, see if we can find an equivalent one
4168     // which is legal.
4169     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
4170       // If the comparison was an awkward floating-point == or != and one of
4171       // the comparison operands is infinity or negative infinity, convert the
4172       // condition to a less-awkward <= or >=.
4173       if (CFP->getValueAPF().isInfinity()) {
4174         bool IsNegInf = CFP->getValueAPF().isNegative();
4175         ISD::CondCode NewCond = ISD::SETCC_INVALID;
4176         switch (Cond) {
4177         case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
4178         case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
4179         case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
4180         case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
4181         default: break;
4182         }
4183         if (NewCond != ISD::SETCC_INVALID &&
4184             isCondCodeLegal(NewCond, N0.getSimpleValueType()))
4185           return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4186       }
4187     }
4188   }
4189 
4190   if (N0 == N1) {
4191     // The sext(setcc()) => setcc() optimization relies on the appropriate
4192     // constant being emitted.
4193     assert(!N0.getValueType().isInteger() &&
4194            "Integer types should be handled by FoldSetCC");
4195 
4196     bool EqTrue = ISD::isTrueWhenEqual(Cond);
4197     unsigned UOF = ISD::getUnorderedFlavor(Cond);
4198     if (UOF == 2) // FP operators that are undefined on NaNs.
4199       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4200     if (UOF == unsigned(EqTrue))
4201       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4202     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
4203     // if it is not already.
4204     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
4205     if (NewCond != Cond &&
4206         (DCI.isBeforeLegalizeOps() ||
4207                             isCondCodeLegal(NewCond, N0.getSimpleValueType())))
4208       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4209   }
4210 
4211   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4212       N0.getValueType().isInteger()) {
4213     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
4214         N0.getOpcode() == ISD::XOR) {
4215       // Simplify (X+Y) == (X+Z) -->  Y == Z
4216       if (N0.getOpcode() == N1.getOpcode()) {
4217         if (N0.getOperand(0) == N1.getOperand(0))
4218           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
4219         if (N0.getOperand(1) == N1.getOperand(1))
4220           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
4221         if (isCommutativeBinOp(N0.getOpcode())) {
4222           // If X op Y == Y op X, try other combinations.
4223           if (N0.getOperand(0) == N1.getOperand(1))
4224             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
4225                                 Cond);
4226           if (N0.getOperand(1) == N1.getOperand(0))
4227             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
4228                                 Cond);
4229         }
4230       }
4231 
4232       // If RHS is a legal immediate value for a compare instruction, we need
4233       // to be careful about increasing register pressure needlessly.
4234       bool LegalRHSImm = false;
4235 
4236       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
4237         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4238           // Turn (X+C1) == C2 --> X == C2-C1
4239           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
4240             return DAG.getSetCC(dl, VT, N0.getOperand(0),
4241                                 DAG.getConstant(RHSC->getAPIntValue()-
4242                                                 LHSR->getAPIntValue(),
4243                                 dl, N0.getValueType()), Cond);
4244           }
4245 
4246           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
4247           if (N0.getOpcode() == ISD::XOR)
4248             // If we know that all of the inverted bits are zero, don't bother
4249             // performing the inversion.
4250             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
4251               return
4252                 DAG.getSetCC(dl, VT, N0.getOperand(0),
4253                              DAG.getConstant(LHSR->getAPIntValue() ^
4254                                                RHSC->getAPIntValue(),
4255                                              dl, N0.getValueType()),
4256                              Cond);
4257         }
4258 
4259         // Turn (C1-X) == C2 --> X == C1-C2
4260         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
4261           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
4262             return
4263               DAG.getSetCC(dl, VT, N0.getOperand(1),
4264                            DAG.getConstant(SUBC->getAPIntValue() -
4265                                              RHSC->getAPIntValue(),
4266                                            dl, N0.getValueType()),
4267                            Cond);
4268           }
4269         }
4270 
4271         // Could RHSC fold directly into a compare?
4272         if (RHSC->getValueType(0).getSizeInBits() <= 64)
4273           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
4274       }
4275 
4276       // (X+Y) == X --> Y == 0 and similar folds.
4277       // Don't do this if X is an immediate that can fold into a cmp
4278       // instruction and X+Y has other uses. It could be an induction variable
4279       // chain, and the transform would increase register pressure.
4280       if (!LegalRHSImm || N0.hasOneUse())
4281         if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
4282           return V;
4283     }
4284 
4285     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
4286         N1.getOpcode() == ISD::XOR)
4287       if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
4288         return V;
4289 
4290     if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
4291       return V;
4292   }
4293 
4294   // Fold remainder of division by a constant.
4295   if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
4296       N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4297     AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4298 
4299     // When division is cheap or optimizing for minimum size,
4300     // fall through to DIVREM creation by skipping this fold.
4301     if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttribute(Attribute::MinSize)) {
4302       if (N0.getOpcode() == ISD::UREM) {
4303         if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
4304           return Folded;
4305       } else if (N0.getOpcode() == ISD::SREM) {
4306         if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
4307           return Folded;
4308       }
4309     }
4310   }
4311 
4312   // Fold away ALL boolean setcc's.
4313   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
4314     SDValue Temp;
4315     switch (Cond) {
4316     default: llvm_unreachable("Unknown integer setcc!");
4317     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
4318       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4319       N0 = DAG.getNOT(dl, Temp, OpVT);
4320       if (!DCI.isCalledByLegalizer())
4321         DCI.AddToWorklist(Temp.getNode());
4322       break;
4323     case ISD::SETNE:  // X != Y   -->  (X^Y)
4324       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4325       break;
4326     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
4327     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
4328       Temp = DAG.getNOT(dl, N0, OpVT);
4329       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
4330       if (!DCI.isCalledByLegalizer())
4331         DCI.AddToWorklist(Temp.getNode());
4332       break;
4333     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
4334     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
4335       Temp = DAG.getNOT(dl, N1, OpVT);
4336       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
4337       if (!DCI.isCalledByLegalizer())
4338         DCI.AddToWorklist(Temp.getNode());
4339       break;
4340     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
4341     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
4342       Temp = DAG.getNOT(dl, N0, OpVT);
4343       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
4344       if (!DCI.isCalledByLegalizer())
4345         DCI.AddToWorklist(Temp.getNode());
4346       break;
4347     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
4348     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
4349       Temp = DAG.getNOT(dl, N1, OpVT);
4350       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
4351       break;
4352     }
4353     if (VT.getScalarType() != MVT::i1) {
4354       if (!DCI.isCalledByLegalizer())
4355         DCI.AddToWorklist(N0.getNode());
4356       // FIXME: If running after legalize, we probably can't do this.
4357       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
4358       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
4359     }
4360     return N0;
4361   }
4362 
4363   // Could not fold it.
4364   return SDValue();
4365 }
4366 
4367 /// Returns true (and the GlobalValue and the offset) if the node is a
4368 /// GlobalAddress + offset.
4369 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA,
4370                                     int64_t &Offset) const {
4371 
4372   SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
4373 
4374   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
4375     GA = GASD->getGlobal();
4376     Offset += GASD->getOffset();
4377     return true;
4378   }
4379 
4380   if (N->getOpcode() == ISD::ADD) {
4381     SDValue N1 = N->getOperand(0);
4382     SDValue N2 = N->getOperand(1);
4383     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
4384       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
4385         Offset += V->getSExtValue();
4386         return true;
4387       }
4388     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
4389       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
4390         Offset += V->getSExtValue();
4391         return true;
4392       }
4393     }
4394   }
4395 
4396   return false;
4397 }
4398 
4399 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
4400                                           DAGCombinerInfo &DCI) const {
4401   // Default implementation: no optimization.
4402   return SDValue();
4403 }
4404 
4405 //===----------------------------------------------------------------------===//
4406 //  Inline Assembler Implementation Methods
4407 //===----------------------------------------------------------------------===//
4408 
4409 TargetLowering::ConstraintType
4410 TargetLowering::getConstraintType(StringRef Constraint) const {
4411   unsigned S = Constraint.size();
4412 
4413   if (S == 1) {
4414     switch (Constraint[0]) {
4415     default: break;
4416     case 'r':
4417       return C_RegisterClass;
4418     case 'm': // memory
4419     case 'o': // offsetable
4420     case 'V': // not offsetable
4421       return C_Memory;
4422     case 'n': // Simple Integer
4423     case 'E': // Floating Point Constant
4424     case 'F': // Floating Point Constant
4425       return C_Immediate;
4426     case 'i': // Simple Integer or Relocatable Constant
4427     case 's': // Relocatable Constant
4428     case 'p': // Address.
4429     case 'X': // Allow ANY value.
4430     case 'I': // Target registers.
4431     case 'J':
4432     case 'K':
4433     case 'L':
4434     case 'M':
4435     case 'N':
4436     case 'O':
4437     case 'P':
4438     case '<':
4439     case '>':
4440       return C_Other;
4441     }
4442   }
4443 
4444   if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
4445     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
4446       return C_Memory;
4447     return C_Register;
4448   }
4449   return C_Unknown;
4450 }
4451 
4452 /// Try to replace an X constraint, which matches anything, with another that
4453 /// has more specific requirements based on the type of the corresponding
4454 /// operand.
4455 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4456   if (ConstraintVT.isInteger())
4457     return "r";
4458   if (ConstraintVT.isFloatingPoint())
4459     return "f"; // works for many targets
4460   return nullptr;
4461 }
4462 
4463 SDValue TargetLowering::LowerAsmOutputForConstraint(
4464     SDValue &Chain, SDValue &Flag, const SDLoc &DL,
4465     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
4466   return SDValue();
4467 }
4468 
4469 /// Lower the specified operand into the Ops vector.
4470 /// If it is invalid, don't add anything to Ops.
4471 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4472                                                   std::string &Constraint,
4473                                                   std::vector<SDValue> &Ops,
4474                                                   SelectionDAG &DAG) const {
4475 
4476   if (Constraint.length() > 1) return;
4477 
4478   char ConstraintLetter = Constraint[0];
4479   switch (ConstraintLetter) {
4480   default: break;
4481   case 'X':     // Allows any operand; labels (basic block) use this.
4482     if (Op.getOpcode() == ISD::BasicBlock ||
4483         Op.getOpcode() == ISD::TargetBlockAddress) {
4484       Ops.push_back(Op);
4485       return;
4486     }
4487     LLVM_FALLTHROUGH;
4488   case 'i':    // Simple Integer or Relocatable Constant
4489   case 'n':    // Simple Integer
4490   case 's': {  // Relocatable Constant
4491 
4492     GlobalAddressSDNode *GA;
4493     ConstantSDNode *C;
4494     BlockAddressSDNode *BA;
4495     uint64_t Offset = 0;
4496 
4497     // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
4498     // etc., since getelementpointer is variadic. We can't use
4499     // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
4500     // while in this case the GA may be furthest from the root node which is
4501     // likely an ISD::ADD.
4502     while (1) {
4503       if ((GA = dyn_cast<GlobalAddressSDNode>(Op)) && ConstraintLetter != 'n') {
4504         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
4505                                                  GA->getValueType(0),
4506                                                  Offset + GA->getOffset()));
4507         return;
4508       }
4509       if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
4510         // gcc prints these as sign extended.  Sign extend value to 64 bits
4511         // now; without this it would get ZExt'd later in
4512         // ScheduleDAGSDNodes::EmitNode, which is very generic.
4513         bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
4514         BooleanContent BCont = getBooleanContents(MVT::i64);
4515         ISD::NodeType ExtOpc =
4516             IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
4517         int64_t ExtVal =
4518             ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
4519         Ops.push_back(
4520             DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
4521         return;
4522       }
4523       if ((BA = dyn_cast<BlockAddressSDNode>(Op)) && ConstraintLetter != 'n') {
4524         Ops.push_back(DAG.getTargetBlockAddress(
4525             BA->getBlockAddress(), BA->getValueType(0),
4526             Offset + BA->getOffset(), BA->getTargetFlags()));
4527         return;
4528       }
4529       const unsigned OpCode = Op.getOpcode();
4530       if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
4531         if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
4532           Op = Op.getOperand(1);
4533         // Subtraction is not commutative.
4534         else if (OpCode == ISD::ADD &&
4535                  (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
4536           Op = Op.getOperand(0);
4537         else
4538           return;
4539         Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
4540         continue;
4541       }
4542       return;
4543     }
4544     break;
4545   }
4546   }
4547 }
4548 
4549 std::pair<unsigned, const TargetRegisterClass *>
4550 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
4551                                              StringRef Constraint,
4552                                              MVT VT) const {
4553   if (Constraint.empty() || Constraint[0] != '{')
4554     return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
4555   assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
4556 
4557   // Remove the braces from around the name.
4558   StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
4559 
4560   std::pair<unsigned, const TargetRegisterClass *> R =
4561       std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
4562 
4563   // Figure out which register class contains this reg.
4564   for (const TargetRegisterClass *RC : RI->regclasses()) {
4565     // If none of the value types for this register class are valid, we
4566     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
4567     if (!isLegalRC(*RI, *RC))
4568       continue;
4569 
4570     for (const MCPhysReg &PR : *RC) {
4571       if (RegName.equals_lower(RI->getRegAsmName(PR))) {
4572         std::pair<unsigned, const TargetRegisterClass *> S =
4573             std::make_pair(PR, RC);
4574 
4575         // If this register class has the requested value type, return it,
4576         // otherwise keep searching and return the first class found
4577         // if no other is found which explicitly has the requested type.
4578         if (RI->isTypeLegalForClass(*RC, VT))
4579           return S;
4580         if (!R.second)
4581           R = S;
4582       }
4583     }
4584   }
4585 
4586   return R;
4587 }
4588 
4589 //===----------------------------------------------------------------------===//
4590 // Constraint Selection.
4591 
4592 /// Return true of this is an input operand that is a matching constraint like
4593 /// "4".
4594 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
4595   assert(!ConstraintCode.empty() && "No known constraint!");
4596   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
4597 }
4598 
4599 /// If this is an input matching constraint, this method returns the output
4600 /// operand it matches.
4601 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
4602   assert(!ConstraintCode.empty() && "No known constraint!");
4603   return atoi(ConstraintCode.c_str());
4604 }
4605 
4606 /// Split up the constraint string from the inline assembly value into the
4607 /// specific constraints and their prefixes, and also tie in the associated
4608 /// operand values.
4609 /// If this returns an empty vector, and if the constraint string itself
4610 /// isn't empty, there was an error parsing.
4611 TargetLowering::AsmOperandInfoVector
4612 TargetLowering::ParseConstraints(const DataLayout &DL,
4613                                  const TargetRegisterInfo *TRI,
4614                                  const CallBase &Call) const {
4615   /// Information about all of the constraints.
4616   AsmOperandInfoVector ConstraintOperands;
4617   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
4618   unsigned maCount = 0; // Largest number of multiple alternative constraints.
4619 
4620   // Do a prepass over the constraints, canonicalizing them, and building up the
4621   // ConstraintOperands list.
4622   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4623   unsigned ResNo = 0; // ResNo - The result number of the next output.
4624 
4625   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
4626     ConstraintOperands.emplace_back(std::move(CI));
4627     AsmOperandInfo &OpInfo = ConstraintOperands.back();
4628 
4629     // Update multiple alternative constraint count.
4630     if (OpInfo.multipleAlternatives.size() > maCount)
4631       maCount = OpInfo.multipleAlternatives.size();
4632 
4633     OpInfo.ConstraintVT = MVT::Other;
4634 
4635     // Compute the value type for each operand.
4636     switch (OpInfo.Type) {
4637     case InlineAsm::isOutput:
4638       // Indirect outputs just consume an argument.
4639       if (OpInfo.isIndirect) {
4640         OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
4641         break;
4642       }
4643 
4644       // The return value of the call is this value.  As such, there is no
4645       // corresponding argument.
4646       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
4647       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
4648         OpInfo.ConstraintVT =
4649             getSimpleValueType(DL, STy->getElementType(ResNo));
4650       } else {
4651         assert(ResNo == 0 && "Asm only has one result!");
4652         OpInfo.ConstraintVT = getSimpleValueType(DL, Call.getType());
4653       }
4654       ++ResNo;
4655       break;
4656     case InlineAsm::isInput:
4657       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
4658       break;
4659     case InlineAsm::isClobber:
4660       // Nothing to do.
4661       break;
4662     }
4663 
4664     if (OpInfo.CallOperandVal) {
4665       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
4666       if (OpInfo.isIndirect) {
4667         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
4668         if (!PtrTy)
4669           report_fatal_error("Indirect operand for inline asm not a pointer!");
4670         OpTy = PtrTy->getElementType();
4671       }
4672 
4673       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
4674       if (StructType *STy = dyn_cast<StructType>(OpTy))
4675         if (STy->getNumElements() == 1)
4676           OpTy = STy->getElementType(0);
4677 
4678       // If OpTy is not a single value, it may be a struct/union that we
4679       // can tile with integers.
4680       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4681         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
4682         switch (BitSize) {
4683         default: break;
4684         case 1:
4685         case 8:
4686         case 16:
4687         case 32:
4688         case 64:
4689         case 128:
4690           OpInfo.ConstraintVT =
4691               MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
4692           break;
4693         }
4694       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
4695         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
4696         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
4697       } else {
4698         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
4699       }
4700     }
4701   }
4702 
4703   // If we have multiple alternative constraints, select the best alternative.
4704   if (!ConstraintOperands.empty()) {
4705     if (maCount) {
4706       unsigned bestMAIndex = 0;
4707       int bestWeight = -1;
4708       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
4709       int weight = -1;
4710       unsigned maIndex;
4711       // Compute the sums of the weights for each alternative, keeping track
4712       // of the best (highest weight) one so far.
4713       for (maIndex = 0; maIndex < maCount; ++maIndex) {
4714         int weightSum = 0;
4715         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4716              cIndex != eIndex; ++cIndex) {
4717           AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
4718           if (OpInfo.Type == InlineAsm::isClobber)
4719             continue;
4720 
4721           // If this is an output operand with a matching input operand,
4722           // look up the matching input. If their types mismatch, e.g. one
4723           // is an integer, the other is floating point, or their sizes are
4724           // different, flag it as an maCantMatch.
4725           if (OpInfo.hasMatchingInput()) {
4726             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4727             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4728               if ((OpInfo.ConstraintVT.isInteger() !=
4729                    Input.ConstraintVT.isInteger()) ||
4730                   (OpInfo.ConstraintVT.getSizeInBits() !=
4731                    Input.ConstraintVT.getSizeInBits())) {
4732                 weightSum = -1; // Can't match.
4733                 break;
4734               }
4735             }
4736           }
4737           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
4738           if (weight == -1) {
4739             weightSum = -1;
4740             break;
4741           }
4742           weightSum += weight;
4743         }
4744         // Update best.
4745         if (weightSum > bestWeight) {
4746           bestWeight = weightSum;
4747           bestMAIndex = maIndex;
4748         }
4749       }
4750 
4751       // Now select chosen alternative in each constraint.
4752       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4753            cIndex != eIndex; ++cIndex) {
4754         AsmOperandInfo &cInfo = ConstraintOperands[cIndex];
4755         if (cInfo.Type == InlineAsm::isClobber)
4756           continue;
4757         cInfo.selectAlternative(bestMAIndex);
4758       }
4759     }
4760   }
4761 
4762   // Check and hook up tied operands, choose constraint code to use.
4763   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4764        cIndex != eIndex; ++cIndex) {
4765     AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
4766 
4767     // If this is an output operand with a matching input operand, look up the
4768     // matching input. If their types mismatch, e.g. one is an integer, the
4769     // other is floating point, or their sizes are different, flag it as an
4770     // error.
4771     if (OpInfo.hasMatchingInput()) {
4772       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4773 
4774       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4775         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
4776             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
4777                                          OpInfo.ConstraintVT);
4778         std::pair<unsigned, const TargetRegisterClass *> InputRC =
4779             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
4780                                          Input.ConstraintVT);
4781         if ((OpInfo.ConstraintVT.isInteger() !=
4782              Input.ConstraintVT.isInteger()) ||
4783             (MatchRC.second != InputRC.second)) {
4784           report_fatal_error("Unsupported asm: input constraint"
4785                              " with a matching output constraint of"
4786                              " incompatible type!");
4787         }
4788       }
4789     }
4790   }
4791 
4792   return ConstraintOperands;
4793 }
4794 
4795 /// Return an integer indicating how general CT is.
4796 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
4797   switch (CT) {
4798   case TargetLowering::C_Immediate:
4799   case TargetLowering::C_Other:
4800   case TargetLowering::C_Unknown:
4801     return 0;
4802   case TargetLowering::C_Register:
4803     return 1;
4804   case TargetLowering::C_RegisterClass:
4805     return 2;
4806   case TargetLowering::C_Memory:
4807     return 3;
4808   }
4809   llvm_unreachable("Invalid constraint type");
4810 }
4811 
4812 /// Examine constraint type and operand type and determine a weight value.
4813 /// This object must already have been set up with the operand type
4814 /// and the current alternative constraint selected.
4815 TargetLowering::ConstraintWeight
4816   TargetLowering::getMultipleConstraintMatchWeight(
4817     AsmOperandInfo &info, int maIndex) const {
4818   InlineAsm::ConstraintCodeVector *rCodes;
4819   if (maIndex >= (int)info.multipleAlternatives.size())
4820     rCodes = &info.Codes;
4821   else
4822     rCodes = &info.multipleAlternatives[maIndex].Codes;
4823   ConstraintWeight BestWeight = CW_Invalid;
4824 
4825   // Loop over the options, keeping track of the most general one.
4826   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
4827     ConstraintWeight weight =
4828       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
4829     if (weight > BestWeight)
4830       BestWeight = weight;
4831   }
4832 
4833   return BestWeight;
4834 }
4835 
4836 /// Examine constraint type and operand type and determine a weight value.
4837 /// This object must already have been set up with the operand type
4838 /// and the current alternative constraint selected.
4839 TargetLowering::ConstraintWeight
4840   TargetLowering::getSingleConstraintMatchWeight(
4841     AsmOperandInfo &info, const char *constraint) const {
4842   ConstraintWeight weight = CW_Invalid;
4843   Value *CallOperandVal = info.CallOperandVal;
4844     // If we don't have a value, we can't do a match,
4845     // but allow it at the lowest weight.
4846   if (!CallOperandVal)
4847     return CW_Default;
4848   // Look at the constraint type.
4849   switch (*constraint) {
4850     case 'i': // immediate integer.
4851     case 'n': // immediate integer with a known value.
4852       if (isa<ConstantInt>(CallOperandVal))
4853         weight = CW_Constant;
4854       break;
4855     case 's': // non-explicit intregal immediate.
4856       if (isa<GlobalValue>(CallOperandVal))
4857         weight = CW_Constant;
4858       break;
4859     case 'E': // immediate float if host format.
4860     case 'F': // immediate float.
4861       if (isa<ConstantFP>(CallOperandVal))
4862         weight = CW_Constant;
4863       break;
4864     case '<': // memory operand with autodecrement.
4865     case '>': // memory operand with autoincrement.
4866     case 'm': // memory operand.
4867     case 'o': // offsettable memory operand
4868     case 'V': // non-offsettable memory operand
4869       weight = CW_Memory;
4870       break;
4871     case 'r': // general register.
4872     case 'g': // general register, memory operand or immediate integer.
4873               // note: Clang converts "g" to "imr".
4874       if (CallOperandVal->getType()->isIntegerTy())
4875         weight = CW_Register;
4876       break;
4877     case 'X': // any operand.
4878   default:
4879     weight = CW_Default;
4880     break;
4881   }
4882   return weight;
4883 }
4884 
4885 /// If there are multiple different constraints that we could pick for this
4886 /// operand (e.g. "imr") try to pick the 'best' one.
4887 /// This is somewhat tricky: constraints fall into four classes:
4888 ///    Other         -> immediates and magic values
4889 ///    Register      -> one specific register
4890 ///    RegisterClass -> a group of regs
4891 ///    Memory        -> memory
4892 /// Ideally, we would pick the most specific constraint possible: if we have
4893 /// something that fits into a register, we would pick it.  The problem here
4894 /// is that if we have something that could either be in a register or in
4895 /// memory that use of the register could cause selection of *other*
4896 /// operands to fail: they might only succeed if we pick memory.  Because of
4897 /// this the heuristic we use is:
4898 ///
4899 ///  1) If there is an 'other' constraint, and if the operand is valid for
4900 ///     that constraint, use it.  This makes us take advantage of 'i'
4901 ///     constraints when available.
4902 ///  2) Otherwise, pick the most general constraint present.  This prefers
4903 ///     'm' over 'r', for example.
4904 ///
4905 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
4906                              const TargetLowering &TLI,
4907                              SDValue Op, SelectionDAG *DAG) {
4908   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
4909   unsigned BestIdx = 0;
4910   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
4911   int BestGenerality = -1;
4912 
4913   // Loop over the options, keeping track of the most general one.
4914   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
4915     TargetLowering::ConstraintType CType =
4916       TLI.getConstraintType(OpInfo.Codes[i]);
4917 
4918     // Indirect 'other' or 'immediate' constraints are not allowed.
4919     if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
4920                                CType == TargetLowering::C_Register ||
4921                                CType == TargetLowering::C_RegisterClass))
4922       continue;
4923 
4924     // If this is an 'other' or 'immediate' constraint, see if the operand is
4925     // valid for it. For example, on X86 we might have an 'rI' constraint. If
4926     // the operand is an integer in the range [0..31] we want to use I (saving a
4927     // load of a register), otherwise we must use 'r'.
4928     if ((CType == TargetLowering::C_Other ||
4929          CType == TargetLowering::C_Immediate) && Op.getNode()) {
4930       assert(OpInfo.Codes[i].size() == 1 &&
4931              "Unhandled multi-letter 'other' constraint");
4932       std::vector<SDValue> ResultOps;
4933       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
4934                                        ResultOps, *DAG);
4935       if (!ResultOps.empty()) {
4936         BestType = CType;
4937         BestIdx = i;
4938         break;
4939       }
4940     }
4941 
4942     // Things with matching constraints can only be registers, per gcc
4943     // documentation.  This mainly affects "g" constraints.
4944     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
4945       continue;
4946 
4947     // This constraint letter is more general than the previous one, use it.
4948     int Generality = getConstraintGenerality(CType);
4949     if (Generality > BestGenerality) {
4950       BestType = CType;
4951       BestIdx = i;
4952       BestGenerality = Generality;
4953     }
4954   }
4955 
4956   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
4957   OpInfo.ConstraintType = BestType;
4958 }
4959 
4960 /// Determines the constraint code and constraint type to use for the specific
4961 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
4962 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
4963                                             SDValue Op,
4964                                             SelectionDAG *DAG) const {
4965   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
4966 
4967   // Single-letter constraints ('r') are very common.
4968   if (OpInfo.Codes.size() == 1) {
4969     OpInfo.ConstraintCode = OpInfo.Codes[0];
4970     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
4971   } else {
4972     ChooseConstraint(OpInfo, *this, Op, DAG);
4973   }
4974 
4975   // 'X' matches anything.
4976   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
4977     // Labels and constants are handled elsewhere ('X' is the only thing
4978     // that matches labels).  For Functions, the type here is the type of
4979     // the result, which is not what we want to look at; leave them alone.
4980     Value *v = OpInfo.CallOperandVal;
4981     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
4982       OpInfo.CallOperandVal = v;
4983       return;
4984     }
4985 
4986     if (Op.getNode() && Op.getOpcode() == ISD::TargetBlockAddress)
4987       return;
4988 
4989     // Otherwise, try to resolve it to something we know about by looking at
4990     // the actual operand type.
4991     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
4992       OpInfo.ConstraintCode = Repl;
4993       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
4994     }
4995   }
4996 }
4997 
4998 /// Given an exact SDIV by a constant, create a multiplication
4999 /// with the multiplicative inverse of the constant.
5000 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N,
5001                               const SDLoc &dl, SelectionDAG &DAG,
5002                               SmallVectorImpl<SDNode *> &Created) {
5003   SDValue Op0 = N->getOperand(0);
5004   SDValue Op1 = N->getOperand(1);
5005   EVT VT = N->getValueType(0);
5006   EVT SVT = VT.getScalarType();
5007   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
5008   EVT ShSVT = ShVT.getScalarType();
5009 
5010   bool UseSRA = false;
5011   SmallVector<SDValue, 16> Shifts, Factors;
5012 
5013   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5014     if (C->isNullValue())
5015       return false;
5016     APInt Divisor = C->getAPIntValue();
5017     unsigned Shift = Divisor.countTrailingZeros();
5018     if (Shift) {
5019       Divisor.ashrInPlace(Shift);
5020       UseSRA = true;
5021     }
5022     // Calculate the multiplicative inverse, using Newton's method.
5023     APInt t;
5024     APInt Factor = Divisor;
5025     while ((t = Divisor * Factor) != 1)
5026       Factor *= APInt(Divisor.getBitWidth(), 2) - t;
5027     Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
5028     Factors.push_back(DAG.getConstant(Factor, dl, SVT));
5029     return true;
5030   };
5031 
5032   // Collect all magic values from the build vector.
5033   if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
5034     return SDValue();
5035 
5036   SDValue Shift, Factor;
5037   if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
5038     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5039     Factor = DAG.getBuildVector(VT, dl, Factors);
5040   } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
5041     assert(Shifts.size() == 1 && Factors.size() == 1 &&
5042            "Expected matchUnaryPredicate to return one element for scalable "
5043            "vectors");
5044     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5045     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5046   } else {
5047     assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
5048     Shift = Shifts[0];
5049     Factor = Factors[0];
5050   }
5051 
5052   SDValue Res = Op0;
5053 
5054   // Shift the value upfront if it is even, so the LSB is one.
5055   if (UseSRA) {
5056     // TODO: For UDIV use SRL instead of SRA.
5057     SDNodeFlags Flags;
5058     Flags.setExact(true);
5059     Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
5060     Created.push_back(Res.getNode());
5061   }
5062 
5063   return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
5064 }
5065 
5066 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
5067                               SelectionDAG &DAG,
5068                               SmallVectorImpl<SDNode *> &Created) const {
5069   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5070   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5071   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
5072     return SDValue(N, 0); // Lower SDIV as SDIV
5073   return SDValue();
5074 }
5075 
5076 /// Given an ISD::SDIV node expressing a divide by constant,
5077 /// return a DAG expression to select that will generate the same value by
5078 /// multiplying by a magic number.
5079 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5080 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
5081                                   bool IsAfterLegalization,
5082                                   SmallVectorImpl<SDNode *> &Created) const {
5083   SDLoc dl(N);
5084   EVT VT = N->getValueType(0);
5085   EVT SVT = VT.getScalarType();
5086   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5087   EVT ShSVT = ShVT.getScalarType();
5088   unsigned EltBits = VT.getScalarSizeInBits();
5089   EVT MulVT;
5090 
5091   // Check to see if we can do this.
5092   // FIXME: We should be more aggressive here.
5093   if (!isTypeLegal(VT)) {
5094     // Limit this to simple scalars for now.
5095     if (VT.isVector() || !VT.isSimple())
5096       return SDValue();
5097 
5098     // If this type will be promoted to a large enough type with a legal
5099     // multiply operation, we can go ahead and do this transform.
5100     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5101       return SDValue();
5102 
5103     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5104     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5105         !isOperationLegal(ISD::MUL, MulVT))
5106       return SDValue();
5107   }
5108 
5109   // If the sdiv has an 'exact' bit we can use a simpler lowering.
5110   if (N->getFlags().hasExact())
5111     return BuildExactSDIV(*this, N, dl, DAG, Created);
5112 
5113   SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
5114 
5115   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5116     if (C->isNullValue())
5117       return false;
5118 
5119     const APInt &Divisor = C->getAPIntValue();
5120     APInt::ms magics = Divisor.magic();
5121     int NumeratorFactor = 0;
5122     int ShiftMask = -1;
5123 
5124     if (Divisor.isOneValue() || Divisor.isAllOnesValue()) {
5125       // If d is +1/-1, we just multiply the numerator by +1/-1.
5126       NumeratorFactor = Divisor.getSExtValue();
5127       magics.m = 0;
5128       magics.s = 0;
5129       ShiftMask = 0;
5130     } else if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
5131       // If d > 0 and m < 0, add the numerator.
5132       NumeratorFactor = 1;
5133     } else if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
5134       // If d < 0 and m > 0, subtract the numerator.
5135       NumeratorFactor = -1;
5136     }
5137 
5138     MagicFactors.push_back(DAG.getConstant(magics.m, dl, SVT));
5139     Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
5140     Shifts.push_back(DAG.getConstant(magics.s, dl, ShSVT));
5141     ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
5142     return true;
5143   };
5144 
5145   SDValue N0 = N->getOperand(0);
5146   SDValue N1 = N->getOperand(1);
5147 
5148   // Collect the shifts / magic values from each element.
5149   if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
5150     return SDValue();
5151 
5152   SDValue MagicFactor, Factor, Shift, ShiftMask;
5153   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5154     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5155     Factor = DAG.getBuildVector(VT, dl, Factors);
5156     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5157     ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
5158   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5159     assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
5160            Shifts.size() == 1 && ShiftMasks.size() == 1 &&
5161            "Expected matchUnaryPredicate to return one element for scalable "
5162            "vectors");
5163     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5164     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5165     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5166     ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
5167   } else {
5168     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5169     MagicFactor = MagicFactors[0];
5170     Factor = Factors[0];
5171     Shift = Shifts[0];
5172     ShiftMask = ShiftMasks[0];
5173   }
5174 
5175   // Multiply the numerator (operand 0) by the magic value.
5176   // FIXME: We should support doing a MUL in a wider type.
5177   auto GetMULHS = [&](SDValue X, SDValue Y) {
5178     // If the type isn't legal, use a wider mul of the the type calculated
5179     // earlier.
5180     if (!isTypeLegal(VT)) {
5181       X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
5182       Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
5183       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5184       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5185                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5186       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5187     }
5188 
5189     if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization))
5190       return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
5191     if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) {
5192       SDValue LoHi =
5193           DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5194       return SDValue(LoHi.getNode(), 1);
5195     }
5196     return SDValue();
5197   };
5198 
5199   SDValue Q = GetMULHS(N0, MagicFactor);
5200   if (!Q)
5201     return SDValue();
5202 
5203   Created.push_back(Q.getNode());
5204 
5205   // (Optionally) Add/subtract the numerator using Factor.
5206   Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
5207   Created.push_back(Factor.getNode());
5208   Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
5209   Created.push_back(Q.getNode());
5210 
5211   // Shift right algebraic by shift value.
5212   Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
5213   Created.push_back(Q.getNode());
5214 
5215   // Extract the sign bit, mask it and add it to the quotient.
5216   SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
5217   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
5218   Created.push_back(T.getNode());
5219   T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
5220   Created.push_back(T.getNode());
5221   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
5222 }
5223 
5224 /// Given an ISD::UDIV node expressing a divide by constant,
5225 /// return a DAG expression to select that will generate the same value by
5226 /// multiplying by a magic number.
5227 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5228 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
5229                                   bool IsAfterLegalization,
5230                                   SmallVectorImpl<SDNode *> &Created) const {
5231   SDLoc dl(N);
5232   EVT VT = N->getValueType(0);
5233   EVT SVT = VT.getScalarType();
5234   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5235   EVT ShSVT = ShVT.getScalarType();
5236   unsigned EltBits = VT.getScalarSizeInBits();
5237   EVT MulVT;
5238 
5239   // Check to see if we can do this.
5240   // FIXME: We should be more aggressive here.
5241   if (!isTypeLegal(VT)) {
5242     // Limit this to simple scalars for now.
5243     if (VT.isVector() || !VT.isSimple())
5244       return SDValue();
5245 
5246     // If this type will be promoted to a large enough type with a legal
5247     // multiply operation, we can go ahead and do this transform.
5248     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5249       return SDValue();
5250 
5251     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5252     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5253         !isOperationLegal(ISD::MUL, MulVT))
5254       return SDValue();
5255   }
5256 
5257   bool UseNPQ = false;
5258   SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
5259 
5260   auto BuildUDIVPattern = [&](ConstantSDNode *C) {
5261     if (C->isNullValue())
5262       return false;
5263     // FIXME: We should use a narrower constant when the upper
5264     // bits are known to be zero.
5265     const APInt& Divisor = C->getAPIntValue();
5266     APInt::mu magics = Divisor.magicu();
5267     unsigned PreShift = 0, PostShift = 0;
5268 
5269     // If the divisor is even, we can avoid using the expensive fixup by
5270     // shifting the divided value upfront.
5271     if (magics.a != 0 && !Divisor[0]) {
5272       PreShift = Divisor.countTrailingZeros();
5273       // Get magic number for the shifted divisor.
5274       magics = Divisor.lshr(PreShift).magicu(PreShift);
5275       assert(magics.a == 0 && "Should use cheap fixup now");
5276     }
5277 
5278     APInt Magic = magics.m;
5279 
5280     unsigned SelNPQ;
5281     if (magics.a == 0 || Divisor.isOneValue()) {
5282       assert(magics.s < Divisor.getBitWidth() &&
5283              "We shouldn't generate an undefined shift!");
5284       PostShift = magics.s;
5285       SelNPQ = false;
5286     } else {
5287       PostShift = magics.s - 1;
5288       SelNPQ = true;
5289     }
5290 
5291     PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT));
5292     MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT));
5293     NPQFactors.push_back(
5294         DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
5295                                : APInt::getNullValue(EltBits),
5296                         dl, SVT));
5297     PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT));
5298     UseNPQ |= SelNPQ;
5299     return true;
5300   };
5301 
5302   SDValue N0 = N->getOperand(0);
5303   SDValue N1 = N->getOperand(1);
5304 
5305   // Collect the shifts/magic values from each element.
5306   if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
5307     return SDValue();
5308 
5309   SDValue PreShift, PostShift, MagicFactor, NPQFactor;
5310   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5311     PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
5312     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5313     NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
5314     PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
5315   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5316     assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
5317            NPQFactors.size() == 1 && PostShifts.size() == 1 &&
5318            "Expected matchUnaryPredicate to return one for scalable vectors");
5319     PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
5320     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5321     NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
5322     PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
5323   } else {
5324     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5325     PreShift = PreShifts[0];
5326     MagicFactor = MagicFactors[0];
5327     PostShift = PostShifts[0];
5328   }
5329 
5330   SDValue Q = N0;
5331   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
5332   Created.push_back(Q.getNode());
5333 
5334   // FIXME: We should support doing a MUL in a wider type.
5335   auto GetMULHU = [&](SDValue X, SDValue Y) {
5336     // If the type isn't legal, use a wider mul of the the type calculated
5337     // earlier.
5338     if (!isTypeLegal(VT)) {
5339       X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
5340       Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
5341       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5342       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5343                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5344       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5345     }
5346 
5347     if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization))
5348       return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
5349     if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) {
5350       SDValue LoHi =
5351           DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5352       return SDValue(LoHi.getNode(), 1);
5353     }
5354     return SDValue(); // No mulhu or equivalent
5355   };
5356 
5357   // Multiply the numerator (operand 0) by the magic value.
5358   Q = GetMULHU(Q, MagicFactor);
5359   if (!Q)
5360     return SDValue();
5361 
5362   Created.push_back(Q.getNode());
5363 
5364   if (UseNPQ) {
5365     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
5366     Created.push_back(NPQ.getNode());
5367 
5368     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
5369     // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
5370     if (VT.isVector())
5371       NPQ = GetMULHU(NPQ, NPQFactor);
5372     else
5373       NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
5374 
5375     Created.push_back(NPQ.getNode());
5376 
5377     Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
5378     Created.push_back(Q.getNode());
5379   }
5380 
5381   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
5382   Created.push_back(Q.getNode());
5383 
5384   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5385 
5386   SDValue One = DAG.getConstant(1, dl, VT);
5387   SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
5388   return DAG.getSelect(dl, VT, IsOne, N0, Q);
5389 }
5390 
5391 /// If all values in Values that *don't* match the predicate are same 'splat'
5392 /// value, then replace all values with that splat value.
5393 /// Else, if AlternativeReplacement was provided, then replace all values that
5394 /// do match predicate with AlternativeReplacement value.
5395 static void
5396 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values,
5397                           std::function<bool(SDValue)> Predicate,
5398                           SDValue AlternativeReplacement = SDValue()) {
5399   SDValue Replacement;
5400   // Is there a value for which the Predicate does *NOT* match? What is it?
5401   auto SplatValue = llvm::find_if_not(Values, Predicate);
5402   if (SplatValue != Values.end()) {
5403     // Does Values consist only of SplatValue's and values matching Predicate?
5404     if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
5405           return Value == *SplatValue || Predicate(Value);
5406         })) // Then we shall replace values matching predicate with SplatValue.
5407       Replacement = *SplatValue;
5408   }
5409   if (!Replacement) {
5410     // Oops, we did not find the "baseline" splat value.
5411     if (!AlternativeReplacement)
5412       return; // Nothing to do.
5413     // Let's replace with provided value then.
5414     Replacement = AlternativeReplacement;
5415   }
5416   std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
5417 }
5418 
5419 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
5420 /// where the divisor is constant and the comparison target is zero,
5421 /// return a DAG expression that will generate the same comparison result
5422 /// using only multiplications, additions and shifts/rotations.
5423 /// Ref: "Hacker's Delight" 10-17.
5424 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
5425                                         SDValue CompTargetNode,
5426                                         ISD::CondCode Cond,
5427                                         DAGCombinerInfo &DCI,
5428                                         const SDLoc &DL) const {
5429   SmallVector<SDNode *, 5> Built;
5430   if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
5431                                          DCI, DL, Built)) {
5432     for (SDNode *N : Built)
5433       DCI.AddToWorklist(N);
5434     return Folded;
5435   }
5436 
5437   return SDValue();
5438 }
5439 
5440 SDValue
5441 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
5442                                   SDValue CompTargetNode, ISD::CondCode Cond,
5443                                   DAGCombinerInfo &DCI, const SDLoc &DL,
5444                                   SmallVectorImpl<SDNode *> &Created) const {
5445   // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
5446   // - D must be constant, with D = D0 * 2^K where D0 is odd
5447   // - P is the multiplicative inverse of D0 modulo 2^W
5448   // - Q = floor(((2^W) - 1) / D)
5449   // where W is the width of the common type of N and D.
5450   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5451          "Only applicable for (in)equality comparisons.");
5452 
5453   SelectionDAG &DAG = DCI.DAG;
5454 
5455   EVT VT = REMNode.getValueType();
5456   EVT SVT = VT.getScalarType();
5457   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5458   EVT ShSVT = ShVT.getScalarType();
5459 
5460   // If MUL is unavailable, we cannot proceed in any case.
5461   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
5462     return SDValue();
5463 
5464   bool ComparingWithAllZeros = true;
5465   bool AllComparisonsWithNonZerosAreTautological = true;
5466   bool HadTautologicalLanes = false;
5467   bool AllLanesAreTautological = true;
5468   bool HadEvenDivisor = false;
5469   bool AllDivisorsArePowerOfTwo = true;
5470   bool HadTautologicalInvertedLanes = false;
5471   SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts;
5472 
5473   auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
5474     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
5475     if (CDiv->isNullValue())
5476       return false;
5477 
5478     const APInt &D = CDiv->getAPIntValue();
5479     const APInt &Cmp = CCmp->getAPIntValue();
5480 
5481     ComparingWithAllZeros &= Cmp.isNullValue();
5482 
5483     // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
5484     // if C2 is not less than C1, the comparison is always false.
5485     // But we will only be able to produce the comparison that will give the
5486     // opposive tautological answer. So this lane would need to be fixed up.
5487     bool TautologicalInvertedLane = D.ule(Cmp);
5488     HadTautologicalInvertedLanes |= TautologicalInvertedLane;
5489 
5490     // If all lanes are tautological (either all divisors are ones, or divisor
5491     // is not greater than the constant we are comparing with),
5492     // we will prefer to avoid the fold.
5493     bool TautologicalLane = D.isOneValue() || TautologicalInvertedLane;
5494     HadTautologicalLanes |= TautologicalLane;
5495     AllLanesAreTautological &= TautologicalLane;
5496 
5497     // If we are comparing with non-zero, we need'll need  to subtract said
5498     // comparison value from the LHS. But there is no point in doing that if
5499     // every lane where we are comparing with non-zero is tautological..
5500     if (!Cmp.isNullValue())
5501       AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
5502 
5503     // Decompose D into D0 * 2^K
5504     unsigned K = D.countTrailingZeros();
5505     assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate.");
5506     APInt D0 = D.lshr(K);
5507 
5508     // D is even if it has trailing zeros.
5509     HadEvenDivisor |= (K != 0);
5510     // D is a power-of-two if D0 is one.
5511     // If all divisors are power-of-two, we will prefer to avoid the fold.
5512     AllDivisorsArePowerOfTwo &= D0.isOneValue();
5513 
5514     // P = inv(D0, 2^W)
5515     // 2^W requires W + 1 bits, so we have to extend and then truncate.
5516     unsigned W = D.getBitWidth();
5517     APInt P = D0.zext(W + 1)
5518                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
5519                   .trunc(W);
5520     assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable
5521     assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check.");
5522 
5523     // Q = floor((2^W - 1) u/ D)
5524     // R = ((2^W - 1) u% D)
5525     APInt Q, R;
5526     APInt::udivrem(APInt::getAllOnesValue(W), D, Q, R);
5527 
5528     // If we are comparing with zero, then that comparison constant is okay,
5529     // else it may need to be one less than that.
5530     if (Cmp.ugt(R))
5531       Q -= 1;
5532 
5533     assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) &&
5534            "We are expecting that K is always less than all-ones for ShSVT");
5535 
5536     // If the lane is tautological the result can be constant-folded.
5537     if (TautologicalLane) {
5538       // Set P and K amount to a bogus values so we can try to splat them.
5539       P = 0;
5540       K = -1;
5541       // And ensure that comparison constant is tautological,
5542       // it will always compare true/false.
5543       Q = -1;
5544     }
5545 
5546     PAmts.push_back(DAG.getConstant(P, DL, SVT));
5547     KAmts.push_back(
5548         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
5549     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
5550     return true;
5551   };
5552 
5553   SDValue N = REMNode.getOperand(0);
5554   SDValue D = REMNode.getOperand(1);
5555 
5556   // Collect the values from each element.
5557   if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
5558     return SDValue();
5559 
5560   // If all lanes are tautological, the result can be constant-folded.
5561   if (AllLanesAreTautological)
5562     return SDValue();
5563 
5564   // If this is a urem by a powers-of-two, avoid the fold since it can be
5565   // best implemented as a bit test.
5566   if (AllDivisorsArePowerOfTwo)
5567     return SDValue();
5568 
5569   SDValue PVal, KVal, QVal;
5570   if (VT.isVector()) {
5571     if (HadTautologicalLanes) {
5572       // Try to turn PAmts into a splat, since we don't care about the values
5573       // that are currently '0'. If we can't, just keep '0'`s.
5574       turnVectorIntoSplatVector(PAmts, isNullConstant);
5575       // Try to turn KAmts into a splat, since we don't care about the values
5576       // that are currently '-1'. If we can't, change them to '0'`s.
5577       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
5578                                 DAG.getConstant(0, DL, ShSVT));
5579     }
5580 
5581     PVal = DAG.getBuildVector(VT, DL, PAmts);
5582     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
5583     QVal = DAG.getBuildVector(VT, DL, QAmts);
5584   } else {
5585     PVal = PAmts[0];
5586     KVal = KAmts[0];
5587     QVal = QAmts[0];
5588   }
5589 
5590   if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
5591     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
5592       return SDValue(); // FIXME: Could/should use `ISD::ADD`?
5593     assert(CompTargetNode.getValueType() == N.getValueType() &&
5594            "Expecting that the types on LHS and RHS of comparisons match.");
5595     N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
5596   }
5597 
5598   // (mul N, P)
5599   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
5600   Created.push_back(Op0.getNode());
5601 
5602   // Rotate right only if any divisor was even. We avoid rotates for all-odd
5603   // divisors as a performance improvement, since rotating by 0 is a no-op.
5604   if (HadEvenDivisor) {
5605     // We need ROTR to do this.
5606     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
5607       return SDValue();
5608     SDNodeFlags Flags;
5609     Flags.setExact(true);
5610     // UREM: (rotr (mul N, P), K)
5611     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags);
5612     Created.push_back(Op0.getNode());
5613   }
5614 
5615   // UREM: (setule/setugt (rotr (mul N, P), K), Q)
5616   SDValue NewCC =
5617       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
5618                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
5619   if (!HadTautologicalInvertedLanes)
5620     return NewCC;
5621 
5622   // If any lanes previously compared always-false, the NewCC will give
5623   // always-true result for them, so we need to fixup those lanes.
5624   // Or the other way around for inequality predicate.
5625   assert(VT.isVector() && "Can/should only get here for vectors.");
5626   Created.push_back(NewCC.getNode());
5627 
5628   // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
5629   // if C2 is not less than C1, the comparison is always false.
5630   // But we have produced the comparison that will give the
5631   // opposive tautological answer. So these lanes would need to be fixed up.
5632   SDValue TautologicalInvertedChannels =
5633       DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
5634   Created.push_back(TautologicalInvertedChannels.getNode());
5635 
5636   // NOTE: we avoid letting illegal types through even if we're before legalize
5637   // ops – legalization has a hard time producing good code for this.
5638   if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
5639     // If we have a vector select, let's replace the comparison results in the
5640     // affected lanes with the correct tautological result.
5641     SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
5642                                               DL, SETCCVT, SETCCVT);
5643     return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
5644                        Replacement, NewCC);
5645   }
5646 
5647   // Else, we can just invert the comparison result in the appropriate lanes.
5648   //
5649   // NOTE: see the note above VSELECT above.
5650   if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
5651     return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
5652                        TautologicalInvertedChannels);
5653 
5654   return SDValue(); // Don't know how to lower.
5655 }
5656 
5657 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
5658 /// where the divisor is constant and the comparison target is zero,
5659 /// return a DAG expression that will generate the same comparison result
5660 /// using only multiplications, additions and shifts/rotations.
5661 /// Ref: "Hacker's Delight" 10-17.
5662 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
5663                                         SDValue CompTargetNode,
5664                                         ISD::CondCode Cond,
5665                                         DAGCombinerInfo &DCI,
5666                                         const SDLoc &DL) const {
5667   SmallVector<SDNode *, 7> Built;
5668   if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
5669                                          DCI, DL, Built)) {
5670     assert(Built.size() <= 7 && "Max size prediction failed.");
5671     for (SDNode *N : Built)
5672       DCI.AddToWorklist(N);
5673     return Folded;
5674   }
5675 
5676   return SDValue();
5677 }
5678 
5679 SDValue
5680 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
5681                                   SDValue CompTargetNode, ISD::CondCode Cond,
5682                                   DAGCombinerInfo &DCI, const SDLoc &DL,
5683                                   SmallVectorImpl<SDNode *> &Created) const {
5684   // Fold:
5685   //   (seteq/ne (srem N, D), 0)
5686   // To:
5687   //   (setule/ugt (rotr (add (mul N, P), A), K), Q)
5688   //
5689   // - D must be constant, with D = D0 * 2^K where D0 is odd
5690   // - P is the multiplicative inverse of D0 modulo 2^W
5691   // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
5692   // - Q = floor((2 * A) / (2^K))
5693   // where W is the width of the common type of N and D.
5694   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5695          "Only applicable for (in)equality comparisons.");
5696 
5697   SelectionDAG &DAG = DCI.DAG;
5698 
5699   EVT VT = REMNode.getValueType();
5700   EVT SVT = VT.getScalarType();
5701   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5702   EVT ShSVT = ShVT.getScalarType();
5703 
5704   // If we are after ops legalization, and MUL is unavailable, we can not
5705   // proceed.
5706   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
5707     return SDValue();
5708 
5709   // TODO: Could support comparing with non-zero too.
5710   ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
5711   if (!CompTarget || !CompTarget->isNullValue())
5712     return SDValue();
5713 
5714   bool HadIntMinDivisor = false;
5715   bool HadOneDivisor = false;
5716   bool AllDivisorsAreOnes = true;
5717   bool HadEvenDivisor = false;
5718   bool NeedToApplyOffset = false;
5719   bool AllDivisorsArePowerOfTwo = true;
5720   SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
5721 
5722   auto BuildSREMPattern = [&](ConstantSDNode *C) {
5723     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
5724     if (C->isNullValue())
5725       return false;
5726 
5727     // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
5728 
5729     // WARNING: this fold is only valid for positive divisors!
5730     APInt D = C->getAPIntValue();
5731     if (D.isNegative())
5732       D.negate(); //  `rem %X, -C` is equivalent to `rem %X, C`
5733 
5734     HadIntMinDivisor |= D.isMinSignedValue();
5735 
5736     // If all divisors are ones, we will prefer to avoid the fold.
5737     HadOneDivisor |= D.isOneValue();
5738     AllDivisorsAreOnes &= D.isOneValue();
5739 
5740     // Decompose D into D0 * 2^K
5741     unsigned K = D.countTrailingZeros();
5742     assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate.");
5743     APInt D0 = D.lshr(K);
5744 
5745     if (!D.isMinSignedValue()) {
5746       // D is even if it has trailing zeros; unless it's INT_MIN, in which case
5747       // we don't care about this lane in this fold, we'll special-handle it.
5748       HadEvenDivisor |= (K != 0);
5749     }
5750 
5751     // D is a power-of-two if D0 is one. This includes INT_MIN.
5752     // If all divisors are power-of-two, we will prefer to avoid the fold.
5753     AllDivisorsArePowerOfTwo &= D0.isOneValue();
5754 
5755     // P = inv(D0, 2^W)
5756     // 2^W requires W + 1 bits, so we have to extend and then truncate.
5757     unsigned W = D.getBitWidth();
5758     APInt P = D0.zext(W + 1)
5759                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
5760                   .trunc(W);
5761     assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable
5762     assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check.");
5763 
5764     // A = floor((2^(W - 1) - 1) / D0) & -2^K
5765     APInt A = APInt::getSignedMaxValue(W).udiv(D0);
5766     A.clearLowBits(K);
5767 
5768     if (!D.isMinSignedValue()) {
5769       // If divisor INT_MIN, then we don't care about this lane in this fold,
5770       // we'll special-handle it.
5771       NeedToApplyOffset |= A != 0;
5772     }
5773 
5774     // Q = floor((2 * A) / (2^K))
5775     APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
5776 
5777     assert(APInt::getAllOnesValue(SVT.getSizeInBits()).ugt(A) &&
5778            "We are expecting that A is always less than all-ones for SVT");
5779     assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) &&
5780            "We are expecting that K is always less than all-ones for ShSVT");
5781 
5782     // If the divisor is 1 the result can be constant-folded. Likewise, we
5783     // don't care about INT_MIN lanes, those can be set to undef if appropriate.
5784     if (D.isOneValue()) {
5785       // Set P, A and K to a bogus values so we can try to splat them.
5786       P = 0;
5787       A = -1;
5788       K = -1;
5789 
5790       // x ?% 1 == 0  <-->  true  <-->  x u<= -1
5791       Q = -1;
5792     }
5793 
5794     PAmts.push_back(DAG.getConstant(P, DL, SVT));
5795     AAmts.push_back(DAG.getConstant(A, DL, SVT));
5796     KAmts.push_back(
5797         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
5798     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
5799     return true;
5800   };
5801 
5802   SDValue N = REMNode.getOperand(0);
5803   SDValue D = REMNode.getOperand(1);
5804 
5805   // Collect the values from each element.
5806   if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
5807     return SDValue();
5808 
5809   // If this is a srem by a one, avoid the fold since it can be constant-folded.
5810   if (AllDivisorsAreOnes)
5811     return SDValue();
5812 
5813   // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
5814   // since it can be best implemented as a bit test.
5815   if (AllDivisorsArePowerOfTwo)
5816     return SDValue();
5817 
5818   SDValue PVal, AVal, KVal, QVal;
5819   if (D.getOpcode() == ISD::BUILD_VECTOR) {
5820     if (HadOneDivisor) {
5821       // Try to turn PAmts into a splat, since we don't care about the values
5822       // that are currently '0'. If we can't, just keep '0'`s.
5823       turnVectorIntoSplatVector(PAmts, isNullConstant);
5824       // Try to turn AAmts into a splat, since we don't care about the
5825       // values that are currently '-1'. If we can't, change them to '0'`s.
5826       turnVectorIntoSplatVector(AAmts, isAllOnesConstant,
5827                                 DAG.getConstant(0, DL, SVT));
5828       // Try to turn KAmts into a splat, since we don't care about the values
5829       // that are currently '-1'. If we can't, change them to '0'`s.
5830       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
5831                                 DAG.getConstant(0, DL, ShSVT));
5832     }
5833 
5834     PVal = DAG.getBuildVector(VT, DL, PAmts);
5835     AVal = DAG.getBuildVector(VT, DL, AAmts);
5836     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
5837     QVal = DAG.getBuildVector(VT, DL, QAmts);
5838   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
5839     assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
5840            QAmts.size() == 1 &&
5841            "Expected matchUnaryPredicate to return one element for scalable "
5842            "vectors");
5843     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
5844     AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
5845     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
5846     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
5847   } else {
5848     assert(isa<ConstantSDNode>(D) && "Expected a constant");
5849     PVal = PAmts[0];
5850     AVal = AAmts[0];
5851     KVal = KAmts[0];
5852     QVal = QAmts[0];
5853   }
5854 
5855   // (mul N, P)
5856   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
5857   Created.push_back(Op0.getNode());
5858 
5859   if (NeedToApplyOffset) {
5860     // We need ADD to do this.
5861     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
5862       return SDValue();
5863 
5864     // (add (mul N, P), A)
5865     Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
5866     Created.push_back(Op0.getNode());
5867   }
5868 
5869   // Rotate right only if any divisor was even. We avoid rotates for all-odd
5870   // divisors as a performance improvement, since rotating by 0 is a no-op.
5871   if (HadEvenDivisor) {
5872     // We need ROTR to do this.
5873     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
5874       return SDValue();
5875     SDNodeFlags Flags;
5876     Flags.setExact(true);
5877     // SREM: (rotr (add (mul N, P), A), K)
5878     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags);
5879     Created.push_back(Op0.getNode());
5880   }
5881 
5882   // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
5883   SDValue Fold =
5884       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
5885                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
5886 
5887   // If we didn't have lanes with INT_MIN divisor, then we're done.
5888   if (!HadIntMinDivisor)
5889     return Fold;
5890 
5891   // That fold is only valid for positive divisors. Which effectively means,
5892   // it is invalid for INT_MIN divisors. So if we have such a lane,
5893   // we must fix-up results for said lanes.
5894   assert(VT.isVector() && "Can/should only get here for vectors.");
5895 
5896   // NOTE: we avoid letting illegal types through even if we're before legalize
5897   // ops – legalization has a hard time producing good code for the code that
5898   // follows.
5899   if (!isOperationLegalOrCustom(ISD::SETEQ, VT) ||
5900       !isOperationLegalOrCustom(ISD::AND, VT) ||
5901       !isOperationLegalOrCustom(Cond, VT) ||
5902       !isOperationLegalOrCustom(ISD::VSELECT, VT))
5903     return SDValue();
5904 
5905   Created.push_back(Fold.getNode());
5906 
5907   SDValue IntMin = DAG.getConstant(
5908       APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT);
5909   SDValue IntMax = DAG.getConstant(
5910       APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT);
5911   SDValue Zero =
5912       DAG.getConstant(APInt::getNullValue(SVT.getScalarSizeInBits()), DL, VT);
5913 
5914   // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded.
5915   SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ);
5916   Created.push_back(DivisorIsIntMin.getNode());
5917 
5918   // (N s% INT_MIN) ==/!= 0  <-->  (N & INT_MAX) ==/!= 0
5919   SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax);
5920   Created.push_back(Masked.getNode());
5921   SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond);
5922   Created.push_back(MaskedIsZero.getNode());
5923 
5924   // To produce final result we need to blend 2 vectors: 'SetCC' and
5925   // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick
5926   // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is
5927   // constant-folded, select can get lowered to a shuffle with constant mask.
5928   SDValue Blended =
5929       DAG.getNode(ISD::VSELECT, DL, VT, DivisorIsIntMin, MaskedIsZero, Fold);
5930 
5931   return Blended;
5932 }
5933 
5934 bool TargetLowering::
5935 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
5936   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
5937     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
5938                                 "be a constant integer");
5939     return true;
5940   }
5941 
5942   return false;
5943 }
5944 
5945 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
5946                                          const DenormalMode &Mode) const {
5947   SDLoc DL(Op);
5948   EVT VT = Op.getValueType();
5949   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5950   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5951   // Testing it with denormal inputs to avoid wrong estimate.
5952   if (Mode.Input == DenormalMode::IEEE) {
5953     // This is specifically a check for the handling of denormal inputs,
5954     // not the result.
5955 
5956     // Test = fabs(X) < SmallestNormal
5957     const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
5958     APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
5959     SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
5960     SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
5961     return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
5962   }
5963   // Test = X == 0.0
5964   return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
5965 }
5966 
5967 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
5968                                              bool LegalOps, bool OptForSize,
5969                                              NegatibleCost &Cost,
5970                                              unsigned Depth) const {
5971   // fneg is removable even if it has multiple uses.
5972   if (Op.getOpcode() == ISD::FNEG) {
5973     Cost = NegatibleCost::Cheaper;
5974     return Op.getOperand(0);
5975   }
5976 
5977   // Don't recurse exponentially.
5978   if (Depth > SelectionDAG::MaxRecursionDepth)
5979     return SDValue();
5980 
5981   // Pre-increment recursion depth for use in recursive calls.
5982   ++Depth;
5983   const SDNodeFlags Flags = Op->getFlags();
5984   const TargetOptions &Options = DAG.getTarget().Options;
5985   EVT VT = Op.getValueType();
5986   unsigned Opcode = Op.getOpcode();
5987 
5988   // Don't allow anything with multiple uses unless we know it is free.
5989   if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
5990     bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
5991                         isFPExtFree(VT, Op.getOperand(0).getValueType());
5992     if (!IsFreeExtend)
5993       return SDValue();
5994   }
5995 
5996   auto RemoveDeadNode = [&](SDValue N) {
5997     if (N && N.getNode()->use_empty())
5998       DAG.RemoveDeadNode(N.getNode());
5999   };
6000 
6001   SDLoc DL(Op);
6002 
6003   // Because getNegatedExpression can delete nodes we need a handle to keep
6004   // temporary nodes alive in case the recursion manages to create an identical
6005   // node.
6006   std::list<HandleSDNode> Handles;
6007 
6008   switch (Opcode) {
6009   case ISD::ConstantFP: {
6010     // Don't invert constant FP values after legalization unless the target says
6011     // the negated constant is legal.
6012     bool IsOpLegal =
6013         isOperationLegal(ISD::ConstantFP, VT) ||
6014         isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
6015                      OptForSize);
6016 
6017     if (LegalOps && !IsOpLegal)
6018       break;
6019 
6020     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
6021     V.changeSign();
6022     SDValue CFP = DAG.getConstantFP(V, DL, VT);
6023 
6024     // If we already have the use of the negated floating constant, it is free
6025     // to negate it even it has multiple uses.
6026     if (!Op.hasOneUse() && CFP.use_empty())
6027       break;
6028     Cost = NegatibleCost::Neutral;
6029     return CFP;
6030   }
6031   case ISD::BUILD_VECTOR: {
6032     // Only permit BUILD_VECTOR of constants.
6033     if (llvm::any_of(Op->op_values(), [&](SDValue N) {
6034           return !N.isUndef() && !isa<ConstantFPSDNode>(N);
6035         }))
6036       break;
6037 
6038     bool IsOpLegal =
6039         (isOperationLegal(ISD::ConstantFP, VT) &&
6040          isOperationLegal(ISD::BUILD_VECTOR, VT)) ||
6041         llvm::all_of(Op->op_values(), [&](SDValue N) {
6042           return N.isUndef() ||
6043                  isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
6044                               OptForSize);
6045         });
6046 
6047     if (LegalOps && !IsOpLegal)
6048       break;
6049 
6050     SmallVector<SDValue, 4> Ops;
6051     for (SDValue C : Op->op_values()) {
6052       if (C.isUndef()) {
6053         Ops.push_back(C);
6054         continue;
6055       }
6056       APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
6057       V.changeSign();
6058       Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
6059     }
6060     Cost = NegatibleCost::Neutral;
6061     return DAG.getBuildVector(VT, DL, Ops);
6062   }
6063   case ISD::FADD: {
6064     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6065       break;
6066 
6067     // After operation legalization, it might not be legal to create new FSUBs.
6068     if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
6069       break;
6070     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6071 
6072     // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
6073     NegatibleCost CostX = NegatibleCost::Expensive;
6074     SDValue NegX =
6075         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6076     // Prevent this node from being deleted by the next call.
6077     if (NegX)
6078       Handles.emplace_back(NegX);
6079 
6080     // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
6081     NegatibleCost CostY = NegatibleCost::Expensive;
6082     SDValue NegY =
6083         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6084 
6085     // We're done with the handles.
6086     Handles.clear();
6087 
6088     // Negate the X if its cost is less or equal than Y.
6089     if (NegX && (CostX <= CostY)) {
6090       Cost = CostX;
6091       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
6092       if (NegY != N)
6093         RemoveDeadNode(NegY);
6094       return N;
6095     }
6096 
6097     // Negate the Y if it is not expensive.
6098     if (NegY) {
6099       Cost = CostY;
6100       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
6101       if (NegX != N)
6102         RemoveDeadNode(NegX);
6103       return N;
6104     }
6105     break;
6106   }
6107   case ISD::FSUB: {
6108     // We can't turn -(A-B) into B-A when we honor signed zeros.
6109     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6110       break;
6111 
6112     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6113     // fold (fneg (fsub 0, Y)) -> Y
6114     if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
6115       if (C->isZero()) {
6116         Cost = NegatibleCost::Cheaper;
6117         return Y;
6118       }
6119 
6120     // fold (fneg (fsub X, Y)) -> (fsub Y, X)
6121     Cost = NegatibleCost::Neutral;
6122     return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
6123   }
6124   case ISD::FMUL:
6125   case ISD::FDIV: {
6126     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6127 
6128     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
6129     NegatibleCost CostX = NegatibleCost::Expensive;
6130     SDValue NegX =
6131         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6132     // Prevent this node from being deleted by the next call.
6133     if (NegX)
6134       Handles.emplace_back(NegX);
6135 
6136     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
6137     NegatibleCost CostY = NegatibleCost::Expensive;
6138     SDValue NegY =
6139         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6140 
6141     // We're done with the handles.
6142     Handles.clear();
6143 
6144     // Negate the X if its cost is less or equal than Y.
6145     if (NegX && (CostX <= CostY)) {
6146       Cost = CostX;
6147       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
6148       if (NegY != N)
6149         RemoveDeadNode(NegY);
6150       return N;
6151     }
6152 
6153     // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
6154     if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
6155       if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
6156         break;
6157 
6158     // Negate the Y if it is not expensive.
6159     if (NegY) {
6160       Cost = CostY;
6161       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
6162       if (NegX != N)
6163         RemoveDeadNode(NegX);
6164       return N;
6165     }
6166     break;
6167   }
6168   case ISD::FMA:
6169   case ISD::FMAD: {
6170     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6171       break;
6172 
6173     SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
6174     NegatibleCost CostZ = NegatibleCost::Expensive;
6175     SDValue NegZ =
6176         getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
6177     // Give up if fail to negate the Z.
6178     if (!NegZ)
6179       break;
6180 
6181     // Prevent this node from being deleted by the next two calls.
6182     Handles.emplace_back(NegZ);
6183 
6184     // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
6185     NegatibleCost CostX = NegatibleCost::Expensive;
6186     SDValue NegX =
6187         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6188     // Prevent this node from being deleted by the next call.
6189     if (NegX)
6190       Handles.emplace_back(NegX);
6191 
6192     // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
6193     NegatibleCost CostY = NegatibleCost::Expensive;
6194     SDValue NegY =
6195         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6196 
6197     // We're done with the handles.
6198     Handles.clear();
6199 
6200     // Negate the X if its cost is less or equal than Y.
6201     if (NegX && (CostX <= CostY)) {
6202       Cost = std::min(CostX, CostZ);
6203       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
6204       if (NegY != N)
6205         RemoveDeadNode(NegY);
6206       return N;
6207     }
6208 
6209     // Negate the Y if it is not expensive.
6210     if (NegY) {
6211       Cost = std::min(CostY, CostZ);
6212       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
6213       if (NegX != N)
6214         RemoveDeadNode(NegX);
6215       return N;
6216     }
6217     break;
6218   }
6219 
6220   case ISD::FP_EXTEND:
6221   case ISD::FSIN:
6222     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6223                                             OptForSize, Cost, Depth))
6224       return DAG.getNode(Opcode, DL, VT, NegV);
6225     break;
6226   case ISD::FP_ROUND:
6227     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6228                                             OptForSize, Cost, Depth))
6229       return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
6230     break;
6231   }
6232 
6233   return SDValue();
6234 }
6235 
6236 //===----------------------------------------------------------------------===//
6237 // Legalization Utilities
6238 //===----------------------------------------------------------------------===//
6239 
6240 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
6241                                     SDValue LHS, SDValue RHS,
6242                                     SmallVectorImpl<SDValue> &Result,
6243                                     EVT HiLoVT, SelectionDAG &DAG,
6244                                     MulExpansionKind Kind, SDValue LL,
6245                                     SDValue LH, SDValue RL, SDValue RH) const {
6246   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
6247          Opcode == ISD::SMUL_LOHI);
6248 
6249   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
6250                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
6251   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
6252                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
6253   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6254                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
6255   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6256                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
6257 
6258   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
6259     return false;
6260 
6261   unsigned OuterBitSize = VT.getScalarSizeInBits();
6262   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
6263 
6264   // LL, LH, RL, and RH must be either all NULL or all set to a value.
6265   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
6266          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
6267 
6268   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
6269   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
6270                           bool Signed) -> bool {
6271     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
6272       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
6273       Hi = SDValue(Lo.getNode(), 1);
6274       return true;
6275     }
6276     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
6277       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
6278       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
6279       return true;
6280     }
6281     return false;
6282   };
6283 
6284   SDValue Lo, Hi;
6285 
6286   if (!LL.getNode() && !RL.getNode() &&
6287       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6288     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
6289     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
6290   }
6291 
6292   if (!LL.getNode())
6293     return false;
6294 
6295   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
6296   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
6297       DAG.MaskedValueIsZero(RHS, HighMask)) {
6298     // The inputs are both zero-extended.
6299     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
6300       Result.push_back(Lo);
6301       Result.push_back(Hi);
6302       if (Opcode != ISD::MUL) {
6303         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6304         Result.push_back(Zero);
6305         Result.push_back(Zero);
6306       }
6307       return true;
6308     }
6309   }
6310 
6311   if (!VT.isVector() && Opcode == ISD::MUL &&
6312       DAG.ComputeNumSignBits(LHS) > InnerBitSize &&
6313       DAG.ComputeNumSignBits(RHS) > InnerBitSize) {
6314     // The input values are both sign-extended.
6315     // TODO non-MUL case?
6316     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
6317       Result.push_back(Lo);
6318       Result.push_back(Hi);
6319       return true;
6320     }
6321   }
6322 
6323   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
6324   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
6325   if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) {
6326     // FIXME getShiftAmountTy does not always return a sensible result when VT
6327     // is an illegal type, and so the type may be too small to fit the shift
6328     // amount. Override it with i32. The shift will have to be legalized.
6329     ShiftAmountTy = MVT::i32;
6330   }
6331   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
6332 
6333   if (!LH.getNode() && !RH.getNode() &&
6334       isOperationLegalOrCustom(ISD::SRL, VT) &&
6335       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6336     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
6337     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
6338     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
6339     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
6340   }
6341 
6342   if (!LH.getNode())
6343     return false;
6344 
6345   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
6346     return false;
6347 
6348   Result.push_back(Lo);
6349 
6350   if (Opcode == ISD::MUL) {
6351     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
6352     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
6353     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
6354     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
6355     Result.push_back(Hi);
6356     return true;
6357   }
6358 
6359   // Compute the full width result.
6360   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
6361     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
6362     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6363     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
6364     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
6365   };
6366 
6367   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6368   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
6369     return false;
6370 
6371   // This is effectively the add part of a multiply-add of half-sized operands,
6372   // so it cannot overflow.
6373   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6374 
6375   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
6376     return false;
6377 
6378   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6379   EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6380 
6381   bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
6382                   isOperationLegalOrCustom(ISD::ADDE, VT));
6383   if (UseGlue)
6384     Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
6385                        Merge(Lo, Hi));
6386   else
6387     Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next,
6388                        Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
6389 
6390   SDValue Carry = Next.getValue(1);
6391   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6392   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
6393 
6394   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
6395     return false;
6396 
6397   if (UseGlue)
6398     Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
6399                      Carry);
6400   else
6401     Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
6402                      Zero, Carry);
6403 
6404   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6405 
6406   if (Opcode == ISD::SMUL_LOHI) {
6407     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6408                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
6409     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
6410 
6411     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6412                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
6413     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
6414   }
6415 
6416   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6417   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
6418   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6419   return true;
6420 }
6421 
6422 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
6423                                SelectionDAG &DAG, MulExpansionKind Kind,
6424                                SDValue LL, SDValue LH, SDValue RL,
6425                                SDValue RH) const {
6426   SmallVector<SDValue, 2> Result;
6427   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
6428                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
6429                            DAG, Kind, LL, LH, RL, RH);
6430   if (Ok) {
6431     assert(Result.size() == 2);
6432     Lo = Result[0];
6433     Hi = Result[1];
6434   }
6435   return Ok;
6436 }
6437 
6438 // Check that (every element of) Z is undef or not an exact multiple of BW.
6439 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
6440   return ISD::matchUnaryPredicate(
6441       Z,
6442       [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
6443       true);
6444 }
6445 
6446 bool TargetLowering::expandFunnelShift(SDNode *Node, SDValue &Result,
6447                                        SelectionDAG &DAG) const {
6448   EVT VT = Node->getValueType(0);
6449 
6450   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
6451                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
6452                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
6453                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
6454     return false;
6455 
6456   SDValue X = Node->getOperand(0);
6457   SDValue Y = Node->getOperand(1);
6458   SDValue Z = Node->getOperand(2);
6459 
6460   unsigned BW = VT.getScalarSizeInBits();
6461   bool IsFSHL = Node->getOpcode() == ISD::FSHL;
6462   SDLoc DL(SDValue(Node, 0));
6463 
6464   EVT ShVT = Z.getValueType();
6465 
6466   // If a funnel shift in the other direction is more supported, use it.
6467   unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
6468   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
6469       isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
6470     if (isNonZeroModBitWidthOrUndef(Z, BW)) {
6471       // fshl X, Y, Z -> fshr X, Y, -Z
6472       // fshr X, Y, Z -> fshl X, Y, -Z
6473       SDValue Zero = DAG.getConstant(0, DL, ShVT);
6474       Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z);
6475     } else {
6476       // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
6477       // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
6478       SDValue One = DAG.getConstant(1, DL, ShVT);
6479       if (IsFSHL) {
6480         Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
6481         X = DAG.getNode(ISD::SRL, DL, VT, X, One);
6482       } else {
6483         X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
6484         Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
6485       }
6486       Z = DAG.getNOT(DL, Z, ShVT);
6487     }
6488     Result = DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
6489     return true;
6490   }
6491 
6492   SDValue ShX, ShY;
6493   SDValue ShAmt, InvShAmt;
6494   if (isNonZeroModBitWidthOrUndef(Z, BW)) {
6495     // fshl: X << C | Y >> (BW - C)
6496     // fshr: X << (BW - C) | Y >> C
6497     // where C = Z % BW is not zero
6498     SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
6499     ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
6500     InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
6501     ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
6502     ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6503   } else {
6504     // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
6505     // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
6506     SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
6507     if (isPowerOf2_32(BW)) {
6508       // Z % BW -> Z & (BW - 1)
6509       ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
6510       // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
6511       InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
6512     } else {
6513       SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
6514       ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
6515       InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
6516     }
6517 
6518     SDValue One = DAG.getConstant(1, DL, ShVT);
6519     if (IsFSHL) {
6520       ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
6521       SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
6522       ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
6523     } else {
6524       SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
6525       ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
6526       ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
6527     }
6528   }
6529   Result = DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
6530   return true;
6531 }
6532 
6533 // TODO: Merge with expandFunnelShift.
6534 bool TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps,
6535                                SDValue &Result, SelectionDAG &DAG) const {
6536   EVT VT = Node->getValueType(0);
6537   unsigned EltSizeInBits = VT.getScalarSizeInBits();
6538   bool IsLeft = Node->getOpcode() == ISD::ROTL;
6539   SDValue Op0 = Node->getOperand(0);
6540   SDValue Op1 = Node->getOperand(1);
6541   SDLoc DL(SDValue(Node, 0));
6542 
6543   EVT ShVT = Op1.getValueType();
6544   SDValue Zero = DAG.getConstant(0, DL, ShVT);
6545 
6546   // If a rotate in the other direction is supported, use it.
6547   unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
6548   if (isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
6549     SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
6550     Result = DAG.getNode(RevRot, DL, VT, Op0, Sub);
6551     return true;
6552   }
6553 
6554   if (!AllowVectorOps && VT.isVector() &&
6555       (!isOperationLegalOrCustom(ISD::SHL, VT) ||
6556        !isOperationLegalOrCustom(ISD::SRL, VT) ||
6557        !isOperationLegalOrCustom(ISD::SUB, VT) ||
6558        !isOperationLegalOrCustomOrPromote(ISD::OR, VT) ||
6559        !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
6560     return false;
6561 
6562   unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
6563   unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
6564   SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
6565   SDValue ShVal;
6566   SDValue HsVal;
6567   if (isPowerOf2_32(EltSizeInBits)) {
6568     // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
6569     // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
6570     SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
6571     SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
6572     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
6573     SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
6574     HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
6575   } else {
6576     // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
6577     // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
6578     SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
6579     SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
6580     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
6581     SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
6582     SDValue One = DAG.getConstant(1, DL, ShVT);
6583     HsVal =
6584         DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
6585   }
6586   Result = DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
6587   return true;
6588 }
6589 
6590 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi,
6591                                       SelectionDAG &DAG) const {
6592   assert(Node->getNumOperands() == 3 && "Not a double-shift!");
6593   EVT VT = Node->getValueType(0);
6594   unsigned VTBits = VT.getScalarSizeInBits();
6595   assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
6596 
6597   bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
6598   bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
6599   SDValue ShOpLo = Node->getOperand(0);
6600   SDValue ShOpHi = Node->getOperand(1);
6601   SDValue ShAmt = Node->getOperand(2);
6602   EVT ShAmtVT = ShAmt.getValueType();
6603   EVT ShAmtCCVT =
6604       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
6605   SDLoc dl(Node);
6606 
6607   // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
6608   // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
6609   // away during isel.
6610   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
6611                                   DAG.getConstant(VTBits - 1, dl, ShAmtVT));
6612   SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6613                                      DAG.getConstant(VTBits - 1, dl, ShAmtVT))
6614                        : DAG.getConstant(0, dl, VT);
6615 
6616   SDValue Tmp2, Tmp3;
6617   if (IsSHL) {
6618     Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
6619     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
6620   } else {
6621     Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
6622     Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
6623   }
6624 
6625   // If the shift amount is larger or equal than the width of a part we don't
6626   // use the result from the FSHL/FSHR. Insert a test and select the appropriate
6627   // values for large shift amounts.
6628   SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
6629                                 DAG.getConstant(VTBits, dl, ShAmtVT));
6630   SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
6631                               DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
6632 
6633   if (IsSHL) {
6634     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
6635     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
6636   } else {
6637     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
6638     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
6639   }
6640 }
6641 
6642 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
6643                                       SelectionDAG &DAG) const {
6644   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
6645   SDValue Src = Node->getOperand(OpNo);
6646   EVT SrcVT = Src.getValueType();
6647   EVT DstVT = Node->getValueType(0);
6648   SDLoc dl(SDValue(Node, 0));
6649 
6650   // FIXME: Only f32 to i64 conversions are supported.
6651   if (SrcVT != MVT::f32 || DstVT != MVT::i64)
6652     return false;
6653 
6654   if (Node->isStrictFPOpcode())
6655     // When a NaN is converted to an integer a trap is allowed. We can't
6656     // use this expansion here because it would eliminate that trap. Other
6657     // traps are also allowed and cannot be eliminated. See
6658     // IEEE 754-2008 sec 5.8.
6659     return false;
6660 
6661   // Expand f32 -> i64 conversion
6662   // This algorithm comes from compiler-rt's implementation of fixsfdi:
6663   // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
6664   unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
6665   EVT IntVT = SrcVT.changeTypeToInteger();
6666   EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
6667 
6668   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
6669   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
6670   SDValue Bias = DAG.getConstant(127, dl, IntVT);
6671   SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
6672   SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
6673   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
6674 
6675   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
6676 
6677   SDValue ExponentBits = DAG.getNode(
6678       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
6679       DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
6680   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
6681 
6682   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
6683                              DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
6684                              DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
6685   Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
6686 
6687   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
6688                           DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
6689                           DAG.getConstant(0x00800000, dl, IntVT));
6690 
6691   R = DAG.getZExtOrTrunc(R, dl, DstVT);
6692 
6693   R = DAG.getSelectCC(
6694       dl, Exponent, ExponentLoBit,
6695       DAG.getNode(ISD::SHL, dl, DstVT, R,
6696                   DAG.getZExtOrTrunc(
6697                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
6698                       dl, IntShVT)),
6699       DAG.getNode(ISD::SRL, dl, DstVT, R,
6700                   DAG.getZExtOrTrunc(
6701                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
6702                       dl, IntShVT)),
6703       ISD::SETGT);
6704 
6705   SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
6706                             DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
6707 
6708   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
6709                            DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
6710   return true;
6711 }
6712 
6713 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result,
6714                                       SDValue &Chain,
6715                                       SelectionDAG &DAG) const {
6716   SDLoc dl(SDValue(Node, 0));
6717   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
6718   SDValue Src = Node->getOperand(OpNo);
6719 
6720   EVT SrcVT = Src.getValueType();
6721   EVT DstVT = Node->getValueType(0);
6722   EVT SetCCVT =
6723       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
6724   EVT DstSetCCVT =
6725       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
6726 
6727   // Only expand vector types if we have the appropriate vector bit operations.
6728   unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
6729                                                    ISD::FP_TO_SINT;
6730   if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
6731                            !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT)))
6732     return false;
6733 
6734   // If the maximum float value is smaller then the signed integer range,
6735   // the destination signmask can't be represented by the float, so we can
6736   // just use FP_TO_SINT directly.
6737   const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT);
6738   APFloat APF(APFSem, APInt::getNullValue(SrcVT.getScalarSizeInBits()));
6739   APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
6740   if (APFloat::opOverflow &
6741       APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
6742     if (Node->isStrictFPOpcode()) {
6743       Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
6744                            { Node->getOperand(0), Src });
6745       Chain = Result.getValue(1);
6746     } else
6747       Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
6748     return true;
6749   }
6750 
6751   // Don't expand it if there isn't cheap fsub instruction.
6752   if (!isOperationLegalOrCustom(
6753           Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
6754     return false;
6755 
6756   SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
6757   SDValue Sel;
6758 
6759   if (Node->isStrictFPOpcode()) {
6760     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
6761                        Node->getOperand(0), /*IsSignaling*/ true);
6762     Chain = Sel.getValue(1);
6763   } else {
6764     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
6765   }
6766 
6767   bool Strict = Node->isStrictFPOpcode() ||
6768                 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
6769 
6770   if (Strict) {
6771     // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
6772     // signmask then offset (the result of which should be fully representable).
6773     // Sel = Src < 0x8000000000000000
6774     // FltOfs = select Sel, 0, 0x8000000000000000
6775     // IntOfs = select Sel, 0, 0x8000000000000000
6776     // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
6777 
6778     // TODO: Should any fast-math-flags be set for the FSUB?
6779     SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
6780                                    DAG.getConstantFP(0.0, dl, SrcVT), Cst);
6781     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
6782     SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
6783                                    DAG.getConstant(0, dl, DstVT),
6784                                    DAG.getConstant(SignMask, dl, DstVT));
6785     SDValue SInt;
6786     if (Node->isStrictFPOpcode()) {
6787       SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
6788                                 { Chain, Src, FltOfs });
6789       SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
6790                          { Val.getValue(1), Val });
6791       Chain = SInt.getValue(1);
6792     } else {
6793       SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
6794       SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
6795     }
6796     Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
6797   } else {
6798     // Expand based on maximum range of FP_TO_SINT:
6799     // True = fp_to_sint(Src)
6800     // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
6801     // Result = select (Src < 0x8000000000000000), True, False
6802 
6803     SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
6804     // TODO: Should any fast-math-flags be set for the FSUB?
6805     SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
6806                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
6807     False = DAG.getNode(ISD::XOR, dl, DstVT, False,
6808                         DAG.getConstant(SignMask, dl, DstVT));
6809     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
6810     Result = DAG.getSelect(dl, DstVT, Sel, True, False);
6811   }
6812   return true;
6813 }
6814 
6815 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result,
6816                                       SDValue &Chain,
6817                                       SelectionDAG &DAG) const {
6818   // This transform is not correct for converting 0 when rounding mode is set
6819   // to round toward negative infinity which will produce -0.0. So disable under
6820   // strictfp.
6821   if (Node->isStrictFPOpcode())
6822     return false;
6823 
6824   SDValue Src = Node->getOperand(0);
6825   EVT SrcVT = Src.getValueType();
6826   EVT DstVT = Node->getValueType(0);
6827 
6828   if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
6829     return false;
6830 
6831   // Only expand vector types if we have the appropriate vector bit operations.
6832   if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
6833                            !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
6834                            !isOperationLegalOrCustom(ISD::FSUB, DstVT) ||
6835                            !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
6836                            !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
6837     return false;
6838 
6839   SDLoc dl(SDValue(Node, 0));
6840   EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout());
6841 
6842   // Implementation of unsigned i64 to f64 following the algorithm in
6843   // __floatundidf in compiler_rt.  This implementation performs rounding
6844   // correctly in all rounding modes with the exception of converting 0
6845   // when rounding toward negative infinity. In that case the fsub will produce
6846   // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect.
6847   SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
6848   SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
6849       BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT);
6850   SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
6851   SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
6852   SDValue HiShift = DAG.getConstant(32, dl, ShiftVT);
6853 
6854   SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
6855   SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
6856   SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
6857   SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
6858   SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
6859   SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
6860   SDValue HiSub =
6861       DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
6862   Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
6863   return true;
6864 }
6865 
6866 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node,
6867                                               SelectionDAG &DAG) const {
6868   SDLoc dl(Node);
6869   unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ?
6870     ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
6871   EVT VT = Node->getValueType(0);
6872 
6873   if (VT.isScalableVector())
6874     report_fatal_error(
6875         "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
6876 
6877   if (isOperationLegalOrCustom(NewOp, VT)) {
6878     SDValue Quiet0 = Node->getOperand(0);
6879     SDValue Quiet1 = Node->getOperand(1);
6880 
6881     if (!Node->getFlags().hasNoNaNs()) {
6882       // Insert canonicalizes if it's possible we need to quiet to get correct
6883       // sNaN behavior.
6884       if (!DAG.isKnownNeverSNaN(Quiet0)) {
6885         Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
6886                              Node->getFlags());
6887       }
6888       if (!DAG.isKnownNeverSNaN(Quiet1)) {
6889         Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
6890                              Node->getFlags());
6891       }
6892     }
6893 
6894     return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
6895   }
6896 
6897   // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
6898   // instead if there are no NaNs.
6899   if (Node->getFlags().hasNoNaNs()) {
6900     unsigned IEEE2018Op =
6901         Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
6902     if (isOperationLegalOrCustom(IEEE2018Op, VT)) {
6903       return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
6904                          Node->getOperand(1), Node->getFlags());
6905     }
6906   }
6907 
6908   // If none of the above worked, but there are no NaNs, then expand to
6909   // a compare/select sequence.  This is required for correctness since
6910   // InstCombine might have canonicalized a fcmp+select sequence to a
6911   // FMINNUM/FMAXNUM node.  If we were to fall through to the default
6912   // expansion to libcall, we might introduce a link-time dependency
6913   // on libm into a file that originally did not have one.
6914   if (Node->getFlags().hasNoNaNs()) {
6915     ISD::CondCode Pred =
6916         Node->getOpcode() == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
6917     SDValue Op1 = Node->getOperand(0);
6918     SDValue Op2 = Node->getOperand(1);
6919     SDValue SelCC = DAG.getSelectCC(dl, Op1, Op2, Op1, Op2, Pred);
6920     // Copy FMF flags, but always set the no-signed-zeros flag
6921     // as this is implied by the FMINNUM/FMAXNUM semantics.
6922     SDNodeFlags Flags = Node->getFlags();
6923     Flags.setNoSignedZeros(true);
6924     SelCC->setFlags(Flags);
6925     return SelCC;
6926   }
6927 
6928   return SDValue();
6929 }
6930 
6931 bool TargetLowering::expandCTPOP(SDNode *Node, SDValue &Result,
6932                                  SelectionDAG &DAG) const {
6933   SDLoc dl(Node);
6934   EVT VT = Node->getValueType(0);
6935   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6936   SDValue Op = Node->getOperand(0);
6937   unsigned Len = VT.getScalarSizeInBits();
6938   assert(VT.isInteger() && "CTPOP not implemented for this type.");
6939 
6940   // TODO: Add support for irregular type lengths.
6941   if (!(Len <= 128 && Len % 8 == 0))
6942     return false;
6943 
6944   // Only expand vector types if we have the appropriate vector bit operations.
6945   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::ADD, VT) ||
6946                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
6947                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
6948                         (Len != 8 && !isOperationLegalOrCustom(ISD::MUL, VT)) ||
6949                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
6950     return false;
6951 
6952   // This is the "best" algorithm from
6953   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
6954   SDValue Mask55 =
6955       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
6956   SDValue Mask33 =
6957       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
6958   SDValue Mask0F =
6959       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
6960   SDValue Mask01 =
6961       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
6962 
6963   // v = v - ((v >> 1) & 0x55555555...)
6964   Op = DAG.getNode(ISD::SUB, dl, VT, Op,
6965                    DAG.getNode(ISD::AND, dl, VT,
6966                                DAG.getNode(ISD::SRL, dl, VT, Op,
6967                                            DAG.getConstant(1, dl, ShVT)),
6968                                Mask55));
6969   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
6970   Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
6971                    DAG.getNode(ISD::AND, dl, VT,
6972                                DAG.getNode(ISD::SRL, dl, VT, Op,
6973                                            DAG.getConstant(2, dl, ShVT)),
6974                                Mask33));
6975   // v = (v + (v >> 4)) & 0x0F0F0F0F...
6976   Op = DAG.getNode(ISD::AND, dl, VT,
6977                    DAG.getNode(ISD::ADD, dl, VT, Op,
6978                                DAG.getNode(ISD::SRL, dl, VT, Op,
6979                                            DAG.getConstant(4, dl, ShVT))),
6980                    Mask0F);
6981   // v = (v * 0x01010101...) >> (Len - 8)
6982   if (Len > 8)
6983     Op =
6984         DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
6985                     DAG.getConstant(Len - 8, dl, ShVT));
6986 
6987   Result = Op;
6988   return true;
6989 }
6990 
6991 bool TargetLowering::expandCTLZ(SDNode *Node, SDValue &Result,
6992                                 SelectionDAG &DAG) const {
6993   SDLoc dl(Node);
6994   EVT VT = Node->getValueType(0);
6995   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6996   SDValue Op = Node->getOperand(0);
6997   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
6998 
6999   // If the non-ZERO_UNDEF version is supported we can use that instead.
7000   if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
7001       isOperationLegalOrCustom(ISD::CTLZ, VT)) {
7002     Result = DAG.getNode(ISD::CTLZ, dl, VT, Op);
7003     return true;
7004   }
7005 
7006   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7007   if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
7008     EVT SetCCVT =
7009         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7010     SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
7011     SDValue Zero = DAG.getConstant(0, dl, VT);
7012     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7013     Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero,
7014                          DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
7015     return true;
7016   }
7017 
7018   // Only expand vector types if we have the appropriate vector bit operations.
7019   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7020                         !isOperationLegalOrCustom(ISD::CTPOP, VT) ||
7021                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
7022                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
7023     return false;
7024 
7025   // for now, we do this:
7026   // x = x | (x >> 1);
7027   // x = x | (x >> 2);
7028   // ...
7029   // x = x | (x >>16);
7030   // x = x | (x >>32); // for 64-bit input
7031   // return popcount(~x);
7032   //
7033   // Ref: "Hacker's Delight" by Henry Warren
7034   for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) {
7035     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
7036     Op = DAG.getNode(ISD::OR, dl, VT, Op,
7037                      DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
7038   }
7039   Op = DAG.getNOT(dl, Op, VT);
7040   Result = DAG.getNode(ISD::CTPOP, dl, VT, Op);
7041   return true;
7042 }
7043 
7044 bool TargetLowering::expandCTTZ(SDNode *Node, SDValue &Result,
7045                                 SelectionDAG &DAG) const {
7046   SDLoc dl(Node);
7047   EVT VT = Node->getValueType(0);
7048   SDValue Op = Node->getOperand(0);
7049   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7050 
7051   // If the non-ZERO_UNDEF version is supported we can use that instead.
7052   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
7053       isOperationLegalOrCustom(ISD::CTTZ, VT)) {
7054     Result = DAG.getNode(ISD::CTTZ, dl, VT, Op);
7055     return true;
7056   }
7057 
7058   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7059   if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) {
7060     EVT SetCCVT =
7061         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7062     SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op);
7063     SDValue Zero = DAG.getConstant(0, dl, VT);
7064     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7065     Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero,
7066                          DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
7067     return true;
7068   }
7069 
7070   // Only expand vector types if we have the appropriate vector bit operations.
7071   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7072                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
7073                          !isOperationLegalOrCustom(ISD::CTLZ, VT)) ||
7074                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
7075                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
7076                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
7077     return false;
7078 
7079   // for now, we use: { return popcount(~x & (x - 1)); }
7080   // unless the target has ctlz but not ctpop, in which case we use:
7081   // { return 32 - nlz(~x & (x-1)); }
7082   // Ref: "Hacker's Delight" by Henry Warren
7083   SDValue Tmp = DAG.getNode(
7084       ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
7085       DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
7086 
7087   // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
7088   if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) {
7089     Result =
7090         DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
7091                     DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
7092     return true;
7093   }
7094 
7095   Result = DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
7096   return true;
7097 }
7098 
7099 bool TargetLowering::expandABS(SDNode *N, SDValue &Result,
7100                                SelectionDAG &DAG, bool IsNegative) const {
7101   SDLoc dl(N);
7102   EVT VT = N->getValueType(0);
7103   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7104   SDValue Op = N->getOperand(0);
7105 
7106   // abs(x) -> smax(x,sub(0,x))
7107   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7108       isOperationLegal(ISD::SMAX, VT)) {
7109     SDValue Zero = DAG.getConstant(0, dl, VT);
7110     Result = DAG.getNode(ISD::SMAX, dl, VT, Op,
7111                          DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7112     return true;
7113   }
7114 
7115   // abs(x) -> umin(x,sub(0,x))
7116   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7117       isOperationLegal(ISD::UMIN, VT)) {
7118     SDValue Zero = DAG.getConstant(0, dl, VT);
7119     Result = DAG.getNode(ISD::UMIN, dl, VT, Op,
7120                          DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7121     return true;
7122   }
7123 
7124   // 0 - abs(x) -> smin(x, sub(0,x))
7125   if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
7126       isOperationLegal(ISD::SMIN, VT)) {
7127     SDValue Zero = DAG.getConstant(0, dl, VT);
7128     Result = DAG.getNode(ISD::SMIN, dl, VT, Op,
7129                          DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7130     return true;
7131   }
7132 
7133   // Only expand vector types if we have the appropriate vector operations.
7134   if (VT.isVector() &&
7135       (!isOperationLegalOrCustom(ISD::SRA, VT) ||
7136        (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
7137        (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
7138        !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
7139     return false;
7140 
7141   SDValue Shift =
7142       DAG.getNode(ISD::SRA, dl, VT, Op,
7143                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT));
7144   if (!IsNegative) {
7145     SDValue Add = DAG.getNode(ISD::ADD, dl, VT, Op, Shift);
7146     Result = DAG.getNode(ISD::XOR, dl, VT, Add, Shift);
7147   } else {
7148     // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
7149     SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
7150     Result = DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
7151   }
7152   return true;
7153 }
7154 
7155 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const {
7156   SDLoc dl(N);
7157   EVT VT = N->getValueType(0);
7158   SDValue Op = N->getOperand(0);
7159 
7160   if (!VT.isSimple())
7161     return SDValue();
7162 
7163   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
7164   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
7165   switch (VT.getSimpleVT().getScalarType().SimpleTy) {
7166   default:
7167     return SDValue();
7168   case MVT::i16:
7169     // Use a rotate by 8. This can be further expanded if necessary.
7170     return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7171   case MVT::i32:
7172     Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7173     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7174     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7175     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7176     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
7177                        DAG.getConstant(0xFF0000, dl, VT));
7178     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
7179     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
7180     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
7181     return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
7182   case MVT::i64:
7183     Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
7184     Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
7185     Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7186     Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7187     Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7188     Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7189     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
7190     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
7191     Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7,
7192                        DAG.getConstant(255ULL<<48, dl, VT));
7193     Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6,
7194                        DAG.getConstant(255ULL<<40, dl, VT));
7195     Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5,
7196                        DAG.getConstant(255ULL<<32, dl, VT));
7197     Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
7198                        DAG.getConstant(255ULL<<24, dl, VT));
7199     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
7200                        DAG.getConstant(255ULL<<16, dl, VT));
7201     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
7202                        DAG.getConstant(255ULL<<8 , dl, VT));
7203     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
7204     Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
7205     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
7206     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
7207     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
7208     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
7209     return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
7210   }
7211 }
7212 
7213 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const {
7214   SDLoc dl(N);
7215   EVT VT = N->getValueType(0);
7216   SDValue Op = N->getOperand(0);
7217   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
7218   unsigned Sz = VT.getScalarSizeInBits();
7219 
7220   SDValue Tmp, Tmp2, Tmp3;
7221 
7222   // If we can, perform BSWAP first and then the mask+swap the i4, then i2
7223   // and finally the i1 pairs.
7224   // TODO: We can easily support i4/i2 legal types if any target ever does.
7225   if (Sz >= 8 && isPowerOf2_32(Sz)) {
7226     // Create the masks - repeating the pattern every byte.
7227     APInt MaskHi4 = APInt::getSplat(Sz, APInt(8, 0xF0));
7228     APInt MaskHi2 = APInt::getSplat(Sz, APInt(8, 0xCC));
7229     APInt MaskHi1 = APInt::getSplat(Sz, APInt(8, 0xAA));
7230     APInt MaskLo4 = APInt::getSplat(Sz, APInt(8, 0x0F));
7231     APInt MaskLo2 = APInt::getSplat(Sz, APInt(8, 0x33));
7232     APInt MaskLo1 = APInt::getSplat(Sz, APInt(8, 0x55));
7233 
7234     // BSWAP if the type is wider than a single byte.
7235     Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
7236 
7237     // swap i4: ((V & 0xF0) >> 4) | ((V & 0x0F) << 4)
7238     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi4, dl, VT));
7239     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo4, dl, VT));
7240     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(4, dl, SHVT));
7241     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
7242     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7243 
7244     // swap i2: ((V & 0xCC) >> 2) | ((V & 0x33) << 2)
7245     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi2, dl, VT));
7246     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo2, dl, VT));
7247     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(2, dl, SHVT));
7248     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
7249     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7250 
7251     // swap i1: ((V & 0xAA) >> 1) | ((V & 0x55) << 1)
7252     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi1, dl, VT));
7253     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo1, dl, VT));
7254     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(1, dl, SHVT));
7255     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
7256     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7257     return Tmp;
7258   }
7259 
7260   Tmp = DAG.getConstant(0, dl, VT);
7261   for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
7262     if (I < J)
7263       Tmp2 =
7264           DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
7265     else
7266       Tmp2 =
7267           DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
7268 
7269     APInt Shift(Sz, 1);
7270     Shift <<= J;
7271     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
7272     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
7273   }
7274 
7275   return Tmp;
7276 }
7277 
7278 std::pair<SDValue, SDValue>
7279 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
7280                                     SelectionDAG &DAG) const {
7281   SDLoc SL(LD);
7282   SDValue Chain = LD->getChain();
7283   SDValue BasePTR = LD->getBasePtr();
7284   EVT SrcVT = LD->getMemoryVT();
7285   EVT DstVT = LD->getValueType(0);
7286   ISD::LoadExtType ExtType = LD->getExtensionType();
7287 
7288   if (SrcVT.isScalableVector())
7289     report_fatal_error("Cannot scalarize scalable vector loads");
7290 
7291   unsigned NumElem = SrcVT.getVectorNumElements();
7292 
7293   EVT SrcEltVT = SrcVT.getScalarType();
7294   EVT DstEltVT = DstVT.getScalarType();
7295 
7296   // A vector must always be stored in memory as-is, i.e. without any padding
7297   // between the elements, since various code depend on it, e.g. in the
7298   // handling of a bitcast of a vector type to int, which may be done with a
7299   // vector store followed by an integer load. A vector that does not have
7300   // elements that are byte-sized must therefore be stored as an integer
7301   // built out of the extracted vector elements.
7302   if (!SrcEltVT.isByteSized()) {
7303     unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
7304     EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
7305 
7306     unsigned NumSrcBits = SrcVT.getSizeInBits();
7307     EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
7308 
7309     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
7310     SDValue SrcEltBitMask = DAG.getConstant(
7311         APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
7312 
7313     // Load the whole vector and avoid masking off the top bits as it makes
7314     // the codegen worse.
7315     SDValue Load =
7316         DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR,
7317                        LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(),
7318                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
7319 
7320     SmallVector<SDValue, 8> Vals;
7321     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7322       unsigned ShiftIntoIdx =
7323           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
7324       SDValue ShiftAmount =
7325           DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(),
7326                                      LoadVT, SL, /*LegalTypes=*/false);
7327       SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
7328       SDValue Elt =
7329           DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
7330       SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
7331 
7332       if (ExtType != ISD::NON_EXTLOAD) {
7333         unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
7334         Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
7335       }
7336 
7337       Vals.push_back(Scalar);
7338     }
7339 
7340     SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
7341     return std::make_pair(Value, Load.getValue(1));
7342   }
7343 
7344   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
7345   assert(SrcEltVT.isByteSized());
7346 
7347   SmallVector<SDValue, 8> Vals;
7348   SmallVector<SDValue, 8> LoadChains;
7349 
7350   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7351     SDValue ScalarLoad =
7352         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
7353                        LD->getPointerInfo().getWithOffset(Idx * Stride),
7354                        SrcEltVT, LD->getOriginalAlign(),
7355                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
7356 
7357     BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride));
7358 
7359     Vals.push_back(ScalarLoad.getValue(0));
7360     LoadChains.push_back(ScalarLoad.getValue(1));
7361   }
7362 
7363   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
7364   SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
7365 
7366   return std::make_pair(Value, NewChain);
7367 }
7368 
7369 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
7370                                              SelectionDAG &DAG) const {
7371   SDLoc SL(ST);
7372 
7373   SDValue Chain = ST->getChain();
7374   SDValue BasePtr = ST->getBasePtr();
7375   SDValue Value = ST->getValue();
7376   EVT StVT = ST->getMemoryVT();
7377 
7378   if (StVT.isScalableVector())
7379     report_fatal_error("Cannot scalarize scalable vector stores");
7380 
7381   // The type of the data we want to save
7382   EVT RegVT = Value.getValueType();
7383   EVT RegSclVT = RegVT.getScalarType();
7384 
7385   // The type of data as saved in memory.
7386   EVT MemSclVT = StVT.getScalarType();
7387 
7388   unsigned NumElem = StVT.getVectorNumElements();
7389 
7390   // A vector must always be stored in memory as-is, i.e. without any padding
7391   // between the elements, since various code depend on it, e.g. in the
7392   // handling of a bitcast of a vector type to int, which may be done with a
7393   // vector store followed by an integer load. A vector that does not have
7394   // elements that are byte-sized must therefore be stored as an integer
7395   // built out of the extracted vector elements.
7396   if (!MemSclVT.isByteSized()) {
7397     unsigned NumBits = StVT.getSizeInBits();
7398     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
7399 
7400     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
7401 
7402     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7403       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
7404                                 DAG.getVectorIdxConstant(Idx, SL));
7405       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
7406       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
7407       unsigned ShiftIntoIdx =
7408           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
7409       SDValue ShiftAmount =
7410           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
7411       SDValue ShiftedElt =
7412           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
7413       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
7414     }
7415 
7416     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
7417                         ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
7418                         ST->getAAInfo());
7419   }
7420 
7421   // Store Stride in bytes
7422   unsigned Stride = MemSclVT.getSizeInBits() / 8;
7423   assert(Stride && "Zero stride!");
7424   // Extract each of the elements from the original vector and save them into
7425   // memory individually.
7426   SmallVector<SDValue, 8> Stores;
7427   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7428     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
7429                               DAG.getVectorIdxConstant(Idx, SL));
7430 
7431     SDValue Ptr =
7432         DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride));
7433 
7434     // This scalar TruncStore may be illegal, but we legalize it later.
7435     SDValue Store = DAG.getTruncStore(
7436         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
7437         MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
7438         ST->getAAInfo());
7439 
7440     Stores.push_back(Store);
7441   }
7442 
7443   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
7444 }
7445 
7446 std::pair<SDValue, SDValue>
7447 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
7448   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
7449          "unaligned indexed loads not implemented!");
7450   SDValue Chain = LD->getChain();
7451   SDValue Ptr = LD->getBasePtr();
7452   EVT VT = LD->getValueType(0);
7453   EVT LoadedVT = LD->getMemoryVT();
7454   SDLoc dl(LD);
7455   auto &MF = DAG.getMachineFunction();
7456 
7457   if (VT.isFloatingPoint() || VT.isVector()) {
7458     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
7459     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
7460       if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
7461           LoadedVT.isVector()) {
7462         // Scalarize the load and let the individual components be handled.
7463         return scalarizeVectorLoad(LD, DAG);
7464       }
7465 
7466       // Expand to a (misaligned) integer load of the same size,
7467       // then bitconvert to floating point or vector.
7468       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
7469                                     LD->getMemOperand());
7470       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
7471       if (LoadedVT != VT)
7472         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
7473                              ISD::ANY_EXTEND, dl, VT, Result);
7474 
7475       return std::make_pair(Result, newLoad.getValue(1));
7476     }
7477 
7478     // Copy the value to a (aligned) stack slot using (unaligned) integer
7479     // loads and stores, then do a (aligned) load from the stack slot.
7480     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
7481     unsigned LoadedBytes = LoadedVT.getStoreSize();
7482     unsigned RegBytes = RegVT.getSizeInBits() / 8;
7483     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
7484 
7485     // Make sure the stack slot is also aligned for the register type.
7486     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
7487     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
7488     SmallVector<SDValue, 8> Stores;
7489     SDValue StackPtr = StackBase;
7490     unsigned Offset = 0;
7491 
7492     EVT PtrVT = Ptr.getValueType();
7493     EVT StackPtrVT = StackPtr.getValueType();
7494 
7495     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
7496     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
7497 
7498     // Do all but one copies using the full register width.
7499     for (unsigned i = 1; i < NumRegs; i++) {
7500       // Load one integer register's worth from the original location.
7501       SDValue Load = DAG.getLoad(
7502           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
7503           LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
7504           LD->getAAInfo());
7505       // Follow the load with a store to the stack slot.  Remember the store.
7506       Stores.push_back(DAG.getStore(
7507           Load.getValue(1), dl, Load, StackPtr,
7508           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
7509       // Increment the pointers.
7510       Offset += RegBytes;
7511 
7512       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
7513       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
7514     }
7515 
7516     // The last copy may be partial.  Do an extending load.
7517     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
7518                                   8 * (LoadedBytes - Offset));
7519     SDValue Load =
7520         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
7521                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
7522                        LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
7523                        LD->getAAInfo());
7524     // Follow the load with a store to the stack slot.  Remember the store.
7525     // On big-endian machines this requires a truncating store to ensure
7526     // that the bits end up in the right place.
7527     Stores.push_back(DAG.getTruncStore(
7528         Load.getValue(1), dl, Load, StackPtr,
7529         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
7530 
7531     // The order of the stores doesn't matter - say it with a TokenFactor.
7532     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7533 
7534     // Finally, perform the original load only redirected to the stack slot.
7535     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
7536                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
7537                           LoadedVT);
7538 
7539     // Callers expect a MERGE_VALUES node.
7540     return std::make_pair(Load, TF);
7541   }
7542 
7543   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
7544          "Unaligned load of unsupported type.");
7545 
7546   // Compute the new VT that is half the size of the old one.  This is an
7547   // integer MVT.
7548   unsigned NumBits = LoadedVT.getSizeInBits();
7549   EVT NewLoadedVT;
7550   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
7551   NumBits >>= 1;
7552 
7553   Align Alignment = LD->getOriginalAlign();
7554   unsigned IncrementSize = NumBits / 8;
7555   ISD::LoadExtType HiExtType = LD->getExtensionType();
7556 
7557   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
7558   if (HiExtType == ISD::NON_EXTLOAD)
7559     HiExtType = ISD::ZEXTLOAD;
7560 
7561   // Load the value in two parts
7562   SDValue Lo, Hi;
7563   if (DAG.getDataLayout().isLittleEndian()) {
7564     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
7565                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7566                         LD->getAAInfo());
7567 
7568     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
7569     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
7570                         LD->getPointerInfo().getWithOffset(IncrementSize),
7571                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7572                         LD->getAAInfo());
7573   } else {
7574     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
7575                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7576                         LD->getAAInfo());
7577 
7578     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
7579     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
7580                         LD->getPointerInfo().getWithOffset(IncrementSize),
7581                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7582                         LD->getAAInfo());
7583   }
7584 
7585   // aggregate the two parts
7586   SDValue ShiftAmount =
7587       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
7588                                                     DAG.getDataLayout()));
7589   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
7590   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
7591 
7592   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
7593                              Hi.getValue(1));
7594 
7595   return std::make_pair(Result, TF);
7596 }
7597 
7598 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
7599                                              SelectionDAG &DAG) const {
7600   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
7601          "unaligned indexed stores not implemented!");
7602   SDValue Chain = ST->getChain();
7603   SDValue Ptr = ST->getBasePtr();
7604   SDValue Val = ST->getValue();
7605   EVT VT = Val.getValueType();
7606   Align Alignment = ST->getOriginalAlign();
7607   auto &MF = DAG.getMachineFunction();
7608   EVT StoreMemVT = ST->getMemoryVT();
7609 
7610   SDLoc dl(ST);
7611   if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
7612     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7613     if (isTypeLegal(intVT)) {
7614       if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
7615           StoreMemVT.isVector()) {
7616         // Scalarize the store and let the individual components be handled.
7617         SDValue Result = scalarizeVectorStore(ST, DAG);
7618         return Result;
7619       }
7620       // Expand to a bitconvert of the value to the integer type of the
7621       // same size, then a (misaligned) int store.
7622       // FIXME: Does not handle truncating floating point stores!
7623       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
7624       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
7625                             Alignment, ST->getMemOperand()->getFlags());
7626       return Result;
7627     }
7628     // Do a (aligned) store to a stack slot, then copy from the stack slot
7629     // to the final destination using (unaligned) integer loads and stores.
7630     MVT RegVT = getRegisterType(
7631         *DAG.getContext(),
7632         EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
7633     EVT PtrVT = Ptr.getValueType();
7634     unsigned StoredBytes = StoreMemVT.getStoreSize();
7635     unsigned RegBytes = RegVT.getSizeInBits() / 8;
7636     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
7637 
7638     // Make sure the stack slot is also aligned for the register type.
7639     SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
7640     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
7641 
7642     // Perform the original store, only redirected to the stack slot.
7643     SDValue Store = DAG.getTruncStore(
7644         Chain, dl, Val, StackPtr,
7645         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
7646 
7647     EVT StackPtrVT = StackPtr.getValueType();
7648 
7649     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
7650     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
7651     SmallVector<SDValue, 8> Stores;
7652     unsigned Offset = 0;
7653 
7654     // Do all but one copies using the full register width.
7655     for (unsigned i = 1; i < NumRegs; i++) {
7656       // Load one integer register's worth from the stack slot.
7657       SDValue Load = DAG.getLoad(
7658           RegVT, dl, Store, StackPtr,
7659           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
7660       // Store it to the final location.  Remember the store.
7661       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
7662                                     ST->getPointerInfo().getWithOffset(Offset),
7663                                     ST->getOriginalAlign(),
7664                                     ST->getMemOperand()->getFlags()));
7665       // Increment the pointers.
7666       Offset += RegBytes;
7667       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
7668       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
7669     }
7670 
7671     // The last store may be partial.  Do a truncating store.  On big-endian
7672     // machines this requires an extending load from the stack slot to ensure
7673     // that the bits are in the right place.
7674     EVT LoadMemVT =
7675         EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
7676 
7677     // Load from the stack slot.
7678     SDValue Load = DAG.getExtLoad(
7679         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
7680         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
7681 
7682     Stores.push_back(
7683         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
7684                           ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
7685                           ST->getOriginalAlign(),
7686                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
7687     // The order of the stores doesn't matter - say it with a TokenFactor.
7688     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7689     return Result;
7690   }
7691 
7692   assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
7693          "Unaligned store of unknown type.");
7694   // Get the half-size VT
7695   EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
7696   unsigned NumBits = NewStoredVT.getFixedSizeInBits();
7697   unsigned IncrementSize = NumBits / 8;
7698 
7699   // Divide the stored value in two parts.
7700   SDValue ShiftAmount = DAG.getConstant(
7701       NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout()));
7702   SDValue Lo = Val;
7703   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
7704 
7705   // Store the two parts
7706   SDValue Store1, Store2;
7707   Store1 = DAG.getTruncStore(Chain, dl,
7708                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
7709                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
7710                              ST->getMemOperand()->getFlags());
7711 
7712   Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
7713   Store2 = DAG.getTruncStore(
7714       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
7715       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
7716       ST->getMemOperand()->getFlags(), ST->getAAInfo());
7717 
7718   SDValue Result =
7719       DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
7720   return Result;
7721 }
7722 
7723 SDValue
7724 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
7725                                        const SDLoc &DL, EVT DataVT,
7726                                        SelectionDAG &DAG,
7727                                        bool IsCompressedMemory) const {
7728   SDValue Increment;
7729   EVT AddrVT = Addr.getValueType();
7730   EVT MaskVT = Mask.getValueType();
7731   assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
7732          "Incompatible types of Data and Mask");
7733   if (IsCompressedMemory) {
7734     if (DataVT.isScalableVector())
7735       report_fatal_error(
7736           "Cannot currently handle compressed memory with scalable vectors");
7737     // Incrementing the pointer according to number of '1's in the mask.
7738     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
7739     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
7740     if (MaskIntVT.getSizeInBits() < 32) {
7741       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
7742       MaskIntVT = MVT::i32;
7743     }
7744 
7745     // Count '1's with POPCNT.
7746     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
7747     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
7748     // Scale is an element size in bytes.
7749     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
7750                                     AddrVT);
7751     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
7752   } else if (DataVT.isScalableVector()) {
7753     Increment = DAG.getVScale(DL, AddrVT,
7754                               APInt(AddrVT.getFixedSizeInBits(),
7755                                     DataVT.getStoreSize().getKnownMinSize()));
7756   } else
7757     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
7758 
7759   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
7760 }
7761 
7762 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG,
7763                                        SDValue Idx,
7764                                        EVT VecVT,
7765                                        const SDLoc &dl) {
7766   if (!VecVT.isScalableVector() && isa<ConstantSDNode>(Idx))
7767     return Idx;
7768 
7769   EVT IdxVT = Idx.getValueType();
7770   unsigned NElts = VecVT.getVectorMinNumElements();
7771   if (VecVT.isScalableVector()) {
7772     // If this is a constant index and we know the value is less than the
7773     // minimum number of elements then it's safe to return Idx.
7774     if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
7775       if (IdxCst->getZExtValue() < NElts)
7776         return Idx;
7777     SDValue VS =
7778         DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
7779     SDValue Sub =
7780         DAG.getNode(ISD::SUB, dl, IdxVT, VS, DAG.getConstant(1, dl, IdxVT));
7781     return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
7782   }
7783   if (isPowerOf2_32(NElts)) {
7784     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts));
7785     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
7786                        DAG.getConstant(Imm, dl, IdxVT));
7787   }
7788   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
7789                      DAG.getConstant(NElts - 1, dl, IdxVT));
7790 }
7791 
7792 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
7793                                                 SDValue VecPtr, EVT VecVT,
7794                                                 SDValue Index) const {
7795   SDLoc dl(Index);
7796   // Make sure the index type is big enough to compute in.
7797   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
7798 
7799   EVT EltVT = VecVT.getVectorElementType();
7800 
7801   // Calculate the element offset and add it to the pointer.
7802   unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
7803   assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
7804          "Converting bits to bytes lost precision");
7805 
7806   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl);
7807 
7808   EVT IdxVT = Index.getValueType();
7809 
7810   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
7811                       DAG.getConstant(EltSize, dl, IdxVT));
7812   return DAG.getMemBasePlusOffset(VecPtr, Index, dl);
7813 }
7814 
7815 //===----------------------------------------------------------------------===//
7816 // Implementation of Emulated TLS Model
7817 //===----------------------------------------------------------------------===//
7818 
7819 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
7820                                                 SelectionDAG &DAG) const {
7821   // Access to address of TLS varialbe xyz is lowered to a function call:
7822   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
7823   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7824   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
7825   SDLoc dl(GA);
7826 
7827   ArgListTy Args;
7828   ArgListEntry Entry;
7829   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
7830   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
7831   StringRef EmuTlsVarName(NameString);
7832   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
7833   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
7834   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
7835   Entry.Ty = VoidPtrType;
7836   Args.push_back(Entry);
7837 
7838   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
7839 
7840   TargetLowering::CallLoweringInfo CLI(DAG);
7841   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
7842   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
7843   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7844 
7845   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7846   // At last for X86 targets, maybe good for other targets too?
7847   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7848   MFI.setAdjustsStack(true); // Is this only for X86 target?
7849   MFI.setHasCalls(true);
7850 
7851   assert((GA->getOffset() == 0) &&
7852          "Emulated TLS must have zero offset in GlobalAddressSDNode");
7853   return CallResult.first;
7854 }
7855 
7856 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
7857                                                 SelectionDAG &DAG) const {
7858   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
7859   if (!isCtlzFast())
7860     return SDValue();
7861   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7862   SDLoc dl(Op);
7863   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7864     if (C->isNullValue() && CC == ISD::SETEQ) {
7865       EVT VT = Op.getOperand(0).getValueType();
7866       SDValue Zext = Op.getOperand(0);
7867       if (VT.bitsLT(MVT::i32)) {
7868         VT = MVT::i32;
7869         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
7870       }
7871       unsigned Log2b = Log2_32(VT.getSizeInBits());
7872       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
7873       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
7874                                 DAG.getConstant(Log2b, dl, MVT::i32));
7875       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
7876     }
7877   }
7878   return SDValue();
7879 }
7880 
7881 // Convert redundant addressing modes (e.g. scaling is redundant
7882 // when accessing bytes).
7883 ISD::MemIndexType
7884 TargetLowering::getCanonicalIndexType(ISD::MemIndexType IndexType, EVT MemVT,
7885                                       SDValue Offsets) const {
7886   bool IsScaledIndex =
7887       (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::UNSIGNED_SCALED);
7888   bool IsSignedIndex =
7889       (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::SIGNED_UNSCALED);
7890 
7891   // Scaling is unimportant for bytes, canonicalize to unscaled.
7892   if (IsScaledIndex && MemVT.getScalarType() == MVT::i8) {
7893     IsScaledIndex = false;
7894     IndexType = IsSignedIndex ? ISD::SIGNED_UNSCALED : ISD::UNSIGNED_UNSCALED;
7895   }
7896 
7897   return IndexType;
7898 }
7899 
7900 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const {
7901   SDValue Op0 = Node->getOperand(0);
7902   SDValue Op1 = Node->getOperand(1);
7903   EVT VT = Op0.getValueType();
7904   unsigned Opcode = Node->getOpcode();
7905   SDLoc DL(Node);
7906 
7907   // umin(x,y) -> sub(x,usubsat(x,y))
7908   if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
7909       isOperationLegal(ISD::USUBSAT, VT)) {
7910     return DAG.getNode(ISD::SUB, DL, VT, Op0,
7911                        DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
7912   }
7913 
7914   // umax(x,y) -> add(x,usubsat(y,x))
7915   if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
7916       isOperationLegal(ISD::USUBSAT, VT)) {
7917     return DAG.getNode(ISD::ADD, DL, VT, Op0,
7918                        DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
7919   }
7920 
7921   // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
7922   ISD::CondCode CC;
7923   switch (Opcode) {
7924   default: llvm_unreachable("How did we get here?");
7925   case ISD::SMAX: CC = ISD::SETGT; break;
7926   case ISD::SMIN: CC = ISD::SETLT; break;
7927   case ISD::UMAX: CC = ISD::SETUGT; break;
7928   case ISD::UMIN: CC = ISD::SETULT; break;
7929   }
7930 
7931   // FIXME: Should really try to split the vector in case it's legal on a
7932   // subvector.
7933   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
7934     return DAG.UnrollVectorOp(Node);
7935 
7936   SDValue Cond = DAG.getSetCC(DL, VT, Op0, Op1, CC);
7937   return DAG.getSelect(DL, VT, Cond, Op0, Op1);
7938 }
7939 
7940 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const {
7941   unsigned Opcode = Node->getOpcode();
7942   SDValue LHS = Node->getOperand(0);
7943   SDValue RHS = Node->getOperand(1);
7944   EVT VT = LHS.getValueType();
7945   SDLoc dl(Node);
7946 
7947   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
7948   assert(VT.isInteger() && "Expected operands to be integers");
7949 
7950   // usub.sat(a, b) -> umax(a, b) - b
7951   if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
7952     SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
7953     return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
7954   }
7955 
7956   // uadd.sat(a, b) -> umin(a, ~b) + b
7957   if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
7958     SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
7959     SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
7960     return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
7961   }
7962 
7963   unsigned OverflowOp;
7964   switch (Opcode) {
7965   case ISD::SADDSAT:
7966     OverflowOp = ISD::SADDO;
7967     break;
7968   case ISD::UADDSAT:
7969     OverflowOp = ISD::UADDO;
7970     break;
7971   case ISD::SSUBSAT:
7972     OverflowOp = ISD::SSUBO;
7973     break;
7974   case ISD::USUBSAT:
7975     OverflowOp = ISD::USUBO;
7976     break;
7977   default:
7978     llvm_unreachable("Expected method to receive signed or unsigned saturation "
7979                      "addition or subtraction node.");
7980   }
7981 
7982   // FIXME: Should really try to split the vector in case it's legal on a
7983   // subvector.
7984   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
7985     return DAG.UnrollVectorOp(Node);
7986 
7987   unsigned BitWidth = LHS.getScalarValueSizeInBits();
7988   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7989   SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
7990   SDValue SumDiff = Result.getValue(0);
7991   SDValue Overflow = Result.getValue(1);
7992   SDValue Zero = DAG.getConstant(0, dl, VT);
7993   SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
7994 
7995   if (Opcode == ISD::UADDSAT) {
7996     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
7997       // (LHS + RHS) | OverflowMask
7998       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
7999       return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
8000     }
8001     // Overflow ? 0xffff.... : (LHS + RHS)
8002     return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
8003   }
8004 
8005   if (Opcode == ISD::USUBSAT) {
8006     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
8007       // (LHS - RHS) & ~OverflowMask
8008       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
8009       SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
8010       return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
8011     }
8012     // Overflow ? 0 : (LHS - RHS)
8013     return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
8014   }
8015 
8016   // SatMax -> Overflow && SumDiff < 0
8017   // SatMin -> Overflow && SumDiff >= 0
8018   APInt MinVal = APInt::getSignedMinValue(BitWidth);
8019   APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
8020   SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8021   SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8022   SDValue SumNeg = DAG.getSetCC(dl, BoolVT, SumDiff, Zero, ISD::SETLT);
8023   Result = DAG.getSelect(dl, VT, SumNeg, SatMax, SatMin);
8024   return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
8025 }
8026 
8027 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const {
8028   unsigned Opcode = Node->getOpcode();
8029   bool IsSigned = Opcode == ISD::SSHLSAT;
8030   SDValue LHS = Node->getOperand(0);
8031   SDValue RHS = Node->getOperand(1);
8032   EVT VT = LHS.getValueType();
8033   SDLoc dl(Node);
8034 
8035   assert((Node->getOpcode() == ISD::SSHLSAT ||
8036           Node->getOpcode() == ISD::USHLSAT) &&
8037           "Expected a SHLSAT opcode");
8038   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
8039   assert(VT.isInteger() && "Expected operands to be integers");
8040 
8041   // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
8042 
8043   unsigned BW = VT.getScalarSizeInBits();
8044   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
8045   SDValue Orig =
8046       DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
8047 
8048   SDValue SatVal;
8049   if (IsSigned) {
8050     SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
8051     SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
8052     SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT),
8053                              SatMin, SatMax, ISD::SETLT);
8054   } else {
8055     SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
8056   }
8057   Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE);
8058 
8059   return Result;
8060 }
8061 
8062 SDValue
8063 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const {
8064   assert((Node->getOpcode() == ISD::SMULFIX ||
8065           Node->getOpcode() == ISD::UMULFIX ||
8066           Node->getOpcode() == ISD::SMULFIXSAT ||
8067           Node->getOpcode() == ISD::UMULFIXSAT) &&
8068          "Expected a fixed point multiplication opcode");
8069 
8070   SDLoc dl(Node);
8071   SDValue LHS = Node->getOperand(0);
8072   SDValue RHS = Node->getOperand(1);
8073   EVT VT = LHS.getValueType();
8074   unsigned Scale = Node->getConstantOperandVal(2);
8075   bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
8076                      Node->getOpcode() == ISD::UMULFIXSAT);
8077   bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
8078                  Node->getOpcode() == ISD::SMULFIXSAT);
8079   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8080   unsigned VTSize = VT.getScalarSizeInBits();
8081 
8082   if (!Scale) {
8083     // [us]mul.fix(a, b, 0) -> mul(a, b)
8084     if (!Saturating) {
8085       if (isOperationLegalOrCustom(ISD::MUL, VT))
8086         return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8087     } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
8088       SDValue Result =
8089           DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8090       SDValue Product = Result.getValue(0);
8091       SDValue Overflow = Result.getValue(1);
8092       SDValue Zero = DAG.getConstant(0, dl, VT);
8093 
8094       APInt MinVal = APInt::getSignedMinValue(VTSize);
8095       APInt MaxVal = APInt::getSignedMaxValue(VTSize);
8096       SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8097       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8098       SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Product, Zero, ISD::SETLT);
8099       Result = DAG.getSelect(dl, VT, ProdNeg, SatMax, SatMin);
8100       return DAG.getSelect(dl, VT, Overflow, Result, Product);
8101     } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
8102       SDValue Result =
8103           DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8104       SDValue Product = Result.getValue(0);
8105       SDValue Overflow = Result.getValue(1);
8106 
8107       APInt MaxVal = APInt::getMaxValue(VTSize);
8108       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8109       return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
8110     }
8111   }
8112 
8113   assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
8114          "Expected scale to be less than the number of bits if signed or at "
8115          "most the number of bits if unsigned.");
8116   assert(LHS.getValueType() == RHS.getValueType() &&
8117          "Expected both operands to be the same type");
8118 
8119   // Get the upper and lower bits of the result.
8120   SDValue Lo, Hi;
8121   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
8122   unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
8123   if (isOperationLegalOrCustom(LoHiOp, VT)) {
8124     SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
8125     Lo = Result.getValue(0);
8126     Hi = Result.getValue(1);
8127   } else if (isOperationLegalOrCustom(HiOp, VT)) {
8128     Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8129     Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
8130   } else if (VT.isVector()) {
8131     return SDValue();
8132   } else {
8133     report_fatal_error("Unable to expand fixed point multiplication.");
8134   }
8135 
8136   if (Scale == VTSize)
8137     // Result is just the top half since we'd be shifting by the width of the
8138     // operand. Overflow impossible so this works for both UMULFIX and
8139     // UMULFIXSAT.
8140     return Hi;
8141 
8142   // The result will need to be shifted right by the scale since both operands
8143   // are scaled. The result is given to us in 2 halves, so we only want part of
8144   // both in the result.
8145   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
8146   SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
8147                                DAG.getConstant(Scale, dl, ShiftTy));
8148   if (!Saturating)
8149     return Result;
8150 
8151   if (!Signed) {
8152     // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
8153     // widened multiplication) aren't all zeroes.
8154 
8155     // Saturate to max if ((Hi >> Scale) != 0),
8156     // which is the same as if (Hi > ((1 << Scale) - 1))
8157     APInt MaxVal = APInt::getMaxValue(VTSize);
8158     SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale),
8159                                       dl, VT);
8160     Result = DAG.getSelectCC(dl, Hi, LowMask,
8161                              DAG.getConstant(MaxVal, dl, VT), Result,
8162                              ISD::SETUGT);
8163 
8164     return Result;
8165   }
8166 
8167   // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
8168   // widened multiplication) aren't all ones or all zeroes.
8169 
8170   SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
8171   SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
8172 
8173   if (Scale == 0) {
8174     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
8175                                DAG.getConstant(VTSize - 1, dl, ShiftTy));
8176     SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
8177     // Saturated to SatMin if wide product is negative, and SatMax if wide
8178     // product is positive ...
8179     SDValue Zero = DAG.getConstant(0, dl, VT);
8180     SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax,
8181                                                ISD::SETLT);
8182     // ... but only if we overflowed.
8183     return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
8184   }
8185 
8186   //  We handled Scale==0 above so all the bits to examine is in Hi.
8187 
8188   // Saturate to max if ((Hi >> (Scale - 1)) > 0),
8189   // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
8190   SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1),
8191                                     dl, VT);
8192   Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT);
8193   // Saturate to min if (Hi >> (Scale - 1)) < -1),
8194   // which is the same as if (HI < (-1 << (Scale - 1))
8195   SDValue HighMask =
8196       DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1),
8197                       dl, VT);
8198   Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT);
8199   return Result;
8200 }
8201 
8202 SDValue
8203 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
8204                                     SDValue LHS, SDValue RHS,
8205                                     unsigned Scale, SelectionDAG &DAG) const {
8206   assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
8207           Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
8208          "Expected a fixed point division opcode");
8209 
8210   EVT VT = LHS.getValueType();
8211   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
8212   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
8213   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8214 
8215   // If there is enough room in the type to upscale the LHS or downscale the
8216   // RHS before the division, we can perform it in this type without having to
8217   // resize. For signed operations, the LHS headroom is the number of
8218   // redundant sign bits, and for unsigned ones it is the number of zeroes.
8219   // The headroom for the RHS is the number of trailing zeroes.
8220   unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
8221                             : DAG.computeKnownBits(LHS).countMinLeadingZeros();
8222   unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
8223 
8224   // For signed saturating operations, we need to be able to detect true integer
8225   // division overflow; that is, when you have MIN / -EPS. However, this
8226   // is undefined behavior and if we emit divisions that could take such
8227   // values it may cause undesired behavior (arithmetic exceptions on x86, for
8228   // example).
8229   // Avoid this by requiring an extra bit so that we never get this case.
8230   // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
8231   // signed saturating division, we need to emit a whopping 32-bit division.
8232   if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
8233     return SDValue();
8234 
8235   unsigned LHSShift = std::min(LHSLead, Scale);
8236   unsigned RHSShift = Scale - LHSShift;
8237 
8238   // At this point, we know that if we shift the LHS up by LHSShift and the
8239   // RHS down by RHSShift, we can emit a regular division with a final scaling
8240   // factor of Scale.
8241 
8242   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
8243   if (LHSShift)
8244     LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
8245                       DAG.getConstant(LHSShift, dl, ShiftTy));
8246   if (RHSShift)
8247     RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
8248                       DAG.getConstant(RHSShift, dl, ShiftTy));
8249 
8250   SDValue Quot;
8251   if (Signed) {
8252     // For signed operations, if the resulting quotient is negative and the
8253     // remainder is nonzero, subtract 1 from the quotient to round towards
8254     // negative infinity.
8255     SDValue Rem;
8256     // FIXME: Ideally we would always produce an SDIVREM here, but if the
8257     // type isn't legal, SDIVREM cannot be expanded. There is no reason why
8258     // we couldn't just form a libcall, but the type legalizer doesn't do it.
8259     if (isTypeLegal(VT) &&
8260         isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
8261       Quot = DAG.getNode(ISD::SDIVREM, dl,
8262                          DAG.getVTList(VT, VT),
8263                          LHS, RHS);
8264       Rem = Quot.getValue(1);
8265       Quot = Quot.getValue(0);
8266     } else {
8267       Quot = DAG.getNode(ISD::SDIV, dl, VT,
8268                          LHS, RHS);
8269       Rem = DAG.getNode(ISD::SREM, dl, VT,
8270                         LHS, RHS);
8271     }
8272     SDValue Zero = DAG.getConstant(0, dl, VT);
8273     SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
8274     SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
8275     SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
8276     SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
8277     SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
8278                                DAG.getConstant(1, dl, VT));
8279     Quot = DAG.getSelect(dl, VT,
8280                          DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
8281                          Sub1, Quot);
8282   } else
8283     Quot = DAG.getNode(ISD::UDIV, dl, VT,
8284                        LHS, RHS);
8285 
8286   return Quot;
8287 }
8288 
8289 void TargetLowering::expandUADDSUBO(
8290     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
8291   SDLoc dl(Node);
8292   SDValue LHS = Node->getOperand(0);
8293   SDValue RHS = Node->getOperand(1);
8294   bool IsAdd = Node->getOpcode() == ISD::UADDO;
8295 
8296   // If ADD/SUBCARRY is legal, use that instead.
8297   unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY;
8298   if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
8299     SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
8300     SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
8301                                     { LHS, RHS, CarryIn });
8302     Result = SDValue(NodeCarry.getNode(), 0);
8303     Overflow = SDValue(NodeCarry.getNode(), 1);
8304     return;
8305   }
8306 
8307   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
8308                             LHS.getValueType(), LHS, RHS);
8309 
8310   EVT ResultType = Node->getValueType(1);
8311   EVT SetCCType = getSetCCResultType(
8312       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
8313   ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
8314   SDValue SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
8315   Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
8316 }
8317 
8318 void TargetLowering::expandSADDSUBO(
8319     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
8320   SDLoc dl(Node);
8321   SDValue LHS = Node->getOperand(0);
8322   SDValue RHS = Node->getOperand(1);
8323   bool IsAdd = Node->getOpcode() == ISD::SADDO;
8324 
8325   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
8326                             LHS.getValueType(), LHS, RHS);
8327 
8328   EVT ResultType = Node->getValueType(1);
8329   EVT OType = getSetCCResultType(
8330       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
8331 
8332   // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
8333   unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
8334   if (isOperationLegalOrCustom(OpcSat, LHS.getValueType())) {
8335     SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
8336     SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
8337     Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
8338     return;
8339   }
8340 
8341   SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
8342 
8343   // For an addition, the result should be less than one of the operands (LHS)
8344   // if and only if the other operand (RHS) is negative, otherwise there will
8345   // be overflow.
8346   // For a subtraction, the result should be less than one of the operands
8347   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
8348   // otherwise there will be overflow.
8349   SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
8350   SDValue ConditionRHS =
8351       DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT);
8352 
8353   Overflow = DAG.getBoolExtOrTrunc(
8354       DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl,
8355       ResultType, ResultType);
8356 }
8357 
8358 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result,
8359                                 SDValue &Overflow, SelectionDAG &DAG) const {
8360   SDLoc dl(Node);
8361   EVT VT = Node->getValueType(0);
8362   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8363   SDValue LHS = Node->getOperand(0);
8364   SDValue RHS = Node->getOperand(1);
8365   bool isSigned = Node->getOpcode() == ISD::SMULO;
8366 
8367   // For power-of-two multiplications we can use a simpler shift expansion.
8368   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
8369     const APInt &C = RHSC->getAPIntValue();
8370     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
8371     if (C.isPowerOf2()) {
8372       // smulo(x, signed_min) is same as umulo(x, signed_min).
8373       bool UseArithShift = isSigned && !C.isMinSignedValue();
8374       EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout());
8375       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy);
8376       Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
8377       Overflow = DAG.getSetCC(dl, SetCCVT,
8378           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
8379                       dl, VT, Result, ShiftAmt),
8380           LHS, ISD::SETNE);
8381       return true;
8382     }
8383   }
8384 
8385   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2);
8386   if (VT.isVector())
8387     WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT,
8388                               VT.getVectorNumElements());
8389 
8390   SDValue BottomHalf;
8391   SDValue TopHalf;
8392   static const unsigned Ops[2][3] =
8393       { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
8394         { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
8395   if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
8396     BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8397     TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
8398   } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
8399     BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
8400                              RHS);
8401     TopHalf = BottomHalf.getValue(1);
8402   } else if (isTypeLegal(WideVT)) {
8403     LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
8404     RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
8405     SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
8406     BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
8407     SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl,
8408         getShiftAmountTy(WideVT, DAG.getDataLayout()));
8409     TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
8410                           DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
8411   } else {
8412     if (VT.isVector())
8413       return false;
8414 
8415     // We can fall back to a libcall with an illegal type for the MUL if we
8416     // have a libcall big enough.
8417     // Also, we can fall back to a division in some cases, but that's a big
8418     // performance hit in the general case.
8419     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
8420     if (WideVT == MVT::i16)
8421       LC = RTLIB::MUL_I16;
8422     else if (WideVT == MVT::i32)
8423       LC = RTLIB::MUL_I32;
8424     else if (WideVT == MVT::i64)
8425       LC = RTLIB::MUL_I64;
8426     else if (WideVT == MVT::i128)
8427       LC = RTLIB::MUL_I128;
8428     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
8429 
8430     SDValue HiLHS;
8431     SDValue HiRHS;
8432     if (isSigned) {
8433       // The high part is obtained by SRA'ing all but one of the bits of low
8434       // part.
8435       unsigned LoSize = VT.getFixedSizeInBits();
8436       HiLHS =
8437           DAG.getNode(ISD::SRA, dl, VT, LHS,
8438                       DAG.getConstant(LoSize - 1, dl,
8439                                       getPointerTy(DAG.getDataLayout())));
8440       HiRHS =
8441           DAG.getNode(ISD::SRA, dl, VT, RHS,
8442                       DAG.getConstant(LoSize - 1, dl,
8443                                       getPointerTy(DAG.getDataLayout())));
8444     } else {
8445         HiLHS = DAG.getConstant(0, dl, VT);
8446         HiRHS = DAG.getConstant(0, dl, VT);
8447     }
8448 
8449     // Here we're passing the 2 arguments explicitly as 4 arguments that are
8450     // pre-lowered to the correct types. This all depends upon WideVT not
8451     // being a legal type for the architecture and thus has to be split to
8452     // two arguments.
8453     SDValue Ret;
8454     TargetLowering::MakeLibCallOptions CallOptions;
8455     CallOptions.setSExt(isSigned);
8456     CallOptions.setIsPostTypeLegalization(true);
8457     if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) {
8458       // Halves of WideVT are packed into registers in different order
8459       // depending on platform endianness. This is usually handled by
8460       // the C calling convention, but we can't defer to it in
8461       // the legalizer.
8462       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
8463       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
8464     } else {
8465       SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
8466       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
8467     }
8468     assert(Ret.getOpcode() == ISD::MERGE_VALUES &&
8469            "Ret value is a collection of constituent nodes holding result.");
8470     if (DAG.getDataLayout().isLittleEndian()) {
8471       // Same as above.
8472       BottomHalf = Ret.getOperand(0);
8473       TopHalf = Ret.getOperand(1);
8474     } else {
8475       BottomHalf = Ret.getOperand(1);
8476       TopHalf = Ret.getOperand(0);
8477     }
8478   }
8479 
8480   Result = BottomHalf;
8481   if (isSigned) {
8482     SDValue ShiftAmt = DAG.getConstant(
8483         VT.getScalarSizeInBits() - 1, dl,
8484         getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
8485     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
8486     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
8487   } else {
8488     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
8489                             DAG.getConstant(0, dl, VT), ISD::SETNE);
8490   }
8491 
8492   // Truncate the result if SetCC returns a larger type than needed.
8493   EVT RType = Node->getValueType(1);
8494   if (RType.bitsLT(Overflow.getValueType()))
8495     Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
8496 
8497   assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
8498          "Unexpected result type for S/UMULO legalization");
8499   return true;
8500 }
8501 
8502 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const {
8503   SDLoc dl(Node);
8504   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
8505   SDValue Op = Node->getOperand(0);
8506   EVT VT = Op.getValueType();
8507 
8508   if (VT.isScalableVector())
8509     report_fatal_error(
8510         "Expanding reductions for scalable vectors is undefined.");
8511 
8512   // Try to use a shuffle reduction for power of two vectors.
8513   if (VT.isPow2VectorType()) {
8514     while (VT.getVectorNumElements() > 1) {
8515       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
8516       if (!isOperationLegalOrCustom(BaseOpcode, HalfVT))
8517         break;
8518 
8519       SDValue Lo, Hi;
8520       std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
8521       Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi);
8522       VT = HalfVT;
8523     }
8524   }
8525 
8526   EVT EltVT = VT.getVectorElementType();
8527   unsigned NumElts = VT.getVectorNumElements();
8528 
8529   SmallVector<SDValue, 8> Ops;
8530   DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
8531 
8532   SDValue Res = Ops[0];
8533   for (unsigned i = 1; i < NumElts; i++)
8534     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags());
8535 
8536   // Result type may be wider than element type.
8537   if (EltVT != Node->getValueType(0))
8538     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
8539   return Res;
8540 }
8541 
8542 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const {
8543   SDLoc dl(Node);
8544   SDValue AccOp = Node->getOperand(0);
8545   SDValue VecOp = Node->getOperand(1);
8546   SDNodeFlags Flags = Node->getFlags();
8547 
8548   EVT VT = VecOp.getValueType();
8549   EVT EltVT = VT.getVectorElementType();
8550 
8551   if (VT.isScalableVector())
8552     report_fatal_error(
8553         "Expanding reductions for scalable vectors is undefined.");
8554 
8555   unsigned NumElts = VT.getVectorNumElements();
8556 
8557   SmallVector<SDValue, 8> Ops;
8558   DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
8559 
8560   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
8561 
8562   SDValue Res = AccOp;
8563   for (unsigned i = 0; i < NumElts; i++)
8564     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
8565 
8566   return Res;
8567 }
8568 
8569 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result,
8570                                SelectionDAG &DAG) const {
8571   EVT VT = Node->getValueType(0);
8572   SDLoc dl(Node);
8573   bool isSigned = Node->getOpcode() == ISD::SREM;
8574   unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
8575   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
8576   SDValue Dividend = Node->getOperand(0);
8577   SDValue Divisor = Node->getOperand(1);
8578   if (isOperationLegalOrCustom(DivRemOpc, VT)) {
8579     SDVTList VTs = DAG.getVTList(VT, VT);
8580     Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
8581     return true;
8582   }
8583   if (isOperationLegalOrCustom(DivOpc, VT)) {
8584     // X % Y -> X-X/Y*Y
8585     SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
8586     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
8587     Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
8588     return true;
8589   }
8590   return false;
8591 }
8592 
8593 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node,
8594                                             SelectionDAG &DAG) const {
8595   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
8596   SDLoc dl(SDValue(Node, 0));
8597   SDValue Src = Node->getOperand(0);
8598 
8599   // DstVT is the result type, while SatVT is the size to which we saturate
8600   EVT SrcVT = Src.getValueType();
8601   EVT DstVT = Node->getValueType(0);
8602 
8603   EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
8604   unsigned SatWidth = SatVT.getScalarSizeInBits();
8605   unsigned DstWidth = DstVT.getScalarSizeInBits();
8606   assert(SatWidth <= DstWidth &&
8607          "Expected saturation width smaller than result width");
8608 
8609   // Determine minimum and maximum integer values and their corresponding
8610   // floating-point values.
8611   APInt MinInt, MaxInt;
8612   if (IsSigned) {
8613     MinInt = APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth);
8614     MaxInt = APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth);
8615   } else {
8616     MinInt = APInt::getMinValue(SatWidth).zextOrSelf(DstWidth);
8617     MaxInt = APInt::getMaxValue(SatWidth).zextOrSelf(DstWidth);
8618   }
8619 
8620   // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as
8621   // libcall emission cannot handle this. Large result types will fail.
8622   if (SrcVT == MVT::f16) {
8623     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
8624     SrcVT = Src.getValueType();
8625   }
8626 
8627   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
8628   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
8629 
8630   APFloat::opStatus MinStatus =
8631       MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
8632   APFloat::opStatus MaxStatus =
8633       MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
8634   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
8635                              !(MaxStatus & APFloat::opStatus::opInexact);
8636 
8637   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
8638   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
8639 
8640   // If the integer bounds are exactly representable as floats and min/max are
8641   // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
8642   // of comparisons and selects.
8643   bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) &&
8644                      isOperationLegal(ISD::FMAXNUM, SrcVT);
8645   if (AreExactFloatBounds && MinMaxLegal) {
8646     SDValue Clamped = Src;
8647 
8648     // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat.
8649     Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode);
8650     // Clamp by MaxFloat from above. NaN cannot occur.
8651     Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode);
8652     // Convert clamped value to integer.
8653     SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
8654                                   dl, DstVT, Clamped);
8655 
8656     // In the unsigned case we're done, because we mapped NaN to MinFloat,
8657     // which will cast to zero.
8658     if (!IsSigned)
8659       return FpToInt;
8660 
8661     // Otherwise, select 0 if Src is NaN.
8662     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
8663     return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt,
8664                            ISD::CondCode::SETUO);
8665   }
8666 
8667   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
8668   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
8669 
8670   // Result of direct conversion. The assumption here is that the operation is
8671   // non-trapping and it's fine to apply it to an out-of-range value if we
8672   // select it away later.
8673   SDValue FpToInt =
8674       DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
8675 
8676   SDValue Select = FpToInt;
8677 
8678   // If Src ULT MinFloat, select MinInt. In particular, this also selects
8679   // MinInt if Src is NaN.
8680   Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select,
8681                            ISD::CondCode::SETULT);
8682   // If Src OGT MaxFloat, select MaxInt.
8683   Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select,
8684                            ISD::CondCode::SETOGT);
8685 
8686   // In the unsigned case we are done, because we mapped NaN to MinInt, which
8687   // is already zero.
8688   if (!IsSigned)
8689     return Select;
8690 
8691   // Otherwise, select 0 if Src is NaN.
8692   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
8693   return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
8694 }
8695 
8696 SDValue TargetLowering::expandVectorSplice(SDNode *Node,
8697                                            SelectionDAG &DAG) const {
8698   assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!");
8699   assert(Node->getValueType(0).isScalableVector() &&
8700          "Fixed length vector types expected to use SHUFFLE_VECTOR!");
8701 
8702   EVT VT = Node->getValueType(0);
8703   SDValue V1 = Node->getOperand(0);
8704   SDValue V2 = Node->getOperand(1);
8705   int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue();
8706   SDLoc DL(Node);
8707 
8708   // Expand through memory thusly:
8709   //  Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
8710   //  Store V1, Ptr
8711   //  Store V2, Ptr + sizeof(V1)
8712   //  If (Imm < 0)
8713   //    TrailingElts = -Imm
8714   //    Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt))
8715   //  else
8716   //    Ptr = Ptr + (Imm * sizeof(VT.Elt))
8717   //  Res = Load Ptr
8718 
8719   Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
8720 
8721   EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8722                                VT.getVectorElementCount() * 2);
8723   SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
8724   EVT PtrVT = StackPtr.getValueType();
8725   auto &MF = DAG.getMachineFunction();
8726   auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
8727   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
8728 
8729   // Store the lo part of CONCAT_VECTORS(V1, V2)
8730   SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo);
8731   // Store the hi part of CONCAT_VECTORS(V1, V2)
8732   SDValue OffsetToV2 = DAG.getVScale(
8733       DL, PtrVT,
8734       APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
8735   SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2);
8736   SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo);
8737 
8738   if (Imm >= 0) {
8739     // Load back the required element. getVectorElementPointer takes care of
8740     // clamping the index if it's out-of-bounds.
8741     StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2));
8742     // Load the spliced result
8743     return DAG.getLoad(VT, DL, StoreV2, StackPtr,
8744                        MachinePointerInfo::getUnknownStack(MF));
8745   }
8746 
8747   uint64_t TrailingElts = -Imm;
8748 
8749   // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2.
8750   TypeSize EltByteSize = VT.getVectorElementType().getStoreSize();
8751   SDValue TrailingBytes =
8752       DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT);
8753 
8754   if (TrailingElts > VT.getVectorMinNumElements()) {
8755     SDValue VLBytes = DAG.getVScale(
8756         DL, PtrVT,
8757         APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
8758     TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes);
8759   }
8760 
8761   // Calculate the start address of the spliced result.
8762   StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
8763 
8764   // Load the spliced result
8765   return DAG.getLoad(VT, DL, StoreV2, StackPtr2,
8766                      MachinePointerInfo::getUnknownStack(MF));
8767 }
8768 
8769 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT,
8770                                            SDValue &LHS, SDValue &RHS,
8771                                            SDValue &CC, bool &NeedInvert,
8772                                            const SDLoc &dl, SDValue &Chain,
8773                                            bool IsSignaling) const {
8774   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8775   MVT OpVT = LHS.getSimpleValueType();
8776   ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
8777   NeedInvert = false;
8778   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
8779   default:
8780     llvm_unreachable("Unknown condition code action!");
8781   case TargetLowering::Legal:
8782     // Nothing to do.
8783     break;
8784   case TargetLowering::Expand: {
8785     ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
8786     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
8787       std::swap(LHS, RHS);
8788       CC = DAG.getCondCode(InvCC);
8789       return true;
8790     }
8791     // Swapping operands didn't work. Try inverting the condition.
8792     bool NeedSwap = false;
8793     InvCC = getSetCCInverse(CCCode, OpVT);
8794     if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
8795       // If inverting the condition is not enough, try swapping operands
8796       // on top of it.
8797       InvCC = ISD::getSetCCSwappedOperands(InvCC);
8798       NeedSwap = true;
8799     }
8800     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
8801       CC = DAG.getCondCode(InvCC);
8802       NeedInvert = true;
8803       if (NeedSwap)
8804         std::swap(LHS, RHS);
8805       return true;
8806     }
8807 
8808     ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
8809     unsigned Opc = 0;
8810     switch (CCCode) {
8811     default:
8812       llvm_unreachable("Don't know how to expand this condition!");
8813     case ISD::SETUO:
8814       if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) {
8815         CC1 = ISD::SETUNE;
8816         CC2 = ISD::SETUNE;
8817         Opc = ISD::OR;
8818         break;
8819       }
8820       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
8821              "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
8822       NeedInvert = true;
8823       LLVM_FALLTHROUGH;
8824     case ISD::SETO:
8825       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
8826              "If SETO is expanded, SETOEQ must be legal!");
8827       CC1 = ISD::SETOEQ;
8828       CC2 = ISD::SETOEQ;
8829       Opc = ISD::AND;
8830       break;
8831     case ISD::SETONE:
8832     case ISD::SETUEQ:
8833       // If the SETUO or SETO CC isn't legal, we might be able to use
8834       // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
8835       // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
8836       // the operands.
8837       CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
8838       if (!TLI.isCondCodeLegal(CC2, OpVT) &&
8839           (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) ||
8840            TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) {
8841         CC1 = ISD::SETOGT;
8842         CC2 = ISD::SETOLT;
8843         Opc = ISD::OR;
8844         NeedInvert = ((unsigned)CCCode & 0x8U);
8845         break;
8846       }
8847       LLVM_FALLTHROUGH;
8848     case ISD::SETOEQ:
8849     case ISD::SETOGT:
8850     case ISD::SETOGE:
8851     case ISD::SETOLT:
8852     case ISD::SETOLE:
8853     case ISD::SETUNE:
8854     case ISD::SETUGT:
8855     case ISD::SETUGE:
8856     case ISD::SETULT:
8857     case ISD::SETULE:
8858       // If we are floating point, assign and break, otherwise fall through.
8859       if (!OpVT.isInteger()) {
8860         // We can use the 4th bit to tell if we are the unordered
8861         // or ordered version of the opcode.
8862         CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
8863         Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
8864         CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
8865         break;
8866       }
8867       // Fallthrough if we are unsigned integer.
8868       LLVM_FALLTHROUGH;
8869     case ISD::SETLE:
8870     case ISD::SETGT:
8871     case ISD::SETGE:
8872     case ISD::SETLT:
8873     case ISD::SETNE:
8874     case ISD::SETEQ:
8875       // If all combinations of inverting the condition and swapping operands
8876       // didn't work then we have no means to expand the condition.
8877       llvm_unreachable("Don't know how to expand this condition!");
8878     }
8879 
8880     SDValue SetCC1, SetCC2;
8881     if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
8882       // If we aren't the ordered or unorder operation,
8883       // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
8884       SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
8885       SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
8886     } else {
8887       // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
8888       SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
8889       SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
8890     }
8891     if (Chain)
8892       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
8893                           SetCC2.getValue(1));
8894     LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
8895     RHS = SDValue();
8896     CC = SDValue();
8897     return true;
8898   }
8899   }
8900   return false;
8901 }
8902