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