OSDN Git Service

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