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