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