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