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