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