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"
25 /// InitLibcallNames - Set default libcall names.
27 static void InitLibcallNames(const char **Names) {
28 Names[RTLIB::SHL_I32] = "__ashlsi3";
29 Names[RTLIB::SHL_I64] = "__ashldi3";
30 Names[RTLIB::SRL_I32] = "__lshrsi3";
31 Names[RTLIB::SRL_I64] = "__lshrdi3";
32 Names[RTLIB::SRA_I32] = "__ashrsi3";
33 Names[RTLIB::SRA_I64] = "__ashrdi3";
34 Names[RTLIB::MUL_I32] = "__mulsi3";
35 Names[RTLIB::MUL_I64] = "__muldi3";
36 Names[RTLIB::SDIV_I32] = "__divsi3";
37 Names[RTLIB::SDIV_I64] = "__divdi3";
38 Names[RTLIB::UDIV_I32] = "__udivsi3";
39 Names[RTLIB::UDIV_I64] = "__udivdi3";
40 Names[RTLIB::SREM_I32] = "__modsi3";
41 Names[RTLIB::SREM_I64] = "__moddi3";
42 Names[RTLIB::UREM_I32] = "__umodsi3";
43 Names[RTLIB::UREM_I64] = "__umoddi3";
44 Names[RTLIB::NEG_I32] = "__negsi2";
45 Names[RTLIB::NEG_I64] = "__negdi2";
46 Names[RTLIB::ADD_F32] = "__addsf3";
47 Names[RTLIB::ADD_F64] = "__adddf3";
48 Names[RTLIB::SUB_F32] = "__subsf3";
49 Names[RTLIB::SUB_F64] = "__subdf3";
50 Names[RTLIB::MUL_F32] = "__mulsf3";
51 Names[RTLIB::MUL_F64] = "__muldf3";
52 Names[RTLIB::DIV_F32] = "__divsf3";
53 Names[RTLIB::DIV_F64] = "__divdf3";
54 Names[RTLIB::REM_F32] = "fmodf";
55 Names[RTLIB::REM_F64] = "fmod";
56 Names[RTLIB::NEG_F32] = "__negsf2";
57 Names[RTLIB::NEG_F64] = "__negdf2";
58 Names[RTLIB::POWI_F32] = "__powisf2";
59 Names[RTLIB::POWI_F64] = "__powidf2";
60 Names[RTLIB::SQRT_F32] = "sqrtf";
61 Names[RTLIB::SQRT_F64] = "sqrt";
62 Names[RTLIB::SIN_F32] = "sinf";
63 Names[RTLIB::SIN_F64] = "sin";
64 Names[RTLIB::COS_F32] = "cosf";
65 Names[RTLIB::COS_F64] = "cos";
66 Names[RTLIB::FPEXT_F32_F64] = "__extendsfdf2";
67 Names[RTLIB::FPROUND_F64_F32] = "__truncdfsf2";
68 Names[RTLIB::FPTOSINT_F32_I32] = "__fixsfsi";
69 Names[RTLIB::FPTOSINT_F32_I64] = "__fixsfdi";
70 Names[RTLIB::FPTOSINT_F64_I32] = "__fixdfsi";
71 Names[RTLIB::FPTOSINT_F64_I64] = "__fixdfdi";
72 Names[RTLIB::FPTOSINT_LD_I64] = "__fixxfdi";
73 Names[RTLIB::FPTOUINT_F32_I32] = "__fixunssfsi";
74 Names[RTLIB::FPTOUINT_F32_I64] = "__fixunssfdi";
75 Names[RTLIB::FPTOUINT_F64_I32] = "__fixunsdfsi";
76 Names[RTLIB::FPTOUINT_F64_I64] = "__fixunsdfdi";
77 Names[RTLIB::FPTOUINT_LD_I32] = "__fixunsxfsi";
78 Names[RTLIB::FPTOUINT_LD_I64] = "__fixunsxfdi";
79 Names[RTLIB::SINTTOFP_I32_F32] = "__floatsisf";
80 Names[RTLIB::SINTTOFP_I32_F64] = "__floatsidf";
81 Names[RTLIB::SINTTOFP_I64_F32] = "__floatdisf";
82 Names[RTLIB::SINTTOFP_I64_F64] = "__floatdidf";
83 Names[RTLIB::SINTTOFP_I64_LD] = "__floatdixf";
84 Names[RTLIB::UINTTOFP_I32_F32] = "__floatunsisf";
85 Names[RTLIB::UINTTOFP_I32_F64] = "__floatunsidf";
86 Names[RTLIB::UINTTOFP_I64_F32] = "__floatundisf";
87 Names[RTLIB::UINTTOFP_I64_F64] = "__floatundidf";
88 Names[RTLIB::OEQ_F32] = "__eqsf2";
89 Names[RTLIB::OEQ_F64] = "__eqdf2";
90 Names[RTLIB::UNE_F32] = "__nesf2";
91 Names[RTLIB::UNE_F64] = "__nedf2";
92 Names[RTLIB::OGE_F32] = "__gesf2";
93 Names[RTLIB::OGE_F64] = "__gedf2";
94 Names[RTLIB::OLT_F32] = "__ltsf2";
95 Names[RTLIB::OLT_F64] = "__ltdf2";
96 Names[RTLIB::OLE_F32] = "__lesf2";
97 Names[RTLIB::OLE_F64] = "__ledf2";
98 Names[RTLIB::OGT_F32] = "__gtsf2";
99 Names[RTLIB::OGT_F64] = "__gtdf2";
100 Names[RTLIB::UO_F32] = "__unordsf2";
101 Names[RTLIB::UO_F64] = "__unorddf2";
102 Names[RTLIB::O_F32] = "__unordsf2";
103 Names[RTLIB::O_F64] = "__unorddf2";
106 /// InitCmpLibcallCCs - Set default comparison libcall CC.
108 static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
109 memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
110 CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
111 CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
112 CCs[RTLIB::UNE_F32] = ISD::SETNE;
113 CCs[RTLIB::UNE_F64] = ISD::SETNE;
114 CCs[RTLIB::OGE_F32] = ISD::SETGE;
115 CCs[RTLIB::OGE_F64] = ISD::SETGE;
116 CCs[RTLIB::OLT_F32] = ISD::SETLT;
117 CCs[RTLIB::OLT_F64] = ISD::SETLT;
118 CCs[RTLIB::OLE_F32] = ISD::SETLE;
119 CCs[RTLIB::OLE_F64] = ISD::SETLE;
120 CCs[RTLIB::OGT_F32] = ISD::SETGT;
121 CCs[RTLIB::OGT_F64] = ISD::SETGT;
122 CCs[RTLIB::UO_F32] = ISD::SETNE;
123 CCs[RTLIB::UO_F64] = ISD::SETNE;
124 CCs[RTLIB::O_F32] = ISD::SETEQ;
125 CCs[RTLIB::O_F64] = ISD::SETEQ;
128 TargetLowering::TargetLowering(TargetMachine &tm)
129 : TM(tm), TD(TM.getTargetData()) {
130 assert(ISD::BUILTIN_OP_END <= 156 &&
131 "Fixed size array in TargetLowering is not large enough!");
132 // All operations default to being supported.
133 memset(OpActions, 0, sizeof(OpActions));
134 memset(LoadXActions, 0, sizeof(LoadXActions));
135 memset(&StoreXActions, 0, sizeof(StoreXActions));
136 memset(&IndexedModeActions, 0, sizeof(IndexedModeActions));
137 memset(&ConvertActions, 0, sizeof(ConvertActions));
139 // Set all indexed load / store to expand.
140 for (unsigned VT = 0; VT != (unsigned)MVT::LAST_VALUETYPE; ++VT) {
141 for (unsigned IM = (unsigned)ISD::PRE_INC;
142 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
143 setIndexedLoadAction(IM, (MVT::ValueType)VT, Expand);
144 setIndexedStoreAction(IM, (MVT::ValueType)VT, Expand);
148 IsLittleEndian = TD->isLittleEndian();
149 UsesGlobalOffsetTable = false;
150 ShiftAmountTy = SetCCResultTy = PointerTy = getValueType(TD->getIntPtrType());
151 ShiftAmtHandling = Undefined;
152 memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*));
153 memset(TargetDAGCombineArray, 0, array_lengthof(TargetDAGCombineArray));
154 maxStoresPerMemset = maxStoresPerMemcpy = maxStoresPerMemmove = 8;
155 allowUnalignedMemoryAccesses = false;
156 UseUnderscoreSetJmp = false;
157 UseUnderscoreLongJmp = false;
158 SelectIsExpensive = false;
159 IntDivIsCheap = false;
160 Pow2DivIsCheap = false;
161 StackPointerRegisterToSaveRestore = 0;
162 ExceptionPointerRegister = 0;
163 ExceptionSelectorRegister = 0;
164 SchedPreferenceInfo = SchedulingForLatency;
166 JumpBufAlignment = 0;
167 IfCvtBlockSizeLimit = 2;
169 InitLibcallNames(LibcallRoutineNames);
170 InitCmpLibcallCCs(CmpLibcallCCs);
173 TargetLowering::~TargetLowering() {}
175 /// computeRegisterProperties - Once all of the register classes are added,
176 /// this allows us to compute derived properties we expose.
177 void TargetLowering::computeRegisterProperties() {
178 assert(MVT::LAST_VALUETYPE <= 32 &&
179 "Too many value types for ValueTypeActions to hold!");
181 // Everything defaults to needing one register.
182 for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
183 NumRegistersForVT[i] = 1;
184 RegisterTypeForVT[i] = TransformToType[i] = i;
186 // ...except isVoid, which doesn't need any registers.
187 NumRegistersForVT[MVT::isVoid] = 0;
189 // Find the largest integer register class.
190 unsigned LargestIntReg = MVT::i128;
191 for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg)
192 assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
194 // Every integer value type larger than this largest register takes twice as
195 // many registers to represent as the previous ValueType.
196 for (MVT::ValueType ExpandedReg = LargestIntReg + 1;
197 MVT::isInteger(ExpandedReg); ++ExpandedReg) {
198 NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
199 RegisterTypeForVT[ExpandedReg] = LargestIntReg;
200 TransformToType[ExpandedReg] = ExpandedReg - 1;
201 ValueTypeActions.setTypeAction(ExpandedReg, Expand);
204 // Inspect all of the ValueType's smaller than the largest integer
205 // register to see which ones need promotion.
206 MVT::ValueType LegalIntReg = LargestIntReg;
207 for (MVT::ValueType IntReg = LargestIntReg - 1;
208 IntReg >= MVT::i1; --IntReg) {
209 if (isTypeLegal(IntReg)) {
210 LegalIntReg = IntReg;
212 RegisterTypeForVT[IntReg] = TransformToType[IntReg] = LegalIntReg;
213 ValueTypeActions.setTypeAction(IntReg, Promote);
217 // Decide how to handle f64. If the target does not have native f64 support,
218 // expand it to i64 and we will be generating soft float library calls.
219 if (!isTypeLegal(MVT::f64)) {
220 NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
221 RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
222 TransformToType[MVT::f64] = MVT::i64;
223 ValueTypeActions.setTypeAction(MVT::f64, Expand);
226 // Decide how to handle f32. If the target does not have native support for
227 // f32, promote it to f64 if it is legal. Otherwise, expand it to i32.
228 if (!isTypeLegal(MVT::f32)) {
229 if (isTypeLegal(MVT::f64)) {
230 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::f64];
231 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::f64];
232 TransformToType[MVT::f32] = MVT::f64;
233 ValueTypeActions.setTypeAction(MVT::f32, Promote);
235 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
236 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
237 TransformToType[MVT::f32] = MVT::i32;
238 ValueTypeActions.setTypeAction(MVT::f32, Expand);
242 // Loop over all of the vector value types to see which need transformations.
243 for (MVT::ValueType i = MVT::FIRST_VECTOR_VALUETYPE;
244 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
245 if (!isTypeLegal(i)) {
246 MVT::ValueType IntermediateVT, RegisterVT;
247 unsigned NumIntermediates;
248 NumRegistersForVT[i] =
249 getVectorTypeBreakdown(i,
250 IntermediateVT, NumIntermediates,
252 RegisterTypeForVT[i] = RegisterVT;
253 TransformToType[i] = MVT::Other; // this isn't actually used
254 ValueTypeActions.setTypeAction(i, Expand);
259 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
263 /// getVectorTypeBreakdown - Vector types are broken down into some number of
264 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
265 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
266 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
268 /// This method returns the number of registers needed, and the VT for each
269 /// register. It also returns the VT and quantity of the intermediate values
270 /// before they are promoted/expanded.
272 unsigned TargetLowering::getVectorTypeBreakdown(MVT::ValueType VT,
273 MVT::ValueType &IntermediateVT,
274 unsigned &NumIntermediates,
275 MVT::ValueType &RegisterVT) const {
276 // Figure out the right, legal destination reg to copy into.
277 unsigned NumElts = MVT::getVectorNumElements(VT);
278 MVT::ValueType EltTy = MVT::getVectorElementType(VT);
280 unsigned NumVectorRegs = 1;
282 // Divide the input until we get to a supported size. This will always
283 // end with a scalar if the target doesn't support vectors.
284 while (NumElts > 1 &&
285 !isTypeLegal(MVT::getVectorType(EltTy, NumElts))) {
290 NumIntermediates = NumVectorRegs;
292 MVT::ValueType NewVT = MVT::getVectorType(EltTy, NumElts);
293 if (!isTypeLegal(NewVT))
295 IntermediateVT = NewVT;
297 MVT::ValueType DestVT = getTypeToTransformTo(NewVT);
299 if (DestVT < NewVT) {
300 // Value is expanded, e.g. i64 -> i16.
301 return NumVectorRegs*(MVT::getSizeInBits(NewVT)/MVT::getSizeInBits(DestVT));
303 // Otherwise, promotion or legal types use the same number of registers as
304 // the vector decimated to the appropriate level.
305 return NumVectorRegs;
311 //===----------------------------------------------------------------------===//
312 // Optimization Methods
313 //===----------------------------------------------------------------------===//
315 /// ShrinkDemandedConstant - Check to see if the specified operand of the
316 /// specified instruction is a constant integer. If so, check to see if there
317 /// are any bits set in the constant that are not demanded. If so, shrink the
318 /// constant and return true.
319 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDOperand Op,
321 // FIXME: ISD::SELECT, ISD::SELECT_CC
322 switch(Op.getOpcode()) {
327 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
328 if ((~Demanded & C->getValue()) != 0) {
329 MVT::ValueType VT = Op.getValueType();
330 SDOperand New = DAG.getNode(Op.getOpcode(), VT, Op.getOperand(0),
331 DAG.getConstant(Demanded & C->getValue(),
333 return CombineTo(Op, New);
340 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
341 /// DemandedMask bits of the result of Op are ever used downstream. If we can
342 /// use this information to simplify Op, create a new simplified DAG node and
343 /// return true, returning the original and new nodes in Old and New. Otherwise,
344 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
345 /// the expression (used to simplify the caller). The KnownZero/One bits may
346 /// only be accurate for those bits in the DemandedMask.
347 bool TargetLowering::SimplifyDemandedBits(SDOperand Op, uint64_t DemandedMask,
350 TargetLoweringOpt &TLO,
351 unsigned Depth) const {
352 KnownZero = KnownOne = 0; // Don't know anything.
354 // The masks are not wide enough to represent this type! Should use APInt.
355 if (Op.getValueType() == MVT::i128)
358 // Other users may use these bits.
359 if (!Op.Val->hasOneUse()) {
361 // If not at the root, Just compute the KnownZero/KnownOne bits to
362 // simplify things downstream.
363 TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
366 // If this is the root being simplified, allow it to have multiple uses,
367 // just set the DemandedMask to all bits.
368 DemandedMask = MVT::getIntVTBitMask(Op.getValueType());
369 } else if (DemandedMask == 0) {
370 // Not demanding any bits from Op.
371 if (Op.getOpcode() != ISD::UNDEF)
372 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::UNDEF, Op.getValueType()));
374 } else if (Depth == 6) { // Limit search depth.
378 uint64_t KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
379 switch (Op.getOpcode()) {
381 // We know all of the bits for a constant!
382 KnownOne = cast<ConstantSDNode>(Op)->getValue() & DemandedMask;
383 KnownZero = ~KnownOne & DemandedMask;
384 return false; // Don't fall through, will infinitely loop.
386 // If the RHS is a constant, check to see if the LHS would be zero without
387 // using the bits from the RHS. Below, we use knowledge about the RHS to
388 // simplify the LHS, here we're using information from the LHS to simplify
390 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
391 uint64_t LHSZero, LHSOne;
392 TLO.DAG.ComputeMaskedBits(Op.getOperand(0), DemandedMask,
393 LHSZero, LHSOne, Depth+1);
394 // If the LHS already has zeros where RHSC does, this and is dead.
395 if ((LHSZero & DemandedMask) == (~RHSC->getValue() & DemandedMask))
396 return TLO.CombineTo(Op, Op.getOperand(0));
397 // If any of the set bits in the RHS are known zero on the LHS, shrink
399 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & DemandedMask))
403 if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero,
404 KnownOne, TLO, Depth+1))
406 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
407 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & ~KnownZero,
408 KnownZero2, KnownOne2, TLO, Depth+1))
410 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
412 // If all of the demanded bits are known one on one side, return the other.
413 // These bits cannot contribute to the result of the 'and'.
414 if ((DemandedMask & ~KnownZero2 & KnownOne)==(DemandedMask & ~KnownZero2))
415 return TLO.CombineTo(Op, Op.getOperand(0));
416 if ((DemandedMask & ~KnownZero & KnownOne2)==(DemandedMask & ~KnownZero))
417 return TLO.CombineTo(Op, Op.getOperand(1));
418 // If all of the demanded bits in the inputs are known zeros, return zero.
419 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
420 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
421 // If the RHS is a constant, see if we can simplify it.
422 if (TLO.ShrinkDemandedConstant(Op, DemandedMask & ~KnownZero2))
425 // Output known-1 bits are only known if set in both the LHS & RHS.
426 KnownOne &= KnownOne2;
427 // Output known-0 are known to be clear if zero in either the LHS | RHS.
428 KnownZero |= KnownZero2;
431 if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero,
432 KnownOne, TLO, Depth+1))
434 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
435 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & ~KnownOne,
436 KnownZero2, KnownOne2, TLO, Depth+1))
438 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
440 // If all of the demanded bits are known zero on one side, return the other.
441 // These bits cannot contribute to the result of the 'or'.
442 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
443 return TLO.CombineTo(Op, Op.getOperand(0));
444 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
445 return TLO.CombineTo(Op, Op.getOperand(1));
446 // If all of the potentially set bits on one side are known to be set on
447 // the other side, just use the 'other' side.
448 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
449 (DemandedMask & (~KnownZero)))
450 return TLO.CombineTo(Op, Op.getOperand(0));
451 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
452 (DemandedMask & (~KnownZero2)))
453 return TLO.CombineTo(Op, Op.getOperand(1));
454 // If the RHS is a constant, see if we can simplify it.
455 if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
458 // Output known-0 bits are only known if clear in both the LHS & RHS.
459 KnownZero &= KnownZero2;
460 // Output known-1 are known to be set if set in either the LHS | RHS.
461 KnownOne |= KnownOne2;
464 if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero,
465 KnownOne, TLO, Depth+1))
467 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
468 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask, KnownZero2,
469 KnownOne2, TLO, Depth+1))
471 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
473 // If all of the demanded bits are known zero on one side, return the other.
474 // These bits cannot contribute to the result of the 'xor'.
475 if ((DemandedMask & KnownZero) == DemandedMask)
476 return TLO.CombineTo(Op, Op.getOperand(0));
477 if ((DemandedMask & KnownZero2) == DemandedMask)
478 return TLO.CombineTo(Op, Op.getOperand(1));
480 // If all of the unknown bits are known to be zero on one side or the other
481 // (but not both) turn this into an *inclusive* or.
482 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
483 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0)
484 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, Op.getValueType(),
488 // Output known-0 bits are known if clear or set in both the LHS & RHS.
489 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
490 // Output known-1 are known to be set if set in only one of the LHS, RHS.
491 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
493 // If all of the demanded bits on one side are known, and all of the set
494 // bits on that side are also known to be set on the other side, turn this
495 // into an AND, as we know the bits will be cleared.
496 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
497 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
498 if ((KnownOne & KnownOne2) == KnownOne) {
499 MVT::ValueType VT = Op.getValueType();
500 SDOperand ANDC = TLO.DAG.getConstant(~KnownOne & DemandedMask, VT);
501 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, VT, Op.getOperand(0),
506 // If the RHS is a constant, see if we can simplify it.
507 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
508 if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
511 KnownZero = KnownZeroOut;
512 KnownOne = KnownOneOut;
515 // If we know the result of a setcc has the top bits zero, use this info.
516 if (getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult)
517 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
520 if (SimplifyDemandedBits(Op.getOperand(2), DemandedMask, KnownZero,
521 KnownOne, TLO, Depth+1))
523 if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero2,
524 KnownOne2, TLO, Depth+1))
526 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
527 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
529 // If the operands are constants, see if we can simplify them.
530 if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
533 // Only known if known in both the LHS and RHS.
534 KnownOne &= KnownOne2;
535 KnownZero &= KnownZero2;
538 if (SimplifyDemandedBits(Op.getOperand(3), DemandedMask, KnownZero,
539 KnownOne, TLO, Depth+1))
541 if (SimplifyDemandedBits(Op.getOperand(2), DemandedMask, KnownZero2,
542 KnownOne2, TLO, Depth+1))
544 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
545 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
547 // If the operands are constants, see if we can simplify them.
548 if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
551 // Only known if known in both the LHS and RHS.
552 KnownOne &= KnownOne2;
553 KnownZero &= KnownZero2;
556 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
557 unsigned ShAmt = SA->getValue();
558 SDOperand InOp = Op.getOperand(0);
560 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
561 // single shift. We can do this if the bottom bits (which are shifted
562 // out) are never demanded.
563 if (InOp.getOpcode() == ISD::SRL &&
564 isa<ConstantSDNode>(InOp.getOperand(1))) {
565 if (ShAmt && (DemandedMask & ((1ULL << ShAmt)-1)) == 0) {
566 unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
567 unsigned Opc = ISD::SHL;
575 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
576 MVT::ValueType VT = Op.getValueType();
577 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
578 InOp.getOperand(0), NewSA));
582 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask >> ShAmt,
583 KnownZero, KnownOne, TLO, Depth+1))
585 KnownZero <<= SA->getValue();
586 KnownOne <<= SA->getValue();
587 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
591 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
592 MVT::ValueType VT = Op.getValueType();
593 unsigned ShAmt = SA->getValue();
594 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
595 unsigned VTSize = MVT::getSizeInBits(VT);
596 SDOperand InOp = Op.getOperand(0);
598 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
599 // single shift. We can do this if the top bits (which are shifted out)
600 // are never demanded.
601 if (InOp.getOpcode() == ISD::SHL &&
602 isa<ConstantSDNode>(InOp.getOperand(1))) {
603 if (ShAmt && (DemandedMask & (~0ULL << (VTSize-ShAmt))) == 0) {
604 unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
605 unsigned Opc = ISD::SRL;
613 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
614 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
615 InOp.getOperand(0), NewSA));
619 // Compute the new bits that are at the top now.
620 if (SimplifyDemandedBits(InOp, (DemandedMask << ShAmt) & TypeMask,
621 KnownZero, KnownOne, TLO, Depth+1))
623 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
624 KnownZero &= TypeMask;
625 KnownOne &= TypeMask;
629 uint64_t HighBits = (1ULL << ShAmt)-1;
630 HighBits <<= VTSize - ShAmt;
631 KnownZero |= HighBits; // High bits known zero.
635 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
636 MVT::ValueType VT = Op.getValueType();
637 unsigned ShAmt = SA->getValue();
639 // Compute the new bits that are at the top now.
640 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
642 uint64_t InDemandedMask = (DemandedMask << ShAmt) & TypeMask;
644 // If any of the demanded bits are produced by the sign extension, we also
645 // demand the input sign bit.
646 uint64_t HighBits = (1ULL << ShAmt)-1;
647 HighBits <<= MVT::getSizeInBits(VT) - ShAmt;
648 if (HighBits & DemandedMask)
649 InDemandedMask |= MVT::getIntVTSignBit(VT);
651 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
652 KnownZero, KnownOne, TLO, Depth+1))
654 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
655 KnownZero &= TypeMask;
656 KnownOne &= TypeMask;
660 // Handle the sign bits.
661 uint64_t SignBit = MVT::getIntVTSignBit(VT);
662 SignBit >>= ShAmt; // Adjust to where it is now in the mask.
664 // If the input sign bit is known to be zero, or if none of the top bits
665 // are demanded, turn this into an unsigned shift right.
666 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
667 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, VT, Op.getOperand(0),
669 } else if (KnownOne & SignBit) { // New bits are known one.
670 KnownOne |= HighBits;
674 case ISD::SIGN_EXTEND_INREG: {
675 MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
677 // Sign extension. Compute the demanded bits in the result that are not
678 // present in the input.
679 uint64_t NewBits = ~MVT::getIntVTBitMask(EVT) & DemandedMask;
681 // If none of the extended bits are demanded, eliminate the sextinreg.
683 return TLO.CombineTo(Op, Op.getOperand(0));
685 uint64_t InSignBit = MVT::getIntVTSignBit(EVT);
686 int64_t InputDemandedBits = DemandedMask & MVT::getIntVTBitMask(EVT);
688 // Since the sign extended bits are demanded, we know that the sign
690 InputDemandedBits |= InSignBit;
692 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
693 KnownZero, KnownOne, TLO, Depth+1))
695 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 // If the sign bit of the input is known set or clear, then we know the
698 // top bits of the result.
700 // If the input sign bit is known zero, convert this into a zero extension.
701 if (KnownZero & InSignBit)
702 return TLO.CombineTo(Op,
703 TLO.DAG.getZeroExtendInReg(Op.getOperand(0), EVT));
705 if (KnownOne & InSignBit) { // Input sign bit known set
707 KnownZero &= ~NewBits;
708 } else { // Input sign bit unknown
709 KnownZero &= ~NewBits;
710 KnownOne &= ~NewBits;
717 MVT::ValueType VT = Op.getValueType();
718 unsigned LowBits = Log2_32(MVT::getSizeInBits(VT))+1;
719 KnownZero = ~((1ULL << LowBits)-1) & MVT::getIntVTBitMask(VT);
724 if (ISD::isZEXTLoad(Op.Val)) {
725 LoadSDNode *LD = cast<LoadSDNode>(Op);
726 MVT::ValueType VT = LD->getLoadedVT();
727 KnownZero |= ~MVT::getIntVTBitMask(VT) & DemandedMask;
731 case ISD::ZERO_EXTEND: {
732 uint64_t InMask = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
734 // If none of the top bits are demanded, convert this into an any_extend.
735 uint64_t NewBits = (~InMask) & DemandedMask;
737 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND,
741 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & InMask,
742 KnownZero, KnownOne, TLO, Depth+1))
744 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
745 KnownZero |= NewBits;
748 case ISD::SIGN_EXTEND: {
749 MVT::ValueType InVT = Op.getOperand(0).getValueType();
750 uint64_t InMask = MVT::getIntVTBitMask(InVT);
751 uint64_t InSignBit = MVT::getIntVTSignBit(InVT);
752 uint64_t NewBits = (~InMask) & DemandedMask;
754 // If none of the top bits are demanded, convert this into an any_extend.
756 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND,Op.getValueType(),
759 // Since some of the sign extended bits are demanded, we know that the sign
761 uint64_t InDemandedBits = DemandedMask & InMask;
762 InDemandedBits |= InSignBit;
764 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
765 KnownOne, TLO, Depth+1))
768 // If the sign bit is known zero, convert this to a zero extend.
769 if (KnownZero & InSignBit)
770 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND,
774 // If the sign bit is known one, the top bits match.
775 if (KnownOne & InSignBit) {
777 KnownZero &= ~NewBits;
778 } else { // Otherwise, top bits aren't known.
779 KnownOne &= ~NewBits;
780 KnownZero &= ~NewBits;
784 case ISD::ANY_EXTEND: {
785 uint64_t InMask = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
786 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & InMask,
787 KnownZero, KnownOne, TLO, Depth+1))
789 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
792 case ISD::TRUNCATE: {
793 // Simplify the input, using demanded bit information, and compute the known
794 // zero/one bits live out.
795 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
796 KnownZero, KnownOne, TLO, Depth+1))
799 // If the input is only used by this truncate, see if we can shrink it based
800 // on the known demanded bits.
801 if (Op.getOperand(0).Val->hasOneUse()) {
802 SDOperand In = Op.getOperand(0);
803 switch (In.getOpcode()) {
806 // Shrink SRL by a constant if none of the high bits shifted in are
808 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1))){
809 uint64_t HighBits = MVT::getIntVTBitMask(In.getValueType());
810 HighBits &= ~MVT::getIntVTBitMask(Op.getValueType());
811 HighBits >>= ShAmt->getValue();
813 if (ShAmt->getValue() < MVT::getSizeInBits(Op.getValueType()) &&
814 (DemandedMask & HighBits) == 0) {
815 // None of the shifted in bits are needed. Add a truncate of the
816 // shift input, then shift it.
817 SDOperand NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE,
820 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL,Op.getValueType(),
821 NewTrunc, In.getOperand(1)));
828 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
829 uint64_t OutMask = MVT::getIntVTBitMask(Op.getValueType());
830 KnownZero &= OutMask;
834 case ISD::AssertZext: {
835 MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
836 uint64_t InMask = MVT::getIntVTBitMask(VT);
837 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & InMask,
838 KnownZero, KnownOne, TLO, Depth+1))
840 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
841 KnownZero |= ~InMask & DemandedMask;
846 case ISD::INTRINSIC_WO_CHAIN:
847 case ISD::INTRINSIC_W_CHAIN:
848 case ISD::INTRINSIC_VOID:
849 // Just use ComputeMaskedBits to compute output bits.
850 TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
854 // If we know the value of all of the demanded bits, return this as a
856 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
857 return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
862 /// computeMaskedBitsForTargetNode - Determine which of the bits specified
863 /// in Mask are known to be either zero or one and return them in the
864 /// KnownZero/KnownOne bitsets.
865 void TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
869 const SelectionDAG &DAG,
870 unsigned Depth) const {
871 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
872 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
873 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
874 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
875 "Should use MaskedValueIsZero if you don't know whether Op"
876 " is a target node!");
881 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
882 /// targets that want to expose additional information about sign bits to the
884 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDOperand Op,
885 unsigned Depth) const {
886 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
887 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
888 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
889 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
890 "Should use ComputeNumSignBits if you don't know whether Op"
891 " is a target node!");
896 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
897 /// and cc. If it is unable to simplify it, return a null SDOperand.
899 TargetLowering::SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
900 ISD::CondCode Cond, bool foldBooleans,
901 DAGCombinerInfo &DCI) const {
902 SelectionDAG &DAG = DCI.DAG;
904 // These setcc operations always fold.
908 case ISD::SETFALSE2: return DAG.getConstant(0, VT);
910 case ISD::SETTRUE2: return DAG.getConstant(1, VT);
913 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
914 uint64_t C1 = N1C->getValue();
915 if (isa<ConstantSDNode>(N0.Val)) {
916 return DAG.FoldSetCC(VT, N0, N1, Cond);
918 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
919 // equality comparison, then we're just comparing whether X itself is
921 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
922 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
923 N0.getOperand(1).getOpcode() == ISD::Constant) {
924 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
925 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
926 ShAmt == Log2_32(MVT::getSizeInBits(N0.getValueType()))) {
927 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
928 // (srl (ctlz x), 5) == 0 -> X != 0
929 // (srl (ctlz x), 5) != 1 -> X != 0
932 // (srl (ctlz x), 5) != 0 -> X == 0
933 // (srl (ctlz x), 5) == 1 -> X == 0
936 SDOperand Zero = DAG.getConstant(0, N0.getValueType());
937 return DAG.getSetCC(VT, N0.getOperand(0).getOperand(0),
942 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
943 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
944 unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
946 // If the comparison constant has bits in the upper part, the
947 // zero-extended value could never match.
948 if (C1 & (~0ULL << InSize)) {
949 unsigned VSize = MVT::getSizeInBits(N0.getValueType());
953 case ISD::SETEQ: return DAG.getConstant(0, VT);
956 case ISD::SETNE: return DAG.getConstant(1, VT);
959 // True if the sign bit of C1 is set.
960 return DAG.getConstant((C1 & (1ULL << (VSize-1))) != 0, VT);
963 // True if the sign bit of C1 isn't set.
964 return DAG.getConstant((C1 & (1ULL << (VSize-1))) == 0, VT);
970 // Otherwise, we can perform the comparison with the low bits.
978 return DAG.getSetCC(VT, N0.getOperand(0),
979 DAG.getConstant(C1, N0.getOperand(0).getValueType()),
982 break; // todo, be more careful with signed comparisons
984 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
985 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
986 MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
987 unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
988 MVT::ValueType ExtDstTy = N0.getValueType();
989 unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
991 // If the extended part has any inconsistent bits, it cannot ever
992 // compare equal. In other words, they have to be all ones or all
995 (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
996 if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
997 return DAG.getConstant(Cond == ISD::SETNE, VT);
1000 MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
1001 if (Op0Ty == ExtSrcTy) {
1002 ZextOp = N0.getOperand(0);
1004 int64_t Imm = ~0ULL >> (64-ExtSrcTyBits);
1005 ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
1006 DAG.getConstant(Imm, Op0Ty));
1008 if (!DCI.isCalledByLegalizer())
1009 DCI.AddToWorklist(ZextOp.Val);
1010 // Otherwise, make this a use of a zext.
1011 return DAG.getSetCC(VT, ZextOp,
1012 DAG.getConstant(C1 & (~0ULL>>(64-ExtSrcTyBits)),
1015 } else if ((N1C->getValue() == 0 || N1C->getValue() == 1) &&
1016 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1018 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
1019 if (N0.getOpcode() == ISD::SETCC) {
1020 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getValue() != 1);
1024 // Invert the condition.
1025 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1026 CC = ISD::getSetCCInverse(CC,
1027 MVT::isInteger(N0.getOperand(0).getValueType()));
1028 return DAG.getSetCC(VT, N0.getOperand(0), N0.getOperand(1), CC);
1031 if ((N0.getOpcode() == ISD::XOR ||
1032 (N0.getOpcode() == ISD::AND &&
1033 N0.getOperand(0).getOpcode() == ISD::XOR &&
1034 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1035 isa<ConstantSDNode>(N0.getOperand(1)) &&
1036 cast<ConstantSDNode>(N0.getOperand(1))->getValue() == 1) {
1037 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1038 // can only do this if the top bits are known zero.
1039 if (DAG.MaskedValueIsZero(N0,
1040 MVT::getIntVTBitMask(N0.getValueType())-1)){
1041 // Okay, get the un-inverted input value.
1043 if (N0.getOpcode() == ISD::XOR)
1044 Val = N0.getOperand(0);
1046 assert(N0.getOpcode() == ISD::AND &&
1047 N0.getOperand(0).getOpcode() == ISD::XOR);
1048 // ((X^1)&1)^1 -> X & 1
1049 Val = DAG.getNode(ISD::AND, N0.getValueType(),
1050 N0.getOperand(0).getOperand(0),
1053 return DAG.getSetCC(VT, Val, N1,
1054 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1059 uint64_t MinVal, MaxVal;
1060 unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
1061 if (ISD::isSignedIntSetCC(Cond)) {
1062 MinVal = 1ULL << (OperandBitSize-1);
1063 if (OperandBitSize != 1) // Avoid X >> 64, which is undefined.
1064 MaxVal = ~0ULL >> (65-OperandBitSize);
1069 MaxVal = ~0ULL >> (64-OperandBitSize);
1072 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1073 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1074 if (C1 == MinVal) return DAG.getConstant(1, VT); // X >= MIN --> true
1075 --C1; // X >= C0 --> X > (C0-1)
1076 return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
1077 (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
1080 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1081 if (C1 == MaxVal) return DAG.getConstant(1, VT); // X <= MAX --> true
1082 ++C1; // X <= C0 --> X < (C0+1)
1083 return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
1084 (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
1087 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1088 return DAG.getConstant(0, VT); // X < MIN --> false
1089 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1090 return DAG.getConstant(1, VT); // X >= MIN --> true
1091 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1092 return DAG.getConstant(0, VT); // X > MAX --> false
1093 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1094 return DAG.getConstant(1, VT); // X <= MAX --> true
1096 // Canonicalize setgt X, Min --> setne X, Min
1097 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1098 return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1099 // Canonicalize setlt X, Max --> setne X, Max
1100 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1101 return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1103 // If we have setult X, 1, turn it into seteq X, 0
1104 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1105 return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
1107 // If we have setugt X, Max-1, turn it into seteq X, Max
1108 else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1109 return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
1112 // If we have "setcc X, C0", check to see if we can shrink the immediate
1115 // SETUGT X, SINTMAX -> SETLT X, 0
1116 if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
1117 C1 == (~0ULL >> (65-OperandBitSize)))
1118 return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
1121 // FIXME: Implement the rest of these.
1123 // Fold bit comparisons when we can.
1124 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1125 VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
1126 if (ConstantSDNode *AndRHS =
1127 dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1128 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
1129 // Perform the xform if the AND RHS is a single bit.
1130 if (isPowerOf2_64(AndRHS->getValue())) {
1131 return DAG.getNode(ISD::SRL, VT, N0,
1132 DAG.getConstant(Log2_64(AndRHS->getValue()),
1133 getShiftAmountTy()));
1135 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
1136 // (X & 8) == 8 --> (X & 8) >> 3
1137 // Perform the xform if C1 is a single bit.
1138 if (isPowerOf2_64(C1)) {
1139 return DAG.getNode(ISD::SRL, VT, N0,
1140 DAG.getConstant(Log2_64(C1), getShiftAmountTy()));
1145 } else if (isa<ConstantSDNode>(N0.Val)) {
1146 // Ensure that the constant occurs on the RHS.
1147 return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
1150 if (isa<ConstantFPSDNode>(N0.Val)) {
1151 // Constant fold or commute setcc.
1152 SDOperand O = DAG.FoldSetCC(VT, N0, N1, Cond);
1153 if (O.Val) return O;
1157 // We can always fold X == X for integer setcc's.
1158 if (MVT::isInteger(N0.getValueType()))
1159 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1160 unsigned UOF = ISD::getUnorderedFlavor(Cond);
1161 if (UOF == 2) // FP operators that are undefined on NaNs.
1162 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1163 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
1164 return DAG.getConstant(UOF, VT);
1165 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
1166 // if it is not already.
1167 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
1168 if (NewCond != Cond)
1169 return DAG.getSetCC(VT, N0, N1, NewCond);
1172 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1173 MVT::isInteger(N0.getValueType())) {
1174 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
1175 N0.getOpcode() == ISD::XOR) {
1176 // Simplify (X+Y) == (X+Z) --> Y == Z
1177 if (N0.getOpcode() == N1.getOpcode()) {
1178 if (N0.getOperand(0) == N1.getOperand(0))
1179 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
1180 if (N0.getOperand(1) == N1.getOperand(1))
1181 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
1182 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
1183 // If X op Y == Y op X, try other combinations.
1184 if (N0.getOperand(0) == N1.getOperand(1))
1185 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
1186 if (N0.getOperand(1) == N1.getOperand(0))
1187 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
1191 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
1192 if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1193 // Turn (X+C1) == C2 --> X == C2-C1
1194 if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
1195 return DAG.getSetCC(VT, N0.getOperand(0),
1196 DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
1197 N0.getValueType()), Cond);
1200 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
1201 if (N0.getOpcode() == ISD::XOR)
1202 // If we know that all of the inverted bits are zero, don't bother
1203 // performing the inversion.
1204 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getValue()))
1205 return DAG.getSetCC(VT, N0.getOperand(0),
1206 DAG.getConstant(LHSR->getValue()^RHSC->getValue(),
1207 N0.getValueType()), Cond);
1210 // Turn (C1-X) == C2 --> X == C1-C2
1211 if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1212 if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) {
1213 return DAG.getSetCC(VT, N0.getOperand(1),
1214 DAG.getConstant(SUBC->getValue()-RHSC->getValue(),
1215 N0.getValueType()), Cond);
1220 // Simplify (X+Z) == X --> Z == 0
1221 if (N0.getOperand(0) == N1)
1222 return DAG.getSetCC(VT, N0.getOperand(1),
1223 DAG.getConstant(0, N0.getValueType()), Cond);
1224 if (N0.getOperand(1) == N1) {
1225 if (DAG.isCommutativeBinOp(N0.getOpcode()))
1226 return DAG.getSetCC(VT, N0.getOperand(0),
1227 DAG.getConstant(0, N0.getValueType()), Cond);
1228 else if (N0.Val->hasOneUse()) {
1229 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
1230 // (Z-X) == X --> Z == X<<1
1231 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
1233 DAG.getConstant(1, getShiftAmountTy()));
1234 if (!DCI.isCalledByLegalizer())
1235 DCI.AddToWorklist(SH.Val);
1236 return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
1241 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
1242 N1.getOpcode() == ISD::XOR) {
1243 // Simplify X == (X+Z) --> Z == 0
1244 if (N1.getOperand(0) == N0) {
1245 return DAG.getSetCC(VT, N1.getOperand(1),
1246 DAG.getConstant(0, N1.getValueType()), Cond);
1247 } else if (N1.getOperand(1) == N0) {
1248 if (DAG.isCommutativeBinOp(N1.getOpcode())) {
1249 return DAG.getSetCC(VT, N1.getOperand(0),
1250 DAG.getConstant(0, N1.getValueType()), Cond);
1251 } else if (N1.Val->hasOneUse()) {
1252 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
1253 // X == (Z-X) --> X<<1 == Z
1254 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0,
1255 DAG.getConstant(1, getShiftAmountTy()));
1256 if (!DCI.isCalledByLegalizer())
1257 DCI.AddToWorklist(SH.Val);
1258 return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
1264 // Fold away ALL boolean setcc's.
1266 if (N0.getValueType() == MVT::i1 && foldBooleans) {
1268 default: assert(0 && "Unknown integer setcc!");
1269 case ISD::SETEQ: // X == Y -> (X^Y)^1
1270 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1271 N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
1272 if (!DCI.isCalledByLegalizer())
1273 DCI.AddToWorklist(Temp.Val);
1275 case ISD::SETNE: // X != Y --> (X^Y)
1276 N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1278 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> X^1 & Y
1279 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> X^1 & Y
1280 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1281 N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
1282 if (!DCI.isCalledByLegalizer())
1283 DCI.AddToWorklist(Temp.Val);
1285 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> Y^1 & X
1286 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> Y^1 & X
1287 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1288 N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
1289 if (!DCI.isCalledByLegalizer())
1290 DCI.AddToWorklist(Temp.Val);
1292 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> X^1 | Y
1293 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> X^1 | Y
1294 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1295 N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
1296 if (!DCI.isCalledByLegalizer())
1297 DCI.AddToWorklist(Temp.Val);
1299 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> Y^1 | X
1300 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> Y^1 | X
1301 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1302 N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
1305 if (VT != MVT::i1) {
1306 if (!DCI.isCalledByLegalizer())
1307 DCI.AddToWorklist(N0.Val);
1308 // FIXME: If running after legalize, we probably can't do this.
1309 N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
1314 // Could not fold it.
1318 SDOperand TargetLowering::
1319 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1320 // Default implementation: no optimization.
1324 //===----------------------------------------------------------------------===//
1325 // Inline Assembler Implementation Methods
1326 //===----------------------------------------------------------------------===//
1328 TargetLowering::ConstraintType
1329 TargetLowering::getConstraintType(const std::string &Constraint) const {
1330 // FIXME: lots more standard ones to handle.
1331 if (Constraint.size() == 1) {
1332 switch (Constraint[0]) {
1334 case 'r': return C_RegisterClass;
1336 case 'o': // offsetable
1337 case 'V': // not offsetable
1339 case 'i': // Simple Integer or Relocatable Constant
1340 case 'n': // Simple Integer
1341 case 's': // Relocatable Constant
1342 case 'X': // Allow ANY value.
1343 case 'I': // Target registers.
1355 if (Constraint.size() > 1 && Constraint[0] == '{' &&
1356 Constraint[Constraint.size()-1] == '}')
1361 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1362 /// vector. If it is invalid, don't add anything to Ops.
1363 void TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
1364 char ConstraintLetter,
1365 std::vector<SDOperand> &Ops,
1366 SelectionDAG &DAG) {
1367 switch (ConstraintLetter) {
1369 case 'i': // Simple Integer or Relocatable Constant
1370 case 'n': // Simple Integer
1371 case 's': // Relocatable Constant
1372 case 'X': { // Allows any operand.
1373 // These operands are interested in values of the form (GV+C), where C may
1374 // be folded in as an offset of GV, or it may be explicitly added. Also, it
1375 // is possible and fine if either GV or C are missing.
1376 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
1377 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1379 // If we have "(add GV, C)", pull out GV/C
1380 if (Op.getOpcode() == ISD::ADD) {
1381 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1382 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
1383 if (C == 0 || GA == 0) {
1384 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1385 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
1387 if (C == 0 || GA == 0)
1391 // If we find a valid operand, map to the TargetXXX version so that the
1392 // value itself doesn't get selected.
1393 if (GA) { // Either &GV or &GV+C
1394 if (ConstraintLetter != 'n') {
1395 int64_t Offs = GA->getOffset();
1396 if (C) Offs += C->getValue();
1397 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
1398 Op.getValueType(), Offs));
1402 if (C) { // just C, no GV.
1403 // Simple constants are not allowed for 's'.
1404 if (ConstraintLetter != 's') {
1405 Ops.push_back(DAG.getTargetConstant(C->getValue(), Op.getValueType()));
1414 std::vector<unsigned> TargetLowering::
1415 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1416 MVT::ValueType VT) const {
1417 return std::vector<unsigned>();
1421 std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
1422 getRegForInlineAsmConstraint(const std::string &Constraint,
1423 MVT::ValueType VT) const {
1424 if (Constraint[0] != '{')
1425 return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1426 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
1428 // Remove the braces from around the name.
1429 std::string RegName(Constraint.begin()+1, Constraint.end()-1);
1431 // Figure out which register class contains this reg.
1432 const MRegisterInfo *RI = TM.getRegisterInfo();
1433 for (MRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
1434 E = RI->regclass_end(); RCI != E; ++RCI) {
1435 const TargetRegisterClass *RC = *RCI;
1437 // If none of the the value types for this register class are valid, we
1438 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1439 bool isLegal = false;
1440 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1442 if (isTypeLegal(*I)) {
1448 if (!isLegal) continue;
1450 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
1452 if (StringsEqualNoCase(RegName, RI->get(*I).Name))
1453 return std::make_pair(*I, RC);
1457 return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1460 //===----------------------------------------------------------------------===//
1461 // Loop Strength Reduction hooks
1462 //===----------------------------------------------------------------------===//
1464 /// isLegalAddressingMode - Return true if the addressing mode represented
1465 /// by AM is legal for this target, for a load/store of the specified type.
1466 bool TargetLowering::isLegalAddressingMode(const AddrMode &AM,
1467 const Type *Ty) const {
1468 // The default implementation of this implements a conservative RISCy, r+r and
1471 // Allows a sign-extended 16-bit immediate field.
1472 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
1475 // No global is ever allowed as a base.
1479 // Only support r+r,
1481 case 0: // "r+i" or just "i", depending on HasBaseReg.
1484 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
1486 // Otherwise we have r+r or r+i.
1489 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
1491 // Allow 2*r as r+r.
1498 // Magic for divide replacement
1501 int64_t m; // magic number
1502 int64_t s; // shift amount
1506 uint64_t m; // magic number
1507 int64_t a; // add indicator
1508 int64_t s; // shift amount
1511 /// magic - calculate the magic numbers required to codegen an integer sdiv as
1512 /// a sequence of multiply and shifts. Requires that the divisor not be 0, 1,
1514 static ms magic32(int32_t d) {
1516 uint32_t ad, anc, delta, q1, r1, q2, r2, t;
1517 const uint32_t two31 = 0x80000000U;
1521 t = two31 + ((uint32_t)d >> 31);
1522 anc = t - 1 - t%ad; // absolute value of nc
1523 p = 31; // initialize p
1524 q1 = two31/anc; // initialize q1 = 2p/abs(nc)
1525 r1 = two31 - q1*anc; // initialize r1 = rem(2p,abs(nc))
1526 q2 = two31/ad; // initialize q2 = 2p/abs(d)
1527 r2 = two31 - q2*ad; // initialize r2 = rem(2p,abs(d))
1530 q1 = 2*q1; // update q1 = 2p/abs(nc)
1531 r1 = 2*r1; // update r1 = rem(2p/abs(nc))
1532 if (r1 >= anc) { // must be unsigned comparison
1536 q2 = 2*q2; // update q2 = 2p/abs(d)
1537 r2 = 2*r2; // update r2 = rem(2p/abs(d))
1538 if (r2 >= ad) { // must be unsigned comparison
1543 } while (q1 < delta || (q1 == delta && r1 == 0));
1545 mag.m = (int32_t)(q2 + 1); // make sure to sign extend
1546 if (d < 0) mag.m = -mag.m; // resulting magic number
1547 mag.s = p - 32; // resulting shift
1551 /// magicu - calculate the magic numbers required to codegen an integer udiv as
1552 /// a sequence of multiply, add and shifts. Requires that the divisor not be 0.
1553 static mu magicu32(uint32_t d) {
1555 uint32_t nc, delta, q1, r1, q2, r2;
1557 magu.a = 0; // initialize "add" indicator
1559 p = 31; // initialize p
1560 q1 = 0x80000000/nc; // initialize q1 = 2p/nc
1561 r1 = 0x80000000 - q1*nc; // initialize r1 = rem(2p,nc)
1562 q2 = 0x7FFFFFFF/d; // initialize q2 = (2p-1)/d
1563 r2 = 0x7FFFFFFF - q2*d; // initialize r2 = rem((2p-1),d)
1566 if (r1 >= nc - r1 ) {
1567 q1 = 2*q1 + 1; // update q1
1568 r1 = 2*r1 - nc; // update r1
1571 q1 = 2*q1; // update q1
1572 r1 = 2*r1; // update r1
1574 if (r2 + 1 >= d - r2) {
1575 if (q2 >= 0x7FFFFFFF) magu.a = 1;
1576 q2 = 2*q2 + 1; // update q2
1577 r2 = 2*r2 + 1 - d; // update r2
1580 if (q2 >= 0x80000000) magu.a = 1;
1581 q2 = 2*q2; // update q2
1582 r2 = 2*r2 + 1; // update r2
1585 } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
1586 magu.m = q2 + 1; // resulting magic number
1587 magu.s = p - 32; // resulting shift
1591 /// magic - calculate the magic numbers required to codegen an integer sdiv as
1592 /// a sequence of multiply and shifts. Requires that the divisor not be 0, 1,
1594 static ms magic64(int64_t d) {
1596 uint64_t ad, anc, delta, q1, r1, q2, r2, t;
1597 const uint64_t two63 = 9223372036854775808ULL; // 2^63
1600 ad = d >= 0 ? d : -d;
1601 t = two63 + ((uint64_t)d >> 63);
1602 anc = t - 1 - t%ad; // absolute value of nc
1603 p = 63; // initialize p
1604 q1 = two63/anc; // initialize q1 = 2p/abs(nc)
1605 r1 = two63 - q1*anc; // initialize r1 = rem(2p,abs(nc))
1606 q2 = two63/ad; // initialize q2 = 2p/abs(d)
1607 r2 = two63 - q2*ad; // initialize r2 = rem(2p,abs(d))
1610 q1 = 2*q1; // update q1 = 2p/abs(nc)
1611 r1 = 2*r1; // update r1 = rem(2p/abs(nc))
1612 if (r1 >= anc) { // must be unsigned comparison
1616 q2 = 2*q2; // update q2 = 2p/abs(d)
1617 r2 = 2*r2; // update r2 = rem(2p/abs(d))
1618 if (r2 >= ad) { // must be unsigned comparison
1623 } while (q1 < delta || (q1 == delta && r1 == 0));
1626 if (d < 0) mag.m = -mag.m; // resulting magic number
1627 mag.s = p - 64; // resulting shift
1631 /// magicu - calculate the magic numbers required to codegen an integer udiv as
1632 /// a sequence of multiply, add and shifts. Requires that the divisor not be 0.
1633 static mu magicu64(uint64_t d)
1636 uint64_t nc, delta, q1, r1, q2, r2;
1638 magu.a = 0; // initialize "add" indicator
1640 p = 63; // initialize p
1641 q1 = 0x8000000000000000ull/nc; // initialize q1 = 2p/nc
1642 r1 = 0x8000000000000000ull - q1*nc; // initialize r1 = rem(2p,nc)
1643 q2 = 0x7FFFFFFFFFFFFFFFull/d; // initialize q2 = (2p-1)/d
1644 r2 = 0x7FFFFFFFFFFFFFFFull - q2*d; // initialize r2 = rem((2p-1),d)
1647 if (r1 >= nc - r1 ) {
1648 q1 = 2*q1 + 1; // update q1
1649 r1 = 2*r1 - nc; // update r1
1652 q1 = 2*q1; // update q1
1653 r1 = 2*r1; // update r1
1655 if (r2 + 1 >= d - r2) {
1656 if (q2 >= 0x7FFFFFFFFFFFFFFFull) magu.a = 1;
1657 q2 = 2*q2 + 1; // update q2
1658 r2 = 2*r2 + 1 - d; // update r2
1661 if (q2 >= 0x8000000000000000ull) magu.a = 1;
1662 q2 = 2*q2; // update q2
1663 r2 = 2*r2 + 1; // update r2
1666 } while (p < 128 && (q1 < delta || (q1 == delta && r1 == 0)));
1667 magu.m = q2 + 1; // resulting magic number
1668 magu.s = p - 64; // resulting shift
1672 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
1673 /// return a DAG expression to select that will generate the same value by
1674 /// multiplying by a magic number. See:
1675 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
1676 SDOperand TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
1677 std::vector<SDNode*>* Created) const {
1678 MVT::ValueType VT = N->getValueType(0);
1680 // Check to see if we can do this.
1681 if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
1682 return SDOperand(); // BuildSDIV only operates on i32 or i64
1683 if (!isOperationLegal(ISD::MULHS, VT))
1684 return SDOperand(); // Make sure the target supports MULHS.
1686 int64_t d = cast<ConstantSDNode>(N->getOperand(1))->getSignExtended();
1687 ms magics = (VT == MVT::i32) ? magic32(d) : magic64(d);
1689 // Multiply the numerator (operand 0) by the magic value
1690 SDOperand Q = DAG.getNode(ISD::MULHS, VT, N->getOperand(0),
1691 DAG.getConstant(magics.m, VT));
1692 // If d > 0 and m < 0, add the numerator
1693 if (d > 0 && magics.m < 0) {
1694 Q = DAG.getNode(ISD::ADD, VT, Q, N->getOperand(0));
1696 Created->push_back(Q.Val);
1698 // If d < 0 and m > 0, subtract the numerator.
1699 if (d < 0 && magics.m > 0) {
1700 Q = DAG.getNode(ISD::SUB, VT, Q, N->getOperand(0));
1702 Created->push_back(Q.Val);
1704 // Shift right algebraic if shift value is nonzero
1706 Q = DAG.getNode(ISD::SRA, VT, Q,
1707 DAG.getConstant(magics.s, getShiftAmountTy()));
1709 Created->push_back(Q.Val);
1711 // Extract the sign bit and add it to the quotient
1713 DAG.getNode(ISD::SRL, VT, Q, DAG.getConstant(MVT::getSizeInBits(VT)-1,
1714 getShiftAmountTy()));
1716 Created->push_back(T.Val);
1717 return DAG.getNode(ISD::ADD, VT, Q, T);
1720 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
1721 /// return a DAG expression to select that will generate the same value by
1722 /// multiplying by a magic number. See:
1723 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
1724 SDOperand TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
1725 std::vector<SDNode*>* Created) const {
1726 MVT::ValueType VT = N->getValueType(0);
1728 // Check to see if we can do this.
1729 if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
1730 return SDOperand(); // BuildUDIV only operates on i32 or i64
1731 if (!isOperationLegal(ISD::MULHU, VT))
1732 return SDOperand(); // Make sure the target supports MULHU.
1734 uint64_t d = cast<ConstantSDNode>(N->getOperand(1))->getValue();
1735 mu magics = (VT == MVT::i32) ? magicu32(d) : magicu64(d);
1737 // Multiply the numerator (operand 0) by the magic value
1738 SDOperand Q = DAG.getNode(ISD::MULHU, VT, N->getOperand(0),
1739 DAG.getConstant(magics.m, VT));
1741 Created->push_back(Q.Val);
1743 if (magics.a == 0) {
1744 return DAG.getNode(ISD::SRL, VT, Q,
1745 DAG.getConstant(magics.s, getShiftAmountTy()));
1747 SDOperand NPQ = DAG.getNode(ISD::SUB, VT, N->getOperand(0), Q);
1749 Created->push_back(NPQ.Val);
1750 NPQ = DAG.getNode(ISD::SRL, VT, NPQ,
1751 DAG.getConstant(1, getShiftAmountTy()));
1753 Created->push_back(NPQ.Val);
1754 NPQ = DAG.getNode(ISD::ADD, VT, NPQ, Q);
1756 Created->push_back(NPQ.Val);
1757 return DAG.getNode(ISD::SRL, VT, NPQ,
1758 DAG.getConstant(magics.s-1, getShiftAmountTy()));