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