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