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