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