1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Target/TargetLowering.h"
15 #include "llvm/Target/TargetData.h"
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/Target/MRegisterInfo.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Target/TargetAsmInfo.h"
26 /// InitLibcallNames - Set default libcall names.
28 static void InitLibcallNames(const char **Names) {
29 Names[RTLIB::SHL_I32] = "__ashlsi3";
30 Names[RTLIB::SHL_I64] = "__ashldi3";
31 Names[RTLIB::SRL_I32] = "__lshrsi3";
32 Names[RTLIB::SRL_I64] = "__lshrdi3";
33 Names[RTLIB::SRA_I32] = "__ashrsi3";
34 Names[RTLIB::SRA_I64] = "__ashrdi3";
35 Names[RTLIB::MUL_I32] = "__mulsi3";
36 Names[RTLIB::MUL_I64] = "__muldi3";
37 Names[RTLIB::SDIV_I32] = "__divsi3";
38 Names[RTLIB::SDIV_I64] = "__divdi3";
39 Names[RTLIB::UDIV_I32] = "__udivsi3";
40 Names[RTLIB::UDIV_I64] = "__udivdi3";
41 Names[RTLIB::SREM_I32] = "__modsi3";
42 Names[RTLIB::SREM_I64] = "__moddi3";
43 Names[RTLIB::UREM_I32] = "__umodsi3";
44 Names[RTLIB::UREM_I64] = "__umoddi3";
45 Names[RTLIB::NEG_I32] = "__negsi2";
46 Names[RTLIB::NEG_I64] = "__negdi2";
47 Names[RTLIB::ADD_F32] = "__addsf3";
48 Names[RTLIB::ADD_F64] = "__adddf3";
49 Names[RTLIB::SUB_F32] = "__subsf3";
50 Names[RTLIB::SUB_F64] = "__subdf3";
51 Names[RTLIB::MUL_F32] = "__mulsf3";
52 Names[RTLIB::MUL_F64] = "__muldf3";
53 Names[RTLIB::DIV_F32] = "__divsf3";
54 Names[RTLIB::DIV_F64] = "__divdf3";
55 Names[RTLIB::REM_F32] = "fmodf";
56 Names[RTLIB::REM_F64] = "fmod";
57 Names[RTLIB::NEG_F32] = "__negsf2";
58 Names[RTLIB::NEG_F64] = "__negdf2";
59 Names[RTLIB::POWI_F32] = "__powisf2";
60 Names[RTLIB::POWI_F64] = "__powidf2";
61 Names[RTLIB::POWI_LD] = "__powixf2";
62 Names[RTLIB::SQRT_F32] = "sqrtf";
63 Names[RTLIB::SQRT_F64] = "sqrt";
64 Names[RTLIB::SQRT_LD] = "sqrtl";
65 Names[RTLIB::SIN_F32] = "sinf";
66 Names[RTLIB::SIN_F64] = "sin";
67 Names[RTLIB::COS_F32] = "cosf";
68 Names[RTLIB::COS_F64] = "cos";
69 Names[RTLIB::FPEXT_F32_F64] = "__extendsfdf2";
70 Names[RTLIB::FPROUND_F64_F32] = "__truncdfsf2";
71 Names[RTLIB::FPTOSINT_F32_I32] = "__fixsfsi";
72 Names[RTLIB::FPTOSINT_F32_I64] = "__fixsfdi";
73 Names[RTLIB::FPTOSINT_F64_I32] = "__fixdfsi";
74 Names[RTLIB::FPTOSINT_F64_I64] = "__fixdfdi";
75 Names[RTLIB::FPTOSINT_LD_I64] = "__fixxfdi";
76 Names[RTLIB::FPTOUINT_F32_I32] = "__fixunssfsi";
77 Names[RTLIB::FPTOUINT_F32_I64] = "__fixunssfdi";
78 Names[RTLIB::FPTOUINT_F64_I32] = "__fixunsdfsi";
79 Names[RTLIB::FPTOUINT_F64_I64] = "__fixunsdfdi";
80 Names[RTLIB::FPTOUINT_LD_I32] = "__fixunsxfsi";
81 Names[RTLIB::FPTOUINT_LD_I64] = "__fixunsxfdi";
82 Names[RTLIB::SINTTOFP_I32_F32] = "__floatsisf";
83 Names[RTLIB::SINTTOFP_I32_F64] = "__floatsidf";
84 Names[RTLIB::SINTTOFP_I64_F32] = "__floatdisf";
85 Names[RTLIB::SINTTOFP_I64_F64] = "__floatdidf";
86 Names[RTLIB::SINTTOFP_I64_LD] = "__floatdixf";
87 Names[RTLIB::UINTTOFP_I32_F32] = "__floatunsisf";
88 Names[RTLIB::UINTTOFP_I32_F64] = "__floatunsidf";
89 Names[RTLIB::UINTTOFP_I64_F32] = "__floatundisf";
90 Names[RTLIB::UINTTOFP_I64_F64] = "__floatundidf";
91 Names[RTLIB::OEQ_F32] = "__eqsf2";
92 Names[RTLIB::OEQ_F64] = "__eqdf2";
93 Names[RTLIB::UNE_F32] = "__nesf2";
94 Names[RTLIB::UNE_F64] = "__nedf2";
95 Names[RTLIB::OGE_F32] = "__gesf2";
96 Names[RTLIB::OGE_F64] = "__gedf2";
97 Names[RTLIB::OLT_F32] = "__ltsf2";
98 Names[RTLIB::OLT_F64] = "__ltdf2";
99 Names[RTLIB::OLE_F32] = "__lesf2";
100 Names[RTLIB::OLE_F64] = "__ledf2";
101 Names[RTLIB::OGT_F32] = "__gtsf2";
102 Names[RTLIB::OGT_F64] = "__gtdf2";
103 Names[RTLIB::UO_F32] = "__unordsf2";
104 Names[RTLIB::UO_F64] = "__unorddf2";
105 Names[RTLIB::O_F32] = "__unordsf2";
106 Names[RTLIB::O_F64] = "__unorddf2";
109 /// InitCmpLibcallCCs - Set default comparison libcall CC.
111 static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
112 memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
113 CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
114 CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
115 CCs[RTLIB::UNE_F32] = ISD::SETNE;
116 CCs[RTLIB::UNE_F64] = ISD::SETNE;
117 CCs[RTLIB::OGE_F32] = ISD::SETGE;
118 CCs[RTLIB::OGE_F64] = ISD::SETGE;
119 CCs[RTLIB::OLT_F32] = ISD::SETLT;
120 CCs[RTLIB::OLT_F64] = ISD::SETLT;
121 CCs[RTLIB::OLE_F32] = ISD::SETLE;
122 CCs[RTLIB::OLE_F64] = ISD::SETLE;
123 CCs[RTLIB::OGT_F32] = ISD::SETGT;
124 CCs[RTLIB::OGT_F64] = ISD::SETGT;
125 CCs[RTLIB::UO_F32] = ISD::SETNE;
126 CCs[RTLIB::UO_F64] = ISD::SETNE;
127 CCs[RTLIB::O_F32] = ISD::SETEQ;
128 CCs[RTLIB::O_F64] = ISD::SETEQ;
131 TargetLowering::TargetLowering(TargetMachine &tm)
132 : TM(tm), TD(TM.getTargetData()) {
133 assert(ISD::BUILTIN_OP_END <= 156 &&
134 "Fixed size array in TargetLowering is not large enough!");
135 // All operations default to being supported.
136 memset(OpActions, 0, sizeof(OpActions));
137 memset(LoadXActions, 0, sizeof(LoadXActions));
138 memset(&StoreXActions, 0, sizeof(StoreXActions));
139 memset(&IndexedModeActions, 0, sizeof(IndexedModeActions));
140 memset(&ConvertActions, 0, sizeof(ConvertActions));
142 // Set all indexed load / store to expand.
143 for (unsigned VT = 0; VT != (unsigned)MVT::LAST_VALUETYPE; ++VT) {
144 for (unsigned IM = (unsigned)ISD::PRE_INC;
145 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
146 setIndexedLoadAction(IM, (MVT::ValueType)VT, Expand);
147 setIndexedStoreAction(IM, (MVT::ValueType)VT, Expand);
151 IsLittleEndian = TD->isLittleEndian();
152 UsesGlobalOffsetTable = false;
153 ShiftAmountTy = SetCCResultTy = PointerTy = getValueType(TD->getIntPtrType());
154 ShiftAmtHandling = Undefined;
155 memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*));
156 memset(TargetDAGCombineArray, 0, array_lengthof(TargetDAGCombineArray));
157 maxStoresPerMemset = maxStoresPerMemcpy = maxStoresPerMemmove = 8;
158 allowUnalignedMemoryAccesses = false;
159 UseUnderscoreSetJmp = false;
160 UseUnderscoreLongJmp = false;
161 SelectIsExpensive = false;
162 IntDivIsCheap = false;
163 Pow2DivIsCheap = false;
164 StackPointerRegisterToSaveRestore = 0;
165 ExceptionPointerRegister = 0;
166 ExceptionSelectorRegister = 0;
167 SetCCResultContents = UndefinedSetCCResult;
168 SchedPreferenceInfo = SchedulingForLatency;
170 JumpBufAlignment = 0;
171 IfCvtBlockSizeLimit = 2;
173 InitLibcallNames(LibcallRoutineNames);
174 InitCmpLibcallCCs(CmpLibcallCCs);
176 // Tell Legalize whether the assembler supports DEBUG_LOC.
177 if (!TM.getTargetAsmInfo()->hasDotLocAndDotFile())
178 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
181 TargetLowering::~TargetLowering() {}
183 /// computeRegisterProperties - Once all of the register classes are added,
184 /// this allows us to compute derived properties we expose.
185 void TargetLowering::computeRegisterProperties() {
186 assert(MVT::LAST_VALUETYPE <= 32 &&
187 "Too many value types for ValueTypeActions to hold!");
189 // Everything defaults to needing one register.
190 for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
191 NumRegistersForVT[i] = 1;
192 RegisterTypeForVT[i] = TransformToType[i] = i;
194 // ...except isVoid, which doesn't need any registers.
195 NumRegistersForVT[MVT::isVoid] = 0;
197 // Find the largest integer register class.
198 unsigned LargestIntReg = MVT::i128;
199 for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg)
200 assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
202 // Every integer value type larger than this largest register takes twice as
203 // many registers to represent as the previous ValueType.
204 for (MVT::ValueType ExpandedReg = LargestIntReg + 1;
205 MVT::isInteger(ExpandedReg); ++ExpandedReg) {
206 NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
207 RegisterTypeForVT[ExpandedReg] = LargestIntReg;
208 TransformToType[ExpandedReg] = ExpandedReg - 1;
209 ValueTypeActions.setTypeAction(ExpandedReg, Expand);
212 // Inspect all of the ValueType's smaller than the largest integer
213 // register to see which ones need promotion.
214 MVT::ValueType LegalIntReg = LargestIntReg;
215 for (MVT::ValueType IntReg = LargestIntReg - 1;
216 IntReg >= MVT::i1; --IntReg) {
217 if (isTypeLegal(IntReg)) {
218 LegalIntReg = IntReg;
220 RegisterTypeForVT[IntReg] = TransformToType[IntReg] = LegalIntReg;
221 ValueTypeActions.setTypeAction(IntReg, Promote);
225 // Decide how to handle f64. If the target does not have native f64 support,
226 // expand it to i64 and we will be generating soft float library calls.
227 if (!isTypeLegal(MVT::f64)) {
228 NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
229 RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
230 TransformToType[MVT::f64] = MVT::i64;
231 ValueTypeActions.setTypeAction(MVT::f64, Expand);
234 // Decide how to handle f32. If the target does not have native support for
235 // f32, promote it to f64 if it is legal. Otherwise, expand it to i32.
236 if (!isTypeLegal(MVT::f32)) {
237 if (isTypeLegal(MVT::f64)) {
238 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::f64];
239 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::f64];
240 TransformToType[MVT::f32] = MVT::f64;
241 ValueTypeActions.setTypeAction(MVT::f32, Promote);
243 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
244 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
245 TransformToType[MVT::f32] = MVT::i32;
246 ValueTypeActions.setTypeAction(MVT::f32, Expand);
250 // Loop over all of the vector value types to see which need transformations.
251 for (MVT::ValueType i = MVT::FIRST_VECTOR_VALUETYPE;
252 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
253 if (!isTypeLegal(i)) {
254 MVT::ValueType IntermediateVT, RegisterVT;
255 unsigned NumIntermediates;
256 NumRegistersForVT[i] =
257 getVectorTypeBreakdown(i,
258 IntermediateVT, NumIntermediates,
260 RegisterTypeForVT[i] = RegisterVT;
261 TransformToType[i] = MVT::Other; // this isn't actually used
262 ValueTypeActions.setTypeAction(i, Expand);
267 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
271 /// getVectorTypeBreakdown - Vector types are broken down into some number of
272 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
273 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
274 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
276 /// This method returns the number of registers needed, and the VT for each
277 /// register. It also returns the VT and quantity of the intermediate values
278 /// before they are promoted/expanded.
280 unsigned TargetLowering::getVectorTypeBreakdown(MVT::ValueType VT,
281 MVT::ValueType &IntermediateVT,
282 unsigned &NumIntermediates,
283 MVT::ValueType &RegisterVT) const {
284 // Figure out the right, legal destination reg to copy into.
285 unsigned NumElts = MVT::getVectorNumElements(VT);
286 MVT::ValueType EltTy = MVT::getVectorElementType(VT);
288 unsigned NumVectorRegs = 1;
290 // Divide the input until we get to a supported size. This will always
291 // end with a scalar if the target doesn't support vectors.
292 while (NumElts > 1 &&
293 !isTypeLegal(MVT::getVectorType(EltTy, NumElts))) {
298 NumIntermediates = NumVectorRegs;
300 MVT::ValueType NewVT = MVT::getVectorType(EltTy, NumElts);
301 if (!isTypeLegal(NewVT))
303 IntermediateVT = NewVT;
305 MVT::ValueType DestVT = getTypeToTransformTo(NewVT);
307 if (DestVT < NewVT) {
308 // Value is expanded, e.g. i64 -> i16.
309 return NumVectorRegs*(MVT::getSizeInBits(NewVT)/MVT::getSizeInBits(DestVT));
311 // Otherwise, promotion or legal types use the same number of registers as
312 // the vector decimated to the appropriate level.
313 return NumVectorRegs;
319 //===----------------------------------------------------------------------===//
320 // Optimization Methods
321 //===----------------------------------------------------------------------===//
323 /// ShrinkDemandedConstant - Check to see if the specified operand of the
324 /// specified instruction is a constant integer. If so, check to see if there
325 /// are any bits set in the constant that are not demanded. If so, shrink the
326 /// constant and return true.
327 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDOperand Op,
329 // FIXME: ISD::SELECT, ISD::SELECT_CC
330 switch(Op.getOpcode()) {
335 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
336 if ((~Demanded & C->getValue()) != 0) {
337 MVT::ValueType VT = Op.getValueType();
338 SDOperand New = DAG.getNode(Op.getOpcode(), VT, Op.getOperand(0),
339 DAG.getConstant(Demanded & C->getValue(),
341 return CombineTo(Op, New);
348 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
349 /// DemandedMask bits of the result of Op are ever used downstream. If we can
350 /// use this information to simplify Op, create a new simplified DAG node and
351 /// return true, returning the original and new nodes in Old and New. Otherwise,
352 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
353 /// the expression (used to simplify the caller). The KnownZero/One bits may
354 /// only be accurate for those bits in the DemandedMask.
355 bool TargetLowering::SimplifyDemandedBits(SDOperand Op, uint64_t DemandedMask,
358 TargetLoweringOpt &TLO,
359 unsigned Depth) const {
360 KnownZero = KnownOne = 0; // Don't know anything.
362 // The masks are not wide enough to represent this type! Should use APInt.
363 if (Op.getValueType() == MVT::i128)
366 // Other users may use these bits.
367 if (!Op.Val->hasOneUse()) {
369 // If not at the root, Just compute the KnownZero/KnownOne bits to
370 // simplify things downstream.
371 TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
374 // If this is the root being simplified, allow it to have multiple uses,
375 // just set the DemandedMask to all bits.
376 DemandedMask = MVT::getIntVTBitMask(Op.getValueType());
377 } else if (DemandedMask == 0) {
378 // Not demanding any bits from Op.
379 if (Op.getOpcode() != ISD::UNDEF)
380 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::UNDEF, Op.getValueType()));
382 } else if (Depth == 6) { // Limit search depth.
386 uint64_t KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
387 switch (Op.getOpcode()) {
389 // We know all of the bits for a constant!
390 KnownOne = cast<ConstantSDNode>(Op)->getValue() & DemandedMask;
391 KnownZero = ~KnownOne & DemandedMask;
392 return false; // Don't fall through, will infinitely loop.
394 // If the RHS is a constant, check to see if the LHS would be zero without
395 // using the bits from the RHS. Below, we use knowledge about the RHS to
396 // simplify the LHS, here we're using information from the LHS to simplify
398 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
399 uint64_t LHSZero, LHSOne;
400 TLO.DAG.ComputeMaskedBits(Op.getOperand(0), DemandedMask,
401 LHSZero, LHSOne, Depth+1);
402 // If the LHS already has zeros where RHSC does, this and is dead.
403 if ((LHSZero & DemandedMask) == (~RHSC->getValue() & DemandedMask))
404 return TLO.CombineTo(Op, Op.getOperand(0));
405 // If any of the set bits in the RHS are known zero on the LHS, shrink
407 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & DemandedMask))
411 if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero,
412 KnownOne, TLO, Depth+1))
414 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
415 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & ~KnownZero,
416 KnownZero2, KnownOne2, TLO, Depth+1))
418 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
420 // If all of the demanded bits are known one on one side, return the other.
421 // These bits cannot contribute to the result of the 'and'.
422 if ((DemandedMask & ~KnownZero2 & KnownOne)==(DemandedMask & ~KnownZero2))
423 return TLO.CombineTo(Op, Op.getOperand(0));
424 if ((DemandedMask & ~KnownZero & KnownOne2)==(DemandedMask & ~KnownZero))
425 return TLO.CombineTo(Op, Op.getOperand(1));
426 // If all of the demanded bits in the inputs are known zeros, return zero.
427 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
428 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
429 // If the RHS is a constant, see if we can simplify it.
430 if (TLO.ShrinkDemandedConstant(Op, DemandedMask & ~KnownZero2))
433 // Output known-1 bits are only known if set in both the LHS & RHS.
434 KnownOne &= KnownOne2;
435 // Output known-0 are known to be clear if zero in either the LHS | RHS.
436 KnownZero |= KnownZero2;
439 if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero,
440 KnownOne, TLO, Depth+1))
442 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
443 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & ~KnownOne,
444 KnownZero2, KnownOne2, TLO, Depth+1))
446 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
448 // If all of the demanded bits are known zero on one side, return the other.
449 // These bits cannot contribute to the result of the 'or'.
450 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
451 return TLO.CombineTo(Op, Op.getOperand(0));
452 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
453 return TLO.CombineTo(Op, Op.getOperand(1));
454 // If all of the potentially set bits on one side are known to be set on
455 // the other side, just use the 'other' side.
456 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
457 (DemandedMask & (~KnownZero)))
458 return TLO.CombineTo(Op, Op.getOperand(0));
459 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
460 (DemandedMask & (~KnownZero2)))
461 return TLO.CombineTo(Op, Op.getOperand(1));
462 // If the RHS is a constant, see if we can simplify it.
463 if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
466 // Output known-0 bits are only known if clear in both the LHS & RHS.
467 KnownZero &= KnownZero2;
468 // Output known-1 are known to be set if set in either the LHS | RHS.
469 KnownOne |= KnownOne2;
472 if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero,
473 KnownOne, TLO, Depth+1))
475 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
476 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask, KnownZero2,
477 KnownOne2, TLO, Depth+1))
479 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
481 // If all of the demanded bits are known zero on one side, return the other.
482 // These bits cannot contribute to the result of the 'xor'.
483 if ((DemandedMask & KnownZero) == DemandedMask)
484 return TLO.CombineTo(Op, Op.getOperand(0));
485 if ((DemandedMask & KnownZero2) == DemandedMask)
486 return TLO.CombineTo(Op, Op.getOperand(1));
488 // If all of the unknown bits are known to be zero on one side or the other
489 // (but not both) turn this into an *inclusive* or.
490 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
491 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0)
492 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, Op.getValueType(),
496 // Output known-0 bits are known if clear or set in both the LHS & RHS.
497 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
498 // Output known-1 are known to be set if set in only one of the LHS, RHS.
499 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
501 // If all of the demanded bits on one side are known, and all of the set
502 // bits on that side are also known to be set on the other side, turn this
503 // into an AND, as we know the bits will be cleared.
504 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
505 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
506 if ((KnownOne & KnownOne2) == KnownOne) {
507 MVT::ValueType VT = Op.getValueType();
508 SDOperand ANDC = TLO.DAG.getConstant(~KnownOne & DemandedMask, VT);
509 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, VT, Op.getOperand(0),
514 // If the RHS is a constant, see if we can simplify it.
515 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
516 if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
519 KnownZero = KnownZeroOut;
520 KnownOne = KnownOneOut;
523 // If we know the result of a setcc has the top bits zero, use this info.
524 if (getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult)
525 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
528 if (SimplifyDemandedBits(Op.getOperand(2), DemandedMask, KnownZero,
529 KnownOne, TLO, Depth+1))
531 if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero2,
532 KnownOne2, TLO, Depth+1))
534 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
535 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
537 // If the operands are constants, see if we can simplify them.
538 if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
541 // Only known if known in both the LHS and RHS.
542 KnownOne &= KnownOne2;
543 KnownZero &= KnownZero2;
546 if (SimplifyDemandedBits(Op.getOperand(3), DemandedMask, KnownZero,
547 KnownOne, TLO, Depth+1))
549 if (SimplifyDemandedBits(Op.getOperand(2), DemandedMask, KnownZero2,
550 KnownOne2, TLO, Depth+1))
552 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
553 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
555 // If the operands are constants, see if we can simplify them.
556 if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
559 // Only known if known in both the LHS and RHS.
560 KnownOne &= KnownOne2;
561 KnownZero &= KnownZero2;
564 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
565 unsigned ShAmt = SA->getValue();
566 SDOperand InOp = Op.getOperand(0);
568 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
569 // single shift. We can do this if the bottom bits (which are shifted
570 // out) are never demanded.
571 if (InOp.getOpcode() == ISD::SRL &&
572 isa<ConstantSDNode>(InOp.getOperand(1))) {
573 if (ShAmt && (DemandedMask & ((1ULL << ShAmt)-1)) == 0) {
574 unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
575 unsigned Opc = ISD::SHL;
583 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
584 MVT::ValueType VT = Op.getValueType();
585 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
586 InOp.getOperand(0), NewSA));
590 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask >> ShAmt,
591 KnownZero, KnownOne, TLO, Depth+1))
593 KnownZero <<= SA->getValue();
594 KnownOne <<= SA->getValue();
595 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
599 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
600 MVT::ValueType VT = Op.getValueType();
601 unsigned ShAmt = SA->getValue();
602 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
603 unsigned VTSize = MVT::getSizeInBits(VT);
604 SDOperand InOp = Op.getOperand(0);
606 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
607 // single shift. We can do this if the top bits (which are shifted out)
608 // are never demanded.
609 if (InOp.getOpcode() == ISD::SHL &&
610 isa<ConstantSDNode>(InOp.getOperand(1))) {
611 if (ShAmt && (DemandedMask & (~0ULL << (VTSize-ShAmt))) == 0) {
612 unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
613 unsigned Opc = ISD::SRL;
621 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
622 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
623 InOp.getOperand(0), NewSA));
627 // Compute the new bits that are at the top now.
628 if (SimplifyDemandedBits(InOp, (DemandedMask << ShAmt) & TypeMask,
629 KnownZero, KnownOne, TLO, Depth+1))
631 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
632 KnownZero &= TypeMask;
633 KnownOne &= TypeMask;
637 uint64_t HighBits = (1ULL << ShAmt)-1;
638 HighBits <<= VTSize - ShAmt;
639 KnownZero |= HighBits; // High bits known zero.
643 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
644 MVT::ValueType VT = Op.getValueType();
645 unsigned ShAmt = SA->getValue();
647 // Compute the new bits that are at the top now.
648 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
650 uint64_t InDemandedMask = (DemandedMask << ShAmt) & TypeMask;
652 // If any of the demanded bits are produced by the sign extension, we also
653 // demand the input sign bit.
654 uint64_t HighBits = (1ULL << ShAmt)-1;
655 HighBits <<= MVT::getSizeInBits(VT) - ShAmt;
656 if (HighBits & DemandedMask)
657 InDemandedMask |= MVT::getIntVTSignBit(VT);
659 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
660 KnownZero, KnownOne, TLO, Depth+1))
662 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
663 KnownZero &= TypeMask;
664 KnownOne &= TypeMask;
668 // Handle the sign bits.
669 uint64_t SignBit = MVT::getIntVTSignBit(VT);
670 SignBit >>= ShAmt; // Adjust to where it is now in the mask.
672 // If the input sign bit is known to be zero, or if none of the top bits
673 // are demanded, turn this into an unsigned shift right.
674 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
675 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, VT, Op.getOperand(0),
677 } else if (KnownOne & SignBit) { // New bits are known one.
678 KnownOne |= HighBits;
682 case ISD::SIGN_EXTEND_INREG: {
683 MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
685 // Sign extension. Compute the demanded bits in the result that are not
686 // present in the input.
687 uint64_t NewBits = ~MVT::getIntVTBitMask(EVT) & DemandedMask;
689 // If none of the extended bits are demanded, eliminate the sextinreg.
691 return TLO.CombineTo(Op, Op.getOperand(0));
693 uint64_t InSignBit = MVT::getIntVTSignBit(EVT);
694 int64_t InputDemandedBits = DemandedMask & MVT::getIntVTBitMask(EVT);
696 // Since the sign extended bits are demanded, we know that the sign
698 InputDemandedBits |= InSignBit;
700 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
701 KnownZero, KnownOne, TLO, Depth+1))
703 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
705 // If the sign bit of the input is known set or clear, then we know the
706 // top bits of the result.
708 // If the input sign bit is known zero, convert this into a zero extension.
709 if (KnownZero & InSignBit)
710 return TLO.CombineTo(Op,
711 TLO.DAG.getZeroExtendInReg(Op.getOperand(0), EVT));
713 if (KnownOne & InSignBit) { // Input sign bit known set
715 KnownZero &= ~NewBits;
716 } else { // Input sign bit unknown
717 KnownZero &= ~NewBits;
718 KnownOne &= ~NewBits;
725 MVT::ValueType VT = Op.getValueType();
726 unsigned LowBits = Log2_32(MVT::getSizeInBits(VT))+1;
727 KnownZero = ~((1ULL << LowBits)-1) & MVT::getIntVTBitMask(VT);
732 if (ISD::isZEXTLoad(Op.Val)) {
733 LoadSDNode *LD = cast<LoadSDNode>(Op);
734 MVT::ValueType VT = LD->getLoadedVT();
735 KnownZero |= ~MVT::getIntVTBitMask(VT) & DemandedMask;
739 case ISD::ZERO_EXTEND: {
740 uint64_t InMask = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
742 // If none of the top bits are demanded, convert this into an any_extend.
743 uint64_t NewBits = (~InMask) & DemandedMask;
745 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND,
749 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & InMask,
750 KnownZero, KnownOne, TLO, Depth+1))
752 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
753 KnownZero |= NewBits;
756 case ISD::SIGN_EXTEND: {
757 MVT::ValueType InVT = Op.getOperand(0).getValueType();
758 uint64_t InMask = MVT::getIntVTBitMask(InVT);
759 uint64_t InSignBit = MVT::getIntVTSignBit(InVT);
760 uint64_t NewBits = (~InMask) & DemandedMask;
762 // If none of the top bits are demanded, convert this into an any_extend.
764 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND,Op.getValueType(),
767 // Since some of the sign extended bits are demanded, we know that the sign
769 uint64_t InDemandedBits = DemandedMask & InMask;
770 InDemandedBits |= InSignBit;
772 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
773 KnownOne, TLO, Depth+1))
776 // If the sign bit is known zero, convert this to a zero extend.
777 if (KnownZero & InSignBit)
778 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND,
782 // If the sign bit is known one, the top bits match.
783 if (KnownOne & InSignBit) {
785 KnownZero &= ~NewBits;
786 } else { // Otherwise, top bits aren't known.
787 KnownOne &= ~NewBits;
788 KnownZero &= ~NewBits;
792 case ISD::ANY_EXTEND: {
793 uint64_t InMask = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
794 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & InMask,
795 KnownZero, KnownOne, TLO, Depth+1))
797 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
800 case ISD::TRUNCATE: {
801 // Simplify the input, using demanded bit information, and compute the known
802 // zero/one bits live out.
803 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
804 KnownZero, KnownOne, TLO, Depth+1))
807 // If the input is only used by this truncate, see if we can shrink it based
808 // on the known demanded bits.
809 if (Op.getOperand(0).Val->hasOneUse()) {
810 SDOperand In = Op.getOperand(0);
811 switch (In.getOpcode()) {
814 // Shrink SRL by a constant if none of the high bits shifted in are
816 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1))){
817 uint64_t HighBits = MVT::getIntVTBitMask(In.getValueType());
818 HighBits &= ~MVT::getIntVTBitMask(Op.getValueType());
819 HighBits >>= ShAmt->getValue();
821 if (ShAmt->getValue() < MVT::getSizeInBits(Op.getValueType()) &&
822 (DemandedMask & HighBits) == 0) {
823 // None of the shifted in bits are needed. Add a truncate of the
824 // shift input, then shift it.
825 SDOperand NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE,
828 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL,Op.getValueType(),
829 NewTrunc, In.getOperand(1)));
836 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
837 uint64_t OutMask = MVT::getIntVTBitMask(Op.getValueType());
838 KnownZero &= OutMask;
842 case ISD::AssertZext: {
843 MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
844 uint64_t InMask = MVT::getIntVTBitMask(VT);
845 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & InMask,
846 KnownZero, KnownOne, TLO, Depth+1))
848 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
849 KnownZero |= ~InMask & DemandedMask;
854 case ISD::INTRINSIC_WO_CHAIN:
855 case ISD::INTRINSIC_W_CHAIN:
856 case ISD::INTRINSIC_VOID:
857 // Just use ComputeMaskedBits to compute output bits.
858 TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
862 // If we know the value of all of the demanded bits, return this as a
864 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
865 return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
870 /// computeMaskedBitsForTargetNode - Determine which of the bits specified
871 /// in Mask are known to be either zero or one and return them in the
872 /// KnownZero/KnownOne bitsets.
873 void TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
877 const SelectionDAG &DAG,
878 unsigned Depth) const {
879 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
880 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
881 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
882 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
883 "Should use MaskedValueIsZero if you don't know whether Op"
884 " is a target node!");
889 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
890 /// targets that want to expose additional information about sign bits to the
892 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDOperand Op,
893 unsigned Depth) const {
894 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
895 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
896 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
897 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
898 "Should use ComputeNumSignBits if you don't know whether Op"
899 " is a target node!");
904 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
905 /// and cc. If it is unable to simplify it, return a null SDOperand.
907 TargetLowering::SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
908 ISD::CondCode Cond, bool foldBooleans,
909 DAGCombinerInfo &DCI) const {
910 SelectionDAG &DAG = DCI.DAG;
912 // These setcc operations always fold.
916 case ISD::SETFALSE2: return DAG.getConstant(0, VT);
918 case ISD::SETTRUE2: return DAG.getConstant(1, VT);
921 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
922 uint64_t C1 = N1C->getValue();
923 if (isa<ConstantSDNode>(N0.Val)) {
924 return DAG.FoldSetCC(VT, N0, N1, Cond);
926 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
927 // equality comparison, then we're just comparing whether X itself is
929 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
930 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
931 N0.getOperand(1).getOpcode() == ISD::Constant) {
932 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
933 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
934 ShAmt == Log2_32(MVT::getSizeInBits(N0.getValueType()))) {
935 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
936 // (srl (ctlz x), 5) == 0 -> X != 0
937 // (srl (ctlz x), 5) != 1 -> X != 0
940 // (srl (ctlz x), 5) != 0 -> X == 0
941 // (srl (ctlz x), 5) == 1 -> X == 0
944 SDOperand Zero = DAG.getConstant(0, N0.getValueType());
945 return DAG.getSetCC(VT, N0.getOperand(0).getOperand(0),
950 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
951 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
952 unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
954 // If the comparison constant has bits in the upper part, the
955 // zero-extended value could never match.
956 if (C1 & (~0ULL << InSize)) {
957 unsigned VSize = MVT::getSizeInBits(N0.getValueType());
961 case ISD::SETEQ: return DAG.getConstant(0, VT);
964 case ISD::SETNE: return DAG.getConstant(1, VT);
967 // True if the sign bit of C1 is set.
968 return DAG.getConstant((C1 & (1ULL << (VSize-1))) != 0, VT);
971 // True if the sign bit of C1 isn't set.
972 return DAG.getConstant((C1 & (1ULL << (VSize-1))) == 0, VT);
978 // Otherwise, we can perform the comparison with the low bits.
986 return DAG.getSetCC(VT, N0.getOperand(0),
987 DAG.getConstant(C1, N0.getOperand(0).getValueType()),
990 break; // todo, be more careful with signed comparisons
992 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
993 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
994 MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
995 unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
996 MVT::ValueType ExtDstTy = N0.getValueType();
997 unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
999 // If the extended part has any inconsistent bits, it cannot ever
1000 // compare equal. In other words, they have to be all ones or all
1003 (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
1004 if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
1005 return DAG.getConstant(Cond == ISD::SETNE, VT);
1008 MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
1009 if (Op0Ty == ExtSrcTy) {
1010 ZextOp = N0.getOperand(0);
1012 int64_t Imm = ~0ULL >> (64-ExtSrcTyBits);
1013 ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
1014 DAG.getConstant(Imm, Op0Ty));
1016 if (!DCI.isCalledByLegalizer())
1017 DCI.AddToWorklist(ZextOp.Val);
1018 // Otherwise, make this a use of a zext.
1019 return DAG.getSetCC(VT, ZextOp,
1020 DAG.getConstant(C1 & (~0ULL>>(64-ExtSrcTyBits)),
1023 } else if ((N1C->getValue() == 0 || N1C->getValue() == 1) &&
1024 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1026 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
1027 if (N0.getOpcode() == ISD::SETCC) {
1028 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getValue() != 1);
1032 // Invert the condition.
1033 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1034 CC = ISD::getSetCCInverse(CC,
1035 MVT::isInteger(N0.getOperand(0).getValueType()));
1036 return DAG.getSetCC(VT, N0.getOperand(0), N0.getOperand(1), CC);
1039 if ((N0.getOpcode() == ISD::XOR ||
1040 (N0.getOpcode() == ISD::AND &&
1041 N0.getOperand(0).getOpcode() == ISD::XOR &&
1042 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1043 isa<ConstantSDNode>(N0.getOperand(1)) &&
1044 cast<ConstantSDNode>(N0.getOperand(1))->getValue() == 1) {
1045 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1046 // can only do this if the top bits are known zero.
1047 if (DAG.MaskedValueIsZero(N0,
1048 MVT::getIntVTBitMask(N0.getValueType())-1)){
1049 // Okay, get the un-inverted input value.
1051 if (N0.getOpcode() == ISD::XOR)
1052 Val = N0.getOperand(0);
1054 assert(N0.getOpcode() == ISD::AND &&
1055 N0.getOperand(0).getOpcode() == ISD::XOR);
1056 // ((X^1)&1)^1 -> X & 1
1057 Val = DAG.getNode(ISD::AND, N0.getValueType(),
1058 N0.getOperand(0).getOperand(0),
1061 return DAG.getSetCC(VT, Val, N1,
1062 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1067 uint64_t MinVal, MaxVal;
1068 unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
1069 if (ISD::isSignedIntSetCC(Cond)) {
1070 MinVal = 1ULL << (OperandBitSize-1);
1071 if (OperandBitSize != 1) // Avoid X >> 64, which is undefined.
1072 MaxVal = ~0ULL >> (65-OperandBitSize);
1077 MaxVal = ~0ULL >> (64-OperandBitSize);
1080 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1081 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1082 if (C1 == MinVal) return DAG.getConstant(1, VT); // X >= MIN --> true
1083 --C1; // X >= C0 --> X > (C0-1)
1084 return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
1085 (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
1088 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1089 if (C1 == MaxVal) return DAG.getConstant(1, VT); // X <= MAX --> true
1090 ++C1; // X <= C0 --> X < (C0+1)
1091 return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
1092 (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
1095 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1096 return DAG.getConstant(0, VT); // X < MIN --> false
1097 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1098 return DAG.getConstant(1, VT); // X >= MIN --> true
1099 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1100 return DAG.getConstant(0, VT); // X > MAX --> false
1101 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1102 return DAG.getConstant(1, VT); // X <= MAX --> true
1104 // Canonicalize setgt X, Min --> setne X, Min
1105 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1106 return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1107 // Canonicalize setlt X, Max --> setne X, Max
1108 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1109 return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1111 // If we have setult X, 1, turn it into seteq X, 0
1112 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1113 return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
1115 // If we have setugt X, Max-1, turn it into seteq X, Max
1116 else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1117 return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
1120 // If we have "setcc X, C0", check to see if we can shrink the immediate
1123 // SETUGT X, SINTMAX -> SETLT X, 0
1124 if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
1125 C1 == (~0ULL >> (65-OperandBitSize)))
1126 return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
1129 // FIXME: Implement the rest of these.
1131 // Fold bit comparisons when we can.
1132 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1133 VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
1134 if (ConstantSDNode *AndRHS =
1135 dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1136 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
1137 // Perform the xform if the AND RHS is a single bit.
1138 if (isPowerOf2_64(AndRHS->getValue())) {
1139 return DAG.getNode(ISD::SRL, VT, N0,
1140 DAG.getConstant(Log2_64(AndRHS->getValue()),
1141 getShiftAmountTy()));
1143 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
1144 // (X & 8) == 8 --> (X & 8) >> 3
1145 // Perform the xform if C1 is a single bit.
1146 if (isPowerOf2_64(C1)) {
1147 return DAG.getNode(ISD::SRL, VT, N0,
1148 DAG.getConstant(Log2_64(C1), getShiftAmountTy()));
1153 } else if (isa<ConstantSDNode>(N0.Val)) {
1154 // Ensure that the constant occurs on the RHS.
1155 return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
1158 if (isa<ConstantFPSDNode>(N0.Val)) {
1159 // Constant fold or commute setcc.
1160 SDOperand O = DAG.FoldSetCC(VT, N0, N1, Cond);
1161 if (O.Val) return O;
1165 // We can always fold X == X for integer setcc's.
1166 if (MVT::isInteger(N0.getValueType()))
1167 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1168 unsigned UOF = ISD::getUnorderedFlavor(Cond);
1169 if (UOF == 2) // FP operators that are undefined on NaNs.
1170 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1171 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
1172 return DAG.getConstant(UOF, VT);
1173 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
1174 // if it is not already.
1175 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
1176 if (NewCond != Cond)
1177 return DAG.getSetCC(VT, N0, N1, NewCond);
1180 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1181 MVT::isInteger(N0.getValueType())) {
1182 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
1183 N0.getOpcode() == ISD::XOR) {
1184 // Simplify (X+Y) == (X+Z) --> Y == Z
1185 if (N0.getOpcode() == N1.getOpcode()) {
1186 if (N0.getOperand(0) == N1.getOperand(0))
1187 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
1188 if (N0.getOperand(1) == N1.getOperand(1))
1189 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
1190 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
1191 // If X op Y == Y op X, try other combinations.
1192 if (N0.getOperand(0) == N1.getOperand(1))
1193 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
1194 if (N0.getOperand(1) == N1.getOperand(0))
1195 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
1199 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
1200 if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1201 // Turn (X+C1) == C2 --> X == C2-C1
1202 if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
1203 return DAG.getSetCC(VT, N0.getOperand(0),
1204 DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
1205 N0.getValueType()), Cond);
1208 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
1209 if (N0.getOpcode() == ISD::XOR)
1210 // If we know that all of the inverted bits are zero, don't bother
1211 // performing the inversion.
1212 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getValue()))
1213 return DAG.getSetCC(VT, N0.getOperand(0),
1214 DAG.getConstant(LHSR->getValue()^RHSC->getValue(),
1215 N0.getValueType()), Cond);
1218 // Turn (C1-X) == C2 --> X == C1-C2
1219 if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1220 if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) {
1221 return DAG.getSetCC(VT, N0.getOperand(1),
1222 DAG.getConstant(SUBC->getValue()-RHSC->getValue(),
1223 N0.getValueType()), Cond);
1228 // Simplify (X+Z) == X --> Z == 0
1229 if (N0.getOperand(0) == N1)
1230 return DAG.getSetCC(VT, N0.getOperand(1),
1231 DAG.getConstant(0, N0.getValueType()), Cond);
1232 if (N0.getOperand(1) == N1) {
1233 if (DAG.isCommutativeBinOp(N0.getOpcode()))
1234 return DAG.getSetCC(VT, N0.getOperand(0),
1235 DAG.getConstant(0, N0.getValueType()), Cond);
1236 else if (N0.Val->hasOneUse()) {
1237 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
1238 // (Z-X) == X --> Z == X<<1
1239 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
1241 DAG.getConstant(1, getShiftAmountTy()));
1242 if (!DCI.isCalledByLegalizer())
1243 DCI.AddToWorklist(SH.Val);
1244 return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
1249 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
1250 N1.getOpcode() == ISD::XOR) {
1251 // Simplify X == (X+Z) --> Z == 0
1252 if (N1.getOperand(0) == N0) {
1253 return DAG.getSetCC(VT, N1.getOperand(1),
1254 DAG.getConstant(0, N1.getValueType()), Cond);
1255 } else if (N1.getOperand(1) == N0) {
1256 if (DAG.isCommutativeBinOp(N1.getOpcode())) {
1257 return DAG.getSetCC(VT, N1.getOperand(0),
1258 DAG.getConstant(0, N1.getValueType()), Cond);
1259 } else if (N1.Val->hasOneUse()) {
1260 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
1261 // X == (Z-X) --> X<<1 == Z
1262 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0,
1263 DAG.getConstant(1, getShiftAmountTy()));
1264 if (!DCI.isCalledByLegalizer())
1265 DCI.AddToWorklist(SH.Val);
1266 return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
1272 // Fold away ALL boolean setcc's.
1274 if (N0.getValueType() == MVT::i1 && foldBooleans) {
1276 default: assert(0 && "Unknown integer setcc!");
1277 case ISD::SETEQ: // X == Y -> (X^Y)^1
1278 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1279 N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
1280 if (!DCI.isCalledByLegalizer())
1281 DCI.AddToWorklist(Temp.Val);
1283 case ISD::SETNE: // X != Y --> (X^Y)
1284 N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1286 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> X^1 & Y
1287 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> X^1 & Y
1288 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1289 N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
1290 if (!DCI.isCalledByLegalizer())
1291 DCI.AddToWorklist(Temp.Val);
1293 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> Y^1 & X
1294 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> Y^1 & X
1295 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1296 N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
1297 if (!DCI.isCalledByLegalizer())
1298 DCI.AddToWorklist(Temp.Val);
1300 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> X^1 | Y
1301 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> X^1 | Y
1302 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1303 N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
1304 if (!DCI.isCalledByLegalizer())
1305 DCI.AddToWorklist(Temp.Val);
1307 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> Y^1 | X
1308 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> Y^1 | X
1309 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1310 N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
1313 if (VT != MVT::i1) {
1314 if (!DCI.isCalledByLegalizer())
1315 DCI.AddToWorklist(N0.Val);
1316 // FIXME: If running after legalize, we probably can't do this.
1317 N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
1322 // Could not fold it.
1326 SDOperand TargetLowering::
1327 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1328 // Default implementation: no optimization.
1332 //===----------------------------------------------------------------------===//
1333 // Inline Assembler Implementation Methods
1334 //===----------------------------------------------------------------------===//
1336 TargetLowering::ConstraintType
1337 TargetLowering::getConstraintType(const std::string &Constraint) const {
1338 // FIXME: lots more standard ones to handle.
1339 if (Constraint.size() == 1) {
1340 switch (Constraint[0]) {
1342 case 'r': return C_RegisterClass;
1344 case 'o': // offsetable
1345 case 'V': // not offsetable
1347 case 'i': // Simple Integer or Relocatable Constant
1348 case 'n': // Simple Integer
1349 case 's': // Relocatable Constant
1350 case 'X': // Allow ANY value.
1351 case 'I': // Target registers.
1363 if (Constraint.size() > 1 && Constraint[0] == '{' &&
1364 Constraint[Constraint.size()-1] == '}')
1369 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1370 /// vector. If it is invalid, don't add anything to Ops.
1371 void TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
1372 char ConstraintLetter,
1373 std::vector<SDOperand> &Ops,
1374 SelectionDAG &DAG) {
1375 switch (ConstraintLetter) {
1377 case 'i': // Simple Integer or Relocatable Constant
1378 case 'n': // Simple Integer
1379 case 's': // Relocatable Constant
1380 case 'X': { // Allows any operand.
1381 // These operands are interested in values of the form (GV+C), where C may
1382 // be folded in as an offset of GV, or it may be explicitly added. Also, it
1383 // is possible and fine if either GV or C are missing.
1384 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
1385 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1387 // If we have "(add GV, C)", pull out GV/C
1388 if (Op.getOpcode() == ISD::ADD) {
1389 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1390 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
1391 if (C == 0 || GA == 0) {
1392 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1393 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
1395 if (C == 0 || GA == 0)
1399 // If we find a valid operand, map to the TargetXXX version so that the
1400 // value itself doesn't get selected.
1401 if (GA) { // Either &GV or &GV+C
1402 if (ConstraintLetter != 'n') {
1403 int64_t Offs = GA->getOffset();
1404 if (C) Offs += C->getValue();
1405 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
1406 Op.getValueType(), Offs));
1410 if (C) { // just C, no GV.
1411 // Simple constants are not allowed for 's'.
1412 if (ConstraintLetter != 's') {
1413 Ops.push_back(DAG.getTargetConstant(C->getValue(), Op.getValueType()));
1422 std::vector<unsigned> TargetLowering::
1423 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1424 MVT::ValueType VT) const {
1425 return std::vector<unsigned>();
1429 std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
1430 getRegForInlineAsmConstraint(const std::string &Constraint,
1431 MVT::ValueType VT) const {
1432 if (Constraint[0] != '{')
1433 return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1434 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
1436 // Remove the braces from around the name.
1437 std::string RegName(Constraint.begin()+1, Constraint.end()-1);
1439 // Figure out which register class contains this reg.
1440 const MRegisterInfo *RI = TM.getRegisterInfo();
1441 for (MRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
1442 E = RI->regclass_end(); RCI != E; ++RCI) {
1443 const TargetRegisterClass *RC = *RCI;
1445 // If none of the the value types for this register class are valid, we
1446 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1447 bool isLegal = false;
1448 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1450 if (isTypeLegal(*I)) {
1456 if (!isLegal) continue;
1458 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
1460 if (StringsEqualNoCase(RegName, RI->get(*I).Name))
1461 return std::make_pair(*I, RC);
1465 return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1468 //===----------------------------------------------------------------------===//
1469 // Loop Strength Reduction hooks
1470 //===----------------------------------------------------------------------===//
1472 /// isLegalAddressingMode - Return true if the addressing mode represented
1473 /// by AM is legal for this target, for a load/store of the specified type.
1474 bool TargetLowering::isLegalAddressingMode(const AddrMode &AM,
1475 const Type *Ty) const {
1476 // The default implementation of this implements a conservative RISCy, r+r and
1479 // Allows a sign-extended 16-bit immediate field.
1480 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
1483 // No global is ever allowed as a base.
1487 // Only support r+r,
1489 case 0: // "r+i" or just "i", depending on HasBaseReg.
1492 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
1494 // Otherwise we have r+r or r+i.
1497 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
1499 // Allow 2*r as r+r.
1506 // Magic for divide replacement
1509 int64_t m; // magic number
1510 int64_t s; // shift amount
1514 uint64_t m; // magic number
1515 int64_t a; // add indicator
1516 int64_t s; // shift amount
1519 /// magic - calculate the magic numbers required to codegen an integer sdiv as
1520 /// a sequence of multiply and shifts. Requires that the divisor not be 0, 1,
1522 static ms magic32(int32_t d) {
1524 uint32_t ad, anc, delta, q1, r1, q2, r2, t;
1525 const uint32_t two31 = 0x80000000U;
1529 t = two31 + ((uint32_t)d >> 31);
1530 anc = t - 1 - t%ad; // absolute value of nc
1531 p = 31; // initialize p
1532 q1 = two31/anc; // initialize q1 = 2p/abs(nc)
1533 r1 = two31 - q1*anc; // initialize r1 = rem(2p,abs(nc))
1534 q2 = two31/ad; // initialize q2 = 2p/abs(d)
1535 r2 = two31 - q2*ad; // initialize r2 = rem(2p,abs(d))
1538 q1 = 2*q1; // update q1 = 2p/abs(nc)
1539 r1 = 2*r1; // update r1 = rem(2p/abs(nc))
1540 if (r1 >= anc) { // must be unsigned comparison
1544 q2 = 2*q2; // update q2 = 2p/abs(d)
1545 r2 = 2*r2; // update r2 = rem(2p/abs(d))
1546 if (r2 >= ad) { // must be unsigned comparison
1551 } while (q1 < delta || (q1 == delta && r1 == 0));
1553 mag.m = (int32_t)(q2 + 1); // make sure to sign extend
1554 if (d < 0) mag.m = -mag.m; // resulting magic number
1555 mag.s = p - 32; // resulting shift
1559 /// magicu - calculate the magic numbers required to codegen an integer udiv as
1560 /// a sequence of multiply, add and shifts. Requires that the divisor not be 0.
1561 static mu magicu32(uint32_t d) {
1563 uint32_t nc, delta, q1, r1, q2, r2;
1565 magu.a = 0; // initialize "add" indicator
1567 p = 31; // initialize p
1568 q1 = 0x80000000/nc; // initialize q1 = 2p/nc
1569 r1 = 0x80000000 - q1*nc; // initialize r1 = rem(2p,nc)
1570 q2 = 0x7FFFFFFF/d; // initialize q2 = (2p-1)/d
1571 r2 = 0x7FFFFFFF - q2*d; // initialize r2 = rem((2p-1),d)
1574 if (r1 >= nc - r1 ) {
1575 q1 = 2*q1 + 1; // update q1
1576 r1 = 2*r1 - nc; // update r1
1579 q1 = 2*q1; // update q1
1580 r1 = 2*r1; // update r1
1582 if (r2 + 1 >= d - r2) {
1583 if (q2 >= 0x7FFFFFFF) magu.a = 1;
1584 q2 = 2*q2 + 1; // update q2
1585 r2 = 2*r2 + 1 - d; // update r2
1588 if (q2 >= 0x80000000) magu.a = 1;
1589 q2 = 2*q2; // update q2
1590 r2 = 2*r2 + 1; // update r2
1593 } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
1594 magu.m = q2 + 1; // resulting magic number
1595 magu.s = p - 32; // resulting shift
1599 /// magic - calculate the magic numbers required to codegen an integer sdiv as
1600 /// a sequence of multiply and shifts. Requires that the divisor not be 0, 1,
1602 static ms magic64(int64_t d) {
1604 uint64_t ad, anc, delta, q1, r1, q2, r2, t;
1605 const uint64_t two63 = 9223372036854775808ULL; // 2^63
1608 ad = d >= 0 ? d : -d;
1609 t = two63 + ((uint64_t)d >> 63);
1610 anc = t - 1 - t%ad; // absolute value of nc
1611 p = 63; // initialize p
1612 q1 = two63/anc; // initialize q1 = 2p/abs(nc)
1613 r1 = two63 - q1*anc; // initialize r1 = rem(2p,abs(nc))
1614 q2 = two63/ad; // initialize q2 = 2p/abs(d)
1615 r2 = two63 - q2*ad; // initialize r2 = rem(2p,abs(d))
1618 q1 = 2*q1; // update q1 = 2p/abs(nc)
1619 r1 = 2*r1; // update r1 = rem(2p/abs(nc))
1620 if (r1 >= anc) { // must be unsigned comparison
1624 q2 = 2*q2; // update q2 = 2p/abs(d)
1625 r2 = 2*r2; // update r2 = rem(2p/abs(d))
1626 if (r2 >= ad) { // must be unsigned comparison
1631 } while (q1 < delta || (q1 == delta && r1 == 0));
1634 if (d < 0) mag.m = -mag.m; // resulting magic number
1635 mag.s = p - 64; // resulting shift
1639 /// magicu - calculate the magic numbers required to codegen an integer udiv as
1640 /// a sequence of multiply, add and shifts. Requires that the divisor not be 0.
1641 static mu magicu64(uint64_t d)
1644 uint64_t nc, delta, q1, r1, q2, r2;
1646 magu.a = 0; // initialize "add" indicator
1648 p = 63; // initialize p
1649 q1 = 0x8000000000000000ull/nc; // initialize q1 = 2p/nc
1650 r1 = 0x8000000000000000ull - q1*nc; // initialize r1 = rem(2p,nc)
1651 q2 = 0x7FFFFFFFFFFFFFFFull/d; // initialize q2 = (2p-1)/d
1652 r2 = 0x7FFFFFFFFFFFFFFFull - q2*d; // initialize r2 = rem((2p-1),d)
1655 if (r1 >= nc - r1 ) {
1656 q1 = 2*q1 + 1; // update q1
1657 r1 = 2*r1 - nc; // update r1
1660 q1 = 2*q1; // update q1
1661 r1 = 2*r1; // update r1
1663 if (r2 + 1 >= d - r2) {
1664 if (q2 >= 0x7FFFFFFFFFFFFFFFull) magu.a = 1;
1665 q2 = 2*q2 + 1; // update q2
1666 r2 = 2*r2 + 1 - d; // update r2
1669 if (q2 >= 0x8000000000000000ull) magu.a = 1;
1670 q2 = 2*q2; // update q2
1671 r2 = 2*r2 + 1; // update r2
1674 } while (p < 128 && (q1 < delta || (q1 == delta && r1 == 0)));
1675 magu.m = q2 + 1; // resulting magic number
1676 magu.s = p - 64; // resulting shift
1680 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
1681 /// return a DAG expression to select that will generate the same value by
1682 /// multiplying by a magic number. See:
1683 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
1684 SDOperand TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
1685 std::vector<SDNode*>* Created) const {
1686 MVT::ValueType VT = N->getValueType(0);
1688 // Check to see if we can do this.
1689 if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
1690 return SDOperand(); // BuildSDIV only operates on i32 or i64
1691 if (!isOperationLegal(ISD::MULHS, VT))
1692 return SDOperand(); // Make sure the target supports MULHS.
1694 int64_t d = cast<ConstantSDNode>(N->getOperand(1))->getSignExtended();
1695 ms magics = (VT == MVT::i32) ? magic32(d) : magic64(d);
1697 // Multiply the numerator (operand 0) by the magic value
1698 SDOperand Q = DAG.getNode(ISD::MULHS, VT, N->getOperand(0),
1699 DAG.getConstant(magics.m, VT));
1700 // If d > 0 and m < 0, add the numerator
1701 if (d > 0 && magics.m < 0) {
1702 Q = DAG.getNode(ISD::ADD, VT, Q, N->getOperand(0));
1704 Created->push_back(Q.Val);
1706 // If d < 0 and m > 0, subtract the numerator.
1707 if (d < 0 && magics.m > 0) {
1708 Q = DAG.getNode(ISD::SUB, VT, Q, N->getOperand(0));
1710 Created->push_back(Q.Val);
1712 // Shift right algebraic if shift value is nonzero
1714 Q = DAG.getNode(ISD::SRA, VT, Q,
1715 DAG.getConstant(magics.s, getShiftAmountTy()));
1717 Created->push_back(Q.Val);
1719 // Extract the sign bit and add it to the quotient
1721 DAG.getNode(ISD::SRL, VT, Q, DAG.getConstant(MVT::getSizeInBits(VT)-1,
1722 getShiftAmountTy()));
1724 Created->push_back(T.Val);
1725 return DAG.getNode(ISD::ADD, VT, Q, T);
1728 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
1729 /// return a DAG expression to select that will generate the same value by
1730 /// multiplying by a magic number. See:
1731 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
1732 SDOperand TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
1733 std::vector<SDNode*>* Created) const {
1734 MVT::ValueType VT = N->getValueType(0);
1736 // Check to see if we can do this.
1737 if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
1738 return SDOperand(); // BuildUDIV only operates on i32 or i64
1739 if (!isOperationLegal(ISD::MULHU, VT))
1740 return SDOperand(); // Make sure the target supports MULHU.
1742 uint64_t d = cast<ConstantSDNode>(N->getOperand(1))->getValue();
1743 mu magics = (VT == MVT::i32) ? magicu32(d) : magicu64(d);
1745 // Multiply the numerator (operand 0) by the magic value
1746 SDOperand Q = DAG.getNode(ISD::MULHU, VT, N->getOperand(0),
1747 DAG.getConstant(magics.m, VT));
1749 Created->push_back(Q.Val);
1751 if (magics.a == 0) {
1752 return DAG.getNode(ISD::SRL, VT, Q,
1753 DAG.getConstant(magics.s, getShiftAmountTy()));
1755 SDOperand NPQ = DAG.getNode(ISD::SUB, VT, N->getOperand(0), Q);
1757 Created->push_back(NPQ.Val);
1758 NPQ = DAG.getNode(ISD::SRL, VT, NPQ,
1759 DAG.getConstant(1, getShiftAmountTy()));
1761 Created->push_back(NPQ.Val);
1762 NPQ = DAG.getNode(ISD::ADD, VT, NPQ, Q);
1764 Created->push_back(NPQ.Val);
1765 return DAG.getNode(ISD::SRL, VT, NPQ,
1766 DAG.getConstant(magics.s-1, getShiftAmountTy()));