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