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