1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Target/TargetAsmInfo.h"
15 #include "llvm/Target/TargetLowering.h"
16 #include "llvm/Target/TargetSubtarget.h"
17 #include "llvm/Target/TargetData.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Target/TargetRegisterInfo.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/MathExtras.h"
28 /// InitLibcallNames - Set default libcall names.
30 static void InitLibcallNames(const char **Names) {
31 Names[RTLIB::SHL_I32] = "__ashlsi3";
32 Names[RTLIB::SHL_I64] = "__ashldi3";
33 Names[RTLIB::SRL_I32] = "__lshrsi3";
34 Names[RTLIB::SRL_I64] = "__lshrdi3";
35 Names[RTLIB::SRA_I32] = "__ashrsi3";
36 Names[RTLIB::SRA_I64] = "__ashrdi3";
37 Names[RTLIB::MUL_I32] = "__mulsi3";
38 Names[RTLIB::MUL_I64] = "__muldi3";
39 Names[RTLIB::SDIV_I32] = "__divsi3";
40 Names[RTLIB::SDIV_I64] = "__divdi3";
41 Names[RTLIB::UDIV_I32] = "__udivsi3";
42 Names[RTLIB::UDIV_I64] = "__udivdi3";
43 Names[RTLIB::SREM_I32] = "__modsi3";
44 Names[RTLIB::SREM_I64] = "__moddi3";
45 Names[RTLIB::UREM_I32] = "__umodsi3";
46 Names[RTLIB::UREM_I64] = "__umoddi3";
47 Names[RTLIB::NEG_I32] = "__negsi2";
48 Names[RTLIB::NEG_I64] = "__negdi2";
49 Names[RTLIB::ADD_F32] = "__addsf3";
50 Names[RTLIB::ADD_F64] = "__adddf3";
51 Names[RTLIB::ADD_F80] = "__addxf3";
52 Names[RTLIB::ADD_PPCF128] = "__gcc_qadd";
53 Names[RTLIB::SUB_F32] = "__subsf3";
54 Names[RTLIB::SUB_F64] = "__subdf3";
55 Names[RTLIB::SUB_F80] = "__subxf3";
56 Names[RTLIB::SUB_PPCF128] = "__gcc_qsub";
57 Names[RTLIB::MUL_F32] = "__mulsf3";
58 Names[RTLIB::MUL_F64] = "__muldf3";
59 Names[RTLIB::MUL_F80] = "__mulxf3";
60 Names[RTLIB::MUL_PPCF128] = "__gcc_qmul";
61 Names[RTLIB::DIV_F32] = "__divsf3";
62 Names[RTLIB::DIV_F64] = "__divdf3";
63 Names[RTLIB::DIV_F80] = "__divxf3";
64 Names[RTLIB::DIV_PPCF128] = "__gcc_qdiv";
65 Names[RTLIB::REM_F32] = "fmodf";
66 Names[RTLIB::REM_F64] = "fmod";
67 Names[RTLIB::REM_F80] = "fmodl";
68 Names[RTLIB::REM_PPCF128] = "fmodl";
69 Names[RTLIB::POWI_F32] = "__powisf2";
70 Names[RTLIB::POWI_F64] = "__powidf2";
71 Names[RTLIB::POWI_F80] = "__powixf2";
72 Names[RTLIB::POWI_PPCF128] = "__powitf2";
73 Names[RTLIB::SQRT_F32] = "sqrtf";
74 Names[RTLIB::SQRT_F64] = "sqrt";
75 Names[RTLIB::SQRT_F80] = "sqrtl";
76 Names[RTLIB::SQRT_PPCF128] = "sqrtl";
77 Names[RTLIB::SIN_F32] = "sinf";
78 Names[RTLIB::SIN_F64] = "sin";
79 Names[RTLIB::SIN_F80] = "sinl";
80 Names[RTLIB::SIN_PPCF128] = "sinl";
81 Names[RTLIB::COS_F32] = "cosf";
82 Names[RTLIB::COS_F64] = "cos";
83 Names[RTLIB::COS_F80] = "cosl";
84 Names[RTLIB::COS_PPCF128] = "cosl";
85 Names[RTLIB::POW_F32] = "powf";
86 Names[RTLIB::POW_F64] = "pow";
87 Names[RTLIB::POW_F80] = "powl";
88 Names[RTLIB::POW_PPCF128] = "powl";
89 Names[RTLIB::FPEXT_F32_F64] = "__extendsfdf2";
90 Names[RTLIB::FPROUND_F64_F32] = "__truncdfsf2";
91 Names[RTLIB::FPTOSINT_F32_I32] = "__fixsfsi";
92 Names[RTLIB::FPTOSINT_F32_I64] = "__fixsfdi";
93 Names[RTLIB::FPTOSINT_F64_I32] = "__fixdfsi";
94 Names[RTLIB::FPTOSINT_F64_I64] = "__fixdfdi";
95 Names[RTLIB::FPTOSINT_F80_I64] = "__fixxfdi";
96 Names[RTLIB::FPTOSINT_PPCF128_I64] = "__fixtfdi";
97 Names[RTLIB::FPTOUINT_F32_I32] = "__fixunssfsi";
98 Names[RTLIB::FPTOUINT_F32_I64] = "__fixunssfdi";
99 Names[RTLIB::FPTOUINT_F64_I32] = "__fixunsdfsi";
100 Names[RTLIB::FPTOUINT_F64_I64] = "__fixunsdfdi";
101 Names[RTLIB::FPTOUINT_F80_I32] = "__fixunsxfsi";
102 Names[RTLIB::FPTOUINT_F80_I64] = "__fixunsxfdi";
103 Names[RTLIB::FPTOUINT_PPCF128_I64] = "__fixunstfdi";
104 Names[RTLIB::SINTTOFP_I32_F32] = "__floatsisf";
105 Names[RTLIB::SINTTOFP_I32_F64] = "__floatsidf";
106 Names[RTLIB::SINTTOFP_I64_F32] = "__floatdisf";
107 Names[RTLIB::SINTTOFP_I64_F64] = "__floatdidf";
108 Names[RTLIB::SINTTOFP_I64_F80] = "__floatdixf";
109 Names[RTLIB::SINTTOFP_I64_PPCF128] = "__floatditf";
110 Names[RTLIB::UINTTOFP_I32_F32] = "__floatunsisf";
111 Names[RTLIB::UINTTOFP_I32_F64] = "__floatunsidf";
112 Names[RTLIB::UINTTOFP_I64_F32] = "__floatundisf";
113 Names[RTLIB::UINTTOFP_I64_F64] = "__floatundidf";
114 Names[RTLIB::OEQ_F32] = "__eqsf2";
115 Names[RTLIB::OEQ_F64] = "__eqdf2";
116 Names[RTLIB::UNE_F32] = "__nesf2";
117 Names[RTLIB::UNE_F64] = "__nedf2";
118 Names[RTLIB::OGE_F32] = "__gesf2";
119 Names[RTLIB::OGE_F64] = "__gedf2";
120 Names[RTLIB::OLT_F32] = "__ltsf2";
121 Names[RTLIB::OLT_F64] = "__ltdf2";
122 Names[RTLIB::OLE_F32] = "__lesf2";
123 Names[RTLIB::OLE_F64] = "__ledf2";
124 Names[RTLIB::OGT_F32] = "__gtsf2";
125 Names[RTLIB::OGT_F64] = "__gtdf2";
126 Names[RTLIB::UO_F32] = "__unordsf2";
127 Names[RTLIB::UO_F64] = "__unorddf2";
128 Names[RTLIB::O_F32] = "__unordsf2";
129 Names[RTLIB::O_F64] = "__unorddf2";
132 /// InitCmpLibcallCCs - Set default comparison libcall CC.
134 static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
135 memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
136 CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
137 CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
138 CCs[RTLIB::UNE_F32] = ISD::SETNE;
139 CCs[RTLIB::UNE_F64] = ISD::SETNE;
140 CCs[RTLIB::OGE_F32] = ISD::SETGE;
141 CCs[RTLIB::OGE_F64] = ISD::SETGE;
142 CCs[RTLIB::OLT_F32] = ISD::SETLT;
143 CCs[RTLIB::OLT_F64] = ISD::SETLT;
144 CCs[RTLIB::OLE_F32] = ISD::SETLE;
145 CCs[RTLIB::OLE_F64] = ISD::SETLE;
146 CCs[RTLIB::OGT_F32] = ISD::SETGT;
147 CCs[RTLIB::OGT_F64] = ISD::SETGT;
148 CCs[RTLIB::UO_F32] = ISD::SETNE;
149 CCs[RTLIB::UO_F64] = ISD::SETNE;
150 CCs[RTLIB::O_F32] = ISD::SETEQ;
151 CCs[RTLIB::O_F64] = ISD::SETEQ;
154 TargetLowering::TargetLowering(TargetMachine &tm)
155 : TM(tm), TD(TM.getTargetData()) {
156 assert(ISD::BUILTIN_OP_END <= 156 &&
157 "Fixed size array in TargetLowering is not large enough!");
158 // All operations default to being supported.
159 memset(OpActions, 0, sizeof(OpActions));
160 memset(LoadXActions, 0, sizeof(LoadXActions));
161 memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
162 memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
163 memset(ConvertActions, 0, sizeof(ConvertActions));
165 // Set default actions for various operations.
166 for (unsigned VT = 0; VT != (unsigned)MVT::LAST_VALUETYPE; ++VT) {
167 // Default all indexed load / store to expand.
168 for (unsigned IM = (unsigned)ISD::PRE_INC;
169 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
170 setIndexedLoadAction(IM, (MVT::ValueType)VT, Expand);
171 setIndexedStoreAction(IM, (MVT::ValueType)VT, Expand);
174 // These operations default to expand.
175 setOperationAction(ISD::FGETSIGN, (MVT::ValueType)VT, Expand);
178 // ConstantFP nodes default to expand. Targets can either change this to
179 // Legal, in which case all fp constants are legal, or use addLegalFPImmediate
180 // to optimize expansions for certain constants.
181 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
182 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
183 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
185 // Default ISD::TRAP to expand (which turns it into abort).
186 setOperationAction(ISD::TRAP, MVT::Other, Expand);
188 IsLittleEndian = TD->isLittleEndian();
189 UsesGlobalOffsetTable = false;
190 ShiftAmountTy = SetCCResultTy = PointerTy = getValueType(TD->getIntPtrType());
191 ShiftAmtHandling = Undefined;
192 memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*));
193 memset(TargetDAGCombineArray, 0, array_lengthof(TargetDAGCombineArray));
194 maxStoresPerMemset = maxStoresPerMemcpy = maxStoresPerMemmove = 8;
195 allowUnalignedMemoryAccesses = false;
196 UseUnderscoreSetJmp = false;
197 UseUnderscoreLongJmp = false;
198 SelectIsExpensive = false;
199 IntDivIsCheap = false;
200 Pow2DivIsCheap = false;
201 StackPointerRegisterToSaveRestore = 0;
202 ExceptionPointerRegister = 0;
203 ExceptionSelectorRegister = 0;
204 SetCCResultContents = UndefinedSetCCResult;
205 SchedPreferenceInfo = SchedulingForLatency;
207 JumpBufAlignment = 0;
208 IfCvtBlockSizeLimit = 2;
209 IfCvtDupBlockSizeLimit = 0;
210 PrefLoopAlignment = 0;
212 InitLibcallNames(LibcallRoutineNames);
213 InitCmpLibcallCCs(CmpLibcallCCs);
215 // Tell Legalize whether the assembler supports DEBUG_LOC.
216 if (!TM.getTargetAsmInfo()->hasDotLocAndDotFile())
217 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
220 TargetLowering::~TargetLowering() {}
223 SDOperand TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
224 assert(getSubtarget() && "Subtarget not defined");
225 SDOperand ChainOp = Op.getOperand(0);
226 SDOperand DestOp = Op.getOperand(1);
227 SDOperand SourceOp = Op.getOperand(2);
228 SDOperand CountOp = Op.getOperand(3);
229 SDOperand AlignOp = Op.getOperand(4);
230 SDOperand AlwaysInlineOp = Op.getOperand(5);
232 bool AlwaysInline = (bool)cast<ConstantSDNode>(AlwaysInlineOp)->getValue();
233 unsigned Align = (unsigned)cast<ConstantSDNode>(AlignOp)->getValue();
234 if (Align == 0) Align = 1;
236 // If size is unknown, call memcpy.
237 ConstantSDNode *I = dyn_cast<ConstantSDNode>(CountOp);
239 assert(!AlwaysInline && "Cannot inline copy of unknown size");
240 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
243 // If not DWORD aligned or if size is more than threshold, then call memcpy.
244 // The libc version is likely to be faster for the following cases. It can
245 // use the address value and run time information about the CPU.
246 // With glibc 2.6.1 on a core 2, coping an array of 100M longs was 30% faster
247 unsigned Size = I->getValue();
249 (Size <= getSubtarget()->getMaxInlineSizeThreshold() &&
251 return LowerMEMCPYInline(ChainOp, DestOp, SourceOp, Size, Align, DAG);
252 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
256 SDOperand TargetLowering::LowerMEMCPYCall(SDOperand Chain,
261 MVT::ValueType IntPtr = getPointerTy();
262 TargetLowering::ArgListTy Args;
263 TargetLowering::ArgListEntry Entry;
264 Entry.Ty = getTargetData()->getIntPtrType();
265 Entry.Node = Dest; Args.push_back(Entry);
266 Entry.Node = Source; Args.push_back(Entry);
267 Entry.Node = Count; Args.push_back(Entry);
268 std::pair<SDOperand,SDOperand> CallResult =
269 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
270 false, DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
271 return CallResult.second;
275 /// computeRegisterProperties - Once all of the register classes are added,
276 /// this allows us to compute derived properties we expose.
277 void TargetLowering::computeRegisterProperties() {
278 assert(MVT::LAST_VALUETYPE <= 32 &&
279 "Too many value types for ValueTypeActions to hold!");
281 // Everything defaults to needing one register.
282 for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
283 NumRegistersForVT[i] = 1;
284 RegisterTypeForVT[i] = TransformToType[i] = i;
286 // ...except isVoid, which doesn't need any registers.
287 NumRegistersForVT[MVT::isVoid] = 0;
289 // Find the largest integer register class.
290 unsigned LargestIntReg = MVT::i128;
291 for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg)
292 assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
294 // Every integer value type larger than this largest register takes twice as
295 // many registers to represent as the previous ValueType.
296 for (MVT::ValueType ExpandedReg = LargestIntReg + 1;
297 MVT::isInteger(ExpandedReg); ++ExpandedReg) {
298 NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
299 RegisterTypeForVT[ExpandedReg] = LargestIntReg;
300 TransformToType[ExpandedReg] = ExpandedReg - 1;
301 ValueTypeActions.setTypeAction(ExpandedReg, Expand);
304 // Inspect all of the ValueType's smaller than the largest integer
305 // register to see which ones need promotion.
306 MVT::ValueType LegalIntReg = LargestIntReg;
307 for (MVT::ValueType IntReg = LargestIntReg - 1;
308 IntReg >= MVT::i1; --IntReg) {
309 if (isTypeLegal(IntReg)) {
310 LegalIntReg = IntReg;
312 RegisterTypeForVT[IntReg] = TransformToType[IntReg] = LegalIntReg;
313 ValueTypeActions.setTypeAction(IntReg, Promote);
317 // ppcf128 type is really two f64's.
318 if (!isTypeLegal(MVT::ppcf128)) {
319 NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
320 RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
321 TransformToType[MVT::ppcf128] = MVT::f64;
322 ValueTypeActions.setTypeAction(MVT::ppcf128, Expand);
325 // Decide how to handle f64. If the target does not have native f64 support,
326 // expand it to i64 and we will be generating soft float library calls.
327 if (!isTypeLegal(MVT::f64)) {
328 NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
329 RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
330 TransformToType[MVT::f64] = MVT::i64;
331 ValueTypeActions.setTypeAction(MVT::f64, Expand);
334 // Decide how to handle f32. If the target does not have native support for
335 // f32, promote it to f64 if it is legal. Otherwise, expand it to i32.
336 if (!isTypeLegal(MVT::f32)) {
337 if (isTypeLegal(MVT::f64)) {
338 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::f64];
339 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::f64];
340 TransformToType[MVT::f32] = MVT::f64;
341 ValueTypeActions.setTypeAction(MVT::f32, Promote);
343 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
344 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
345 TransformToType[MVT::f32] = MVT::i32;
346 ValueTypeActions.setTypeAction(MVT::f32, Expand);
350 // Loop over all of the vector value types to see which need transformations.
351 for (MVT::ValueType i = MVT::FIRST_VECTOR_VALUETYPE;
352 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
353 if (!isTypeLegal(i)) {
354 MVT::ValueType IntermediateVT, RegisterVT;
355 unsigned NumIntermediates;
356 NumRegistersForVT[i] =
357 getVectorTypeBreakdown(i,
358 IntermediateVT, NumIntermediates,
360 RegisterTypeForVT[i] = RegisterVT;
361 TransformToType[i] = MVT::Other; // this isn't actually used
362 ValueTypeActions.setTypeAction(i, Expand);
367 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
371 /// getVectorTypeBreakdown - Vector types are broken down into some number of
372 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
373 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
374 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
376 /// This method returns the number of registers needed, and the VT for each
377 /// register. It also returns the VT and quantity of the intermediate values
378 /// before they are promoted/expanded.
380 unsigned TargetLowering::getVectorTypeBreakdown(MVT::ValueType VT,
381 MVT::ValueType &IntermediateVT,
382 unsigned &NumIntermediates,
383 MVT::ValueType &RegisterVT) const {
384 // Figure out the right, legal destination reg to copy into.
385 unsigned NumElts = MVT::getVectorNumElements(VT);
386 MVT::ValueType EltTy = MVT::getVectorElementType(VT);
388 unsigned NumVectorRegs = 1;
390 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
391 // could break down into LHS/RHS like LegalizeDAG does.
392 if (!isPowerOf2_32(NumElts)) {
393 NumVectorRegs = NumElts;
397 // Divide the input until we get to a supported size. This will always
398 // end with a scalar if the target doesn't support vectors.
399 while (NumElts > 1 &&
400 !isTypeLegal(MVT::getVectorType(EltTy, NumElts))) {
405 NumIntermediates = NumVectorRegs;
407 MVT::ValueType NewVT = MVT::getVectorType(EltTy, NumElts);
408 if (!isTypeLegal(NewVT))
410 IntermediateVT = NewVT;
412 MVT::ValueType DestVT = getTypeToTransformTo(NewVT);
414 if (DestVT < NewVT) {
415 // Value is expanded, e.g. i64 -> i16.
416 return NumVectorRegs*(MVT::getSizeInBits(NewVT)/MVT::getSizeInBits(DestVT));
418 // Otherwise, promotion or legal types use the same number of registers as
419 // the vector decimated to the appropriate level.
420 return NumVectorRegs;
426 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
427 /// function arguments in the caller parameter area. This is the actual
428 /// alignment, not its logarithm.
429 unsigned TargetLowering::getByValTypeAlignment(const Type *Ty) const {
430 return TD->getCallFrameTypeAlignment(Ty);
433 SDOperand TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
434 SelectionDAG &DAG) const {
435 if (usesGlobalOffsetTable())
436 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
440 //===----------------------------------------------------------------------===//
441 // Optimization Methods
442 //===----------------------------------------------------------------------===//
444 /// ShrinkDemandedConstant - Check to see if the specified operand of the
445 /// specified instruction is a constant integer. If so, check to see if there
446 /// are any bits set in the constant that are not demanded. If so, shrink the
447 /// constant and return true.
448 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDOperand Op,
449 const APInt &Demanded) {
450 // FIXME: ISD::SELECT, ISD::SELECT_CC
451 switch(Op.getOpcode()) {
456 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
457 if (C->getAPIntValue().intersects(~Demanded)) {
458 MVT::ValueType VT = Op.getValueType();
459 SDOperand New = DAG.getNode(Op.getOpcode(), VT, Op.getOperand(0),
460 DAG.getConstant(Demanded &
463 return CombineTo(Op, New);
470 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
471 /// DemandedMask bits of the result of Op are ever used downstream. If we can
472 /// use this information to simplify Op, create a new simplified DAG node and
473 /// return true, returning the original and new nodes in Old and New. Otherwise,
474 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
475 /// the expression (used to simplify the caller). The KnownZero/One bits may
476 /// only be accurate for those bits in the DemandedMask.
477 bool TargetLowering::SimplifyDemandedBits(SDOperand Op,
478 const APInt &DemandedMask,
481 TargetLoweringOpt &TLO,
482 unsigned Depth) const {
483 unsigned BitWidth = DemandedMask.getBitWidth();
484 assert(Op.getValueSizeInBits() == BitWidth &&
485 "Mask size mismatches value type size!");
486 APInt NewMask = DemandedMask;
488 // Don't know anything.
489 KnownZero = KnownOne = APInt(BitWidth, 0);
491 // Other users may use these bits.
492 if (!Op.Val->hasOneUse()) {
494 // If not at the root, Just compute the KnownZero/KnownOne bits to
495 // simplify things downstream.
496 TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
499 // If this is the root being simplified, allow it to have multiple uses,
500 // just set the NewMask to all bits.
501 NewMask = APInt::getAllOnesValue(BitWidth);
502 } else if (DemandedMask == 0) {
503 // Not demanding any bits from Op.
504 if (Op.getOpcode() != ISD::UNDEF)
505 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::UNDEF, Op.getValueType()));
507 } else if (Depth == 6) { // Limit search depth.
511 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
512 switch (Op.getOpcode()) {
514 // We know all of the bits for a constant!
515 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & NewMask;
516 KnownZero = ~KnownOne & NewMask;
517 return false; // Don't fall through, will infinitely loop.
519 // If the RHS is a constant, check to see if the LHS would be zero without
520 // using the bits from the RHS. Below, we use knowledge about the RHS to
521 // simplify the LHS, here we're using information from the LHS to simplify
523 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
524 APInt LHSZero, LHSOne;
525 TLO.DAG.ComputeMaskedBits(Op.getOperand(0), NewMask,
526 LHSZero, LHSOne, Depth+1);
527 // If the LHS already has zeros where RHSC does, this and is dead.
528 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
529 return TLO.CombineTo(Op, Op.getOperand(0));
530 // If any of the set bits in the RHS are known zero on the LHS, shrink
532 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
536 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
537 KnownOne, TLO, Depth+1))
539 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
540 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
541 KnownZero2, KnownOne2, TLO, Depth+1))
543 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
545 // If all of the demanded bits are known one on one side, return the other.
546 // These bits cannot contribute to the result of the 'and'.
547 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
548 return TLO.CombineTo(Op, Op.getOperand(0));
549 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
550 return TLO.CombineTo(Op, Op.getOperand(1));
551 // If all of the demanded bits in the inputs are known zeros, return zero.
552 if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
553 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
554 // If the RHS is a constant, see if we can simplify it.
555 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
558 // Output known-1 bits are only known if set in both the LHS & RHS.
559 KnownOne &= KnownOne2;
560 // Output known-0 are known to be clear if zero in either the LHS | RHS.
561 KnownZero |= KnownZero2;
564 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
565 KnownOne, TLO, Depth+1))
567 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
568 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
569 KnownZero2, KnownOne2, TLO, Depth+1))
571 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
573 // If all of the demanded bits are known zero on one side, return the other.
574 // These bits cannot contribute to the result of the 'or'.
575 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
576 return TLO.CombineTo(Op, Op.getOperand(0));
577 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
578 return TLO.CombineTo(Op, Op.getOperand(1));
579 // If all of the potentially set bits on one side are known to be set on
580 // the other side, just use the 'other' side.
581 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
582 return TLO.CombineTo(Op, Op.getOperand(0));
583 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
584 return TLO.CombineTo(Op, Op.getOperand(1));
585 // If the RHS is a constant, see if we can simplify it.
586 if (TLO.ShrinkDemandedConstant(Op, NewMask))
589 // Output known-0 bits are only known if clear in both the LHS & RHS.
590 KnownZero &= KnownZero2;
591 // Output known-1 are known to be set if set in either the LHS | RHS.
592 KnownOne |= KnownOne2;
595 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
596 KnownOne, TLO, Depth+1))
598 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
599 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
600 KnownOne2, TLO, Depth+1))
602 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
604 // If all of the demanded bits are known zero on one side, return the other.
605 // These bits cannot contribute to the result of the 'xor'.
606 if ((KnownZero & NewMask) == NewMask)
607 return TLO.CombineTo(Op, Op.getOperand(0));
608 if ((KnownZero2 & NewMask) == NewMask)
609 return TLO.CombineTo(Op, Op.getOperand(1));
611 // If all of the unknown bits are known to be zero on one side or the other
612 // (but not both) turn this into an *inclusive* or.
613 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
614 if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
615 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, Op.getValueType(),
619 // Output known-0 bits are known if clear or set in both the LHS & RHS.
620 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
621 // Output known-1 are known to be set if set in only one of the LHS, RHS.
622 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
624 // If all of the demanded bits on one side are known, and all of the set
625 // bits on that side are also known to be set on the other side, turn this
626 // into an AND, as we know the bits will be cleared.
627 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
628 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known
629 if ((KnownOne & KnownOne2) == KnownOne) {
630 MVT::ValueType VT = Op.getValueType();
631 SDOperand ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT);
632 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, VT, Op.getOperand(0),
637 // If the RHS is a constant, see if we can simplify it.
638 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
639 if (TLO.ShrinkDemandedConstant(Op, NewMask))
642 KnownZero = KnownZeroOut;
643 KnownOne = KnownOneOut;
646 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
647 KnownOne, TLO, Depth+1))
649 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
650 KnownOne2, TLO, Depth+1))
652 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
653 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
655 // If the operands are constants, see if we can simplify them.
656 if (TLO.ShrinkDemandedConstant(Op, NewMask))
659 // Only known if known in both the LHS and RHS.
660 KnownOne &= KnownOne2;
661 KnownZero &= KnownZero2;
664 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
665 KnownOne, TLO, Depth+1))
667 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
668 KnownOne2, TLO, Depth+1))
670 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
671 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
673 // If the operands are constants, see if we can simplify them.
674 if (TLO.ShrinkDemandedConstant(Op, NewMask))
677 // Only known if known in both the LHS and RHS.
678 KnownOne &= KnownOne2;
679 KnownZero &= KnownZero2;
682 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
683 unsigned ShAmt = SA->getValue();
684 SDOperand InOp = Op.getOperand(0);
686 // If the shift count is an invalid immediate, don't do anything.
687 if (ShAmt >= BitWidth)
690 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
691 // single shift. We can do this if the bottom bits (which are shifted
692 // out) are never demanded.
693 if (InOp.getOpcode() == ISD::SRL &&
694 isa<ConstantSDNode>(InOp.getOperand(1))) {
695 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
696 unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
697 unsigned Opc = ISD::SHL;
705 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
706 MVT::ValueType VT = Op.getValueType();
707 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
708 InOp.getOperand(0), NewSA));
712 if (SimplifyDemandedBits(Op.getOperand(0), NewMask.lshr(ShAmt),
713 KnownZero, KnownOne, TLO, Depth+1))
715 KnownZero <<= SA->getValue();
716 KnownOne <<= SA->getValue();
717 // low bits known zero.
718 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getValue());
722 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
723 MVT::ValueType VT = Op.getValueType();
724 unsigned ShAmt = SA->getValue();
725 unsigned VTSize = MVT::getSizeInBits(VT);
726 SDOperand InOp = Op.getOperand(0);
728 // If the shift count is an invalid immediate, don't do anything.
729 if (ShAmt >= BitWidth)
732 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
733 // single shift. We can do this if the top bits (which are shifted out)
734 // are never demanded.
735 if (InOp.getOpcode() == ISD::SHL &&
736 isa<ConstantSDNode>(InOp.getOperand(1))) {
737 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
738 unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
739 unsigned Opc = ISD::SRL;
747 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
748 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
749 InOp.getOperand(0), NewSA));
753 // Compute the new bits that are at the top now.
754 if (SimplifyDemandedBits(InOp, (NewMask << ShAmt),
755 KnownZero, KnownOne, TLO, Depth+1))
757 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
758 KnownZero = KnownZero.lshr(ShAmt);
759 KnownOne = KnownOne.lshr(ShAmt);
761 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
762 KnownZero |= HighBits; // High bits known zero.
766 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
767 MVT::ValueType VT = Op.getValueType();
768 unsigned ShAmt = SA->getValue();
770 // If the shift count is an invalid immediate, don't do anything.
771 if (ShAmt >= BitWidth)
774 APInt InDemandedMask = (NewMask << ShAmt);
776 // If any of the demanded bits are produced by the sign extension, we also
777 // demand the input sign bit.
778 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
779 if (HighBits.intersects(NewMask))
780 InDemandedMask |= APInt::getSignBit(MVT::getSizeInBits(VT));
782 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
783 KnownZero, KnownOne, TLO, Depth+1))
785 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
786 KnownZero = KnownZero.lshr(ShAmt);
787 KnownOne = KnownOne.lshr(ShAmt);
789 // Handle the sign bit, adjusted to where it is now in the mask.
790 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
792 // If the input sign bit is known to be zero, or if none of the top bits
793 // are demanded, turn this into an unsigned shift right.
794 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
795 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, VT, Op.getOperand(0),
797 } else if (KnownOne.intersects(SignBit)) { // New bits are known one.
798 KnownOne |= HighBits;
802 case ISD::SIGN_EXTEND_INREG: {
803 MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
805 // Sign extension. Compute the demanded bits in the result that are not
806 // present in the input.
807 APInt NewBits = APInt::getHighBitsSet(BitWidth,
808 BitWidth - MVT::getSizeInBits(EVT)) &
811 // If none of the extended bits are demanded, eliminate the sextinreg.
813 return TLO.CombineTo(Op, Op.getOperand(0));
815 APInt InSignBit = APInt::getSignBit(MVT::getSizeInBits(EVT));
816 InSignBit.zext(BitWidth);
817 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth,
818 MVT::getSizeInBits(EVT)) &
821 // Since the sign extended bits are demanded, we know that the sign
823 InputDemandedBits |= InSignBit;
825 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
826 KnownZero, KnownOne, TLO, Depth+1))
828 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
830 // If the sign bit of the input is known set or clear, then we know the
831 // top bits of the result.
833 // If the input sign bit is known zero, convert this into a zero extension.
834 if (KnownZero.intersects(InSignBit))
835 return TLO.CombineTo(Op,
836 TLO.DAG.getZeroExtendInReg(Op.getOperand(0), EVT));
838 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
840 KnownZero &= ~NewBits;
841 } else { // Input sign bit unknown
842 KnownZero &= ~NewBits;
843 KnownOne &= ~NewBits;
847 case ISD::ZERO_EXTEND: {
848 unsigned OperandBitWidth = Op.getOperand(0).getValueSizeInBits();
849 APInt InMask = NewMask;
850 InMask.trunc(OperandBitWidth);
852 // If none of the top bits are demanded, convert this into an any_extend.
854 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
855 if (!NewBits.intersects(NewMask))
856 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND,
860 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
861 KnownZero, KnownOne, TLO, Depth+1))
863 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
864 KnownZero.zext(BitWidth);
865 KnownOne.zext(BitWidth);
866 KnownZero |= NewBits;
869 case ISD::SIGN_EXTEND: {
870 MVT::ValueType InVT = Op.getOperand(0).getValueType();
871 unsigned InBits = MVT::getSizeInBits(InVT);
872 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits);
873 APInt InSignBit = APInt::getLowBitsSet(BitWidth, InBits);
874 APInt NewBits = ~InMask & NewMask;
876 // If none of the top bits are demanded, convert this into an any_extend.
878 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND,Op.getValueType(),
881 // Since some of the sign extended bits are demanded, we know that the sign
883 APInt InDemandedBits = InMask & NewMask;
884 InDemandedBits |= InSignBit;
885 InDemandedBits.trunc(InBits);
887 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
888 KnownOne, TLO, Depth+1))
890 KnownZero.zext(BitWidth);
891 KnownOne.zext(BitWidth);
893 // If the sign bit is known zero, convert this to a zero extend.
894 if (KnownZero.intersects(InSignBit))
895 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND,
899 // If the sign bit is known one, the top bits match.
900 if (KnownOne.intersects(InSignBit)) {
902 KnownZero &= ~NewBits;
903 } else { // Otherwise, top bits aren't known.
904 KnownOne &= ~NewBits;
905 KnownZero &= ~NewBits;
909 case ISD::ANY_EXTEND: {
910 unsigned OperandBitWidth = Op.getOperand(0).getValueSizeInBits();
911 APInt InMask = NewMask;
912 InMask.trunc(OperandBitWidth);
913 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
914 KnownZero, KnownOne, TLO, Depth+1))
916 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
917 KnownZero.zext(BitWidth);
918 KnownOne.zext(BitWidth);
921 case ISD::TRUNCATE: {
922 // Simplify the input, using demanded bit information, and compute the known
923 // zero/one bits live out.
924 APInt TruncMask = NewMask;
925 TruncMask.zext(Op.getOperand(0).getValueSizeInBits());
926 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
927 KnownZero, KnownOne, TLO, Depth+1))
929 KnownZero.trunc(BitWidth);
930 KnownOne.trunc(BitWidth);
932 // If the input is only used by this truncate, see if we can shrink it based
933 // on the known demanded bits.
934 if (Op.getOperand(0).Val->hasOneUse()) {
935 SDOperand In = Op.getOperand(0);
936 unsigned InBitWidth = In.getValueSizeInBits();
937 switch (In.getOpcode()) {
940 // Shrink SRL by a constant if none of the high bits shifted in are
942 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1))){
943 APInt HighBits = APInt::getHighBitsSet(InBitWidth,
944 InBitWidth - BitWidth);
945 HighBits = HighBits.lshr(ShAmt->getValue());
946 HighBits.trunc(BitWidth);
948 if (ShAmt->getValue() < BitWidth && !(HighBits & NewMask)) {
949 // None of the shifted in bits are needed. Add a truncate of the
950 // shift input, then shift it.
951 SDOperand NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE,
954 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL,Op.getValueType(),
955 NewTrunc, In.getOperand(1)));
962 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
965 case ISD::AssertZext: {
966 MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
967 APInt InMask = APInt::getLowBitsSet(BitWidth,
968 MVT::getSizeInBits(VT));
969 if (SimplifyDemandedBits(Op.getOperand(0), InMask & NewMask,
970 KnownZero, KnownOne, TLO, Depth+1))
972 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
973 KnownZero |= ~InMask & NewMask;
976 case ISD::BIT_CONVERT:
978 // If this is an FP->Int bitcast and if the sign bit is the only thing that
979 // is demanded, turn this into a FGETSIGN.
980 if (NewMask == MVT::getIntVTSignBit(Op.getValueType()) &&
981 MVT::isFloatingPoint(Op.getOperand(0).getValueType()) &&
982 !MVT::isVector(Op.getOperand(0).getValueType())) {
983 // Only do this xform if FGETSIGN is valid or if before legalize.
984 if (!TLO.AfterLegalize ||
985 isOperationLegal(ISD::FGETSIGN, Op.getValueType())) {
986 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
987 // place. We expect the SHL to be eliminated by other optimizations.
988 SDOperand Sign = TLO.DAG.getNode(ISD::FGETSIGN, Op.getValueType(),
990 unsigned ShVal = MVT::getSizeInBits(Op.getValueType())-1;
991 SDOperand ShAmt = TLO.DAG.getConstant(ShVal, getShiftAmountTy());
992 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, Op.getValueType(),
1000 case ISD::INTRINSIC_WO_CHAIN:
1001 case ISD::INTRINSIC_W_CHAIN:
1002 case ISD::INTRINSIC_VOID:
1009 // Just use ComputeMaskedBits to compute output bits.
1010 TLO.DAG.ComputeMaskedBits(Op, NewMask, KnownZero, KnownOne, Depth);
1014 // If we know the value of all of the demanded bits, return this as a
1016 if ((NewMask & (KnownZero|KnownOne)) == NewMask)
1017 return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
1022 /// computeMaskedBitsForTargetNode - Determine which of the bits specified
1023 /// in Mask are known to be either zero or one and return them in the
1024 /// KnownZero/KnownOne bitsets.
1025 void TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
1029 const SelectionDAG &DAG,
1030 unsigned Depth) const {
1031 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1032 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1033 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1034 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1035 "Should use MaskedValueIsZero if you don't know whether Op"
1036 " is a target node!");
1037 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1040 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
1041 /// targets that want to expose additional information about sign bits to the
1043 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDOperand Op,
1044 unsigned Depth) const {
1045 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1046 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1047 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1048 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1049 "Should use ComputeNumSignBits if you don't know whether Op"
1050 " is a target node!");
1055 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
1056 /// and cc. If it is unable to simplify it, return a null SDOperand.
1058 TargetLowering::SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
1059 ISD::CondCode Cond, bool foldBooleans,
1060 DAGCombinerInfo &DCI) const {
1061 SelectionDAG &DAG = DCI.DAG;
1063 // These setcc operations always fold.
1067 case ISD::SETFALSE2: return DAG.getConstant(0, VT);
1069 case ISD::SETTRUE2: return DAG.getConstant(1, VT);
1072 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1073 const APInt &C1 = N1C->getAPIntValue();
1074 if (isa<ConstantSDNode>(N0.Val)) {
1075 return DAG.FoldSetCC(VT, N0, N1, Cond);
1077 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1078 // equality comparison, then we're just comparing whether X itself is
1080 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1081 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1082 N0.getOperand(1).getOpcode() == ISD::Constant) {
1083 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1084 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1085 ShAmt == Log2_32(MVT::getSizeInBits(N0.getValueType()))) {
1086 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1087 // (srl (ctlz x), 5) == 0 -> X != 0
1088 // (srl (ctlz x), 5) != 1 -> X != 0
1091 // (srl (ctlz x), 5) != 0 -> X == 0
1092 // (srl (ctlz x), 5) == 1 -> X == 0
1095 SDOperand Zero = DAG.getConstant(0, N0.getValueType());
1096 return DAG.getSetCC(VT, N0.getOperand(0).getOperand(0),
1101 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1102 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1103 unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
1105 // If the comparison constant has bits in the upper part, the
1106 // zero-extended value could never match.
1107 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1108 C1.getBitWidth() - InSize))) {
1112 case ISD::SETEQ: return DAG.getConstant(0, VT);
1115 case ISD::SETNE: return DAG.getConstant(1, VT);
1118 // True if the sign bit of C1 is set.
1119 return DAG.getConstant(C1.isNegative(), VT);
1122 // True if the sign bit of C1 isn't set.
1123 return DAG.getConstant(C1.isNonNegative(), VT);
1129 // Otherwise, we can perform the comparison with the low bits.
1137 return DAG.getSetCC(VT, N0.getOperand(0),
1138 DAG.getConstant(APInt(C1).trunc(InSize),
1139 N0.getOperand(0).getValueType()),
1142 break; // todo, be more careful with signed comparisons
1144 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1145 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1146 MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1147 unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
1148 MVT::ValueType ExtDstTy = N0.getValueType();
1149 unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
1151 // If the extended part has any inconsistent bits, it cannot ever
1152 // compare equal. In other words, they have to be all ones or all
1155 APInt::getHighBitsSet(ExtDstTyBits, ExtDstTyBits - ExtSrcTyBits);
1156 if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
1157 return DAG.getConstant(Cond == ISD::SETNE, VT);
1160 MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
1161 if (Op0Ty == ExtSrcTy) {
1162 ZextOp = N0.getOperand(0);
1164 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1165 ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
1166 DAG.getConstant(Imm, Op0Ty));
1168 if (!DCI.isCalledByLegalizer())
1169 DCI.AddToWorklist(ZextOp.Val);
1170 // Otherwise, make this a use of a zext.
1171 return DAG.getSetCC(VT, ZextOp,
1172 DAG.getConstant(C1 & APInt::getLowBitsSet(
1177 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1178 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1180 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
1181 if (N0.getOpcode() == ISD::SETCC) {
1182 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getValue() != 1);
1186 // Invert the condition.
1187 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1188 CC = ISD::getSetCCInverse(CC,
1189 MVT::isInteger(N0.getOperand(0).getValueType()));
1190 return DAG.getSetCC(VT, N0.getOperand(0), N0.getOperand(1), CC);
1193 if ((N0.getOpcode() == ISD::XOR ||
1194 (N0.getOpcode() == ISD::AND &&
1195 N0.getOperand(0).getOpcode() == ISD::XOR &&
1196 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1197 isa<ConstantSDNode>(N0.getOperand(1)) &&
1198 cast<ConstantSDNode>(N0.getOperand(1))->getValue() == 1) {
1199 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1200 // can only do this if the top bits are known zero.
1201 unsigned BitWidth = N0.getValueSizeInBits();
1202 if (DAG.MaskedValueIsZero(N0,
1203 APInt::getHighBitsSet(BitWidth,
1205 // Okay, get the un-inverted input value.
1207 if (N0.getOpcode() == ISD::XOR)
1208 Val = N0.getOperand(0);
1210 assert(N0.getOpcode() == ISD::AND &&
1211 N0.getOperand(0).getOpcode() == ISD::XOR);
1212 // ((X^1)&1)^1 -> X & 1
1213 Val = DAG.getNode(ISD::AND, N0.getValueType(),
1214 N0.getOperand(0).getOperand(0),
1217 return DAG.getSetCC(VT, Val, N1,
1218 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1223 APInt MinVal, MaxVal;
1224 unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
1225 if (ISD::isSignedIntSetCC(Cond)) {
1226 MinVal = APInt::getSignedMinValue(OperandBitSize);
1227 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1229 MinVal = APInt::getMinValue(OperandBitSize);
1230 MaxVal = APInt::getMaxValue(OperandBitSize);
1233 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1234 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1235 if (C1 == MinVal) return DAG.getConstant(1, VT); // X >= MIN --> true
1236 // X >= C0 --> X > (C0-1)
1237 return DAG.getSetCC(VT, N0, DAG.getConstant(C1-1, N1.getValueType()),
1238 (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
1241 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1242 if (C1 == MaxVal) return DAG.getConstant(1, VT); // X <= MAX --> true
1243 // X <= C0 --> X < (C0+1)
1244 return DAG.getSetCC(VT, N0, DAG.getConstant(C1+1, N1.getValueType()),
1245 (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
1248 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1249 return DAG.getConstant(0, VT); // X < MIN --> false
1250 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1251 return DAG.getConstant(1, VT); // X >= MIN --> true
1252 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1253 return DAG.getConstant(0, VT); // X > MAX --> false
1254 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1255 return DAG.getConstant(1, VT); // X <= MAX --> true
1257 // Canonicalize setgt X, Min --> setne X, Min
1258 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1259 return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1260 // Canonicalize setlt X, Max --> setne X, Max
1261 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1262 return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1264 // If we have setult X, 1, turn it into seteq X, 0
1265 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1266 return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
1268 // If we have setugt X, Max-1, turn it into seteq X, Max
1269 else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1270 return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
1273 // If we have "setcc X, C0", check to see if we can shrink the immediate
1276 // SETUGT X, SINTMAX -> SETLT X, 0
1277 if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
1278 C1 == (~0ULL >> (65-OperandBitSize)))
1279 return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
1282 // FIXME: Implement the rest of these.
1284 // Fold bit comparisons when we can.
1285 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1286 VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
1287 if (ConstantSDNode *AndRHS =
1288 dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1289 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
1290 // Perform the xform if the AND RHS is a single bit.
1291 if (isPowerOf2_64(AndRHS->getValue())) {
1292 return DAG.getNode(ISD::SRL, VT, N0,
1293 DAG.getConstant(Log2_64(AndRHS->getValue()),
1294 getShiftAmountTy()));
1296 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
1297 // (X & 8) == 8 --> (X & 8) >> 3
1298 // Perform the xform if C1 is a single bit.
1299 if (C1.isPowerOf2()) {
1300 return DAG.getNode(ISD::SRL, VT, N0,
1301 DAG.getConstant(C1.logBase2(), getShiftAmountTy()));
1306 } else if (isa<ConstantSDNode>(N0.Val)) {
1307 // Ensure that the constant occurs on the RHS.
1308 return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
1311 if (isa<ConstantFPSDNode>(N0.Val)) {
1312 // Constant fold or commute setcc.
1313 SDOperand O = DAG.FoldSetCC(VT, N0, N1, Cond);
1314 if (O.Val) return O;
1315 } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1316 // If the RHS of an FP comparison is a constant, simplify it away in
1318 if (CFP->getValueAPF().isNaN()) {
1319 // If an operand is known to be a nan, we can fold it.
1320 switch (ISD::getUnorderedFlavor(Cond)) {
1321 default: assert(0 && "Unknown flavor!");
1322 case 0: // Known false.
1323 return DAG.getConstant(0, VT);
1324 case 1: // Known true.
1325 return DAG.getConstant(1, VT);
1326 case 2: // Undefined.
1327 return DAG.getNode(ISD::UNDEF, VT);
1331 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
1332 // constant if knowing that the operand is non-nan is enough. We prefer to
1333 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1335 if (Cond == ISD::SETO || Cond == ISD::SETUO)
1336 return DAG.getSetCC(VT, N0, N0, Cond);
1340 // We can always fold X == X for integer setcc's.
1341 if (MVT::isInteger(N0.getValueType()))
1342 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1343 unsigned UOF = ISD::getUnorderedFlavor(Cond);
1344 if (UOF == 2) // FP operators that are undefined on NaNs.
1345 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1346 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
1347 return DAG.getConstant(UOF, VT);
1348 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
1349 // if it is not already.
1350 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
1351 if (NewCond != Cond)
1352 return DAG.getSetCC(VT, N0, N1, NewCond);
1355 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1356 MVT::isInteger(N0.getValueType())) {
1357 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
1358 N0.getOpcode() == ISD::XOR) {
1359 // Simplify (X+Y) == (X+Z) --> Y == Z
1360 if (N0.getOpcode() == N1.getOpcode()) {
1361 if (N0.getOperand(0) == N1.getOperand(0))
1362 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
1363 if (N0.getOperand(1) == N1.getOperand(1))
1364 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
1365 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
1366 // If X op Y == Y op X, try other combinations.
1367 if (N0.getOperand(0) == N1.getOperand(1))
1368 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
1369 if (N0.getOperand(1) == N1.getOperand(0))
1370 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
1374 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
1375 if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1376 // Turn (X+C1) == C2 --> X == C2-C1
1377 if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
1378 return DAG.getSetCC(VT, N0.getOperand(0),
1379 DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
1380 N0.getValueType()), Cond);
1383 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
1384 if (N0.getOpcode() == ISD::XOR)
1385 // If we know that all of the inverted bits are zero, don't bother
1386 // performing the inversion.
1387 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
1389 DAG.getSetCC(VT, N0.getOperand(0),
1390 DAG.getConstant(LHSR->getAPIntValue() ^
1391 RHSC->getAPIntValue(),
1396 // Turn (C1-X) == C2 --> X == C1-C2
1397 if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1398 if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) {
1400 DAG.getSetCC(VT, N0.getOperand(1),
1401 DAG.getConstant(SUBC->getAPIntValue() -
1402 RHSC->getAPIntValue(),
1409 // Simplify (X+Z) == X --> Z == 0
1410 if (N0.getOperand(0) == N1)
1411 return DAG.getSetCC(VT, N0.getOperand(1),
1412 DAG.getConstant(0, N0.getValueType()), Cond);
1413 if (N0.getOperand(1) == N1) {
1414 if (DAG.isCommutativeBinOp(N0.getOpcode()))
1415 return DAG.getSetCC(VT, N0.getOperand(0),
1416 DAG.getConstant(0, N0.getValueType()), Cond);
1417 else if (N0.Val->hasOneUse()) {
1418 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
1419 // (Z-X) == X --> Z == X<<1
1420 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
1422 DAG.getConstant(1, getShiftAmountTy()));
1423 if (!DCI.isCalledByLegalizer())
1424 DCI.AddToWorklist(SH.Val);
1425 return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
1430 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
1431 N1.getOpcode() == ISD::XOR) {
1432 // Simplify X == (X+Z) --> Z == 0
1433 if (N1.getOperand(0) == N0) {
1434 return DAG.getSetCC(VT, N1.getOperand(1),
1435 DAG.getConstant(0, N1.getValueType()), Cond);
1436 } else if (N1.getOperand(1) == N0) {
1437 if (DAG.isCommutativeBinOp(N1.getOpcode())) {
1438 return DAG.getSetCC(VT, N1.getOperand(0),
1439 DAG.getConstant(0, N1.getValueType()), Cond);
1440 } else if (N1.Val->hasOneUse()) {
1441 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
1442 // X == (Z-X) --> X<<1 == Z
1443 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0,
1444 DAG.getConstant(1, getShiftAmountTy()));
1445 if (!DCI.isCalledByLegalizer())
1446 DCI.AddToWorklist(SH.Val);
1447 return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
1453 // Fold away ALL boolean setcc's.
1455 if (N0.getValueType() == MVT::i1 && foldBooleans) {
1457 default: assert(0 && "Unknown integer setcc!");
1458 case ISD::SETEQ: // X == Y -> (X^Y)^1
1459 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1460 N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
1461 if (!DCI.isCalledByLegalizer())
1462 DCI.AddToWorklist(Temp.Val);
1464 case ISD::SETNE: // X != Y --> (X^Y)
1465 N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1467 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> X^1 & Y
1468 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> X^1 & Y
1469 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1470 N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
1471 if (!DCI.isCalledByLegalizer())
1472 DCI.AddToWorklist(Temp.Val);
1474 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> Y^1 & X
1475 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> Y^1 & X
1476 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1477 N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
1478 if (!DCI.isCalledByLegalizer())
1479 DCI.AddToWorklist(Temp.Val);
1481 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> X^1 | Y
1482 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> X^1 | Y
1483 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1484 N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
1485 if (!DCI.isCalledByLegalizer())
1486 DCI.AddToWorklist(Temp.Val);
1488 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> Y^1 | X
1489 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> Y^1 | X
1490 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1491 N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
1494 if (VT != MVT::i1) {
1495 if (!DCI.isCalledByLegalizer())
1496 DCI.AddToWorklist(N0.Val);
1497 // FIXME: If running after legalize, we probably can't do this.
1498 N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
1503 // Could not fold it.
1507 SDOperand TargetLowering::
1508 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1509 // Default implementation: no optimization.
1513 //===----------------------------------------------------------------------===//
1514 // Inline Assembler Implementation Methods
1515 //===----------------------------------------------------------------------===//
1517 TargetLowering::ConstraintType
1518 TargetLowering::getConstraintType(const std::string &Constraint) const {
1519 // FIXME: lots more standard ones to handle.
1520 if (Constraint.size() == 1) {
1521 switch (Constraint[0]) {
1523 case 'r': return C_RegisterClass;
1525 case 'o': // offsetable
1526 case 'V': // not offsetable
1528 case 'i': // Simple Integer or Relocatable Constant
1529 case 'n': // Simple Integer
1530 case 's': // Relocatable Constant
1531 case 'X': // Allow ANY value.
1532 case 'I': // Target registers.
1544 if (Constraint.size() > 1 && Constraint[0] == '{' &&
1545 Constraint[Constraint.size()-1] == '}')
1550 /// LowerXConstraint - try to replace an X constraint, which matches anything,
1551 /// with another that has more specific requirements based on the type of the
1552 /// corresponding operand.
1553 void TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT,
1554 std::string& s) const {
1555 if (MVT::isInteger(ConstraintVT))
1557 else if (MVT::isFloatingPoint(ConstraintVT))
1558 s = "f"; // works for many targets
1563 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1564 /// vector. If it is invalid, don't add anything to Ops.
1565 void TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
1566 char ConstraintLetter,
1567 std::vector<SDOperand> &Ops,
1568 SelectionDAG &DAG) {
1569 switch (ConstraintLetter) {
1571 case 'X': // Allows any operand; labels (basic block) use this.
1572 if (Op.getOpcode() == ISD::BasicBlock) {
1577 case 'i': // Simple Integer or Relocatable Constant
1578 case 'n': // Simple Integer
1579 case 's': { // Relocatable Constant
1580 // These operands are interested in values of the form (GV+C), where C may
1581 // be folded in as an offset of GV, or it may be explicitly added. Also, it
1582 // is possible and fine if either GV or C are missing.
1583 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
1584 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1586 // If we have "(add GV, C)", pull out GV/C
1587 if (Op.getOpcode() == ISD::ADD) {
1588 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1589 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
1590 if (C == 0 || GA == 0) {
1591 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1592 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
1594 if (C == 0 || GA == 0)
1598 // If we find a valid operand, map to the TargetXXX version so that the
1599 // value itself doesn't get selected.
1600 if (GA) { // Either &GV or &GV+C
1601 if (ConstraintLetter != 'n') {
1602 int64_t Offs = GA->getOffset();
1603 if (C) Offs += C->getValue();
1604 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
1605 Op.getValueType(), Offs));
1609 if (C) { // just C, no GV.
1610 // Simple constants are not allowed for 's'.
1611 if (ConstraintLetter != 's') {
1612 Ops.push_back(DAG.getTargetConstant(C->getValue(), Op.getValueType()));
1621 std::vector<unsigned> TargetLowering::
1622 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1623 MVT::ValueType VT) const {
1624 return std::vector<unsigned>();
1628 std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
1629 getRegForInlineAsmConstraint(const std::string &Constraint,
1630 MVT::ValueType VT) const {
1631 if (Constraint[0] != '{')
1632 return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1633 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
1635 // Remove the braces from around the name.
1636 std::string RegName(Constraint.begin()+1, Constraint.end()-1);
1638 // Figure out which register class contains this reg.
1639 const TargetRegisterInfo *RI = TM.getRegisterInfo();
1640 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
1641 E = RI->regclass_end(); RCI != E; ++RCI) {
1642 const TargetRegisterClass *RC = *RCI;
1644 // If none of the the value types for this register class are valid, we
1645 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1646 bool isLegal = false;
1647 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1649 if (isTypeLegal(*I)) {
1655 if (!isLegal) continue;
1657 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
1659 if (StringsEqualNoCase(RegName, RI->get(*I).AsmName))
1660 return std::make_pair(*I, RC);
1664 return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1667 //===----------------------------------------------------------------------===//
1668 // Loop Strength Reduction hooks
1669 //===----------------------------------------------------------------------===//
1671 /// isLegalAddressingMode - Return true if the addressing mode represented
1672 /// by AM is legal for this target, for a load/store of the specified type.
1673 bool TargetLowering::isLegalAddressingMode(const AddrMode &AM,
1674 const Type *Ty) const {
1675 // The default implementation of this implements a conservative RISCy, r+r and
1678 // Allows a sign-extended 16-bit immediate field.
1679 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
1682 // No global is ever allowed as a base.
1686 // Only support r+r,
1688 case 0: // "r+i" or just "i", depending on HasBaseReg.
1691 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
1693 // Otherwise we have r+r or r+i.
1696 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
1698 // Allow 2*r as r+r.
1705 // Magic for divide replacement
1708 int64_t m; // magic number
1709 int64_t s; // shift amount
1713 uint64_t m; // magic number
1714 int64_t a; // add indicator
1715 int64_t s; // shift amount
1718 /// magic - calculate the magic numbers required to codegen an integer sdiv as
1719 /// a sequence of multiply and shifts. Requires that the divisor not be 0, 1,
1721 static ms magic32(int32_t d) {
1723 uint32_t ad, anc, delta, q1, r1, q2, r2, t;
1724 const uint32_t two31 = 0x80000000U;
1728 t = two31 + ((uint32_t)d >> 31);
1729 anc = t - 1 - t%ad; // absolute value of nc
1730 p = 31; // initialize p
1731 q1 = two31/anc; // initialize q1 = 2p/abs(nc)
1732 r1 = two31 - q1*anc; // initialize r1 = rem(2p,abs(nc))
1733 q2 = two31/ad; // initialize q2 = 2p/abs(d)
1734 r2 = two31 - q2*ad; // initialize r2 = rem(2p,abs(d))
1737 q1 = 2*q1; // update q1 = 2p/abs(nc)
1738 r1 = 2*r1; // update r1 = rem(2p/abs(nc))
1739 if (r1 >= anc) { // must be unsigned comparison
1743 q2 = 2*q2; // update q2 = 2p/abs(d)
1744 r2 = 2*r2; // update r2 = rem(2p/abs(d))
1745 if (r2 >= ad) { // must be unsigned comparison
1750 } while (q1 < delta || (q1 == delta && r1 == 0));
1752 mag.m = (int32_t)(q2 + 1); // make sure to sign extend
1753 if (d < 0) mag.m = -mag.m; // resulting magic number
1754 mag.s = p - 32; // resulting shift
1758 /// magicu - calculate the magic numbers required to codegen an integer udiv as
1759 /// a sequence of multiply, add and shifts. Requires that the divisor not be 0.
1760 static mu magicu32(uint32_t d) {
1762 uint32_t nc, delta, q1, r1, q2, r2;
1764 magu.a = 0; // initialize "add" indicator
1766 p = 31; // initialize p
1767 q1 = 0x80000000/nc; // initialize q1 = 2p/nc
1768 r1 = 0x80000000 - q1*nc; // initialize r1 = rem(2p,nc)
1769 q2 = 0x7FFFFFFF/d; // initialize q2 = (2p-1)/d
1770 r2 = 0x7FFFFFFF - q2*d; // initialize r2 = rem((2p-1),d)
1773 if (r1 >= nc - r1 ) {
1774 q1 = 2*q1 + 1; // update q1
1775 r1 = 2*r1 - nc; // update r1
1778 q1 = 2*q1; // update q1
1779 r1 = 2*r1; // update r1
1781 if (r2 + 1 >= d - r2) {
1782 if (q2 >= 0x7FFFFFFF) magu.a = 1;
1783 q2 = 2*q2 + 1; // update q2
1784 r2 = 2*r2 + 1 - d; // update r2
1787 if (q2 >= 0x80000000) magu.a = 1;
1788 q2 = 2*q2; // update q2
1789 r2 = 2*r2 + 1; // update r2
1792 } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
1793 magu.m = q2 + 1; // resulting magic number
1794 magu.s = p - 32; // resulting shift
1798 /// magic - calculate the magic numbers required to codegen an integer sdiv as
1799 /// a sequence of multiply and shifts. Requires that the divisor not be 0, 1,
1801 static ms magic64(int64_t d) {
1803 uint64_t ad, anc, delta, q1, r1, q2, r2, t;
1804 const uint64_t two63 = 9223372036854775808ULL; // 2^63
1807 ad = d >= 0 ? d : -d;
1808 t = two63 + ((uint64_t)d >> 63);
1809 anc = t - 1 - t%ad; // absolute value of nc
1810 p = 63; // initialize p
1811 q1 = two63/anc; // initialize q1 = 2p/abs(nc)
1812 r1 = two63 - q1*anc; // initialize r1 = rem(2p,abs(nc))
1813 q2 = two63/ad; // initialize q2 = 2p/abs(d)
1814 r2 = two63 - q2*ad; // initialize r2 = rem(2p,abs(d))
1817 q1 = 2*q1; // update q1 = 2p/abs(nc)
1818 r1 = 2*r1; // update r1 = rem(2p/abs(nc))
1819 if (r1 >= anc) { // must be unsigned comparison
1823 q2 = 2*q2; // update q2 = 2p/abs(d)
1824 r2 = 2*r2; // update r2 = rem(2p/abs(d))
1825 if (r2 >= ad) { // must be unsigned comparison
1830 } while (q1 < delta || (q1 == delta && r1 == 0));
1833 if (d < 0) mag.m = -mag.m; // resulting magic number
1834 mag.s = p - 64; // resulting shift
1838 /// magicu - calculate the magic numbers required to codegen an integer udiv as
1839 /// a sequence of multiply, add and shifts. Requires that the divisor not be 0.
1840 static mu magicu64(uint64_t d)
1843 uint64_t nc, delta, q1, r1, q2, r2;
1845 magu.a = 0; // initialize "add" indicator
1847 p = 63; // initialize p
1848 q1 = 0x8000000000000000ull/nc; // initialize q1 = 2p/nc
1849 r1 = 0x8000000000000000ull - q1*nc; // initialize r1 = rem(2p,nc)
1850 q2 = 0x7FFFFFFFFFFFFFFFull/d; // initialize q2 = (2p-1)/d
1851 r2 = 0x7FFFFFFFFFFFFFFFull - q2*d; // initialize r2 = rem((2p-1),d)
1854 if (r1 >= nc - r1 ) {
1855 q1 = 2*q1 + 1; // update q1
1856 r1 = 2*r1 - nc; // update r1
1859 q1 = 2*q1; // update q1
1860 r1 = 2*r1; // update r1
1862 if (r2 + 1 >= d - r2) {
1863 if (q2 >= 0x7FFFFFFFFFFFFFFFull) magu.a = 1;
1864 q2 = 2*q2 + 1; // update q2
1865 r2 = 2*r2 + 1 - d; // update r2
1868 if (q2 >= 0x8000000000000000ull) magu.a = 1;
1869 q2 = 2*q2; // update q2
1870 r2 = 2*r2 + 1; // update r2
1873 } while (p < 128 && (q1 < delta || (q1 == delta && r1 == 0)));
1874 magu.m = q2 + 1; // resulting magic number
1875 magu.s = p - 64; // resulting shift
1879 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
1880 /// return a DAG expression to select that will generate the same value by
1881 /// multiplying by a magic number. See:
1882 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
1883 SDOperand TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
1884 std::vector<SDNode*>* Created) const {
1885 MVT::ValueType VT = N->getValueType(0);
1887 // Check to see if we can do this.
1888 if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
1889 return SDOperand(); // BuildSDIV only operates on i32 or i64
1891 int64_t d = cast<ConstantSDNode>(N->getOperand(1))->getSignExtended();
1892 ms magics = (VT == MVT::i32) ? magic32(d) : magic64(d);
1894 // Multiply the numerator (operand 0) by the magic value
1896 if (isOperationLegal(ISD::MULHS, VT))
1897 Q = DAG.getNode(ISD::MULHS, VT, N->getOperand(0),
1898 DAG.getConstant(magics.m, VT));
1899 else if (isOperationLegal(ISD::SMUL_LOHI, VT))
1900 Q = SDOperand(DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(VT, VT),
1902 DAG.getConstant(magics.m, VT)).Val, 1);
1904 return SDOperand(); // No mulhs or equvialent
1905 // If d > 0 and m < 0, add the numerator
1906 if (d > 0 && magics.m < 0) {
1907 Q = DAG.getNode(ISD::ADD, VT, Q, N->getOperand(0));
1909 Created->push_back(Q.Val);
1911 // If d < 0 and m > 0, subtract the numerator.
1912 if (d < 0 && magics.m > 0) {
1913 Q = DAG.getNode(ISD::SUB, VT, Q, N->getOperand(0));
1915 Created->push_back(Q.Val);
1917 // Shift right algebraic if shift value is nonzero
1919 Q = DAG.getNode(ISD::SRA, VT, Q,
1920 DAG.getConstant(magics.s, getShiftAmountTy()));
1922 Created->push_back(Q.Val);
1924 // Extract the sign bit and add it to the quotient
1926 DAG.getNode(ISD::SRL, VT, Q, DAG.getConstant(MVT::getSizeInBits(VT)-1,
1927 getShiftAmountTy()));
1929 Created->push_back(T.Val);
1930 return DAG.getNode(ISD::ADD, VT, Q, T);
1933 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
1934 /// return a DAG expression to select that will generate the same value by
1935 /// multiplying by a magic number. See:
1936 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
1937 SDOperand TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
1938 std::vector<SDNode*>* Created) const {
1939 MVT::ValueType VT = N->getValueType(0);
1941 // Check to see if we can do this.
1942 if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
1943 return SDOperand(); // BuildUDIV only operates on i32 or i64
1945 uint64_t d = cast<ConstantSDNode>(N->getOperand(1))->getValue();
1946 mu magics = (VT == MVT::i32) ? magicu32(d) : magicu64(d);
1948 // Multiply the numerator (operand 0) by the magic value
1950 if (isOperationLegal(ISD::MULHU, VT))
1951 Q = DAG.getNode(ISD::MULHU, VT, N->getOperand(0),
1952 DAG.getConstant(magics.m, VT));
1953 else if (isOperationLegal(ISD::UMUL_LOHI, VT))
1954 Q = SDOperand(DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(VT, VT),
1956 DAG.getConstant(magics.m, VT)).Val, 1);
1958 return SDOperand(); // No mulhu or equvialent
1960 Created->push_back(Q.Val);
1962 if (magics.a == 0) {
1963 return DAG.getNode(ISD::SRL, VT, Q,
1964 DAG.getConstant(magics.s, getShiftAmountTy()));
1966 SDOperand NPQ = DAG.getNode(ISD::SUB, VT, N->getOperand(0), Q);
1968 Created->push_back(NPQ.Val);
1969 NPQ = DAG.getNode(ISD::SRL, VT, NPQ,
1970 DAG.getConstant(1, getShiftAmountTy()));
1972 Created->push_back(NPQ.Val);
1973 NPQ = DAG.getNode(ISD::ADD, VT, NPQ, Q);
1975 Created->push_back(NPQ.Val);
1976 return DAG.getNode(ISD::SRL, VT, NPQ,
1977 DAG.getConstant(magics.s-1, getShiftAmountTy()));