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