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