1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/TargetLowering.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/CodeGen/CallingConvLower.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineJumpTableInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/TargetLoweringObjectFile.h"
24 #include "llvm/CodeGen/TargetRegisterInfo.h"
25 #include "llvm/CodeGen/TargetSubtargetInfo.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/KnownBits.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include <cctype>
37 using namespace llvm;
38 
39 /// NOTE: The TargetMachine owns TLOF.
40 TargetLowering::TargetLowering(const TargetMachine &tm)
41   : TargetLoweringBase(tm) {}
42 
43 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
44   return nullptr;
45 }
46 
47 bool TargetLowering::isPositionIndependent() const {
48   return getTargetMachine().isPositionIndependent();
49 }
50 
51 /// Check whether a given call node is in tail position within its function. If
52 /// so, it sets Chain to the input chain of the tail call.
53 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
54                                           SDValue &Chain) const {
55   const Function &F = DAG.getMachineFunction().getFunction();
56 
57   // Conservatively require the attributes of the call to match those of
58   // the return. Ignore noalias because it doesn't affect the call sequence.
59   AttributeList CallerAttrs = F.getAttributes();
60   if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex)
61           .removeAttribute(Attribute::NoAlias)
62           .hasAttributes())
63     return false;
64 
65   // It's not safe to eliminate the sign / zero extension of the return value.
66   if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) ||
67       CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
68     return false;
69 
70   // Check if the only use is a function return node.
71   return isUsedByReturnOnly(Node, Chain);
72 }
73 
74 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
75     const uint32_t *CallerPreservedMask,
76     const SmallVectorImpl<CCValAssign> &ArgLocs,
77     const SmallVectorImpl<SDValue> &OutVals) const {
78   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
79     const CCValAssign &ArgLoc = ArgLocs[I];
80     if (!ArgLoc.isRegLoc())
81       continue;
82     unsigned Reg = ArgLoc.getLocReg();
83     // Only look at callee saved registers.
84     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
85       continue;
86     // Check that we pass the value used for the caller.
87     // (We look for a CopyFromReg reading a virtual register that is used
88     //  for the function live-in value of register Reg)
89     SDValue Value = OutVals[I];
90     if (Value->getOpcode() != ISD::CopyFromReg)
91       return false;
92     unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
93     if (MRI.getLiveInPhysReg(ArgReg) != Reg)
94       return false;
95   }
96   return true;
97 }
98 
99 /// \brief Set CallLoweringInfo attribute flags based on a call instruction
100 /// and called function attributes.
101 void TargetLoweringBase::ArgListEntry::setAttributes(ImmutableCallSite *CS,
102                                                      unsigned ArgIdx) {
103   IsSExt = CS->paramHasAttr(ArgIdx, Attribute::SExt);
104   IsZExt = CS->paramHasAttr(ArgIdx, Attribute::ZExt);
105   IsInReg = CS->paramHasAttr(ArgIdx, Attribute::InReg);
106   IsSRet = CS->paramHasAttr(ArgIdx, Attribute::StructRet);
107   IsNest = CS->paramHasAttr(ArgIdx, Attribute::Nest);
108   IsByVal = CS->paramHasAttr(ArgIdx, Attribute::ByVal);
109   IsInAlloca = CS->paramHasAttr(ArgIdx, Attribute::InAlloca);
110   IsReturned = CS->paramHasAttr(ArgIdx, Attribute::Returned);
111   IsSwiftSelf = CS->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
112   IsSwiftError = CS->paramHasAttr(ArgIdx, Attribute::SwiftError);
113   Alignment  = CS->getParamAlignment(ArgIdx);
114 }
115 
116 /// Generate a libcall taking the given operands as arguments and returning a
117 /// result of type RetVT.
118 std::pair<SDValue, SDValue>
119 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
120                             ArrayRef<SDValue> Ops, bool isSigned,
121                             const SDLoc &dl, bool doesNotReturn,
122                             bool isReturnValueUsed) const {
123   TargetLowering::ArgListTy Args;
124   Args.reserve(Ops.size());
125 
126   TargetLowering::ArgListEntry Entry;
127   for (SDValue Op : Ops) {
128     Entry.Node = Op;
129     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
130     Entry.IsSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
131     Entry.IsZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
132     Args.push_back(Entry);
133   }
134 
135   if (LC == RTLIB::UNKNOWN_LIBCALL)
136     report_fatal_error("Unsupported library call operation!");
137   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
138                                          getPointerTy(DAG.getDataLayout()));
139 
140   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
141   TargetLowering::CallLoweringInfo CLI(DAG);
142   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
143   CLI.setDebugLoc(dl)
144       .setChain(DAG.getEntryNode())
145       .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
146       .setNoReturn(doesNotReturn)
147       .setDiscardResult(!isReturnValueUsed)
148       .setSExtResult(signExtend)
149       .setZExtResult(!signExtend);
150   return LowerCallTo(CLI);
151 }
152 
153 /// Soften the operands of a comparison. This code is shared among BR_CC,
154 /// SELECT_CC, and SETCC handlers.
155 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
156                                          SDValue &NewLHS, SDValue &NewRHS,
157                                          ISD::CondCode &CCCode,
158                                          const SDLoc &dl) const {
159   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
160          && "Unsupported setcc type!");
161 
162   // Expand into one or more soft-fp libcall(s).
163   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
164   bool ShouldInvertCC = false;
165   switch (CCCode) {
166   case ISD::SETEQ:
167   case ISD::SETOEQ:
168     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
169           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
170           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
171     break;
172   case ISD::SETNE:
173   case ISD::SETUNE:
174     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
175           (VT == MVT::f64) ? RTLIB::UNE_F64 :
176           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
177     break;
178   case ISD::SETGE:
179   case ISD::SETOGE:
180     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
181           (VT == MVT::f64) ? RTLIB::OGE_F64 :
182           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
183     break;
184   case ISD::SETLT:
185   case ISD::SETOLT:
186     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
187           (VT == MVT::f64) ? RTLIB::OLT_F64 :
188           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
189     break;
190   case ISD::SETLE:
191   case ISD::SETOLE:
192     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
193           (VT == MVT::f64) ? RTLIB::OLE_F64 :
194           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
195     break;
196   case ISD::SETGT:
197   case ISD::SETOGT:
198     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
199           (VT == MVT::f64) ? RTLIB::OGT_F64 :
200           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
201     break;
202   case ISD::SETUO:
203     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
204           (VT == MVT::f64) ? RTLIB::UO_F64 :
205           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
206     break;
207   case ISD::SETO:
208     LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
209           (VT == MVT::f64) ? RTLIB::O_F64 :
210           (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
211     break;
212   case ISD::SETONE:
213     // SETONE = SETOLT | SETOGT
214     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
215           (VT == MVT::f64) ? RTLIB::OLT_F64 :
216           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
217     LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
218           (VT == MVT::f64) ? RTLIB::OGT_F64 :
219           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
220     break;
221   case ISD::SETUEQ:
222     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
223           (VT == MVT::f64) ? RTLIB::UO_F64 :
224           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
225     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
226           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
227           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
228     break;
229   default:
230     // Invert CC for unordered comparisons
231     ShouldInvertCC = true;
232     switch (CCCode) {
233     case ISD::SETULT:
234       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
235             (VT == MVT::f64) ? RTLIB::OGE_F64 :
236             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
237       break;
238     case ISD::SETULE:
239       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
240             (VT == MVT::f64) ? RTLIB::OGT_F64 :
241             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
242       break;
243     case ISD::SETUGT:
244       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
245             (VT == MVT::f64) ? RTLIB::OLE_F64 :
246             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
247       break;
248     case ISD::SETUGE:
249       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
250             (VT == MVT::f64) ? RTLIB::OLT_F64 :
251             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
252       break;
253     default: llvm_unreachable("Do not know how to soften this setcc!");
254     }
255   }
256 
257   // Use the target specific return value for comparions lib calls.
258   EVT RetVT = getCmpLibcallReturnType();
259   SDValue Ops[2] = {NewLHS, NewRHS};
260   NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
261                        dl).first;
262   NewRHS = DAG.getConstant(0, dl, RetVT);
263 
264   CCCode = getCmpLibcallCC(LC1);
265   if (ShouldInvertCC)
266     CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
267 
268   if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
269     SDValue Tmp = DAG.getNode(
270         ISD::SETCC, dl,
271         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
272         NewLHS, NewRHS, DAG.getCondCode(CCCode));
273     NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
274                          dl).first;
275     NewLHS = DAG.getNode(
276         ISD::SETCC, dl,
277         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
278         NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
279     NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
280     NewRHS = SDValue();
281   }
282 }
283 
284 /// Return the entry encoding for a jump table in the current function. The
285 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
286 unsigned TargetLowering::getJumpTableEncoding() const {
287   // In non-pic modes, just use the address of a block.
288   if (!isPositionIndependent())
289     return MachineJumpTableInfo::EK_BlockAddress;
290 
291   // In PIC mode, if the target supports a GPRel32 directive, use it.
292   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
293     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
294 
295   // Otherwise, use a label difference.
296   return MachineJumpTableInfo::EK_LabelDifference32;
297 }
298 
299 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
300                                                  SelectionDAG &DAG) const {
301   // If our PIC model is GP relative, use the global offset table as the base.
302   unsigned JTEncoding = getJumpTableEncoding();
303 
304   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
305       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
306     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
307 
308   return Table;
309 }
310 
311 /// This returns the relocation base for the given PIC jumptable, the same as
312 /// getPICJumpTableRelocBase, but as an MCExpr.
313 const MCExpr *
314 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
315                                              unsigned JTI,MCContext &Ctx) const{
316   // The normal PIC reloc base is the label at the start of the jump table.
317   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
318 }
319 
320 bool
321 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
322   const TargetMachine &TM = getTargetMachine();
323   const GlobalValue *GV = GA->getGlobal();
324 
325   // If the address is not even local to this DSO we will have to load it from
326   // a got and then add the offset.
327   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
328     return false;
329 
330   // If the code is position independent we will have to add a base register.
331   if (isPositionIndependent())
332     return false;
333 
334   // Otherwise we can do it.
335   return true;
336 }
337 
338 //===----------------------------------------------------------------------===//
339 //  Optimization Methods
340 //===----------------------------------------------------------------------===//
341 
342 /// If the specified instruction has a constant integer operand and there are
343 /// bits set in that constant that are not demanded, then clear those bits and
344 /// return true.
345 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
346                                             TargetLoweringOpt &TLO) const {
347   SelectionDAG &DAG = TLO.DAG;
348   SDLoc DL(Op);
349   unsigned Opcode = Op.getOpcode();
350 
351   // Do target-specific constant optimization.
352   if (targetShrinkDemandedConstant(Op, Demanded, TLO))
353     return TLO.New.getNode();
354 
355   // FIXME: ISD::SELECT, ISD::SELECT_CC
356   switch (Opcode) {
357   default:
358     break;
359   case ISD::XOR:
360   case ISD::AND:
361   case ISD::OR: {
362     auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
363     if (!Op1C)
364       return false;
365 
366     // If this is a 'not' op, don't touch it because that's a canonical form.
367     const APInt &C = Op1C->getAPIntValue();
368     if (Opcode == ISD::XOR && Demanded.isSubsetOf(C))
369       return false;
370 
371     if (!C.isSubsetOf(Demanded)) {
372       EVT VT = Op.getValueType();
373       SDValue NewC = DAG.getConstant(Demanded & C, DL, VT);
374       SDValue NewOp = DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
375       return TLO.CombineTo(Op, NewOp);
376     }
377 
378     break;
379   }
380   }
381 
382   return false;
383 }
384 
385 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
386 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
387 /// generalized for targets with other types of implicit widening casts.
388 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
389                                       const APInt &Demanded,
390                                       TargetLoweringOpt &TLO) const {
391   assert(Op.getNumOperands() == 2 &&
392          "ShrinkDemandedOp only supports binary operators!");
393   assert(Op.getNode()->getNumValues() == 1 &&
394          "ShrinkDemandedOp only supports nodes with one result!");
395 
396   SelectionDAG &DAG = TLO.DAG;
397   SDLoc dl(Op);
398 
399   // Early return, as this function cannot handle vector types.
400   if (Op.getValueType().isVector())
401     return false;
402 
403   // Don't do this if the node has another user, which may require the
404   // full value.
405   if (!Op.getNode()->hasOneUse())
406     return false;
407 
408   // Search for the smallest integer type with free casts to and from
409   // Op's type. For expedience, just check power-of-2 integer types.
410   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
411   unsigned DemandedSize = Demanded.getActiveBits();
412   unsigned SmallVTBits = DemandedSize;
413   if (!isPowerOf2_32(SmallVTBits))
414     SmallVTBits = NextPowerOf2(SmallVTBits);
415   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
416     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
417     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
418         TLI.isZExtFree(SmallVT, Op.getValueType())) {
419       // We found a type with free casts.
420       SDValue X = DAG.getNode(
421           Op.getOpcode(), dl, SmallVT,
422           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
423           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)));
424       assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
425       SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X);
426       return TLO.CombineTo(Op, Z);
427     }
428   }
429   return false;
430 }
431 
432 bool
433 TargetLowering::SimplifyDemandedBits(SDNode *User, unsigned OpIdx,
434                                      const APInt &Demanded,
435                                      DAGCombinerInfo &DCI,
436                                      TargetLoweringOpt &TLO) const {
437   SDValue Op = User->getOperand(OpIdx);
438   KnownBits Known;
439 
440   if (!SimplifyDemandedBits(Op, Demanded, Known, TLO, 0, true))
441     return false;
442 
443 
444   // Old will not always be the same as Op.  For example:
445   //
446   // Demanded = 0xffffff
447   // Op = i64 truncate (i32 and x, 0xffffff)
448   // In this case simplify demand bits will want to replace the 'and' node
449   // with the value 'x', which will give us:
450   // Old = i32 and x, 0xffffff
451   // New = x
452   if (TLO.Old.hasOneUse()) {
453     // For the one use case, we just commit the change.
454     DCI.CommitTargetLoweringOpt(TLO);
455     return true;
456   }
457 
458   // If Old has more than one use then it must be Op, because the
459   // AssumeSingleUse flag is not propogated to recursive calls of
460   // SimplifyDemanded bits, so the only node with multiple use that
461   // it will attempt to combine will be Op.
462   assert(TLO.Old == Op);
463 
464   SmallVector <SDValue, 4> NewOps;
465   for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
466     if (i == OpIdx) {
467       NewOps.push_back(TLO.New);
468       continue;
469     }
470     NewOps.push_back(User->getOperand(i));
471   }
472   User = TLO.DAG.UpdateNodeOperands(User, NewOps);
473   // Op has less users now, so we may be able to perform additional combines
474   // with it.
475   DCI.AddToWorklist(Op.getNode());
476   // User's operands have been updated, so we may be able to do new combines
477   // with it.
478   DCI.AddToWorklist(User);
479   return true;
480 }
481 
482 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask,
483                                           DAGCombinerInfo &DCI) const {
484 
485   SelectionDAG &DAG = DCI.DAG;
486   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
487                         !DCI.isBeforeLegalizeOps());
488   KnownBits Known;
489 
490   bool Simplified = SimplifyDemandedBits(Op, DemandedMask, Known, TLO);
491   if (Simplified)
492     DCI.CommitTargetLoweringOpt(TLO);
493   return Simplified;
494 }
495 
496 /// Look at Op. At this point, we know that only the DemandedMask bits of the
497 /// result of Op are ever used downstream. If we can use this information to
498 /// simplify Op, create a new simplified DAG node and return true, returning the
499 /// original and new nodes in Old and New. Otherwise, analyze the expression and
500 /// return a mask of Known bits for the expression (used to simplify the
501 /// caller).  The Known bits may only be accurate for those bits in the
502 /// DemandedMask.
503 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
504                                           const APInt &DemandedMask,
505                                           KnownBits &Known,
506                                           TargetLoweringOpt &TLO,
507                                           unsigned Depth,
508                                           bool AssumeSingleUse) const {
509   unsigned BitWidth = DemandedMask.getBitWidth();
510   assert(Op.getScalarValueSizeInBits() == BitWidth &&
511          "Mask size mismatches value type size!");
512   APInt NewMask = DemandedMask;
513   SDLoc dl(Op);
514   auto &DL = TLO.DAG.getDataLayout();
515 
516   // Don't know anything.
517   Known = KnownBits(BitWidth);
518 
519   if (Op.getOpcode() == ISD::Constant) {
520     // We know all of the bits for a constant!
521     Known.One = cast<ConstantSDNode>(Op)->getAPIntValue();
522     Known.Zero = ~Known.One;
523     return false;
524   }
525 
526   // Other users may use these bits.
527   EVT VT = Op.getValueType();
528   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
529     if (Depth != 0) {
530       // If not at the root, Just compute the Known bits to
531       // simplify things downstream.
532       TLO.DAG.computeKnownBits(Op, Known, Depth);
533       return false;
534     }
535     // If this is the root being simplified, allow it to have multiple uses,
536     // just set the NewMask to all bits.
537     NewMask = APInt::getAllOnesValue(BitWidth);
538   } else if (DemandedMask == 0) {
539     // Not demanding any bits from Op.
540     if (!Op.isUndef())
541       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
542     return false;
543   } else if (Depth == 6) {        // Limit search depth.
544     return false;
545   }
546 
547   KnownBits Known2, KnownOut;
548   switch (Op.getOpcode()) {
549   case ISD::BUILD_VECTOR:
550     // Collect the known bits that are shared by every constant vector element.
551     Known.Zero.setAllBits(); Known.One.setAllBits();
552     for (SDValue SrcOp : Op->ops()) {
553       if (!isa<ConstantSDNode>(SrcOp)) {
554         // We can only handle all constant values - bail out with no known bits.
555         Known = KnownBits(BitWidth);
556         return false;
557       }
558       Known2.One = cast<ConstantSDNode>(SrcOp)->getAPIntValue();
559       Known2.Zero = ~Known2.One;
560 
561       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
562       if (Known2.One.getBitWidth() != BitWidth) {
563         assert(Known2.getBitWidth() > BitWidth &&
564                "Expected BUILD_VECTOR implicit truncation");
565         Known2 = Known2.trunc(BitWidth);
566       }
567 
568       // Known bits are the values that are shared by every element.
569       // TODO: support per-element known bits.
570       Known.One &= Known2.One;
571       Known.Zero &= Known2.Zero;
572     }
573     return false;   // Don't fall through, will infinitely loop.
574   case ISD::AND:
575     // If the RHS is a constant, check to see if the LHS would be zero without
576     // using the bits from the RHS.  Below, we use knowledge about the RHS to
577     // simplify the LHS, here we're using information from the LHS to simplify
578     // the RHS.
579     if (ConstantSDNode *RHSC = isConstOrConstSplat(Op.getOperand(1))) {
580       SDValue Op0 = Op.getOperand(0);
581       KnownBits LHSKnown;
582       // Do not increment Depth here; that can cause an infinite loop.
583       TLO.DAG.computeKnownBits(Op0, LHSKnown, Depth);
584       // If the LHS already has zeros where RHSC does, this 'and' is dead.
585       if ((LHSKnown.Zero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
586         return TLO.CombineTo(Op, Op0);
587 
588       // If any of the set bits in the RHS are known zero on the LHS, shrink
589       // the constant.
590       if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & NewMask, TLO))
591         return true;
592 
593       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
594       // constant, but if this 'and' is only clearing bits that were just set by
595       // the xor, then this 'and' can be eliminated by shrinking the mask of
596       // the xor. For example, for a 32-bit X:
597       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
598       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
599           LHSKnown.One == ~RHSC->getAPIntValue()) {
600         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0),
601                                       Op.getOperand(1));
602         return TLO.CombineTo(Op, Xor);
603       }
604     }
605 
606     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, Known, TLO, Depth+1))
607       return true;
608     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
609     if (SimplifyDemandedBits(Op.getOperand(0), ~Known.Zero & NewMask,
610                              Known2, TLO, Depth+1))
611       return true;
612     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
613 
614     // If all of the demanded bits are known one on one side, return the other.
615     // These bits cannot contribute to the result of the 'and'.
616     if (NewMask.isSubsetOf(Known2.Zero | Known.One))
617       return TLO.CombineTo(Op, Op.getOperand(0));
618     if (NewMask.isSubsetOf(Known.Zero | Known2.One))
619       return TLO.CombineTo(Op, Op.getOperand(1));
620     // If all of the demanded bits in the inputs are known zeros, return zero.
621     if (NewMask.isSubsetOf(Known.Zero | Known2.Zero))
622       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
623     // If the RHS is a constant, see if we can simplify it.
624     if (ShrinkDemandedConstant(Op, ~Known2.Zero & NewMask, TLO))
625       return true;
626     // If the operation can be done in a smaller type, do so.
627     if (ShrinkDemandedOp(Op, BitWidth, NewMask, TLO))
628       return true;
629 
630     // Output known-1 bits are only known if set in both the LHS & RHS.
631     Known.One &= Known2.One;
632     // Output known-0 are known to be clear if zero in either the LHS | RHS.
633     Known.Zero |= Known2.Zero;
634     break;
635   case ISD::OR:
636     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, Known, TLO, Depth+1))
637       return true;
638     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
639     if (SimplifyDemandedBits(Op.getOperand(0), ~Known.One & NewMask,
640                              Known2, TLO, Depth+1))
641       return true;
642     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
643 
644     // If all of the demanded bits are known zero on one side, return the other.
645     // These bits cannot contribute to the result of the 'or'.
646     if (NewMask.isSubsetOf(Known2.One | Known.Zero))
647       return TLO.CombineTo(Op, Op.getOperand(0));
648     if (NewMask.isSubsetOf(Known.One | Known2.Zero))
649       return TLO.CombineTo(Op, Op.getOperand(1));
650     // If the RHS is a constant, see if we can simplify it.
651     if (ShrinkDemandedConstant(Op, NewMask, TLO))
652       return true;
653     // If the operation can be done in a smaller type, do so.
654     if (ShrinkDemandedOp(Op, BitWidth, NewMask, TLO))
655       return true;
656 
657     // Output known-0 bits are only known if clear in both the LHS & RHS.
658     Known.Zero &= Known2.Zero;
659     // Output known-1 are known to be set if set in either the LHS | RHS.
660     Known.One |= Known2.One;
661     break;
662   case ISD::XOR: {
663     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, Known, TLO, Depth+1))
664       return true;
665     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
666     if (SimplifyDemandedBits(Op.getOperand(0), NewMask, Known2, TLO, Depth+1))
667       return true;
668     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
669 
670     // If all of the demanded bits are known zero on one side, return the other.
671     // These bits cannot contribute to the result of the 'xor'.
672     if (NewMask.isSubsetOf(Known.Zero))
673       return TLO.CombineTo(Op, Op.getOperand(0));
674     if (NewMask.isSubsetOf(Known2.Zero))
675       return TLO.CombineTo(Op, Op.getOperand(1));
676     // If the operation can be done in a smaller type, do so.
677     if (ShrinkDemandedOp(Op, BitWidth, NewMask, TLO))
678       return true;
679 
680     // If all of the unknown bits are known to be zero on one side or the other
681     // (but not both) turn this into an *inclusive* or.
682     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
683     if ((NewMask & ~Known.Zero & ~Known2.Zero) == 0)
684       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT,
685                                                Op.getOperand(0),
686                                                Op.getOperand(1)));
687 
688     // Output known-0 bits are known if clear or set in both the LHS & RHS.
689     KnownOut.Zero = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
690     // Output known-1 are known to be set if set in only one of the LHS, RHS.
691     KnownOut.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
692 
693     // If all of the demanded bits on one side are known, and all of the set
694     // bits on that side are also known to be set on the other side, turn this
695     // into an AND, as we know the bits will be cleared.
696     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
697     // NB: it is okay if more bits are known than are requested
698     if (NewMask.isSubsetOf(Known.Zero|Known.One)) { // all known on one side
699       if (Known.One == Known2.One) { // set bits are the same on both sides
700         SDValue ANDC = TLO.DAG.getConstant(~Known.One & NewMask, dl, VT);
701         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
702                                                  Op.getOperand(0), ANDC));
703       }
704     }
705 
706     // If the RHS is a constant, see if we can change it. Don't alter a -1
707     // constant because that's a 'not' op, and that is better for combining and
708     // codegen.
709     ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1));
710     if (C && !C->isAllOnesValue()) {
711       if (NewMask.isSubsetOf(C->getAPIntValue())) {
712         // We're flipping all demanded bits. Flip the undemanded bits too.
713         SDValue New = TLO.DAG.getNOT(dl, Op.getOperand(0), VT);
714         return TLO.CombineTo(Op, New);
715       }
716       // If we can't turn this into a 'not', try to shrink the constant.
717       if (ShrinkDemandedConstant(Op, NewMask, TLO))
718         return true;
719     }
720 
721     Known = std::move(KnownOut);
722     break;
723   }
724   case ISD::SELECT:
725     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, Known, TLO, Depth+1))
726       return true;
727     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, Known2, TLO, Depth+1))
728       return true;
729     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
730     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
731 
732     // If the operands are constants, see if we can simplify them.
733     if (ShrinkDemandedConstant(Op, NewMask, TLO))
734       return true;
735 
736     // Only known if known in both the LHS and RHS.
737     Known.One &= Known2.One;
738     Known.Zero &= Known2.Zero;
739     break;
740   case ISD::SELECT_CC:
741     if (SimplifyDemandedBits(Op.getOperand(3), NewMask, Known, TLO, Depth+1))
742       return true;
743     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, Known2, TLO, Depth+1))
744       return true;
745     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
746     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
747 
748     // If the operands are constants, see if we can simplify them.
749     if (ShrinkDemandedConstant(Op, NewMask, TLO))
750       return true;
751 
752     // Only known if known in both the LHS and RHS.
753     Known.One &= Known2.One;
754     Known.Zero &= Known2.Zero;
755     break;
756   case ISD::SETCC: {
757     SDValue Op0 = Op.getOperand(0);
758     SDValue Op1 = Op.getOperand(1);
759     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
760     // If (1) we only need the sign-bit, (2) the setcc operands are the same
761     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
762     // -1, we may be able to bypass the setcc.
763     if (NewMask.isSignMask() && Op0.getScalarValueSizeInBits() == BitWidth &&
764         getBooleanContents(VT) ==
765             BooleanContent::ZeroOrNegativeOneBooleanContent) {
766       // If we're testing X < 0, then this compare isn't needed - just use X!
767       // FIXME: We're limiting to integer types here, but this should also work
768       // if we don't care about FP signed-zero. The use of SETLT with FP means
769       // that we don't care about NaNs.
770       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
771           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
772         return TLO.CombineTo(Op, Op0);
773 
774       // TODO: Should we check for other forms of sign-bit comparisons?
775       // Examples: X <= -1, X >= 0
776     }
777     if (getBooleanContents(Op0.getValueType()) ==
778             TargetLowering::ZeroOrOneBooleanContent &&
779         BitWidth > 1)
780       Known.Zero.setBitsFrom(1);
781     break;
782   }
783   case ISD::SHL:
784     if (ConstantSDNode *SA = isConstOrConstSplat(Op.getOperand(1))) {
785       SDValue InOp = Op.getOperand(0);
786 
787       // If the shift count is an invalid immediate, don't do anything.
788       if (SA->getAPIntValue().uge(BitWidth))
789         break;
790 
791       unsigned ShAmt = SA->getZExtValue();
792 
793       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
794       // single shift.  We can do this if the bottom bits (which are shifted
795       // out) are never demanded.
796       if (InOp.getOpcode() == ISD::SRL) {
797         if (ConstantSDNode *SA2 = isConstOrConstSplat(InOp.getOperand(1))) {
798           if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
799             if (SA2->getAPIntValue().ult(BitWidth)) {
800               unsigned C1 = SA2->getZExtValue();
801               unsigned Opc = ISD::SHL;
802               int Diff = ShAmt-C1;
803               if (Diff < 0) {
804                 Diff = -Diff;
805                 Opc = ISD::SRL;
806               }
807 
808               SDValue NewSA =
809                 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
810               return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
811                                                        InOp.getOperand(0),
812                                                        NewSA));
813             }
814           }
815         }
816       }
817 
818       if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt), Known, TLO, Depth+1))
819         return true;
820 
821       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
822       // are not demanded. This will likely allow the anyext to be folded away.
823       if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
824         SDValue InnerOp = InOp.getOperand(0);
825         EVT InnerVT = InnerOp.getValueType();
826         unsigned InnerBits = InnerVT.getScalarSizeInBits();
827         if (ShAmt < InnerBits && NewMask.getActiveBits() <= InnerBits &&
828             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
829           EVT ShTy = getShiftAmountTy(InnerVT, DL);
830           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
831             ShTy = InnerVT;
832           SDValue NarrowShl =
833             TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
834                             TLO.DAG.getConstant(ShAmt, dl, ShTy));
835           return
836             TLO.CombineTo(Op,
837                           TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
838         }
839         // Repeat the SHL optimization above in cases where an extension
840         // intervenes: (shl (anyext (shr x, c1)), c2) to
841         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
842         // aren't demanded (as above) and that the shifted upper c1 bits of
843         // x aren't demanded.
844         if (InOp.hasOneUse() && InnerOp.getOpcode() == ISD::SRL &&
845             InnerOp.hasOneUse()) {
846           if (ConstantSDNode *SA2 = isConstOrConstSplat(InnerOp.getOperand(1))) {
847             unsigned InnerShAmt = SA2->getLimitedValue(InnerBits);
848             if (InnerShAmt < ShAmt &&
849                 InnerShAmt < InnerBits &&
850                 NewMask.getActiveBits() <= (InnerBits - InnerShAmt + ShAmt) &&
851                 NewMask.countTrailingZeros() >= ShAmt) {
852               SDValue NewSA =
853                 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
854                                     Op.getOperand(1).getValueType());
855               SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
856                                                InnerOp.getOperand(0));
857               return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
858                                                        NewExt, NewSA));
859             }
860           }
861         }
862       }
863 
864       Known.Zero <<= ShAmt;
865       Known.One  <<= ShAmt;
866       // low bits known zero.
867       Known.Zero.setLowBits(ShAmt);
868     }
869     break;
870   case ISD::SRL:
871     if (ConstantSDNode *SA = isConstOrConstSplat(Op.getOperand(1))) {
872       SDValue InOp = Op.getOperand(0);
873 
874       // If the shift count is an invalid immediate, don't do anything.
875       if (SA->getAPIntValue().uge(BitWidth))
876         break;
877 
878       unsigned ShAmt = SA->getZExtValue();
879       APInt InDemandedMask = (NewMask << ShAmt);
880 
881       // If the shift is exact, then it does demand the low bits (and knows that
882       // they are zero).
883       if (Op->getFlags().hasExact())
884         InDemandedMask.setLowBits(ShAmt);
885 
886       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
887       // single shift.  We can do this if the top bits (which are shifted out)
888       // are never demanded.
889       if (InOp.getOpcode() == ISD::SHL) {
890         if (ConstantSDNode *SA2 = isConstOrConstSplat(InOp.getOperand(1))) {
891           if (ShAmt &&
892               (NewMask & APInt::getHighBitsSet(BitWidth, ShAmt)) == 0) {
893             if (SA2->getAPIntValue().ult(BitWidth)) {
894               unsigned C1 = SA2->getZExtValue();
895               unsigned Opc = ISD::SRL;
896               int Diff = ShAmt-C1;
897               if (Diff < 0) {
898                 Diff = -Diff;
899                 Opc = ISD::SHL;
900               }
901 
902               SDValue NewSA =
903                 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
904               return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
905                                                        InOp.getOperand(0),
906                                                        NewSA));
907             }
908           }
909         }
910       }
911 
912       // Compute the new bits that are at the top now.
913       if (SimplifyDemandedBits(InOp, InDemandedMask, Known, TLO, Depth+1))
914         return true;
915       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
916       Known.Zero.lshrInPlace(ShAmt);
917       Known.One.lshrInPlace(ShAmt);
918 
919       Known.Zero.setHighBits(ShAmt);  // High bits known zero.
920     }
921     break;
922   case ISD::SRA:
923     // If this is an arithmetic shift right and only the low-bit is set, we can
924     // always convert this into a logical shr, even if the shift amount is
925     // variable.  The low bit of the shift cannot be an input sign bit unless
926     // the shift amount is >= the size of the datatype, which is undefined.
927     if (NewMask.isOneValue())
928       return TLO.CombineTo(Op,
929                            TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
930                                            Op.getOperand(1)));
931 
932     if (ConstantSDNode *SA = isConstOrConstSplat(Op.getOperand(1))) {
933       // If the shift count is an invalid immediate, don't do anything.
934       if (SA->getAPIntValue().uge(BitWidth))
935         break;
936 
937       unsigned ShAmt = SA->getZExtValue();
938       APInt InDemandedMask = (NewMask << ShAmt);
939 
940       // If the shift is exact, then it does demand the low bits (and knows that
941       // they are zero).
942       if (Op->getFlags().hasExact())
943         InDemandedMask.setLowBits(ShAmt);
944 
945       // If any of the demanded bits are produced by the sign extension, we also
946       // demand the input sign bit.
947       if (NewMask.countLeadingZeros() < ShAmt)
948         InDemandedMask.setSignBit();
949 
950       if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask, Known, TLO,
951                                Depth+1))
952         return true;
953       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
954       Known.Zero.lshrInPlace(ShAmt);
955       Known.One.lshrInPlace(ShAmt);
956 
957       // If the input sign bit is known to be zero, or if none of the top bits
958       // are demanded, turn this into an unsigned shift right.
959       if (Known.Zero[BitWidth - ShAmt - 1] ||
960           NewMask.countLeadingZeros() >= ShAmt) {
961         SDNodeFlags Flags;
962         Flags.setExact(Op->getFlags().hasExact());
963         return TLO.CombineTo(Op,
964                              TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
965                                              Op.getOperand(1), Flags));
966       }
967 
968       int Log2 = NewMask.exactLogBase2();
969       if (Log2 >= 0) {
970         // The bit must come from the sign.
971         SDValue NewSA =
972           TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
973                               Op.getOperand(1).getValueType());
974         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
975                                                  Op.getOperand(0), NewSA));
976       }
977 
978       if (Known.One[BitWidth - ShAmt - 1])
979         // New bits are known one.
980         Known.One.setHighBits(ShAmt);
981     }
982     break;
983   case ISD::SIGN_EXTEND_INREG: {
984     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
985     unsigned ExVTBits = ExVT.getScalarSizeInBits();
986 
987     // If we only care about the highest bit, don't bother shifting right.
988     if (NewMask.isSignMask()) {
989       SDValue InOp = Op.getOperand(0);
990       bool AlreadySignExtended =
991         TLO.DAG.ComputeNumSignBits(InOp) >= BitWidth-ExVTBits+1;
992       // However if the input is already sign extended we expect the sign
993       // extension to be dropped altogether later and do not simplify.
994       if (!AlreadySignExtended) {
995         // Compute the correct shift amount type, which must be getShiftAmountTy
996         // for scalar types after legalization.
997         EVT ShiftAmtTy = VT;
998         if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
999           ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
1000 
1001         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl,
1002                                                ShiftAmtTy);
1003         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, InOp,
1004                                                  ShiftAmt));
1005       }
1006     }
1007 
1008     // If none of the extended bits are demanded, eliminate the sextinreg.
1009     if (NewMask.getActiveBits() <= ExVTBits)
1010       return TLO.CombineTo(Op, Op.getOperand(0));
1011 
1012     APInt InputDemandedBits = NewMask.getLoBits(ExVTBits);
1013 
1014     // Since the sign extended bits are demanded, we know that the sign
1015     // bit is demanded.
1016     InputDemandedBits.setBit(ExVTBits - 1);
1017 
1018     if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
1019                              Known, TLO, Depth+1))
1020       return true;
1021     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1022 
1023     // If the sign bit of the input is known set or clear, then we know the
1024     // top bits of the result.
1025 
1026     // If the input sign bit is known zero, convert this into a zero extension.
1027     if (Known.Zero[ExVTBits - 1])
1028       return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(
1029                                    Op.getOperand(0), dl, ExVT.getScalarType()));
1030 
1031     APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
1032     if (Known.One[ExVTBits - 1]) {    // Input sign bit known set
1033       Known.One.setBitsFrom(ExVTBits);
1034       Known.Zero &= Mask;
1035     } else {                       // Input sign bit unknown
1036       Known.Zero &= Mask;
1037       Known.One &= Mask;
1038     }
1039     break;
1040   }
1041   case ISD::BUILD_PAIR: {
1042     EVT HalfVT = Op.getOperand(0).getValueType();
1043     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
1044 
1045     APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
1046     APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
1047 
1048     KnownBits KnownLo, KnownHi;
1049 
1050     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
1051       return true;
1052 
1053     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
1054       return true;
1055 
1056     Known.Zero = KnownLo.Zero.zext(BitWidth) |
1057                 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth);
1058 
1059     Known.One = KnownLo.One.zext(BitWidth) |
1060                KnownHi.One.zext(BitWidth).shl(HalfBitWidth);
1061     break;
1062   }
1063   case ISD::ZERO_EXTEND: {
1064     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1065 
1066     // If none of the top bits are demanded, convert this into an any_extend.
1067     if (NewMask.getActiveBits() <= OperandBitWidth)
1068       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1069                                                Op.getOperand(0)));
1070 
1071     APInt InMask = NewMask.trunc(OperandBitWidth);
1072     if (SimplifyDemandedBits(Op.getOperand(0), InMask, Known, TLO, Depth+1))
1073       return true;
1074     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1075     Known = Known.zext(BitWidth);
1076     Known.Zero.setBitsFrom(OperandBitWidth);
1077     break;
1078   }
1079   case ISD::SIGN_EXTEND: {
1080     unsigned InBits = Op.getOperand(0).getValueType().getScalarSizeInBits();
1081 
1082     // If none of the top bits are demanded, convert this into an any_extend.
1083     if (NewMask.getActiveBits() <= InBits)
1084       return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1085                                               Op.getOperand(0)));
1086 
1087     // Since some of the sign extended bits are demanded, we know that the sign
1088     // bit is demanded.
1089     APInt InDemandedBits = NewMask.trunc(InBits);
1090     InDemandedBits.setBit(InBits - 1);
1091 
1092     if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, Known, TLO,
1093                              Depth+1))
1094       return true;
1095     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1096     // If the sign bit is known one, the top bits match.
1097     Known = Known.sext(BitWidth);
1098 
1099     // If the sign bit is known zero, convert this to a zero extend.
1100     if (Known.isNonNegative())
1101       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT,
1102                                                Op.getOperand(0)));
1103     break;
1104   }
1105   case ISD::ANY_EXTEND: {
1106     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1107     APInt InMask = NewMask.trunc(OperandBitWidth);
1108     if (SimplifyDemandedBits(Op.getOperand(0), InMask, Known, TLO, Depth+1))
1109       return true;
1110     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1111     Known = Known.zext(BitWidth);
1112     break;
1113   }
1114   case ISD::TRUNCATE: {
1115     // Simplify the input, using demanded bit information, and compute the known
1116     // zero/one bits live out.
1117     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1118     APInt TruncMask = NewMask.zext(OperandBitWidth);
1119     if (SimplifyDemandedBits(Op.getOperand(0), TruncMask, Known, TLO, Depth+1))
1120       return true;
1121     Known = Known.trunc(BitWidth);
1122 
1123     // If the input is only used by this truncate, see if we can shrink it based
1124     // on the known demanded bits.
1125     if (Op.getOperand(0).getNode()->hasOneUse()) {
1126       SDValue In = Op.getOperand(0);
1127       switch (In.getOpcode()) {
1128       default: break;
1129       case ISD::SRL:
1130         // Shrink SRL by a constant if none of the high bits shifted in are
1131         // demanded.
1132         if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
1133           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1134           // undesirable.
1135           break;
1136         ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1137         if (!ShAmt)
1138           break;
1139         SDValue Shift = In.getOperand(1);
1140         if (TLO.LegalTypes()) {
1141           uint64_t ShVal = ShAmt->getZExtValue();
1142           Shift = TLO.DAG.getConstant(ShVal, dl, getShiftAmountTy(VT, DL));
1143         }
1144 
1145         if (ShAmt->getZExtValue() < BitWidth) {
1146           APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1147                                                  OperandBitWidth - BitWidth);
1148           HighBits.lshrInPlace(ShAmt->getZExtValue());
1149           HighBits = HighBits.trunc(BitWidth);
1150 
1151           if (!(HighBits & NewMask)) {
1152             // None of the shifted in bits are needed.  Add a truncate of the
1153             // shift input, then shift it.
1154             SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl, VT,
1155                                                In.getOperand(0));
1156             return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc,
1157                                                      Shift));
1158           }
1159         }
1160         break;
1161       }
1162     }
1163 
1164     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1165     break;
1166   }
1167   case ISD::AssertZext: {
1168     // AssertZext demands all of the high bits, plus any of the low bits
1169     // demanded by its users.
1170     EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1171     APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits());
1172     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
1173                              Known, TLO, Depth+1))
1174       return true;
1175     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1176 
1177     Known.Zero |= ~InMask;
1178     break;
1179   }
1180   case ISD::BITCAST:
1181     // If this is an FP->Int bitcast and if the sign bit is the only
1182     // thing demanded, turn this into a FGETSIGN.
1183     if (!TLO.LegalOperations() && !VT.isVector() &&
1184         !Op.getOperand(0).getValueType().isVector() &&
1185         NewMask == APInt::getSignMask(Op.getValueSizeInBits()) &&
1186         Op.getOperand(0).getValueType().isFloatingPoint()) {
1187       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT);
1188       bool i32Legal  = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1189       if ((OpVTLegal || i32Legal) && VT.isSimple() &&
1190            Op.getOperand(0).getValueType() != MVT::f128) {
1191         // Cannot eliminate/lower SHL for f128 yet.
1192         EVT Ty = OpVTLegal ? VT : MVT::i32;
1193         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1194         // place.  We expect the SHL to be eliminated by other optimizations.
1195         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
1196         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
1197         if (!OpVTLegal && OpVTSizeInBits > 32)
1198           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign);
1199         unsigned ShVal = Op.getValueSizeInBits() - 1;
1200         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT);
1201         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
1202       }
1203     }
1204     // If this is a bitcast, let computeKnownBits handle it.  Only do this on a
1205     // recursive call where Known may be useful to the caller.
1206     if (Depth > 0) {
1207       TLO.DAG.computeKnownBits(Op, Known, Depth);
1208       return false;
1209     }
1210     break;
1211   case ISD::ADD:
1212   case ISD::MUL:
1213   case ISD::SUB: {
1214     // Add, Sub, and Mul don't demand any bits in positions beyond that
1215     // of the highest bit demanded of them.
1216     SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
1217     unsigned NewMaskLZ = NewMask.countLeadingZeros();
1218     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - NewMaskLZ);
1219     if (SimplifyDemandedBits(Op0, LoMask, Known2, TLO, Depth + 1) ||
1220         SimplifyDemandedBits(Op1, LoMask, Known2, TLO, Depth + 1) ||
1221         // See if the operation should be performed at a smaller bit width.
1222         ShrinkDemandedOp(Op, BitWidth, NewMask, TLO)) {
1223       SDNodeFlags Flags = Op.getNode()->getFlags();
1224       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
1225         // Disable the nsw and nuw flags. We can no longer guarantee that we
1226         // won't wrap after simplification.
1227         Flags.setNoSignedWrap(false);
1228         Flags.setNoUnsignedWrap(false);
1229         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1,
1230                                         Flags);
1231         return TLO.CombineTo(Op, NewOp);
1232       }
1233       return true;
1234     }
1235 
1236     // If we have a constant operand, we may be able to turn it into -1 if we
1237     // do not demand the high bits. This can make the constant smaller to
1238     // encode, allow more general folding, or match specialized instruction
1239     // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
1240     // is probably not useful (and could be detrimental).
1241     ConstantSDNode *C = isConstOrConstSplat(Op1);
1242     APInt HighMask = APInt::getHighBitsSet(NewMask.getBitWidth(), NewMaskLZ);
1243     if (C && !C->isAllOnesValue() && !C->isOne() &&
1244         (C->getAPIntValue() | HighMask).isAllOnesValue()) {
1245       SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
1246       // We can't guarantee that the new math op doesn't wrap, so explicitly
1247       // clear those flags to prevent folding with a potential existing node
1248       // that has those flags set.
1249       SDNodeFlags Flags;
1250       Flags.setNoSignedWrap(false);
1251       Flags.setNoUnsignedWrap(false);
1252       SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
1253       return TLO.CombineTo(Op, NewOp);
1254     }
1255 
1256     LLVM_FALLTHROUGH;
1257   }
1258   default:
1259     // Just use computeKnownBits to compute output bits.
1260     TLO.DAG.computeKnownBits(Op, Known, Depth);
1261     break;
1262   }
1263 
1264   // If we know the value of all of the demanded bits, return this as a
1265   // constant.
1266   if (NewMask.isSubsetOf(Known.Zero|Known.One)) {
1267     // Avoid folding to a constant if any OpaqueConstant is involved.
1268     const SDNode *N = Op.getNode();
1269     for (SDNodeIterator I = SDNodeIterator::begin(N),
1270          E = SDNodeIterator::end(N); I != E; ++I) {
1271       SDNode *Op = *I;
1272       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1273         if (C->isOpaque())
1274           return false;
1275     }
1276     return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
1277   }
1278 
1279   return false;
1280 }
1281 
1282 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op,
1283                                                 const APInt &DemandedElts,
1284                                                 APInt &KnownUndef,
1285                                                 APInt &KnownZero,
1286                                                 DAGCombinerInfo &DCI) const {
1287   SelectionDAG &DAG = DCI.DAG;
1288   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1289                         !DCI.isBeforeLegalizeOps());
1290 
1291   bool Simplified =
1292       SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
1293   if (Simplified)
1294     DCI.CommitTargetLoweringOpt(TLO);
1295   return Simplified;
1296 }
1297 
1298 bool TargetLowering::SimplifyDemandedVectorElts(
1299     SDValue Op, const APInt &DemandedEltMask, APInt &KnownUndef,
1300     APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
1301     bool AssumeSingleUse) const {
1302   EVT VT = Op.getValueType();
1303   APInt DemandedElts = DemandedEltMask;
1304   unsigned NumElts = DemandedElts.getBitWidth();
1305   assert(VT.isVector() && "Expected vector op");
1306   assert(VT.getVectorNumElements() == NumElts &&
1307          "Mask size mismatches value type element count!");
1308 
1309   KnownUndef = KnownZero = APInt::getNullValue(NumElts);
1310 
1311   // Undef operand.
1312   if (Op.isUndef()) {
1313     KnownUndef.setAllBits();
1314     return false;
1315   }
1316 
1317   // If Op has other users, assume that all elements are needed.
1318   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse)
1319     DemandedElts.setAllBits();
1320 
1321   // Not demanding any elements from Op.
1322   if (DemandedElts == 0) {
1323     KnownUndef.setAllBits();
1324     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1325   }
1326 
1327   // Limit search depth.
1328   if (Depth >= 6)
1329     return false;
1330 
1331   SDLoc DL(Op);
1332   unsigned EltSizeInBits = VT.getScalarSizeInBits();
1333 
1334   switch (Op.getOpcode()) {
1335   case ISD::SCALAR_TO_VECTOR: {
1336     if (!DemandedElts[0]) {
1337       KnownUndef.setAllBits();
1338       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1339     }
1340     KnownUndef.setHighBits(NumElts - 1);
1341     break;
1342   }
1343   case ISD::BUILD_VECTOR: {
1344     // Check all elements and simplify any unused elements with UNDEF.
1345     if (!DemandedElts.isAllOnesValue()) {
1346       // Don't simplify BROADCASTS.
1347       if (llvm::any_of(Op->op_values(),
1348                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
1349         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
1350         bool Updated = false;
1351         for (unsigned i = 0; i != NumElts; ++i) {
1352           if (!DemandedElts[i] && !Ops[i].isUndef()) {
1353             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
1354             KnownUndef.setBit(i);
1355             Updated = true;
1356           }
1357         }
1358         if (Updated)
1359           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
1360       }
1361     }
1362     for (unsigned i = 0; i != NumElts; ++i) {
1363       SDValue SrcOp = Op.getOperand(i);
1364       if (SrcOp.isUndef()) {
1365         KnownUndef.setBit(i);
1366       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
1367                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
1368         KnownZero.setBit(i);
1369       }
1370     }
1371     break;
1372   }
1373   case ISD::CONCAT_VECTORS: {
1374     EVT SubVT = Op.getOperand(0).getValueType();
1375     unsigned NumSubVecs = Op.getNumOperands();
1376     unsigned NumSubElts = SubVT.getVectorNumElements();
1377     for (unsigned i = 0; i != NumSubVecs; ++i) {
1378       SDValue SubOp = Op.getOperand(i);
1379       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1380       APInt SubUndef, SubZero;
1381       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
1382                                      Depth + 1))
1383         return true;
1384       KnownUndef.insertBits(SubUndef, i * NumSubElts);
1385       KnownZero.insertBits(SubZero, i * NumSubElts);
1386     }
1387     break;
1388   }
1389   case ISD::INSERT_SUBVECTOR: {
1390     if (!isa<ConstantSDNode>(Op.getOperand(2)))
1391       break;
1392     SDValue Base = Op.getOperand(0);
1393     SDValue Sub = Op.getOperand(1);
1394     EVT SubVT = Sub.getValueType();
1395     unsigned NumSubElts = SubVT.getVectorNumElements();
1396     APInt Idx = cast<ConstantSDNode>(Op.getOperand(2))->getAPIntValue();
1397     if (Idx.uge(NumElts - NumSubElts))
1398       break;
1399     unsigned SubIdx = Idx.getZExtValue();
1400     APInt SubElts = DemandedElts.extractBits(NumSubElts, SubIdx);
1401     APInt SubUndef, SubZero;
1402     if (SimplifyDemandedVectorElts(Sub, SubElts, SubUndef, SubZero, TLO,
1403                                    Depth + 1))
1404       return true;
1405     APInt BaseElts = DemandedElts;
1406     BaseElts.insertBits(APInt::getNullValue(NumSubElts), SubIdx);
1407     if (SimplifyDemandedVectorElts(Base, BaseElts, KnownUndef, KnownZero, TLO,
1408                                    Depth + 1))
1409       return true;
1410     KnownUndef.insertBits(SubUndef, SubIdx);
1411     KnownZero.insertBits(SubZero, SubIdx);
1412     break;
1413   }
1414   case ISD::INSERT_VECTOR_ELT: {
1415     SDValue Vec = Op.getOperand(0);
1416     SDValue Scl = Op.getOperand(1);
1417     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1418 
1419     // For a legal, constant insertion index, if we don't need this insertion
1420     // then strip it, else remove it from the demanded elts.
1421     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
1422       unsigned Idx = CIdx->getZExtValue();
1423       if (!DemandedElts[Idx])
1424         return TLO.CombineTo(Op, Vec);
1425       DemandedElts.clearBit(Idx);
1426 
1427       if (SimplifyDemandedVectorElts(Vec, DemandedElts, KnownUndef,
1428                                      KnownZero, TLO, Depth + 1))
1429         return true;
1430 
1431       KnownUndef.clearBit(Idx);
1432       if (Scl.isUndef())
1433         KnownUndef.setBit(Idx);
1434 
1435       KnownZero.clearBit(Idx);
1436       if (isNullConstant(Scl) || isNullFPConstant(Scl))
1437         KnownZero.setBit(Idx);
1438       break;
1439     }
1440 
1441     APInt VecUndef, VecZero;
1442     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
1443                                    Depth + 1))
1444       return true;
1445     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
1446     break;
1447   }
1448   case ISD::VSELECT: {
1449     APInt DemandedLHS(DemandedElts);
1450     APInt DemandedRHS(DemandedElts);
1451 
1452     // TODO - add support for constant vselect masks.
1453 
1454     // See if we can simplify either vselect operand.
1455     APInt UndefLHS, ZeroLHS;
1456     APInt UndefRHS, ZeroRHS;
1457     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS,
1458                                    ZeroLHS, TLO, Depth + 1))
1459       return true;
1460     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS,
1461                                    ZeroRHS, TLO, Depth + 1))
1462       return true;
1463 
1464     KnownUndef = UndefLHS & UndefRHS;
1465     KnownZero = ZeroLHS & ZeroRHS;
1466     break;
1467   }
1468   case ISD::VECTOR_SHUFFLE: {
1469     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1470 
1471     // Collect demanded elements from shuffle operands..
1472     APInt DemandedLHS(NumElts, 0);
1473     APInt DemandedRHS(NumElts, 0);
1474     for (unsigned i = 0; i != NumElts; ++i) {
1475       int M = ShuffleMask[i];
1476       if (M < 0 || !DemandedElts[i])
1477         continue;
1478       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
1479       if (M < (int)NumElts)
1480         DemandedLHS.setBit(M);
1481       else
1482         DemandedRHS.setBit(M - NumElts);
1483     }
1484 
1485     // See if we can simplify either shuffle operand.
1486     APInt UndefLHS, ZeroLHS;
1487     APInt UndefRHS, ZeroRHS;
1488     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS,
1489                                    ZeroLHS, TLO, Depth + 1))
1490       return true;
1491     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS,
1492                                    ZeroRHS, TLO, Depth + 1))
1493       return true;
1494 
1495     // Simplify mask using undef elements from LHS/RHS.
1496     bool Updated = false;
1497     bool IdentityLHS = true, IdentityRHS = true;
1498     SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end());
1499     for (unsigned i = 0; i != NumElts; ++i) {
1500       int &M = NewMask[i];
1501       if (M < 0)
1502         continue;
1503       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
1504           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
1505         Updated = true;
1506         M = -1;
1507       }
1508       IdentityLHS &= (M < 0) || (M == (int)i);
1509       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
1510     }
1511 
1512     // Update legal shuffle masks based on demanded elements if it won't reduce
1513     // to Identity which can cause premature removal of the shuffle mask.
1514     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps &&
1515         isShuffleMaskLegal(NewMask, VT))
1516       return TLO.CombineTo(Op,
1517                            TLO.DAG.getVectorShuffle(VT, DL, Op.getOperand(0),
1518                                                     Op.getOperand(1), NewMask));
1519 
1520     // Propagate undef/zero elements from LHS/RHS.
1521     for (unsigned i = 0; i != NumElts; ++i) {
1522       int M = ShuffleMask[i];
1523       if (M < 0) {
1524         KnownUndef.setBit(i);
1525       } else if (M < (int)NumElts) {
1526         if (UndefLHS[M])
1527           KnownUndef.setBit(i);
1528         if (ZeroLHS[M])
1529           KnownZero.setBit(i);
1530       } else {
1531         if (UndefRHS[M - NumElts])
1532           KnownUndef.setBit(i);
1533         if (ZeroRHS[M - NumElts])
1534           KnownZero.setBit(i);
1535       }
1536     }
1537     break;
1538   }
1539   case ISD::ADD:
1540   case ISD::SUB: {
1541     APInt SrcUndef, SrcZero;
1542     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, SrcUndef,
1543                                    SrcZero, TLO, Depth + 1))
1544       return true;
1545     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
1546                                    KnownZero, TLO, Depth + 1))
1547       return true;
1548     KnownZero &= SrcZero;
1549     KnownUndef &= SrcUndef;
1550     break;
1551   }
1552   case ISD::TRUNCATE:
1553     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
1554                                    KnownZero, TLO, Depth + 1))
1555       return true;
1556     break;
1557   default: {
1558     if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
1559       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
1560                                                   KnownZero, TLO, Depth))
1561         return true;
1562     break;
1563   }
1564   }
1565 
1566   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
1567   return false;
1568 }
1569 
1570 /// Determine which of the bits specified in Mask are known to be either zero or
1571 /// one and return them in the Known.
1572 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1573                                                    KnownBits &Known,
1574                                                    const APInt &DemandedElts,
1575                                                    const SelectionDAG &DAG,
1576                                                    unsigned Depth) const {
1577   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1578           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1579           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1580           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1581          "Should use MaskedValueIsZero if you don't know whether Op"
1582          " is a target node!");
1583   Known.resetAll();
1584 }
1585 
1586 void TargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
1587                                                    KnownBits &Known,
1588                                                    const APInt &DemandedElts,
1589                                                    const SelectionDAG &DAG,
1590                                                    unsigned Depth) const {
1591   assert(isa<FrameIndexSDNode>(Op) && "expected FrameIndex");
1592 
1593   if (unsigned Align = DAG.InferPtrAlignment(Op)) {
1594     // The low bits are known zero if the pointer is aligned.
1595     Known.Zero.setLowBits(Log2_32(Align));
1596   }
1597 }
1598 
1599 /// This method can be implemented by targets that want to expose additional
1600 /// information about sign bits to the DAG Combiner.
1601 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1602                                                          const APInt &,
1603                                                          const SelectionDAG &,
1604                                                          unsigned Depth) const {
1605   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1606           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1607           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1608           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1609          "Should use ComputeNumSignBits if you don't know whether Op"
1610          " is a target node!");
1611   return 1;
1612 }
1613 
1614 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
1615     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
1616     TargetLoweringOpt &TLO, unsigned Depth) const {
1617   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1618           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1619           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1620           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1621          "Should use SimplifyDemandedVectorElts if you don't know whether Op"
1622          " is a target node!");
1623   return false;
1624 }
1625 
1626 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
1627 // work with truncating build vectors and vectors with elements of less than
1628 // 8 bits.
1629 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
1630   if (!N)
1631     return false;
1632 
1633   APInt CVal;
1634   if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
1635     CVal = CN->getAPIntValue();
1636   } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) {
1637     auto *CN = BV->getConstantSplatNode();
1638     if (!CN)
1639       return false;
1640 
1641     // If this is a truncating build vector, truncate the splat value.
1642     // Otherwise, we may fail to match the expected values below.
1643     unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits();
1644     CVal = CN->getAPIntValue();
1645     if (BVEltWidth < CVal.getBitWidth())
1646       CVal = CVal.trunc(BVEltWidth);
1647   } else {
1648     return false;
1649   }
1650 
1651   switch (getBooleanContents(N->getValueType(0))) {
1652   case UndefinedBooleanContent:
1653     return CVal[0];
1654   case ZeroOrOneBooleanContent:
1655     return CVal.isOneValue();
1656   case ZeroOrNegativeOneBooleanContent:
1657     return CVal.isAllOnesValue();
1658   }
1659 
1660   llvm_unreachable("Invalid boolean contents");
1661 }
1662 
1663 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
1664   if (!N)
1665     return false;
1666 
1667   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1668   if (!CN) {
1669     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1670     if (!BV)
1671       return false;
1672 
1673     // Only interested in constant splats, we don't care about undef
1674     // elements in identifying boolean constants and getConstantSplatNode
1675     // returns NULL if all ops are undef;
1676     CN = BV->getConstantSplatNode();
1677     if (!CN)
1678       return false;
1679   }
1680 
1681   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
1682     return !CN->getAPIntValue()[0];
1683 
1684   return CN->isNullValue();
1685 }
1686 
1687 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
1688                                        bool SExt) const {
1689   if (VT == MVT::i1)
1690     return N->isOne();
1691 
1692   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
1693   switch (Cnt) {
1694   case TargetLowering::ZeroOrOneBooleanContent:
1695     // An extended value of 1 is always true, unless its original type is i1,
1696     // in which case it will be sign extended to -1.
1697     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
1698   case TargetLowering::UndefinedBooleanContent:
1699   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1700     return N->isAllOnesValue() && SExt;
1701   }
1702   llvm_unreachable("Unexpected enumeration.");
1703 }
1704 
1705 /// This helper function of SimplifySetCC tries to optimize the comparison when
1706 /// either operand of the SetCC node is a bitwise-and instruction.
1707 SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
1708                                              ISD::CondCode Cond,
1709                                              DAGCombinerInfo &DCI,
1710                                              const SDLoc &DL) const {
1711   // Match these patterns in any of their permutations:
1712   // (X & Y) == Y
1713   // (X & Y) != Y
1714   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
1715     std::swap(N0, N1);
1716 
1717   EVT OpVT = N0.getValueType();
1718   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
1719       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
1720     return SDValue();
1721 
1722   SDValue X, Y;
1723   if (N0.getOperand(0) == N1) {
1724     X = N0.getOperand(1);
1725     Y = N0.getOperand(0);
1726   } else if (N0.getOperand(1) == N1) {
1727     X = N0.getOperand(0);
1728     Y = N0.getOperand(1);
1729   } else {
1730     return SDValue();
1731   }
1732 
1733   SelectionDAG &DAG = DCI.DAG;
1734   SDValue Zero = DAG.getConstant(0, DL, OpVT);
1735   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
1736     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
1737     // Note that where Y is variable and is known to have at most one bit set
1738     // (for example, if it is Z & 1) we cannot do this; the expressions are not
1739     // equivalent when Y == 0.
1740     Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1741     if (DCI.isBeforeLegalizeOps() ||
1742         isCondCodeLegal(Cond, N0.getSimpleValueType()))
1743       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
1744   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
1745     // If the target supports an 'and-not' or 'and-complement' logic operation,
1746     // try to use that to make a comparison operation more efficient.
1747     // But don't do this transform if the mask is a single bit because there are
1748     // more efficient ways to deal with that case (for example, 'bt' on x86 or
1749     // 'rlwinm' on PPC).
1750 
1751     // Bail out if the compare operand that we want to turn into a zero is
1752     // already a zero (otherwise, infinite loop).
1753     auto *YConst = dyn_cast<ConstantSDNode>(Y);
1754     if (YConst && YConst->isNullValue())
1755       return SDValue();
1756 
1757     // Transform this into: ~X & Y == 0.
1758     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
1759     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
1760     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
1761   }
1762 
1763   return SDValue();
1764 }
1765 
1766 /// Try to simplify a setcc built with the specified operands and cc. If it is
1767 /// unable to simplify it, return a null SDValue.
1768 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1769                                       ISD::CondCode Cond, bool foldBooleans,
1770                                       DAGCombinerInfo &DCI,
1771                                       const SDLoc &dl) const {
1772   SelectionDAG &DAG = DCI.DAG;
1773   EVT OpVT = N0.getValueType();
1774 
1775   // These setcc operations always fold.
1776   switch (Cond) {
1777   default: break;
1778   case ISD::SETFALSE:
1779   case ISD::SETFALSE2: return DAG.getBoolConstant(false, dl, VT, OpVT);
1780   case ISD::SETTRUE:
1781   case ISD::SETTRUE2:  return DAG.getBoolConstant(true, dl, VT, OpVT);
1782   }
1783 
1784   // Ensure that the constant occurs on the RHS and fold constant comparisons.
1785   // TODO: Handle non-splat vector constants. All undef causes trouble.
1786   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1787   if (isConstOrConstSplat(N0) &&
1788       (DCI.isBeforeLegalizeOps() ||
1789        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1790     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
1791 
1792   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1793     const APInt &C1 = N1C->getAPIntValue();
1794 
1795     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1796     // equality comparison, then we're just comparing whether X itself is
1797     // zero.
1798     if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) &&
1799         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1800         N0.getOperand(1).getOpcode() == ISD::Constant) {
1801       const APInt &ShAmt
1802         = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1803       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1804           ShAmt == Log2_32(N0.getValueSizeInBits())) {
1805         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1806           // (srl (ctlz x), 5) == 0  -> X != 0
1807           // (srl (ctlz x), 5) != 1  -> X != 0
1808           Cond = ISD::SETNE;
1809         } else {
1810           // (srl (ctlz x), 5) != 0  -> X == 0
1811           // (srl (ctlz x), 5) == 1  -> X == 0
1812           Cond = ISD::SETEQ;
1813         }
1814         SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
1815         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1816                             Zero, Cond);
1817       }
1818     }
1819 
1820     SDValue CTPOP = N0;
1821     // Look through truncs that don't change the value of a ctpop.
1822     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1823       CTPOP = N0.getOperand(0);
1824 
1825     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
1826         (N0 == CTPOP ||
1827          N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) {
1828       EVT CTVT = CTPOP.getValueType();
1829       SDValue CTOp = CTPOP.getOperand(0);
1830 
1831       // (ctpop x) u< 2 -> (x & x-1) == 0
1832       // (ctpop x) u> 1 -> (x & x-1) != 0
1833       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1834         SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
1835                                   DAG.getConstant(1, dl, CTVT));
1836         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1837         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
1838         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
1839       }
1840 
1841       // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
1842     }
1843 
1844     // (zext x) == C --> x == (trunc C)
1845     // (sext x) == C --> x == (trunc C)
1846     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1847         DCI.isBeforeLegalize() && N0->hasOneUse()) {
1848       unsigned MinBits = N0.getValueSizeInBits();
1849       SDValue PreExt;
1850       bool Signed = false;
1851       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1852         // ZExt
1853         MinBits = N0->getOperand(0).getValueSizeInBits();
1854         PreExt = N0->getOperand(0);
1855       } else if (N0->getOpcode() == ISD::AND) {
1856         // DAGCombine turns costly ZExts into ANDs
1857         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
1858           if ((C->getAPIntValue()+1).isPowerOf2()) {
1859             MinBits = C->getAPIntValue().countTrailingOnes();
1860             PreExt = N0->getOperand(0);
1861           }
1862       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
1863         // SExt
1864         MinBits = N0->getOperand(0).getValueSizeInBits();
1865         PreExt = N0->getOperand(0);
1866         Signed = true;
1867       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
1868         // ZEXTLOAD / SEXTLOAD
1869         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1870           MinBits = LN0->getMemoryVT().getSizeInBits();
1871           PreExt = N0;
1872         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
1873           Signed = true;
1874           MinBits = LN0->getMemoryVT().getSizeInBits();
1875           PreExt = N0;
1876         }
1877       }
1878 
1879       // Figure out how many bits we need to preserve this constant.
1880       unsigned ReqdBits = Signed ?
1881         C1.getBitWidth() - C1.getNumSignBits() + 1 :
1882         C1.getActiveBits();
1883 
1884       // Make sure we're not losing bits from the constant.
1885       if (MinBits > 0 &&
1886           MinBits < C1.getBitWidth() &&
1887           MinBits >= ReqdBits) {
1888         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1889         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1890           // Will get folded away.
1891           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
1892           if (MinBits == 1 && C1 == 1)
1893             // Invert the condition.
1894             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
1895                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1896           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
1897           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1898         }
1899 
1900         // If truncating the setcc operands is not desirable, we can still
1901         // simplify the expression in some cases:
1902         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
1903         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
1904         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
1905         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
1906         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
1907         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
1908         SDValue TopSetCC = N0->getOperand(0);
1909         unsigned N0Opc = N0->getOpcode();
1910         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
1911         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
1912             TopSetCC.getOpcode() == ISD::SETCC &&
1913             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
1914             (isConstFalseVal(N1C) ||
1915              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
1916 
1917           bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
1918                          (!N1C->isNullValue() && Cond == ISD::SETNE);
1919 
1920           if (!Inverse)
1921             return TopSetCC;
1922 
1923           ISD::CondCode InvCond = ISD::getSetCCInverse(
1924               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
1925               TopSetCC.getOperand(0).getValueType().isInteger());
1926           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
1927                                       TopSetCC.getOperand(1),
1928                                       InvCond);
1929         }
1930       }
1931     }
1932 
1933     // If the LHS is '(and load, const)', the RHS is 0, the test is for
1934     // equality or unsigned, and all 1 bits of the const are in the same
1935     // partial word, see if we can shorten the load.
1936     if (DCI.isBeforeLegalize() &&
1937         !ISD::isSignedIntSetCC(Cond) &&
1938         N0.getOpcode() == ISD::AND && C1 == 0 &&
1939         N0.getNode()->hasOneUse() &&
1940         isa<LoadSDNode>(N0.getOperand(0)) &&
1941         N0.getOperand(0).getNode()->hasOneUse() &&
1942         isa<ConstantSDNode>(N0.getOperand(1))) {
1943       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
1944       APInt bestMask;
1945       unsigned bestWidth = 0, bestOffset = 0;
1946       if (!Lod->isVolatile() && Lod->isUnindexed()) {
1947         unsigned origWidth = N0.getValueSizeInBits();
1948         unsigned maskWidth = origWidth;
1949         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
1950         // 8 bits, but have to be careful...
1951         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1952           origWidth = Lod->getMemoryVT().getSizeInBits();
1953         const APInt &Mask =
1954           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1955         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
1956           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
1957           for (unsigned offset=0; offset<origWidth/width; offset++) {
1958             if (Mask.isSubsetOf(newMask)) {
1959               if (DAG.getDataLayout().isLittleEndian())
1960                 bestOffset = (uint64_t)offset * (width/8);
1961               else
1962                 bestOffset = (origWidth/width - offset - 1) * (width/8);
1963               bestMask = Mask.lshr(offset * (width/8) * 8);
1964               bestWidth = width;
1965               break;
1966             }
1967             newMask <<= width;
1968           }
1969         }
1970       }
1971       if (bestWidth) {
1972         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
1973         if (newVT.isRound()) {
1974           EVT PtrType = Lod->getOperand(1).getValueType();
1975           SDValue Ptr = Lod->getBasePtr();
1976           if (bestOffset != 0)
1977             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
1978                               DAG.getConstant(bestOffset, dl, PtrType));
1979           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1980           SDValue NewLoad = DAG.getLoad(
1981               newVT, dl, Lod->getChain(), Ptr,
1982               Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
1983           return DAG.getSetCC(dl, VT,
1984                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
1985                                       DAG.getConstant(bestMask.trunc(bestWidth),
1986                                                       dl, newVT)),
1987                               DAG.getConstant(0LL, dl, newVT), Cond);
1988         }
1989       }
1990     }
1991 
1992     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1993     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1994       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
1995 
1996       // If the comparison constant has bits in the upper part, the
1997       // zero-extended value could never match.
1998       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1999                                               C1.getBitWidth() - InSize))) {
2000         switch (Cond) {
2001         case ISD::SETUGT:
2002         case ISD::SETUGE:
2003         case ISD::SETEQ:
2004           return DAG.getConstant(0, dl, VT);
2005         case ISD::SETULT:
2006         case ISD::SETULE:
2007         case ISD::SETNE:
2008           return DAG.getConstant(1, dl, VT);
2009         case ISD::SETGT:
2010         case ISD::SETGE:
2011           // True if the sign bit of C1 is set.
2012           return DAG.getConstant(C1.isNegative(), dl, VT);
2013         case ISD::SETLT:
2014         case ISD::SETLE:
2015           // True if the sign bit of C1 isn't set.
2016           return DAG.getConstant(C1.isNonNegative(), dl, VT);
2017         default:
2018           break;
2019         }
2020       }
2021 
2022       // Otherwise, we can perform the comparison with the low bits.
2023       switch (Cond) {
2024       case ISD::SETEQ:
2025       case ISD::SETNE:
2026       case ISD::SETUGT:
2027       case ISD::SETUGE:
2028       case ISD::SETULT:
2029       case ISD::SETULE: {
2030         EVT newVT = N0.getOperand(0).getValueType();
2031         if (DCI.isBeforeLegalizeOps() ||
2032             (isOperationLegal(ISD::SETCC, newVT) &&
2033              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
2034           EVT NewSetCCVT =
2035               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
2036           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
2037 
2038           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
2039                                           NewConst, Cond);
2040           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
2041         }
2042         break;
2043       }
2044       default:
2045         break;   // todo, be more careful with signed comparisons
2046       }
2047     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2048                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2049       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
2050       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
2051       EVT ExtDstTy = N0.getValueType();
2052       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
2053 
2054       // If the constant doesn't fit into the number of bits for the source of
2055       // the sign extension, it is impossible for both sides to be equal.
2056       if (C1.getMinSignedBits() > ExtSrcTyBits)
2057         return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
2058 
2059       SDValue ZextOp;
2060       EVT Op0Ty = N0.getOperand(0).getValueType();
2061       if (Op0Ty == ExtSrcTy) {
2062         ZextOp = N0.getOperand(0);
2063       } else {
2064         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
2065         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
2066                               DAG.getConstant(Imm, dl, Op0Ty));
2067       }
2068       if (!DCI.isCalledByLegalizer())
2069         DCI.AddToWorklist(ZextOp.getNode());
2070       // Otherwise, make this a use of a zext.
2071       return DAG.getSetCC(dl, VT, ZextOp,
2072                           DAG.getConstant(C1 & APInt::getLowBitsSet(
2073                                                               ExtDstTyBits,
2074                                                               ExtSrcTyBits),
2075                                           dl, ExtDstTy),
2076                           Cond);
2077     } else if ((N1C->isNullValue() || N1C->isOne()) &&
2078                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2079       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
2080       if (N0.getOpcode() == ISD::SETCC &&
2081           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
2082         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
2083         if (TrueWhenTrue)
2084           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
2085         // Invert the condition.
2086         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
2087         CC = ISD::getSetCCInverse(CC,
2088                                   N0.getOperand(0).getValueType().isInteger());
2089         if (DCI.isBeforeLegalizeOps() ||
2090             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
2091           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
2092       }
2093 
2094       if ((N0.getOpcode() == ISD::XOR ||
2095            (N0.getOpcode() == ISD::AND &&
2096             N0.getOperand(0).getOpcode() == ISD::XOR &&
2097             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
2098           isa<ConstantSDNode>(N0.getOperand(1)) &&
2099           cast<ConstantSDNode>(N0.getOperand(1))->isOne()) {
2100         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
2101         // can only do this if the top bits are known zero.
2102         unsigned BitWidth = N0.getValueSizeInBits();
2103         if (DAG.MaskedValueIsZero(N0,
2104                                   APInt::getHighBitsSet(BitWidth,
2105                                                         BitWidth-1))) {
2106           // Okay, get the un-inverted input value.
2107           SDValue Val;
2108           if (N0.getOpcode() == ISD::XOR) {
2109             Val = N0.getOperand(0);
2110           } else {
2111             assert(N0.getOpcode() == ISD::AND &&
2112                     N0.getOperand(0).getOpcode() == ISD::XOR);
2113             // ((X^1)&1)^1 -> X & 1
2114             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
2115                               N0.getOperand(0).getOperand(0),
2116                               N0.getOperand(1));
2117           }
2118 
2119           return DAG.getSetCC(dl, VT, Val, N1,
2120                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2121         }
2122       } else if (N1C->isOne() &&
2123                  (VT == MVT::i1 ||
2124                   getBooleanContents(N0->getValueType(0)) ==
2125                       ZeroOrOneBooleanContent)) {
2126         SDValue Op0 = N0;
2127         if (Op0.getOpcode() == ISD::TRUNCATE)
2128           Op0 = Op0.getOperand(0);
2129 
2130         if ((Op0.getOpcode() == ISD::XOR) &&
2131             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
2132             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
2133           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
2134           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
2135           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
2136                               Cond);
2137         }
2138         if (Op0.getOpcode() == ISD::AND &&
2139             isa<ConstantSDNode>(Op0.getOperand(1)) &&
2140             cast<ConstantSDNode>(Op0.getOperand(1))->isOne()) {
2141           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
2142           if (Op0.getValueType().bitsGT(VT))
2143             Op0 = DAG.getNode(ISD::AND, dl, VT,
2144                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
2145                           DAG.getConstant(1, dl, VT));
2146           else if (Op0.getValueType().bitsLT(VT))
2147             Op0 = DAG.getNode(ISD::AND, dl, VT,
2148                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
2149                         DAG.getConstant(1, dl, VT));
2150 
2151           return DAG.getSetCC(dl, VT, Op0,
2152                               DAG.getConstant(0, dl, Op0.getValueType()),
2153                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2154         }
2155         if (Op0.getOpcode() == ISD::AssertZext &&
2156             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
2157           return DAG.getSetCC(dl, VT, Op0,
2158                               DAG.getConstant(0, dl, Op0.getValueType()),
2159                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2160       }
2161     }
2162   }
2163 
2164   // These simplifications apply to splat vectors as well.
2165   // TODO: Handle more splat vector cases.
2166   if (auto *N1C = isConstOrConstSplat(N1)) {
2167     const APInt &C1 = N1C->getAPIntValue();
2168 
2169     APInt MinVal, MaxVal;
2170     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
2171     if (ISD::isSignedIntSetCC(Cond)) {
2172       MinVal = APInt::getSignedMinValue(OperandBitSize);
2173       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
2174     } else {
2175       MinVal = APInt::getMinValue(OperandBitSize);
2176       MaxVal = APInt::getMaxValue(OperandBitSize);
2177     }
2178 
2179     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
2180     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
2181       // X >= MIN --> true
2182       if (C1 == MinVal)
2183         return DAG.getBoolConstant(true, dl, VT, OpVT);
2184 
2185       if (!VT.isVector()) { // TODO: Support this for vectors.
2186         // X >= C0 --> X > (C0 - 1)
2187         APInt C = C1 - 1;
2188         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
2189         if ((DCI.isBeforeLegalizeOps() ||
2190              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
2191             (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
2192                                   isLegalICmpImmediate(C.getSExtValue())))) {
2193           return DAG.getSetCC(dl, VT, N0,
2194                               DAG.getConstant(C, dl, N1.getValueType()),
2195                               NewCC);
2196         }
2197       }
2198     }
2199 
2200     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
2201       // X <= MAX --> true
2202       if (C1 == MaxVal)
2203         return DAG.getBoolConstant(true, dl, VT, OpVT);
2204 
2205       // X <= C0 --> X < (C0 + 1)
2206       if (!VT.isVector()) { // TODO: Support this for vectors.
2207         APInt C = C1 + 1;
2208         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
2209         if ((DCI.isBeforeLegalizeOps() ||
2210              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
2211             (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
2212                                   isLegalICmpImmediate(C.getSExtValue())))) {
2213           return DAG.getSetCC(dl, VT, N0,
2214                               DAG.getConstant(C, dl, N1.getValueType()),
2215                               NewCC);
2216         }
2217       }
2218     }
2219 
2220     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
2221       if (C1 == MinVal)
2222         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
2223 
2224       // TODO: Support this for vectors after legalize ops.
2225       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
2226         // Canonicalize setlt X, Max --> setne X, Max
2227         if (C1 == MaxVal)
2228           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
2229 
2230         // If we have setult X, 1, turn it into seteq X, 0
2231         if (C1 == MinVal+1)
2232           return DAG.getSetCC(dl, VT, N0,
2233                               DAG.getConstant(MinVal, dl, N0.getValueType()),
2234                               ISD::SETEQ);
2235       }
2236     }
2237 
2238     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
2239       if (C1 == MaxVal)
2240         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
2241 
2242       // TODO: Support this for vectors after legalize ops.
2243       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
2244         // Canonicalize setgt X, Min --> setne X, Min
2245         if (C1 == MinVal)
2246           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
2247 
2248         // If we have setugt X, Max-1, turn it into seteq X, Max
2249         if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
2250           return DAG.getSetCC(dl, VT, N0,
2251                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
2252                               ISD::SETEQ);
2253       }
2254     }
2255 
2256     // If we have "setcc X, C0", check to see if we can shrink the immediate
2257     // by changing cc.
2258     // TODO: Support this for vectors after legalize ops.
2259     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
2260       // SETUGT X, SINTMAX  -> SETLT X, 0
2261       if (Cond == ISD::SETUGT &&
2262           C1 == APInt::getSignedMaxValue(OperandBitSize))
2263         return DAG.getSetCC(dl, VT, N0,
2264                             DAG.getConstant(0, dl, N1.getValueType()),
2265                             ISD::SETLT);
2266 
2267       // SETULT X, SINTMIN  -> SETGT X, -1
2268       if (Cond == ISD::SETULT &&
2269           C1 == APInt::getSignedMinValue(OperandBitSize)) {
2270         SDValue ConstMinusOne =
2271             DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
2272                             N1.getValueType());
2273         return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
2274       }
2275     }
2276   }
2277 
2278   // Back to non-vector simplifications.
2279   // TODO: Can we do these for vector splats?
2280   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
2281     const APInt &C1 = N1C->getAPIntValue();
2282 
2283     // Fold bit comparisons when we can.
2284     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2285         (VT == N0.getValueType() ||
2286          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
2287         N0.getOpcode() == ISD::AND) {
2288       auto &DL = DAG.getDataLayout();
2289       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2290         EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
2291                                        !DCI.isBeforeLegalize());
2292         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
2293           // Perform the xform if the AND RHS is a single bit.
2294           if (AndRHS->getAPIntValue().isPowerOf2()) {
2295             return DAG.getNode(ISD::TRUNCATE, dl, VT,
2296                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2297                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
2298                                    ShiftTy)));
2299           }
2300         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
2301           // (X & 8) == 8  -->  (X & 8) >> 3
2302           // Perform the xform if C1 is a single bit.
2303           if (C1.isPowerOf2()) {
2304             return DAG.getNode(ISD::TRUNCATE, dl, VT,
2305                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2306                                       DAG.getConstant(C1.logBase2(), dl,
2307                                                       ShiftTy)));
2308           }
2309         }
2310       }
2311     }
2312 
2313     if (C1.getMinSignedBits() <= 64 &&
2314         !isLegalICmpImmediate(C1.getSExtValue())) {
2315       // (X & -256) == 256 -> (X >> 8) == 1
2316       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2317           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
2318         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2319           const APInt &AndRHSC = AndRHS->getAPIntValue();
2320           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
2321             unsigned ShiftBits = AndRHSC.countTrailingZeros();
2322             auto &DL = DAG.getDataLayout();
2323             EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
2324                                            !DCI.isBeforeLegalize());
2325             EVT CmpTy = N0.getValueType();
2326             SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
2327                                         DAG.getConstant(ShiftBits, dl,
2328                                                         ShiftTy));
2329             SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
2330             return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
2331           }
2332         }
2333       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
2334                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
2335         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
2336         // X <  0x100000000 -> (X >> 32) <  1
2337         // X >= 0x100000000 -> (X >> 32) >= 1
2338         // X <= 0x0ffffffff -> (X >> 32) <  1
2339         // X >  0x0ffffffff -> (X >> 32) >= 1
2340         unsigned ShiftBits;
2341         APInt NewC = C1;
2342         ISD::CondCode NewCond = Cond;
2343         if (AdjOne) {
2344           ShiftBits = C1.countTrailingOnes();
2345           NewC = NewC + 1;
2346           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2347         } else {
2348           ShiftBits = C1.countTrailingZeros();
2349         }
2350         NewC.lshrInPlace(ShiftBits);
2351         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
2352           isLegalICmpImmediate(NewC.getSExtValue())) {
2353           auto &DL = DAG.getDataLayout();
2354           EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
2355                                          !DCI.isBeforeLegalize());
2356           EVT CmpTy = N0.getValueType();
2357           SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
2358                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
2359           SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
2360           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
2361         }
2362       }
2363     }
2364   }
2365 
2366   if (isa<ConstantFPSDNode>(N0.getNode())) {
2367     // Constant fold or commute setcc.
2368     SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
2369     if (O.getNode()) return O;
2370   } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
2371     // If the RHS of an FP comparison is a constant, simplify it away in
2372     // some cases.
2373     if (CFP->getValueAPF().isNaN()) {
2374       // If an operand is known to be a nan, we can fold it.
2375       switch (ISD::getUnorderedFlavor(Cond)) {
2376       default: llvm_unreachable("Unknown flavor!");
2377       case 0:  // Known false.
2378         return DAG.getBoolConstant(false, dl, VT, OpVT);
2379       case 1:  // Known true.
2380         return DAG.getBoolConstant(true, dl, VT, OpVT);
2381       case 2:  // Undefined.
2382         return DAG.getUNDEF(VT);
2383       }
2384     }
2385 
2386     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
2387     // constant if knowing that the operand is non-nan is enough.  We prefer to
2388     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
2389     // materialize 0.0.
2390     if (Cond == ISD::SETO || Cond == ISD::SETUO)
2391       return DAG.getSetCC(dl, VT, N0, N0, Cond);
2392 
2393     // setcc (fneg x), C -> setcc swap(pred) x, -C
2394     if (N0.getOpcode() == ISD::FNEG) {
2395       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
2396       if (DCI.isBeforeLegalizeOps() ||
2397           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
2398         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
2399         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
2400       }
2401     }
2402 
2403     // If the condition is not legal, see if we can find an equivalent one
2404     // which is legal.
2405     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
2406       // If the comparison was an awkward floating-point == or != and one of
2407       // the comparison operands is infinity or negative infinity, convert the
2408       // condition to a less-awkward <= or >=.
2409       if (CFP->getValueAPF().isInfinity()) {
2410         if (CFP->getValueAPF().isNegative()) {
2411           if (Cond == ISD::SETOEQ &&
2412               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2413             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
2414           if (Cond == ISD::SETUEQ &&
2415               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2416             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
2417           if (Cond == ISD::SETUNE &&
2418               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2419             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
2420           if (Cond == ISD::SETONE &&
2421               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2422             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
2423         } else {
2424           if (Cond == ISD::SETOEQ &&
2425               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2426             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
2427           if (Cond == ISD::SETUEQ &&
2428               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2429             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
2430           if (Cond == ISD::SETUNE &&
2431               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2432             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
2433           if (Cond == ISD::SETONE &&
2434               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2435             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
2436         }
2437       }
2438     }
2439   }
2440 
2441   if (N0 == N1) {
2442     // The sext(setcc()) => setcc() optimization relies on the appropriate
2443     // constant being emitted.
2444 
2445     bool EqTrue = ISD::isTrueWhenEqual(Cond);
2446 
2447     // We can always fold X == X for integer setcc's.
2448     if (N0.getValueType().isInteger())
2449       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
2450 
2451     unsigned UOF = ISD::getUnorderedFlavor(Cond);
2452     if (UOF == 2)   // FP operators that are undefined on NaNs.
2453       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
2454     if (UOF == unsigned(EqTrue))
2455       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
2456     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
2457     // if it is not already.
2458     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
2459     if (NewCond != Cond &&
2460         (DCI.isBeforeLegalizeOps() ||
2461          isCondCodeLegal(NewCond, N0.getSimpleValueType())))
2462       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
2463   }
2464 
2465   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2466       N0.getValueType().isInteger()) {
2467     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2468         N0.getOpcode() == ISD::XOR) {
2469       // Simplify (X+Y) == (X+Z) -->  Y == Z
2470       if (N0.getOpcode() == N1.getOpcode()) {
2471         if (N0.getOperand(0) == N1.getOperand(0))
2472           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
2473         if (N0.getOperand(1) == N1.getOperand(1))
2474           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
2475         if (isCommutativeBinOp(N0.getOpcode())) {
2476           // If X op Y == Y op X, try other combinations.
2477           if (N0.getOperand(0) == N1.getOperand(1))
2478             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
2479                                 Cond);
2480           if (N0.getOperand(1) == N1.getOperand(0))
2481             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
2482                                 Cond);
2483         }
2484       }
2485 
2486       // If RHS is a legal immediate value for a compare instruction, we need
2487       // to be careful about increasing register pressure needlessly.
2488       bool LegalRHSImm = false;
2489 
2490       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2491         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2492           // Turn (X+C1) == C2 --> X == C2-C1
2493           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
2494             return DAG.getSetCC(dl, VT, N0.getOperand(0),
2495                                 DAG.getConstant(RHSC->getAPIntValue()-
2496                                                 LHSR->getAPIntValue(),
2497                                 dl, N0.getValueType()), Cond);
2498           }
2499 
2500           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
2501           if (N0.getOpcode() == ISD::XOR)
2502             // If we know that all of the inverted bits are zero, don't bother
2503             // performing the inversion.
2504             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2505               return
2506                 DAG.getSetCC(dl, VT, N0.getOperand(0),
2507                              DAG.getConstant(LHSR->getAPIntValue() ^
2508                                                RHSC->getAPIntValue(),
2509                                              dl, N0.getValueType()),
2510                              Cond);
2511         }
2512 
2513         // Turn (C1-X) == C2 --> X == C1-C2
2514         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
2515           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
2516             return
2517               DAG.getSetCC(dl, VT, N0.getOperand(1),
2518                            DAG.getConstant(SUBC->getAPIntValue() -
2519                                              RHSC->getAPIntValue(),
2520                                            dl, N0.getValueType()),
2521                            Cond);
2522           }
2523         }
2524 
2525         // Could RHSC fold directly into a compare?
2526         if (RHSC->getValueType(0).getSizeInBits() <= 64)
2527           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
2528       }
2529 
2530       // Simplify (X+Z) == X -->  Z == 0
2531       // Don't do this if X is an immediate that can fold into a cmp
2532       // instruction and X+Z has other uses. It could be an induction variable
2533       // chain, and the transform would increase register pressure.
2534       if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
2535         if (N0.getOperand(0) == N1)
2536           return DAG.getSetCC(dl, VT, N0.getOperand(1),
2537                               DAG.getConstant(0, dl, N0.getValueType()), Cond);
2538         if (N0.getOperand(1) == N1) {
2539           if (isCommutativeBinOp(N0.getOpcode()))
2540             return DAG.getSetCC(dl, VT, N0.getOperand(0),
2541                                 DAG.getConstant(0, dl, N0.getValueType()),
2542                                 Cond);
2543           if (N0.getNode()->hasOneUse()) {
2544             assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2545             auto &DL = DAG.getDataLayout();
2546             // (Z-X) == X  --> Z == X<<1
2547             SDValue SH = DAG.getNode(
2548                 ISD::SHL, dl, N1.getValueType(), N1,
2549                 DAG.getConstant(1, dl,
2550                                 getShiftAmountTy(N1.getValueType(), DL,
2551                                                  !DCI.isBeforeLegalize())));
2552             if (!DCI.isCalledByLegalizer())
2553               DCI.AddToWorklist(SH.getNode());
2554             return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2555           }
2556         }
2557       }
2558     }
2559 
2560     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2561         N1.getOpcode() == ISD::XOR) {
2562       // Simplify  X == (X+Z) -->  Z == 0
2563       if (N1.getOperand(0) == N0)
2564         return DAG.getSetCC(dl, VT, N1.getOperand(1),
2565                         DAG.getConstant(0, dl, N1.getValueType()), Cond);
2566       if (N1.getOperand(1) == N0) {
2567         if (isCommutativeBinOp(N1.getOpcode()))
2568           return DAG.getSetCC(dl, VT, N1.getOperand(0),
2569                           DAG.getConstant(0, dl, N1.getValueType()), Cond);
2570         if (N1.getNode()->hasOneUse()) {
2571           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2572           auto &DL = DAG.getDataLayout();
2573           // X == (Z-X)  --> X<<1 == Z
2574           SDValue SH = DAG.getNode(
2575               ISD::SHL, dl, N1.getValueType(), N0,
2576               DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL,
2577                                                       !DCI.isBeforeLegalize())));
2578           if (!DCI.isCalledByLegalizer())
2579             DCI.AddToWorklist(SH.getNode());
2580           return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
2581         }
2582       }
2583     }
2584 
2585     if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl))
2586       return V;
2587   }
2588 
2589   // Fold away ALL boolean setcc's.
2590   SDValue Temp;
2591   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
2592     EVT OpVT = N0.getValueType();
2593     switch (Cond) {
2594     default: llvm_unreachable("Unknown integer setcc!");
2595     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
2596       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
2597       N0 = DAG.getNOT(dl, Temp, OpVT);
2598       if (!DCI.isCalledByLegalizer())
2599         DCI.AddToWorklist(Temp.getNode());
2600       break;
2601     case ISD::SETNE:  // X != Y   -->  (X^Y)
2602       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
2603       break;
2604     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
2605     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
2606       Temp = DAG.getNOT(dl, N0, OpVT);
2607       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
2608       if (!DCI.isCalledByLegalizer())
2609         DCI.AddToWorklist(Temp.getNode());
2610       break;
2611     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
2612     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
2613       Temp = DAG.getNOT(dl, N1, OpVT);
2614       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
2615       if (!DCI.isCalledByLegalizer())
2616         DCI.AddToWorklist(Temp.getNode());
2617       break;
2618     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
2619     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
2620       Temp = DAG.getNOT(dl, N0, OpVT);
2621       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
2622       if (!DCI.isCalledByLegalizer())
2623         DCI.AddToWorklist(Temp.getNode());
2624       break;
2625     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
2626     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
2627       Temp = DAG.getNOT(dl, N1, OpVT);
2628       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
2629       break;
2630     }
2631     if (VT.getScalarType() != MVT::i1) {
2632       if (!DCI.isCalledByLegalizer())
2633         DCI.AddToWorklist(N0.getNode());
2634       // FIXME: If running after legalize, we probably can't do this.
2635       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
2636       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
2637     }
2638     return N0;
2639   }
2640 
2641   // Could not fold it.
2642   return SDValue();
2643 }
2644 
2645 /// Returns true (and the GlobalValue and the offset) if the node is a
2646 /// GlobalAddress + offset.
2647 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
2648                                     int64_t &Offset) const {
2649   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
2650     GA = GASD->getGlobal();
2651     Offset += GASD->getOffset();
2652     return true;
2653   }
2654 
2655   if (N->getOpcode() == ISD::ADD) {
2656     SDValue N1 = N->getOperand(0);
2657     SDValue N2 = N->getOperand(1);
2658     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
2659       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
2660         Offset += V->getSExtValue();
2661         return true;
2662       }
2663     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
2664       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
2665         Offset += V->getSExtValue();
2666         return true;
2667       }
2668     }
2669   }
2670 
2671   return false;
2672 }
2673 
2674 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
2675                                           DAGCombinerInfo &DCI) const {
2676   // Default implementation: no optimization.
2677   return SDValue();
2678 }
2679 
2680 //===----------------------------------------------------------------------===//
2681 //  Inline Assembler Implementation Methods
2682 //===----------------------------------------------------------------------===//
2683 
2684 TargetLowering::ConstraintType
2685 TargetLowering::getConstraintType(StringRef Constraint) const {
2686   unsigned S = Constraint.size();
2687 
2688   if (S == 1) {
2689     switch (Constraint[0]) {
2690     default: break;
2691     case 'r': return C_RegisterClass;
2692     case 'm':    // memory
2693     case 'o':    // offsetable
2694     case 'V':    // not offsetable
2695       return C_Memory;
2696     case 'i':    // Simple Integer or Relocatable Constant
2697     case 'n':    // Simple Integer
2698     case 'E':    // Floating Point Constant
2699     case 'F':    // Floating Point Constant
2700     case 's':    // Relocatable Constant
2701     case 'p':    // Address.
2702     case 'X':    // Allow ANY value.
2703     case 'I':    // Target registers.
2704     case 'J':
2705     case 'K':
2706     case 'L':
2707     case 'M':
2708     case 'N':
2709     case 'O':
2710     case 'P':
2711     case '<':
2712     case '>':
2713       return C_Other;
2714     }
2715   }
2716 
2717   if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
2718     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
2719       return C_Memory;
2720     return C_Register;
2721   }
2722   return C_Unknown;
2723 }
2724 
2725 /// Try to replace an X constraint, which matches anything, with another that
2726 /// has more specific requirements based on the type of the corresponding
2727 /// operand.
2728 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
2729   if (ConstraintVT.isInteger())
2730     return "r";
2731   if (ConstraintVT.isFloatingPoint())
2732     return "f";      // works for many targets
2733   return nullptr;
2734 }
2735 
2736 /// Lower the specified operand into the Ops vector.
2737 /// If it is invalid, don't add anything to Ops.
2738 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2739                                                   std::string &Constraint,
2740                                                   std::vector<SDValue> &Ops,
2741                                                   SelectionDAG &DAG) const {
2742 
2743   if (Constraint.length() > 1) return;
2744 
2745   char ConstraintLetter = Constraint[0];
2746   switch (ConstraintLetter) {
2747   default: break;
2748   case 'X':     // Allows any operand; labels (basic block) use this.
2749     if (Op.getOpcode() == ISD::BasicBlock) {
2750       Ops.push_back(Op);
2751       return;
2752     }
2753     LLVM_FALLTHROUGH;
2754   case 'i':    // Simple Integer or Relocatable Constant
2755   case 'n':    // Simple Integer
2756   case 's': {  // Relocatable Constant
2757     // These operands are interested in values of the form (GV+C), where C may
2758     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
2759     // is possible and fine if either GV or C are missing.
2760     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2761     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2762 
2763     // If we have "(add GV, C)", pull out GV/C
2764     if (Op.getOpcode() == ISD::ADD) {
2765       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2766       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2767       if (!C || !GA) {
2768         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2769         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2770       }
2771       if (!C || !GA) {
2772         C = nullptr;
2773         GA = nullptr;
2774       }
2775     }
2776 
2777     // If we find a valid operand, map to the TargetXXX version so that the
2778     // value itself doesn't get selected.
2779     if (GA) {   // Either &GV   or   &GV+C
2780       if (ConstraintLetter != 'n') {
2781         int64_t Offs = GA->getOffset();
2782         if (C) Offs += C->getZExtValue();
2783         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2784                                                  C ? SDLoc(C) : SDLoc(),
2785                                                  Op.getValueType(), Offs));
2786       }
2787       return;
2788     }
2789     if (C) {   // just C, no GV.
2790       // Simple constants are not allowed for 's'.
2791       if (ConstraintLetter != 's') {
2792         // gcc prints these as sign extended.  Sign extend value to 64 bits
2793         // now; without this it would get ZExt'd later in
2794         // ScheduleDAGSDNodes::EmitNode, which is very generic.
2795         Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
2796                                             SDLoc(C), MVT::i64));
2797       }
2798       return;
2799     }
2800     break;
2801   }
2802   }
2803 }
2804 
2805 std::pair<unsigned, const TargetRegisterClass *>
2806 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
2807                                              StringRef Constraint,
2808                                              MVT VT) const {
2809   if (Constraint.empty() || Constraint[0] != '{')
2810     return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
2811   assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2812 
2813   // Remove the braces from around the name.
2814   StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2815 
2816   std::pair<unsigned, const TargetRegisterClass*> R =
2817     std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
2818 
2819   // Figure out which register class contains this reg.
2820   for (const TargetRegisterClass *RC : RI->regclasses()) {
2821     // If none of the value types for this register class are valid, we
2822     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
2823     if (!isLegalRC(*RI, *RC))
2824       continue;
2825 
2826     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2827          I != E; ++I) {
2828       if (RegName.equals_lower(RI->getRegAsmName(*I))) {
2829         std::pair<unsigned, const TargetRegisterClass*> S =
2830           std::make_pair(*I, RC);
2831 
2832         // If this register class has the requested value type, return it,
2833         // otherwise keep searching and return the first class found
2834         // if no other is found which explicitly has the requested type.
2835         if (RI->isTypeLegalForClass(*RC, VT))
2836           return S;
2837         if (!R.second)
2838           R = S;
2839       }
2840     }
2841   }
2842 
2843   return R;
2844 }
2845 
2846 //===----------------------------------------------------------------------===//
2847 // Constraint Selection.
2848 
2849 /// Return true of this is an input operand that is a matching constraint like
2850 /// "4".
2851 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2852   assert(!ConstraintCode.empty() && "No known constraint!");
2853   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
2854 }
2855 
2856 /// If this is an input matching constraint, this method returns the output
2857 /// operand it matches.
2858 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2859   assert(!ConstraintCode.empty() && "No known constraint!");
2860   return atoi(ConstraintCode.c_str());
2861 }
2862 
2863 /// Split up the constraint string from the inline assembly value into the
2864 /// specific constraints and their prefixes, and also tie in the associated
2865 /// operand values.
2866 /// If this returns an empty vector, and if the constraint string itself
2867 /// isn't empty, there was an error parsing.
2868 TargetLowering::AsmOperandInfoVector
2869 TargetLowering::ParseConstraints(const DataLayout &DL,
2870                                  const TargetRegisterInfo *TRI,
2871                                  ImmutableCallSite CS) const {
2872   /// Information about all of the constraints.
2873   AsmOperandInfoVector ConstraintOperands;
2874   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
2875   unsigned maCount = 0; // Largest number of multiple alternative constraints.
2876 
2877   // Do a prepass over the constraints, canonicalizing them, and building up the
2878   // ConstraintOperands list.
2879   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
2880   unsigned ResNo = 0;   // ResNo - The result number of the next output.
2881 
2882   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2883     ConstraintOperands.emplace_back(std::move(CI));
2884     AsmOperandInfo &OpInfo = ConstraintOperands.back();
2885 
2886     // Update multiple alternative constraint count.
2887     if (OpInfo.multipleAlternatives.size() > maCount)
2888       maCount = OpInfo.multipleAlternatives.size();
2889 
2890     OpInfo.ConstraintVT = MVT::Other;
2891 
2892     // Compute the value type for each operand.
2893     switch (OpInfo.Type) {
2894     case InlineAsm::isOutput:
2895       // Indirect outputs just consume an argument.
2896       if (OpInfo.isIndirect) {
2897         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2898         break;
2899       }
2900 
2901       // The return value of the call is this value.  As such, there is no
2902       // corresponding argument.
2903       assert(!CS.getType()->isVoidTy() &&
2904              "Bad inline asm!");
2905       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
2906         OpInfo.ConstraintVT =
2907             getSimpleValueType(DL, STy->getElementType(ResNo));
2908       } else {
2909         assert(ResNo == 0 && "Asm only has one result!");
2910         OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
2911       }
2912       ++ResNo;
2913       break;
2914     case InlineAsm::isInput:
2915       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2916       break;
2917     case InlineAsm::isClobber:
2918       // Nothing to do.
2919       break;
2920     }
2921 
2922     if (OpInfo.CallOperandVal) {
2923       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
2924       if (OpInfo.isIndirect) {
2925         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
2926         if (!PtrTy)
2927           report_fatal_error("Indirect operand for inline asm not a pointer!");
2928         OpTy = PtrTy->getElementType();
2929       }
2930 
2931       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
2932       if (StructType *STy = dyn_cast<StructType>(OpTy))
2933         if (STy->getNumElements() == 1)
2934           OpTy = STy->getElementType(0);
2935 
2936       // If OpTy is not a single value, it may be a struct/union that we
2937       // can tile with integers.
2938       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
2939         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
2940         switch (BitSize) {
2941         default: break;
2942         case 1:
2943         case 8:
2944         case 16:
2945         case 32:
2946         case 64:
2947         case 128:
2948           OpInfo.ConstraintVT =
2949             MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
2950           break;
2951         }
2952       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
2953         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
2954         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
2955       } else {
2956         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
2957       }
2958     }
2959   }
2960 
2961   // If we have multiple alternative constraints, select the best alternative.
2962   if (!ConstraintOperands.empty()) {
2963     if (maCount) {
2964       unsigned bestMAIndex = 0;
2965       int bestWeight = -1;
2966       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
2967       int weight = -1;
2968       unsigned maIndex;
2969       // Compute the sums of the weights for each alternative, keeping track
2970       // of the best (highest weight) one so far.
2971       for (maIndex = 0; maIndex < maCount; ++maIndex) {
2972         int weightSum = 0;
2973         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2974             cIndex != eIndex; ++cIndex) {
2975           AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2976           if (OpInfo.Type == InlineAsm::isClobber)
2977             continue;
2978 
2979           // If this is an output operand with a matching input operand,
2980           // look up the matching input. If their types mismatch, e.g. one
2981           // is an integer, the other is floating point, or their sizes are
2982           // different, flag it as an maCantMatch.
2983           if (OpInfo.hasMatchingInput()) {
2984             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2985             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2986               if ((OpInfo.ConstraintVT.isInteger() !=
2987                    Input.ConstraintVT.isInteger()) ||
2988                   (OpInfo.ConstraintVT.getSizeInBits() !=
2989                    Input.ConstraintVT.getSizeInBits())) {
2990                 weightSum = -1;  // Can't match.
2991                 break;
2992               }
2993             }
2994           }
2995           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2996           if (weight == -1) {
2997             weightSum = -1;
2998             break;
2999           }
3000           weightSum += weight;
3001         }
3002         // Update best.
3003         if (weightSum > bestWeight) {
3004           bestWeight = weightSum;
3005           bestMAIndex = maIndex;
3006         }
3007       }
3008 
3009       // Now select chosen alternative in each constraint.
3010       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3011           cIndex != eIndex; ++cIndex) {
3012         AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
3013         if (cInfo.Type == InlineAsm::isClobber)
3014           continue;
3015         cInfo.selectAlternative(bestMAIndex);
3016       }
3017     }
3018   }
3019 
3020   // Check and hook up tied operands, choose constraint code to use.
3021   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3022       cIndex != eIndex; ++cIndex) {
3023     AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
3024 
3025     // If this is an output operand with a matching input operand, look up the
3026     // matching input. If their types mismatch, e.g. one is an integer, the
3027     // other is floating point, or their sizes are different, flag it as an
3028     // error.
3029     if (OpInfo.hasMatchingInput()) {
3030       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
3031 
3032       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
3033         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
3034             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
3035                                          OpInfo.ConstraintVT);
3036         std::pair<unsigned, const TargetRegisterClass *> InputRC =
3037             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
3038                                          Input.ConstraintVT);
3039         if ((OpInfo.ConstraintVT.isInteger() !=
3040              Input.ConstraintVT.isInteger()) ||
3041             (MatchRC.second != InputRC.second)) {
3042           report_fatal_error("Unsupported asm: input constraint"
3043                              " with a matching output constraint of"
3044                              " incompatible type!");
3045         }
3046       }
3047     }
3048   }
3049 
3050   return ConstraintOperands;
3051 }
3052 
3053 /// Return an integer indicating how general CT is.
3054 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3055   switch (CT) {
3056   case TargetLowering::C_Other:
3057   case TargetLowering::C_Unknown:
3058     return 0;
3059   case TargetLowering::C_Register:
3060     return 1;
3061   case TargetLowering::C_RegisterClass:
3062     return 2;
3063   case TargetLowering::C_Memory:
3064     return 3;
3065   }
3066   llvm_unreachable("Invalid constraint type");
3067 }
3068 
3069 /// Examine constraint type and operand type and determine a weight value.
3070 /// This object must already have been set up with the operand type
3071 /// and the current alternative constraint selected.
3072 TargetLowering::ConstraintWeight
3073   TargetLowering::getMultipleConstraintMatchWeight(
3074     AsmOperandInfo &info, int maIndex) const {
3075   InlineAsm::ConstraintCodeVector *rCodes;
3076   if (maIndex >= (int)info.multipleAlternatives.size())
3077     rCodes = &info.Codes;
3078   else
3079     rCodes = &info.multipleAlternatives[maIndex].Codes;
3080   ConstraintWeight BestWeight = CW_Invalid;
3081 
3082   // Loop over the options, keeping track of the most general one.
3083   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
3084     ConstraintWeight weight =
3085       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
3086     if (weight > BestWeight)
3087       BestWeight = weight;
3088   }
3089 
3090   return BestWeight;
3091 }
3092 
3093 /// Examine constraint type and operand type and determine a weight value.
3094 /// This object must already have been set up with the operand type
3095 /// and the current alternative constraint selected.
3096 TargetLowering::ConstraintWeight
3097   TargetLowering::getSingleConstraintMatchWeight(
3098     AsmOperandInfo &info, const char *constraint) const {
3099   ConstraintWeight weight = CW_Invalid;
3100   Value *CallOperandVal = info.CallOperandVal;
3101     // If we don't have a value, we can't do a match,
3102     // but allow it at the lowest weight.
3103   if (!CallOperandVal)
3104     return CW_Default;
3105   // Look at the constraint type.
3106   switch (*constraint) {
3107     case 'i': // immediate integer.
3108     case 'n': // immediate integer with a known value.
3109       if (isa<ConstantInt>(CallOperandVal))
3110         weight = CW_Constant;
3111       break;
3112     case 's': // non-explicit intregal immediate.
3113       if (isa<GlobalValue>(CallOperandVal))
3114         weight = CW_Constant;
3115       break;
3116     case 'E': // immediate float if host format.
3117     case 'F': // immediate float.
3118       if (isa<ConstantFP>(CallOperandVal))
3119         weight = CW_Constant;
3120       break;
3121     case '<': // memory operand with autodecrement.
3122     case '>': // memory operand with autoincrement.
3123     case 'm': // memory operand.
3124     case 'o': // offsettable memory operand
3125     case 'V': // non-offsettable memory operand
3126       weight = CW_Memory;
3127       break;
3128     case 'r': // general register.
3129     case 'g': // general register, memory operand or immediate integer.
3130               // note: Clang converts "g" to "imr".
3131       if (CallOperandVal->getType()->isIntegerTy())
3132         weight = CW_Register;
3133       break;
3134     case 'X': // any operand.
3135     default:
3136       weight = CW_Default;
3137       break;
3138   }
3139   return weight;
3140 }
3141 
3142 /// If there are multiple different constraints that we could pick for this
3143 /// operand (e.g. "imr") try to pick the 'best' one.
3144 /// This is somewhat tricky: constraints fall into four classes:
3145 ///    Other         -> immediates and magic values
3146 ///    Register      -> one specific register
3147 ///    RegisterClass -> a group of regs
3148 ///    Memory        -> memory
3149 /// Ideally, we would pick the most specific constraint possible: if we have
3150 /// something that fits into a register, we would pick it.  The problem here
3151 /// is that if we have something that could either be in a register or in
3152 /// memory that use of the register could cause selection of *other*
3153 /// operands to fail: they might only succeed if we pick memory.  Because of
3154 /// this the heuristic we use is:
3155 ///
3156 ///  1) If there is an 'other' constraint, and if the operand is valid for
3157 ///     that constraint, use it.  This makes us take advantage of 'i'
3158 ///     constraints when available.
3159 ///  2) Otherwise, pick the most general constraint present.  This prefers
3160 ///     'm' over 'r', for example.
3161 ///
3162 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
3163                              const TargetLowering &TLI,
3164                              SDValue Op, SelectionDAG *DAG) {
3165   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
3166   unsigned BestIdx = 0;
3167   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
3168   int BestGenerality = -1;
3169 
3170   // Loop over the options, keeping track of the most general one.
3171   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
3172     TargetLowering::ConstraintType CType =
3173       TLI.getConstraintType(OpInfo.Codes[i]);
3174 
3175     // If this is an 'other' constraint, see if the operand is valid for it.
3176     // For example, on X86 we might have an 'rI' constraint.  If the operand
3177     // is an integer in the range [0..31] we want to use I (saving a load
3178     // of a register), otherwise we must use 'r'.
3179     if (CType == TargetLowering::C_Other && Op.getNode()) {
3180       assert(OpInfo.Codes[i].size() == 1 &&
3181              "Unhandled multi-letter 'other' constraint");
3182       std::vector<SDValue> ResultOps;
3183       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
3184                                        ResultOps, *DAG);
3185       if (!ResultOps.empty()) {
3186         BestType = CType;
3187         BestIdx = i;
3188         break;
3189       }
3190     }
3191 
3192     // Things with matching constraints can only be registers, per gcc
3193     // documentation.  This mainly affects "g" constraints.
3194     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
3195       continue;
3196 
3197     // This constraint letter is more general than the previous one, use it.
3198     int Generality = getConstraintGenerality(CType);
3199     if (Generality > BestGenerality) {
3200       BestType = CType;
3201       BestIdx = i;
3202       BestGenerality = Generality;
3203     }
3204   }
3205 
3206   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
3207   OpInfo.ConstraintType = BestType;
3208 }
3209 
3210 /// Determines the constraint code and constraint type to use for the specific
3211 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
3212 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
3213                                             SDValue Op,
3214                                             SelectionDAG *DAG) const {
3215   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
3216 
3217   // Single-letter constraints ('r') are very common.
3218   if (OpInfo.Codes.size() == 1) {
3219     OpInfo.ConstraintCode = OpInfo.Codes[0];
3220     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
3221   } else {
3222     ChooseConstraint(OpInfo, *this, Op, DAG);
3223   }
3224 
3225   // 'X' matches anything.
3226   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
3227     // Labels and constants are handled elsewhere ('X' is the only thing
3228     // that matches labels).  For Functions, the type here is the type of
3229     // the result, which is not what we want to look at; leave them alone.
3230     Value *v = OpInfo.CallOperandVal;
3231     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
3232       OpInfo.CallOperandVal = v;
3233       return;
3234     }
3235 
3236     // Otherwise, try to resolve it to something we know about by looking at
3237     // the actual operand type.
3238     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
3239       OpInfo.ConstraintCode = Repl;
3240       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
3241     }
3242   }
3243 }
3244 
3245 /// \brief Given an exact SDIV by a constant, create a multiplication
3246 /// with the multiplicative inverse of the constant.
3247 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
3248                               const SDLoc &dl, SelectionDAG &DAG,
3249                               std::vector<SDNode *> &Created) {
3250   assert(d != 0 && "Division by zero!");
3251 
3252   // Shift the value upfront if it is even, so the LSB is one.
3253   unsigned ShAmt = d.countTrailingZeros();
3254   if (ShAmt) {
3255     // TODO: For UDIV use SRL instead of SRA.
3256     SDValue Amt =
3257         DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(),
3258                                                         DAG.getDataLayout()));
3259     SDNodeFlags Flags;
3260     Flags.setExact(true);
3261     Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, Flags);
3262     Created.push_back(Op1.getNode());
3263     d.ashrInPlace(ShAmt);
3264   }
3265 
3266   // Calculate the multiplicative inverse, using Newton's method.
3267   APInt t, xn = d;
3268   while ((t = d*xn) != 1)
3269     xn *= APInt(d.getBitWidth(), 2) - t;
3270 
3271   SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
3272   SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
3273   Created.push_back(Mul.getNode());
3274   return Mul;
3275 }
3276 
3277 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
3278                                       SelectionDAG &DAG,
3279                                       std::vector<SDNode *> *Created) const {
3280   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3281   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3282   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
3283     return SDValue(N,0); // Lower SDIV as SDIV
3284   return SDValue();
3285 }
3286 
3287 /// \brief Given an ISD::SDIV node expressing a divide by constant,
3288 /// return a DAG expression to select that will generate the same value by
3289 /// multiplying by a magic number.
3290 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
3291 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
3292                                   SelectionDAG &DAG, bool IsAfterLegalization,
3293                                   std::vector<SDNode *> *Created) const {
3294   assert(Created && "No vector to hold sdiv ops.");
3295 
3296   EVT VT = N->getValueType(0);
3297   SDLoc dl(N);
3298 
3299   // Check to see if we can do this.
3300   // FIXME: We should be more aggressive here.
3301   if (!isTypeLegal(VT))
3302     return SDValue();
3303 
3304   // If the sdiv has an 'exact' bit we can use a simpler lowering.
3305   if (N->getFlags().hasExact())
3306     return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
3307 
3308   APInt::ms magics = Divisor.magic();
3309 
3310   // Multiply the numerator (operand 0) by the magic value
3311   // FIXME: We should support doing a MUL in a wider type
3312   SDValue Q;
3313   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
3314                             isOperationLegalOrCustom(ISD::MULHS, VT))
3315     Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
3316                     DAG.getConstant(magics.m, dl, VT));
3317   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
3318                                  isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
3319     Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
3320                               N->getOperand(0),
3321                               DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
3322   else
3323     return SDValue();       // No mulhs or equvialent
3324   // If d > 0 and m < 0, add the numerator
3325   if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
3326     Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
3327     Created->push_back(Q.getNode());
3328   }
3329   // If d < 0 and m > 0, subtract the numerator.
3330   if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
3331     Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
3332     Created->push_back(Q.getNode());
3333   }
3334   auto &DL = DAG.getDataLayout();
3335   // Shift right algebraic if shift value is nonzero
3336   if (magics.s > 0) {
3337     Q = DAG.getNode(
3338         ISD::SRA, dl, VT, Q,
3339         DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
3340     Created->push_back(Q.getNode());
3341   }
3342   // Extract the sign bit and add it to the quotient
3343   SDValue T =
3344       DAG.getNode(ISD::SRL, dl, VT, Q,
3345                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
3346                                   getShiftAmountTy(Q.getValueType(), DL)));
3347   Created->push_back(T.getNode());
3348   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
3349 }
3350 
3351 /// \brief Given an ISD::UDIV node expressing a divide by constant,
3352 /// return a DAG expression to select that will generate the same value by
3353 /// multiplying by a magic number.
3354 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
3355 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
3356                                   SelectionDAG &DAG, bool IsAfterLegalization,
3357                                   std::vector<SDNode *> *Created) const {
3358   assert(Created && "No vector to hold udiv ops.");
3359 
3360   EVT VT = N->getValueType(0);
3361   SDLoc dl(N);
3362   auto &DL = DAG.getDataLayout();
3363 
3364   // Check to see if we can do this.
3365   // FIXME: We should be more aggressive here.
3366   if (!isTypeLegal(VT))
3367     return SDValue();
3368 
3369   // FIXME: We should use a narrower constant when the upper
3370   // bits are known to be zero.
3371   APInt::mu magics = Divisor.magicu();
3372 
3373   SDValue Q = N->getOperand(0);
3374 
3375   // If the divisor is even, we can avoid using the expensive fixup by shifting
3376   // the divided value upfront.
3377   if (magics.a != 0 && !Divisor[0]) {
3378     unsigned Shift = Divisor.countTrailingZeros();
3379     Q = DAG.getNode(
3380         ISD::SRL, dl, VT, Q,
3381         DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL)));
3382     Created->push_back(Q.getNode());
3383 
3384     // Get magic number for the shifted divisor.
3385     magics = Divisor.lshr(Shift).magicu(Shift);
3386     assert(magics.a == 0 && "Should use cheap fixup now");
3387   }
3388 
3389   // Multiply the numerator (operand 0) by the magic value
3390   // FIXME: We should support doing a MUL in a wider type
3391   if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
3392                             isOperationLegalOrCustom(ISD::MULHU, VT))
3393     Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
3394   else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
3395                                  isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
3396     Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
3397                             DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
3398   else
3399     return SDValue();       // No mulhu or equivalent
3400 
3401   Created->push_back(Q.getNode());
3402 
3403   if (magics.a == 0) {
3404     assert(magics.s < Divisor.getBitWidth() &&
3405            "We shouldn't generate an undefined shift!");
3406     return DAG.getNode(
3407         ISD::SRL, dl, VT, Q,
3408         DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
3409   } else {
3410     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
3411     Created->push_back(NPQ.getNode());
3412     NPQ = DAG.getNode(
3413         ISD::SRL, dl, VT, NPQ,
3414         DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL)));
3415     Created->push_back(NPQ.getNode());
3416     NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
3417     Created->push_back(NPQ.getNode());
3418     return DAG.getNode(
3419         ISD::SRL, dl, VT, NPQ,
3420         DAG.getConstant(magics.s - 1, dl,
3421                         getShiftAmountTy(NPQ.getValueType(), DL)));
3422   }
3423 }
3424 
3425 bool TargetLowering::
3426 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
3427   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
3428     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
3429                                 "be a constant integer");
3430     return true;
3431   }
3432 
3433   return false;
3434 }
3435 
3436 //===----------------------------------------------------------------------===//
3437 // Legalization Utilities
3438 //===----------------------------------------------------------------------===//
3439 
3440 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl,
3441                                     SDValue LHS, SDValue RHS,
3442                                     SmallVectorImpl<SDValue> &Result,
3443                                     EVT HiLoVT, SelectionDAG &DAG,
3444                                     MulExpansionKind Kind, SDValue LL,
3445                                     SDValue LH, SDValue RL, SDValue RH) const {
3446   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
3447          Opcode == ISD::SMUL_LOHI);
3448 
3449   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
3450                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
3451   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
3452                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
3453   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
3454                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
3455   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
3456                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
3457 
3458   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
3459     return false;
3460 
3461   unsigned OuterBitSize = VT.getScalarSizeInBits();
3462   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
3463   unsigned LHSSB = DAG.ComputeNumSignBits(LHS);
3464   unsigned RHSSB = DAG.ComputeNumSignBits(RHS);
3465 
3466   // LL, LH, RL, and RH must be either all NULL or all set to a value.
3467   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
3468          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
3469 
3470   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
3471   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
3472                           bool Signed) -> bool {
3473     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
3474       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
3475       Hi = SDValue(Lo.getNode(), 1);
3476       return true;
3477     }
3478     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
3479       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
3480       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
3481       return true;
3482     }
3483     return false;
3484   };
3485 
3486   SDValue Lo, Hi;
3487 
3488   if (!LL.getNode() && !RL.getNode() &&
3489       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3490     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
3491     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
3492   }
3493 
3494   if (!LL.getNode())
3495     return false;
3496 
3497   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
3498   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
3499       DAG.MaskedValueIsZero(RHS, HighMask)) {
3500     // The inputs are both zero-extended.
3501     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
3502       Result.push_back(Lo);
3503       Result.push_back(Hi);
3504       if (Opcode != ISD::MUL) {
3505         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
3506         Result.push_back(Zero);
3507         Result.push_back(Zero);
3508       }
3509       return true;
3510     }
3511   }
3512 
3513   if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize &&
3514       RHSSB > InnerBitSize) {
3515     // The input values are both sign-extended.
3516     // TODO non-MUL case?
3517     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
3518       Result.push_back(Lo);
3519       Result.push_back(Hi);
3520       return true;
3521     }
3522   }
3523 
3524   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
3525   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
3526   if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) {
3527     // FIXME getShiftAmountTy does not always return a sensible result when VT
3528     // is an illegal type, and so the type may be too small to fit the shift
3529     // amount. Override it with i32. The shift will have to be legalized.
3530     ShiftAmountTy = MVT::i32;
3531   }
3532   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
3533 
3534   if (!LH.getNode() && !RH.getNode() &&
3535       isOperationLegalOrCustom(ISD::SRL, VT) &&
3536       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3537     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
3538     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
3539     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
3540     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
3541   }
3542 
3543   if (!LH.getNode())
3544     return false;
3545 
3546   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
3547     return false;
3548 
3549   Result.push_back(Lo);
3550 
3551   if (Opcode == ISD::MUL) {
3552     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3553     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3554     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3555     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3556     Result.push_back(Hi);
3557     return true;
3558   }
3559 
3560   // Compute the full width result.
3561   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
3562     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3563     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
3564     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3565     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
3566   };
3567 
3568   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
3569   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
3570     return false;
3571 
3572   // This is effectively the add part of a multiply-add of half-sized operands,
3573   // so it cannot overflow.
3574   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
3575 
3576   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
3577     return false;
3578 
3579   Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
3580                      Merge(Lo, Hi));
3581 
3582   SDValue Carry = Next.getValue(1);
3583   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3584   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
3585 
3586   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
3587     return false;
3588 
3589   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
3590   Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
3591                    Carry);
3592   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
3593 
3594   if (Opcode == ISD::SMUL_LOHI) {
3595     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
3596                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
3597     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
3598 
3599     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
3600                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
3601     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
3602   }
3603 
3604   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3605   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
3606   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3607   return true;
3608 }
3609 
3610 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
3611                                SelectionDAG &DAG, MulExpansionKind Kind,
3612                                SDValue LL, SDValue LH, SDValue RL,
3613                                SDValue RH) const {
3614   SmallVector<SDValue, 2> Result;
3615   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N,
3616                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
3617                            DAG, Kind, LL, LH, RL, RH);
3618   if (Ok) {
3619     assert(Result.size() == 2);
3620     Lo = Result[0];
3621     Hi = Result[1];
3622   }
3623   return Ok;
3624 }
3625 
3626 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
3627                                SelectionDAG &DAG) const {
3628   EVT VT = Node->getOperand(0).getValueType();
3629   EVT NVT = Node->getValueType(0);
3630   SDLoc dl(SDValue(Node, 0));
3631 
3632   // FIXME: Only f32 to i64 conversions are supported.
3633   if (VT != MVT::f32 || NVT != MVT::i64)
3634     return false;
3635 
3636   // Expand f32 -> i64 conversion
3637   // This algorithm comes from compiler-rt's implementation of fixsfdi:
3638   // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
3639   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
3640                                 VT.getSizeInBits());
3641   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
3642   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
3643   SDValue Bias = DAG.getConstant(127, dl, IntVT);
3644   SDValue SignMask = DAG.getConstant(APInt::getSignMask(VT.getSizeInBits()), dl,
3645                                      IntVT);
3646   SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
3647   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
3648 
3649   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
3650 
3651   auto &DL = DAG.getDataLayout();
3652   SDValue ExponentBits = DAG.getNode(
3653       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
3654       DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL)));
3655   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
3656 
3657   SDValue Sign = DAG.getNode(
3658       ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
3659       DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL)));
3660   Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
3661 
3662   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
3663       DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
3664       DAG.getConstant(0x00800000, dl, IntVT));
3665 
3666   R = DAG.getZExtOrTrunc(R, dl, NVT);
3667 
3668   R = DAG.getSelectCC(
3669       dl, Exponent, ExponentLoBit,
3670       DAG.getNode(ISD::SHL, dl, NVT, R,
3671                   DAG.getZExtOrTrunc(
3672                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
3673                       dl, getShiftAmountTy(IntVT, DL))),
3674       DAG.getNode(ISD::SRL, dl, NVT, R,
3675                   DAG.getZExtOrTrunc(
3676                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
3677                       dl, getShiftAmountTy(IntVT, DL))),
3678       ISD::SETGT);
3679 
3680   SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
3681       DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
3682       Sign);
3683 
3684   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
3685       DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
3686   return true;
3687 }
3688 
3689 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
3690                                             SelectionDAG &DAG) const {
3691   SDLoc SL(LD);
3692   SDValue Chain = LD->getChain();
3693   SDValue BasePTR = LD->getBasePtr();
3694   EVT SrcVT = LD->getMemoryVT();
3695   ISD::LoadExtType ExtType = LD->getExtensionType();
3696 
3697   unsigned NumElem = SrcVT.getVectorNumElements();
3698 
3699   EVT SrcEltVT = SrcVT.getScalarType();
3700   EVT DstEltVT = LD->getValueType(0).getScalarType();
3701 
3702   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
3703   assert(SrcEltVT.isByteSized());
3704 
3705   EVT PtrVT = BasePTR.getValueType();
3706 
3707   SmallVector<SDValue, 8> Vals;
3708   SmallVector<SDValue, 8> LoadChains;
3709 
3710   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3711     SDValue ScalarLoad =
3712         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
3713                        LD->getPointerInfo().getWithOffset(Idx * Stride),
3714                        SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
3715                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
3716 
3717     BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR,
3718                           DAG.getConstant(Stride, SL, PtrVT));
3719 
3720     Vals.push_back(ScalarLoad.getValue(0));
3721     LoadChains.push_back(ScalarLoad.getValue(1));
3722   }
3723 
3724   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
3725   SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals);
3726 
3727   return DAG.getMergeValues({ Value, NewChain }, SL);
3728 }
3729 
3730 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
3731                                              SelectionDAG &DAG) const {
3732   SDLoc SL(ST);
3733 
3734   SDValue Chain = ST->getChain();
3735   SDValue BasePtr = ST->getBasePtr();
3736   SDValue Value = ST->getValue();
3737   EVT StVT = ST->getMemoryVT();
3738 
3739   // The type of the data we want to save
3740   EVT RegVT = Value.getValueType();
3741   EVT RegSclVT = RegVT.getScalarType();
3742 
3743   // The type of data as saved in memory.
3744   EVT MemSclVT = StVT.getScalarType();
3745 
3746   EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
3747   unsigned NumElem = StVT.getVectorNumElements();
3748 
3749   // A vector must always be stored in memory as-is, i.e. without any padding
3750   // between the elements, since various code depend on it, e.g. in the
3751   // handling of a bitcast of a vector type to int, which may be done with a
3752   // vector store followed by an integer load. A vector that does not have
3753   // elements that are byte-sized must therefore be stored as an integer
3754   // built out of the extracted vector elements.
3755   if (!MemSclVT.isByteSized()) {
3756     unsigned NumBits = StVT.getSizeInBits();
3757     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
3758 
3759     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
3760 
3761     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3762       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
3763                                 DAG.getConstant(Idx, SL, IdxVT));
3764       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
3765       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
3766       unsigned ShiftIntoIdx =
3767           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
3768       SDValue ShiftAmount =
3769           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
3770       SDValue ShiftedElt =
3771           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
3772       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
3773     }
3774 
3775     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
3776                         ST->getAlignment(), ST->getMemOperand()->getFlags(),
3777                         ST->getAAInfo());
3778   }
3779 
3780   // Store Stride in bytes
3781   unsigned Stride = MemSclVT.getSizeInBits() / 8;
3782   assert (Stride && "Zero stride!");
3783   // Extract each of the elements from the original vector and save them into
3784   // memory individually.
3785   SmallVector<SDValue, 8> Stores;
3786   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3787     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
3788                               DAG.getConstant(Idx, SL, IdxVT));
3789 
3790     SDValue Ptr = DAG.getObjectPtrOffset(SL, BasePtr, Idx * Stride);
3791 
3792     // This scalar TruncStore may be illegal, but we legalize it later.
3793     SDValue Store = DAG.getTruncStore(
3794         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
3795         MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
3796         ST->getMemOperand()->getFlags(), ST->getAAInfo());
3797 
3798     Stores.push_back(Store);
3799   }
3800 
3801   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
3802 }
3803 
3804 std::pair<SDValue, SDValue>
3805 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
3806   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
3807          "unaligned indexed loads not implemented!");
3808   SDValue Chain = LD->getChain();
3809   SDValue Ptr = LD->getBasePtr();
3810   EVT VT = LD->getValueType(0);
3811   EVT LoadedVT = LD->getMemoryVT();
3812   SDLoc dl(LD);
3813   auto &MF = DAG.getMachineFunction();
3814 
3815   if (VT.isFloatingPoint() || VT.isVector()) {
3816     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
3817     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
3818       if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) {
3819         // Scalarize the load and let the individual components be handled.
3820         SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
3821         return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
3822       }
3823 
3824       // Expand to a (misaligned) integer load of the same size,
3825       // then bitconvert to floating point or vector.
3826       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
3827                                     LD->getMemOperand());
3828       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
3829       if (LoadedVT != VT)
3830         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
3831                              ISD::ANY_EXTEND, dl, VT, Result);
3832 
3833       return std::make_pair(Result, newLoad.getValue(1));
3834     }
3835 
3836     // Copy the value to a (aligned) stack slot using (unaligned) integer
3837     // loads and stores, then do a (aligned) load from the stack slot.
3838     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
3839     unsigned LoadedBytes = LoadedVT.getStoreSize();
3840     unsigned RegBytes = RegVT.getSizeInBits() / 8;
3841     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
3842 
3843     // Make sure the stack slot is also aligned for the register type.
3844     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
3845     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
3846     SmallVector<SDValue, 8> Stores;
3847     SDValue StackPtr = StackBase;
3848     unsigned Offset = 0;
3849 
3850     EVT PtrVT = Ptr.getValueType();
3851     EVT StackPtrVT = StackPtr.getValueType();
3852 
3853     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3854     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3855 
3856     // Do all but one copies using the full register width.
3857     for (unsigned i = 1; i < NumRegs; i++) {
3858       // Load one integer register's worth from the original location.
3859       SDValue Load = DAG.getLoad(
3860           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
3861           MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
3862           LD->getAAInfo());
3863       // Follow the load with a store to the stack slot.  Remember the store.
3864       Stores.push_back(DAG.getStore(
3865           Load.getValue(1), dl, Load, StackPtr,
3866           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
3867       // Increment the pointers.
3868       Offset += RegBytes;
3869 
3870       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
3871       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
3872     }
3873 
3874     // The last copy may be partial.  Do an extending load.
3875     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3876                                   8 * (LoadedBytes - Offset));
3877     SDValue Load =
3878         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
3879                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
3880                        MinAlign(LD->getAlignment(), Offset),
3881                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
3882     // Follow the load with a store to the stack slot.  Remember the store.
3883     // On big-endian machines this requires a truncating store to ensure
3884     // that the bits end up in the right place.
3885     Stores.push_back(DAG.getTruncStore(
3886         Load.getValue(1), dl, Load, StackPtr,
3887         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
3888 
3889     // The order of the stores doesn't matter - say it with a TokenFactor.
3890     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3891 
3892     // Finally, perform the original load only redirected to the stack slot.
3893     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
3894                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
3895                           LoadedVT);
3896 
3897     // Callers expect a MERGE_VALUES node.
3898     return std::make_pair(Load, TF);
3899   }
3900 
3901   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
3902          "Unaligned load of unsupported type.");
3903 
3904   // Compute the new VT that is half the size of the old one.  This is an
3905   // integer MVT.
3906   unsigned NumBits = LoadedVT.getSizeInBits();
3907   EVT NewLoadedVT;
3908   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
3909   NumBits >>= 1;
3910 
3911   unsigned Alignment = LD->getAlignment();
3912   unsigned IncrementSize = NumBits / 8;
3913   ISD::LoadExtType HiExtType = LD->getExtensionType();
3914 
3915   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
3916   if (HiExtType == ISD::NON_EXTLOAD)
3917     HiExtType = ISD::ZEXTLOAD;
3918 
3919   // Load the value in two parts
3920   SDValue Lo, Hi;
3921   if (DAG.getDataLayout().isLittleEndian()) {
3922     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3923                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3924                         LD->getAAInfo());
3925 
3926     Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
3927     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
3928                         LD->getPointerInfo().getWithOffset(IncrementSize),
3929                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
3930                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
3931   } else {
3932     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3933                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3934                         LD->getAAInfo());
3935 
3936     Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
3937     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
3938                         LD->getPointerInfo().getWithOffset(IncrementSize),
3939                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
3940                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
3941   }
3942 
3943   // aggregate the two parts
3944   SDValue ShiftAmount =
3945       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
3946                                                     DAG.getDataLayout()));
3947   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
3948   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
3949 
3950   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
3951                              Hi.getValue(1));
3952 
3953   return std::make_pair(Result, TF);
3954 }
3955 
3956 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
3957                                              SelectionDAG &DAG) const {
3958   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
3959          "unaligned indexed stores not implemented!");
3960   SDValue Chain = ST->getChain();
3961   SDValue Ptr = ST->getBasePtr();
3962   SDValue Val = ST->getValue();
3963   EVT VT = Val.getValueType();
3964   int Alignment = ST->getAlignment();
3965   auto &MF = DAG.getMachineFunction();
3966 
3967   SDLoc dl(ST);
3968   if (ST->getMemoryVT().isFloatingPoint() ||
3969       ST->getMemoryVT().isVector()) {
3970     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
3971     if (isTypeLegal(intVT)) {
3972       if (!isOperationLegalOrCustom(ISD::STORE, intVT)) {
3973         // Scalarize the store and let the individual components be handled.
3974         SDValue Result = scalarizeVectorStore(ST, DAG);
3975 
3976         return Result;
3977       }
3978       // Expand to a bitconvert of the value to the integer type of the
3979       // same size, then a (misaligned) int store.
3980       // FIXME: Does not handle truncating floating point stores!
3981       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
3982       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
3983                             Alignment, ST->getMemOperand()->getFlags());
3984       return Result;
3985     }
3986     // Do a (aligned) store to a stack slot, then copy from the stack slot
3987     // to the final destination using (unaligned) integer loads and stores.
3988     EVT StoredVT = ST->getMemoryVT();
3989     MVT RegVT =
3990       getRegisterType(*DAG.getContext(),
3991                       EVT::getIntegerVT(*DAG.getContext(),
3992                                         StoredVT.getSizeInBits()));
3993     EVT PtrVT = Ptr.getValueType();
3994     unsigned StoredBytes = StoredVT.getStoreSize();
3995     unsigned RegBytes = RegVT.getSizeInBits() / 8;
3996     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
3997 
3998     // Make sure the stack slot is also aligned for the register type.
3999     SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
4000     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
4001 
4002     // Perform the original store, only redirected to the stack slot.
4003     SDValue Store = DAG.getTruncStore(
4004         Chain, dl, Val, StackPtr,
4005         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoredVT);
4006 
4007     EVT StackPtrVT = StackPtr.getValueType();
4008 
4009     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
4010     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
4011     SmallVector<SDValue, 8> Stores;
4012     unsigned Offset = 0;
4013 
4014     // Do all but one copies using the full register width.
4015     for (unsigned i = 1; i < NumRegs; i++) {
4016       // Load one integer register's worth from the stack slot.
4017       SDValue Load = DAG.getLoad(
4018           RegVT, dl, Store, StackPtr,
4019           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
4020       // Store it to the final location.  Remember the store.
4021       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
4022                                     ST->getPointerInfo().getWithOffset(Offset),
4023                                     MinAlign(ST->getAlignment(), Offset),
4024                                     ST->getMemOperand()->getFlags()));
4025       // Increment the pointers.
4026       Offset += RegBytes;
4027       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
4028       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
4029     }
4030 
4031     // The last store may be partial.  Do a truncating store.  On big-endian
4032     // machines this requires an extending load from the stack slot to ensure
4033     // that the bits are in the right place.
4034     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
4035                                   8 * (StoredBytes - Offset));
4036 
4037     // Load from the stack slot.
4038     SDValue Load = DAG.getExtLoad(
4039         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
4040         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT);
4041 
4042     Stores.push_back(
4043         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
4044                           ST->getPointerInfo().getWithOffset(Offset), MemVT,
4045                           MinAlign(ST->getAlignment(), Offset),
4046                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
4047     // The order of the stores doesn't matter - say it with a TokenFactor.
4048     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
4049     return Result;
4050   }
4051 
4052   assert(ST->getMemoryVT().isInteger() &&
4053          !ST->getMemoryVT().isVector() &&
4054          "Unaligned store of unknown type.");
4055   // Get the half-size VT
4056   EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
4057   int NumBits = NewStoredVT.getSizeInBits();
4058   int IncrementSize = NumBits / 8;
4059 
4060   // Divide the stored value in two parts.
4061   SDValue ShiftAmount =
4062       DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
4063                                                     DAG.getDataLayout()));
4064   SDValue Lo = Val;
4065   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
4066 
4067   // Store the two parts
4068   SDValue Store1, Store2;
4069   Store1 = DAG.getTruncStore(Chain, dl,
4070                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
4071                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
4072                              ST->getMemOperand()->getFlags());
4073 
4074   Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
4075   Alignment = MinAlign(Alignment, IncrementSize);
4076   Store2 = DAG.getTruncStore(
4077       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
4078       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
4079       ST->getMemOperand()->getFlags(), ST->getAAInfo());
4080 
4081   SDValue Result =
4082     DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
4083   return Result;
4084 }
4085 
4086 SDValue
4087 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
4088                                        const SDLoc &DL, EVT DataVT,
4089                                        SelectionDAG &DAG,
4090                                        bool IsCompressedMemory) const {
4091   SDValue Increment;
4092   EVT AddrVT = Addr.getValueType();
4093   EVT MaskVT = Mask.getValueType();
4094   assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() &&
4095          "Incompatible types of Data and Mask");
4096   if (IsCompressedMemory) {
4097     // Incrementing the pointer according to number of '1's in the mask.
4098     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
4099     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
4100     if (MaskIntVT.getSizeInBits() < 32) {
4101       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
4102       MaskIntVT = MVT::i32;
4103     }
4104 
4105     // Count '1's with POPCNT.
4106     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
4107     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
4108     // Scale is an element size in bytes.
4109     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
4110                                     AddrVT);
4111     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
4112   } else
4113     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
4114 
4115   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
4116 }
4117 
4118 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG,
4119                                        SDValue Idx,
4120                                        EVT VecVT,
4121                                        const SDLoc &dl) {
4122   if (isa<ConstantSDNode>(Idx))
4123     return Idx;
4124 
4125   EVT IdxVT = Idx.getValueType();
4126   unsigned NElts = VecVT.getVectorNumElements();
4127   if (isPowerOf2_32(NElts)) {
4128     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(),
4129                                      Log2_32(NElts));
4130     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
4131                        DAG.getConstant(Imm, dl, IdxVT));
4132   }
4133 
4134   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
4135                      DAG.getConstant(NElts - 1, dl, IdxVT));
4136 }
4137 
4138 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
4139                                                 SDValue VecPtr, EVT VecVT,
4140                                                 SDValue Index) const {
4141   SDLoc dl(Index);
4142   // Make sure the index type is big enough to compute in.
4143   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
4144 
4145   EVT EltVT = VecVT.getVectorElementType();
4146 
4147   // Calculate the element offset and add it to the pointer.
4148   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
4149   assert(EltSize * 8 == EltVT.getSizeInBits() &&
4150          "Converting bits to bytes lost precision");
4151 
4152   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl);
4153 
4154   EVT IdxVT = Index.getValueType();
4155 
4156   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
4157                       DAG.getConstant(EltSize, dl, IdxVT));
4158   return DAG.getNode(ISD::ADD, dl, IdxVT, VecPtr, Index);
4159 }
4160 
4161 //===----------------------------------------------------------------------===//
4162 // Implementation of Emulated TLS Model
4163 //===----------------------------------------------------------------------===//
4164 
4165 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
4166                                                 SelectionDAG &DAG) const {
4167   // Access to address of TLS varialbe xyz is lowered to a function call:
4168   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
4169   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4170   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
4171   SDLoc dl(GA);
4172 
4173   ArgListTy Args;
4174   ArgListEntry Entry;
4175   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
4176   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
4177   StringRef EmuTlsVarName(NameString);
4178   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
4179   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
4180   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
4181   Entry.Ty = VoidPtrType;
4182   Args.push_back(Entry);
4183 
4184   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
4185 
4186   TargetLowering::CallLoweringInfo CLI(DAG);
4187   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
4188   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
4189   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
4190 
4191   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
4192   // At last for X86 targets, maybe good for other targets too?
4193   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4194   MFI.setAdjustsStack(true);  // Is this only for X86 target?
4195   MFI.setHasCalls(true);
4196 
4197   assert((GA->getOffset() == 0) &&
4198          "Emulated TLS must have zero offset in GlobalAddressSDNode");
4199   return CallResult.first;
4200 }
4201 
4202 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
4203                                                 SelectionDAG &DAG) const {
4204   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
4205   if (!isCtlzFast())
4206     return SDValue();
4207   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4208   SDLoc dl(Op);
4209   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
4210     if (C->isNullValue() && CC == ISD::SETEQ) {
4211       EVT VT = Op.getOperand(0).getValueType();
4212       SDValue Zext = Op.getOperand(0);
4213       if (VT.bitsLT(MVT::i32)) {
4214         VT = MVT::i32;
4215         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
4216       }
4217       unsigned Log2b = Log2_32(VT.getSizeInBits());
4218       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
4219       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
4220                                 DAG.getConstant(Log2b, dl, MVT::i32));
4221       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
4222     }
4223   }
4224   return SDValue();
4225 }
4226