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