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