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