X86ISelLowering.cpp revision 471e4224809f51652c71f319532697a879a75a0d
1//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the interfaces that X86 uses to lower LLVM code into a 11// selection DAG. 12// 13//===----------------------------------------------------------------------===// 14 15#define DEBUG_TYPE "x86-isel" 16#include "X86.h" 17#include "X86InstrBuilder.h" 18#include "X86ISelLowering.h" 19#include "X86TargetMachine.h" 20#include "X86TargetObjectFile.h" 21#include "Utils/X86ShuffleDecode.h" 22#include "llvm/CallingConv.h" 23#include "llvm/Constants.h" 24#include "llvm/DerivedTypes.h" 25#include "llvm/GlobalAlias.h" 26#include "llvm/GlobalVariable.h" 27#include "llvm/Function.h" 28#include "llvm/Instructions.h" 29#include "llvm/Intrinsics.h" 30#include "llvm/LLVMContext.h" 31#include "llvm/CodeGen/IntrinsicLowering.h" 32#include "llvm/CodeGen/MachineFrameInfo.h" 33#include "llvm/CodeGen/MachineFunction.h" 34#include "llvm/CodeGen/MachineInstrBuilder.h" 35#include "llvm/CodeGen/MachineJumpTableInfo.h" 36#include "llvm/CodeGen/MachineModuleInfo.h" 37#include "llvm/CodeGen/MachineRegisterInfo.h" 38#include "llvm/CodeGen/PseudoSourceValue.h" 39#include "llvm/MC/MCAsmInfo.h" 40#include "llvm/MC/MCContext.h" 41#include "llvm/MC/MCExpr.h" 42#include "llvm/MC/MCSymbol.h" 43#include "llvm/ADT/BitVector.h" 44#include "llvm/ADT/SmallSet.h" 45#include "llvm/ADT/Statistic.h" 46#include "llvm/ADT/StringExtras.h" 47#include "llvm/ADT/VectorExtras.h" 48#include "llvm/Support/CallSite.h" 49#include "llvm/Support/Debug.h" 50#include "llvm/Support/Dwarf.h" 51#include "llvm/Support/ErrorHandling.h" 52#include "llvm/Support/MathExtras.h" 53#include "llvm/Support/raw_ostream.h" 54using namespace llvm; 55using namespace dwarf; 56 57STATISTIC(NumTailCalls, "Number of tail calls"); 58 59// Forward declarations. 60static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 61 SDValue V2); 62 63static SDValue Insert128BitVector(SDValue Result, 64 SDValue Vec, 65 SDValue Idx, 66 SelectionDAG &DAG, 67 DebugLoc dl); 68 69static SDValue Extract128BitVector(SDValue Vec, 70 SDValue Idx, 71 SelectionDAG &DAG, 72 DebugLoc dl); 73 74static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG); 75 76 77/// Generate a DAG to grab 128-bits from a vector > 128 bits. This 78/// sets things up to match to an AVX VEXTRACTF128 instruction or a 79/// simple subregister reference. Idx is an index in the 128 bits we 80/// want. It need not be aligned to a 128-bit bounday. That makes 81/// lowering EXTRACT_VECTOR_ELT operations easier. 82static SDValue Extract128BitVector(SDValue Vec, 83 SDValue Idx, 84 SelectionDAG &DAG, 85 DebugLoc dl) { 86 EVT VT = Vec.getValueType(); 87 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!"); 88 89 EVT ElVT = VT.getVectorElementType(); 90 91 int Factor = VT.getSizeInBits() / 128; 92 93 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), 94 ElVT, 95 VT.getVectorNumElements() / Factor); 96 97 // Extract from UNDEF is UNDEF. 98 if (Vec.getOpcode() == ISD::UNDEF) 99 return DAG.getNode(ISD::UNDEF, dl, ResultVT); 100 101 if (isa<ConstantSDNode>(Idx)) { 102 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 103 104 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR 105 // we can match to VEXTRACTF128. 106 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits(); 107 108 // This is the index of the first element of the 128-bit chunk 109 // we want. 110 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128) 111 * ElemsPerChunk); 112 113 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 114 115 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, 116 VecIdx); 117 118 return Result; 119 } 120 121 return SDValue(); 122} 123 124/// Generate a DAG to put 128-bits into a vector > 128 bits. This 125/// sets things up to match to an AVX VINSERTF128 instruction or a 126/// simple superregister reference. Idx is an index in the 128 bits 127/// we want. It need not be aligned to a 128-bit bounday. That makes 128/// lowering INSERT_VECTOR_ELT operations easier. 129static SDValue Insert128BitVector(SDValue Result, 130 SDValue Vec, 131 SDValue Idx, 132 SelectionDAG &DAG, 133 DebugLoc dl) { 134 if (isa<ConstantSDNode>(Idx)) { 135 EVT VT = Vec.getValueType(); 136 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!"); 137 138 EVT ElVT = VT.getVectorElementType(); 139 140 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 141 142 EVT ResultVT = Result.getValueType(); 143 144 // Insert the relevant 128 bits. 145 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits(); 146 147 // This is the index of the first element of the 128-bit chunk 148 // we want. 149 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128) 150 * ElemsPerChunk); 151 152 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 153 154 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, 155 VecIdx); 156 return Result; 157 } 158 159 return SDValue(); 160} 161 162/// Given two vectors, concat them. 163static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) { 164 DebugLoc dl = Lower.getDebugLoc(); 165 166 assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!"); 167 168 EVT VT = EVT::getVectorVT(*DAG.getContext(), 169 Lower.getValueType().getVectorElementType(), 170 Lower.getValueType().getVectorNumElements() * 2); 171 172 // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors). 173 assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!"); 174 175 // Insert the upper subvector. 176 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper, 177 DAG.getConstant( 178 // This is half the length of the result 179 // vector. Start inserting the upper 128 180 // bits here. 181 Lower.getValueType().getVectorNumElements(), 182 MVT::i32), 183 DAG, dl); 184 185 // Insert the lower subvector. 186 Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl); 187 return Vec; 188} 189 190static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) { 191 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>(); 192 bool is64Bit = Subtarget->is64Bit(); 193 194 if (Subtarget->isTargetEnvMacho()) { 195 if (is64Bit) 196 return new X8664_MachoTargetObjectFile(); 197 return new TargetLoweringObjectFileMachO(); 198 } 199 200 if (Subtarget->isTargetELF()) { 201 if (is64Bit) 202 return new X8664_ELFTargetObjectFile(TM); 203 return new X8632_ELFTargetObjectFile(TM); 204 } 205 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 206 return new TargetLoweringObjectFileCOFF(); 207 llvm_unreachable("unknown subtarget type"); 208} 209 210X86TargetLowering::X86TargetLowering(X86TargetMachine &TM) 211 : TargetLowering(TM, createTLOF(TM)) { 212 Subtarget = &TM.getSubtarget<X86Subtarget>(); 213 X86ScalarSSEf64 = Subtarget->hasXMMInt(); 214 X86ScalarSSEf32 = Subtarget->hasXMM(); 215 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP; 216 217 RegInfo = TM.getRegisterInfo(); 218 TD = getTargetData(); 219 220 // Set up the TargetLowering object. 221 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }; 222 223 // X86 is weird, it always uses i8 for shift amounts and setcc results. 224 setBooleanContents(ZeroOrOneBooleanContent); 225 226 // For 64-bit since we have so many registers use the ILP scheduler, for 227 // 32-bit code use the register pressure specific scheduling. 228 if (Subtarget->is64Bit()) 229 setSchedulingPreference(Sched::ILP); 230 else 231 setSchedulingPreference(Sched::RegPressure); 232 setStackPointerRegisterToSaveRestore(X86StackPtr); 233 234 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) { 235 // Setup Windows compiler runtime calls. 236 setLibcallName(RTLIB::SDIV_I64, "_alldiv"); 237 setLibcallName(RTLIB::UDIV_I64, "_aulldiv"); 238 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2"); 239 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2"); 240 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall); 241 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall); 242 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C); 243 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C); 244 } 245 246 if (Subtarget->isTargetDarwin()) { 247 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp. 248 setUseUnderscoreSetJmp(false); 249 setUseUnderscoreLongJmp(false); 250 } else if (Subtarget->isTargetMingw()) { 251 // MS runtime is weird: it exports _setjmp, but longjmp! 252 setUseUnderscoreSetJmp(true); 253 setUseUnderscoreLongJmp(false); 254 } else { 255 setUseUnderscoreSetJmp(true); 256 setUseUnderscoreLongJmp(true); 257 } 258 259 // Set up the register classes. 260 addRegisterClass(MVT::i8, X86::GR8RegisterClass); 261 addRegisterClass(MVT::i16, X86::GR16RegisterClass); 262 addRegisterClass(MVT::i32, X86::GR32RegisterClass); 263 if (Subtarget->is64Bit()) 264 addRegisterClass(MVT::i64, X86::GR64RegisterClass); 265 266 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 267 268 // We don't accept any truncstore of integer registers. 269 setTruncStoreAction(MVT::i64, MVT::i32, Expand); 270 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 271 setTruncStoreAction(MVT::i64, MVT::i8 , Expand); 272 setTruncStoreAction(MVT::i32, MVT::i16, Expand); 273 setTruncStoreAction(MVT::i32, MVT::i8 , Expand); 274 setTruncStoreAction(MVT::i16, MVT::i8, Expand); 275 276 // SETOEQ and SETUNE require checking two conditions. 277 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand); 278 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand); 279 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand); 280 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand); 281 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand); 282 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand); 283 284 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this 285 // operation. 286 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote); 287 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote); 288 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote); 289 290 if (Subtarget->is64Bit()) { 291 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote); 292 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand); 293 } else if (!UseSoftFloat) { 294 // We have an algorithm for SSE2->double, and we turn this into a 295 // 64-bit FILD followed by conditional FADD for other targets. 296 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 297 // We have an algorithm for SSE2, and we turn this into a 64-bit 298 // FILD for other targets. 299 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom); 300 } 301 302 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have 303 // this operation. 304 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote); 305 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote); 306 307 if (!UseSoftFloat) { 308 // SSE has no i16 to fp conversion, only i32 309 if (X86ScalarSSEf32) { 310 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 311 // f32 and f64 cases are Legal, f80 case is not 312 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 313 } else { 314 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom); 315 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 316 } 317 } else { 318 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 319 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote); 320 } 321 322 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64 323 // are Legal, f80 is custom lowered. 324 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom); 325 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom); 326 327 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have 328 // this operation. 329 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote); 330 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote); 331 332 if (X86ScalarSSEf32) { 333 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote); 334 // f32 and f64 cases are Legal, f80 case is not 335 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 336 } else { 337 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom); 338 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 339 } 340 341 // Handle FP_TO_UINT by promoting the destination to a larger signed 342 // conversion. 343 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote); 344 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote); 345 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote); 346 347 if (Subtarget->is64Bit()) { 348 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand); 349 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote); 350 } else if (!UseSoftFloat) { 351 if (X86ScalarSSEf32 && !Subtarget->hasSSE3()) 352 // Expand FP_TO_UINT into a select. 353 // FIXME: We would like to use a Custom expander here eventually to do 354 // the optimal thing for SSE vs. the default expansion in the legalizer. 355 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand); 356 else 357 // With SSE3 we can use fisttpll to convert to a signed i64; without 358 // SSE, we're stuck with a fistpll. 359 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom); 360 } 361 362 // TODO: when we have SSE, these could be more efficient, by using movd/movq. 363 if (!X86ScalarSSEf64) { 364 setOperationAction(ISD::BITCAST , MVT::f32 , Expand); 365 setOperationAction(ISD::BITCAST , MVT::i32 , Expand); 366 if (Subtarget->is64Bit()) { 367 setOperationAction(ISD::BITCAST , MVT::f64 , Expand); 368 // Without SSE, i64->f64 goes through memory. 369 setOperationAction(ISD::BITCAST , MVT::i64 , Expand); 370 } 371 } 372 373 // Scalar integer divide and remainder are lowered to use operations that 374 // produce two results, to match the available instructions. This exposes 375 // the two-result form to trivial CSE, which is able to combine x/y and x%y 376 // into a single instruction. 377 // 378 // Scalar integer multiply-high is also lowered to use two-result 379 // operations, to match the available instructions. However, plain multiply 380 // (low) operations are left as Legal, as there are single-result 381 // instructions for this in x86. Using the two-result multiply instructions 382 // when both high and low results are needed must be arranged by dagcombine. 383 for (unsigned i = 0, e = 4; i != e; ++i) { 384 MVT VT = IntVTs[i]; 385 setOperationAction(ISD::MULHS, VT, Expand); 386 setOperationAction(ISD::MULHU, VT, Expand); 387 setOperationAction(ISD::SDIV, VT, Expand); 388 setOperationAction(ISD::UDIV, VT, Expand); 389 setOperationAction(ISD::SREM, VT, Expand); 390 setOperationAction(ISD::UREM, VT, Expand); 391 392 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences. 393 setOperationAction(ISD::ADDC, VT, Custom); 394 setOperationAction(ISD::ADDE, VT, Custom); 395 setOperationAction(ISD::SUBC, VT, Custom); 396 setOperationAction(ISD::SUBE, VT, Custom); 397 } 398 399 setOperationAction(ISD::BR_JT , MVT::Other, Expand); 400 setOperationAction(ISD::BRCOND , MVT::Other, Custom); 401 setOperationAction(ISD::BR_CC , MVT::Other, Expand); 402 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand); 403 if (Subtarget->is64Bit()) 404 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal); 405 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal); 406 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal); 407 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand); 408 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand); 409 setOperationAction(ISD::FREM , MVT::f32 , Expand); 410 setOperationAction(ISD::FREM , MVT::f64 , Expand); 411 setOperationAction(ISD::FREM , MVT::f80 , Expand); 412 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom); 413 414 setOperationAction(ISD::CTTZ , MVT::i8 , Custom); 415 setOperationAction(ISD::CTLZ , MVT::i8 , Custom); 416 setOperationAction(ISD::CTTZ , MVT::i16 , Custom); 417 setOperationAction(ISD::CTLZ , MVT::i16 , Custom); 418 setOperationAction(ISD::CTTZ , MVT::i32 , Custom); 419 setOperationAction(ISD::CTLZ , MVT::i32 , Custom); 420 if (Subtarget->is64Bit()) { 421 setOperationAction(ISD::CTTZ , MVT::i64 , Custom); 422 setOperationAction(ISD::CTLZ , MVT::i64 , Custom); 423 } 424 425 if (Subtarget->hasPOPCNT()) { 426 setOperationAction(ISD::CTPOP , MVT::i8 , Promote); 427 } else { 428 setOperationAction(ISD::CTPOP , MVT::i8 , Expand); 429 setOperationAction(ISD::CTPOP , MVT::i16 , Expand); 430 setOperationAction(ISD::CTPOP , MVT::i32 , Expand); 431 if (Subtarget->is64Bit()) 432 setOperationAction(ISD::CTPOP , MVT::i64 , Expand); 433 } 434 435 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom); 436 setOperationAction(ISD::BSWAP , MVT::i16 , Expand); 437 438 // These should be promoted to a larger select which is supported. 439 setOperationAction(ISD::SELECT , MVT::i1 , Promote); 440 // X86 wants to expand cmov itself. 441 setOperationAction(ISD::SELECT , MVT::i8 , Custom); 442 setOperationAction(ISD::SELECT , MVT::i16 , Custom); 443 setOperationAction(ISD::SELECT , MVT::i32 , Custom); 444 setOperationAction(ISD::SELECT , MVT::f32 , Custom); 445 setOperationAction(ISD::SELECT , MVT::f64 , Custom); 446 setOperationAction(ISD::SELECT , MVT::f80 , Custom); 447 setOperationAction(ISD::SETCC , MVT::i8 , Custom); 448 setOperationAction(ISD::SETCC , MVT::i16 , Custom); 449 setOperationAction(ISD::SETCC , MVT::i32 , Custom); 450 setOperationAction(ISD::SETCC , MVT::f32 , Custom); 451 setOperationAction(ISD::SETCC , MVT::f64 , Custom); 452 setOperationAction(ISD::SETCC , MVT::f80 , Custom); 453 if (Subtarget->is64Bit()) { 454 setOperationAction(ISD::SELECT , MVT::i64 , Custom); 455 setOperationAction(ISD::SETCC , MVT::i64 , Custom); 456 } 457 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom); 458 459 // Darwin ABI issue. 460 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom); 461 setOperationAction(ISD::JumpTable , MVT::i32 , Custom); 462 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom); 463 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom); 464 if (Subtarget->is64Bit()) 465 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 466 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom); 467 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom); 468 if (Subtarget->is64Bit()) { 469 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom); 470 setOperationAction(ISD::JumpTable , MVT::i64 , Custom); 471 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom); 472 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom); 473 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom); 474 } 475 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86) 476 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom); 477 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom); 478 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom); 479 if (Subtarget->is64Bit()) { 480 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom); 481 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom); 482 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom); 483 } 484 485 if (Subtarget->hasXMM()) 486 setOperationAction(ISD::PREFETCH , MVT::Other, Legal); 487 488 // We may not have a libcall for MEMBARRIER so we should lower this. 489 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom); 490 491 // On X86 and X86-64, atomic operations are lowered to locked instructions. 492 // Locked instructions, in turn, have implicit fence semantics (all memory 493 // operations are flushed before issuing the locked instruction, and they 494 // are not buffered), so we can fold away the common pattern of 495 // fence-atomic-fence. 496 setShouldFoldAtomicFences(true); 497 498 // Expand certain atomics 499 for (unsigned i = 0, e = 4; i != e; ++i) { 500 MVT VT = IntVTs[i]; 501 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom); 502 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom); 503 } 504 505 if (!Subtarget->is64Bit()) { 506 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom); 507 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 508 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 509 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom); 510 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom); 511 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom); 512 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom); 513 } 514 515 // FIXME - use subtarget debug flags 516 if (!Subtarget->isTargetDarwin() && 517 !Subtarget->isTargetELF() && 518 !Subtarget->isTargetCygMing()) { 519 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand); 520 } 521 522 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand); 523 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand); 524 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand); 525 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand); 526 if (Subtarget->is64Bit()) { 527 setExceptionPointerRegister(X86::RAX); 528 setExceptionSelectorRegister(X86::RDX); 529 } else { 530 setExceptionPointerRegister(X86::EAX); 531 setExceptionSelectorRegister(X86::EDX); 532 } 533 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom); 534 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom); 535 536 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom); 537 538 setOperationAction(ISD::TRAP, MVT::Other, Legal); 539 540 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 541 setOperationAction(ISD::VASTART , MVT::Other, Custom); 542 setOperationAction(ISD::VAEND , MVT::Other, Expand); 543 if (Subtarget->is64Bit()) { 544 setOperationAction(ISD::VAARG , MVT::Other, Custom); 545 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 546 } else { 547 setOperationAction(ISD::VAARG , MVT::Other, Expand); 548 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 549 } 550 551 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 552 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 553 setOperationAction(ISD::DYNAMIC_STACKALLOC, 554 (Subtarget->is64Bit() ? MVT::i64 : MVT::i32), 555 (Subtarget->isTargetCOFF() 556 && !Subtarget->isTargetEnvMacho() 557 ? Custom : Expand)); 558 559 if (!UseSoftFloat && X86ScalarSSEf64) { 560 // f32 and f64 use SSE. 561 // Set up the FP register classes. 562 addRegisterClass(MVT::f32, X86::FR32RegisterClass); 563 addRegisterClass(MVT::f64, X86::FR64RegisterClass); 564 565 // Use ANDPD to simulate FABS. 566 setOperationAction(ISD::FABS , MVT::f64, Custom); 567 setOperationAction(ISD::FABS , MVT::f32, Custom); 568 569 // Use XORP to simulate FNEG. 570 setOperationAction(ISD::FNEG , MVT::f64, Custom); 571 setOperationAction(ISD::FNEG , MVT::f32, Custom); 572 573 // Use ANDPD and ORPD to simulate FCOPYSIGN. 574 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 575 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 576 577 // Lower this to FGETSIGNx86 plus an AND. 578 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom); 579 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom); 580 581 // We don't support sin/cos/fmod 582 setOperationAction(ISD::FSIN , MVT::f64, Expand); 583 setOperationAction(ISD::FCOS , MVT::f64, Expand); 584 setOperationAction(ISD::FSIN , MVT::f32, Expand); 585 setOperationAction(ISD::FCOS , MVT::f32, Expand); 586 587 // Expand FP immediates into loads from the stack, except for the special 588 // cases we handle. 589 addLegalFPImmediate(APFloat(+0.0)); // xorpd 590 addLegalFPImmediate(APFloat(+0.0f)); // xorps 591 } else if (!UseSoftFloat && X86ScalarSSEf32) { 592 // Use SSE for f32, x87 for f64. 593 // Set up the FP register classes. 594 addRegisterClass(MVT::f32, X86::FR32RegisterClass); 595 addRegisterClass(MVT::f64, X86::RFP64RegisterClass); 596 597 // Use ANDPS to simulate FABS. 598 setOperationAction(ISD::FABS , MVT::f32, Custom); 599 600 // Use XORP to simulate FNEG. 601 setOperationAction(ISD::FNEG , MVT::f32, Custom); 602 603 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 604 605 // Use ANDPS and ORPS to simulate FCOPYSIGN. 606 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 607 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 608 609 // We don't support sin/cos/fmod 610 setOperationAction(ISD::FSIN , MVT::f32, Expand); 611 setOperationAction(ISD::FCOS , MVT::f32, Expand); 612 613 // Special cases we handle for FP constants. 614 addLegalFPImmediate(APFloat(+0.0f)); // xorps 615 addLegalFPImmediate(APFloat(+0.0)); // FLD0 616 addLegalFPImmediate(APFloat(+1.0)); // FLD1 617 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 618 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 619 620 if (!UnsafeFPMath) { 621 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 622 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 623 } 624 } else if (!UseSoftFloat) { 625 // f32 and f64 in x87. 626 // Set up the FP register classes. 627 addRegisterClass(MVT::f64, X86::RFP64RegisterClass); 628 addRegisterClass(MVT::f32, X86::RFP32RegisterClass); 629 630 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 631 setOperationAction(ISD::UNDEF, MVT::f32, Expand); 632 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 633 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 634 635 if (!UnsafeFPMath) { 636 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 637 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 638 } 639 addLegalFPImmediate(APFloat(+0.0)); // FLD0 640 addLegalFPImmediate(APFloat(+1.0)); // FLD1 641 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 642 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 643 addLegalFPImmediate(APFloat(+0.0f)); // FLD0 644 addLegalFPImmediate(APFloat(+1.0f)); // FLD1 645 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS 646 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS 647 } 648 649 // Long double always uses X87. 650 if (!UseSoftFloat) { 651 addRegisterClass(MVT::f80, X86::RFP80RegisterClass); 652 setOperationAction(ISD::UNDEF, MVT::f80, Expand); 653 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand); 654 { 655 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended); 656 addLegalFPImmediate(TmpFlt); // FLD0 657 TmpFlt.changeSign(); 658 addLegalFPImmediate(TmpFlt); // FLD0/FCHS 659 660 bool ignored; 661 APFloat TmpFlt2(+1.0); 662 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, 663 &ignored); 664 addLegalFPImmediate(TmpFlt2); // FLD1 665 TmpFlt2.changeSign(); 666 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS 667 } 668 669 if (!UnsafeFPMath) { 670 setOperationAction(ISD::FSIN , MVT::f80 , Expand); 671 setOperationAction(ISD::FCOS , MVT::f80 , Expand); 672 } 673 } 674 675 // Always use a library call for pow. 676 setOperationAction(ISD::FPOW , MVT::f32 , Expand); 677 setOperationAction(ISD::FPOW , MVT::f64 , Expand); 678 setOperationAction(ISD::FPOW , MVT::f80 , Expand); 679 680 setOperationAction(ISD::FLOG, MVT::f80, Expand); 681 setOperationAction(ISD::FLOG2, MVT::f80, Expand); 682 setOperationAction(ISD::FLOG10, MVT::f80, Expand); 683 setOperationAction(ISD::FEXP, MVT::f80, Expand); 684 setOperationAction(ISD::FEXP2, MVT::f80, Expand); 685 686 // First set operation action for all vector types to either promote 687 // (for widening) or expand (for scalarization). Then we will selectively 688 // turn on ones that can be effectively codegen'd. 689 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 690 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) { 691 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand); 692 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand); 693 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand); 694 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand); 695 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand); 696 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand); 697 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand); 698 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand); 699 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand); 700 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand); 701 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand); 702 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand); 703 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand); 704 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand); 705 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand); 706 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand); 707 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 708 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 709 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand); 710 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand); 711 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand); 712 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand); 713 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand); 714 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand); 715 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand); 716 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 717 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 718 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand); 719 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand); 720 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand); 721 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand); 722 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand); 723 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand); 724 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand); 725 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand); 726 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand); 727 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand); 728 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand); 729 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand); 730 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand); 731 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand); 732 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand); 733 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand); 734 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand); 735 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand); 736 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand); 737 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand); 738 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 739 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 740 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand); 741 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand); 742 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand); 743 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand); 744 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand); 745 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 746 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT) 747 setTruncStoreAction((MVT::SimpleValueType)VT, 748 (MVT::SimpleValueType)InnerVT, Expand); 749 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand); 750 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand); 751 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand); 752 } 753 754 // FIXME: In order to prevent SSE instructions being expanded to MMX ones 755 // with -msoft-float, disable use of MMX as well. 756 if (!UseSoftFloat && Subtarget->hasMMX()) { 757 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass); 758 // No operations on x86mmx supported, everything uses intrinsics. 759 } 760 761 // MMX-sized vectors (other than x86mmx) are expected to be expanded 762 // into smaller operations. 763 setOperationAction(ISD::MULHS, MVT::v8i8, Expand); 764 setOperationAction(ISD::MULHS, MVT::v4i16, Expand); 765 setOperationAction(ISD::MULHS, MVT::v2i32, Expand); 766 setOperationAction(ISD::MULHS, MVT::v1i64, Expand); 767 setOperationAction(ISD::AND, MVT::v8i8, Expand); 768 setOperationAction(ISD::AND, MVT::v4i16, Expand); 769 setOperationAction(ISD::AND, MVT::v2i32, Expand); 770 setOperationAction(ISD::AND, MVT::v1i64, Expand); 771 setOperationAction(ISD::OR, MVT::v8i8, Expand); 772 setOperationAction(ISD::OR, MVT::v4i16, Expand); 773 setOperationAction(ISD::OR, MVT::v2i32, Expand); 774 setOperationAction(ISD::OR, MVT::v1i64, Expand); 775 setOperationAction(ISD::XOR, MVT::v8i8, Expand); 776 setOperationAction(ISD::XOR, MVT::v4i16, Expand); 777 setOperationAction(ISD::XOR, MVT::v2i32, Expand); 778 setOperationAction(ISD::XOR, MVT::v1i64, Expand); 779 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand); 780 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand); 781 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand); 782 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand); 783 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand); 784 setOperationAction(ISD::SELECT, MVT::v8i8, Expand); 785 setOperationAction(ISD::SELECT, MVT::v4i16, Expand); 786 setOperationAction(ISD::SELECT, MVT::v2i32, Expand); 787 setOperationAction(ISD::SELECT, MVT::v1i64, Expand); 788 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand); 789 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand); 790 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand); 791 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand); 792 793 if (!UseSoftFloat && Subtarget->hasXMM()) { 794 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass); 795 796 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 797 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 798 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 799 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 800 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 801 setOperationAction(ISD::FNEG, MVT::v4f32, Custom); 802 setOperationAction(ISD::LOAD, MVT::v4f32, Legal); 803 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 804 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom); 805 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 806 setOperationAction(ISD::SELECT, MVT::v4f32, Custom); 807 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom); 808 } 809 810 if (!UseSoftFloat && Subtarget->hasXMMInt()) { 811 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass); 812 813 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM 814 // registers cannot be used even for integer operations. 815 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass); 816 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass); 817 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass); 818 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass); 819 820 setOperationAction(ISD::ADD, MVT::v16i8, Legal); 821 setOperationAction(ISD::ADD, MVT::v8i16, Legal); 822 setOperationAction(ISD::ADD, MVT::v4i32, Legal); 823 setOperationAction(ISD::ADD, MVT::v2i64, Legal); 824 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 825 setOperationAction(ISD::SUB, MVT::v16i8, Legal); 826 setOperationAction(ISD::SUB, MVT::v8i16, Legal); 827 setOperationAction(ISD::SUB, MVT::v4i32, Legal); 828 setOperationAction(ISD::SUB, MVT::v2i64, Legal); 829 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 830 setOperationAction(ISD::FADD, MVT::v2f64, Legal); 831 setOperationAction(ISD::FSUB, MVT::v2f64, Legal); 832 setOperationAction(ISD::FMUL, MVT::v2f64, Legal); 833 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 834 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 835 setOperationAction(ISD::FNEG, MVT::v2f64, Custom); 836 837 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom); 838 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom); 839 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom); 840 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom); 841 842 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom); 843 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom); 844 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 845 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 846 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 847 848 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom); 849 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom); 850 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom); 851 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom); 852 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom); 853 854 // Custom lower build_vector, vector_shuffle, and extract_vector_elt. 855 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) { 856 EVT VT = (MVT::SimpleValueType)i; 857 // Do not attempt to custom lower non-power-of-2 vectors 858 if (!isPowerOf2_32(VT.getVectorNumElements())) 859 continue; 860 // Do not attempt to custom lower non-128-bit vectors 861 if (!VT.is128BitVector()) 862 continue; 863 setOperationAction(ISD::BUILD_VECTOR, 864 VT.getSimpleVT().SimpleTy, Custom); 865 setOperationAction(ISD::VECTOR_SHUFFLE, 866 VT.getSimpleVT().SimpleTy, Custom); 867 setOperationAction(ISD::EXTRACT_VECTOR_ELT, 868 VT.getSimpleVT().SimpleTy, Custom); 869 } 870 871 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 872 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 873 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 874 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 875 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 876 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom); 877 878 if (Subtarget->is64Bit()) { 879 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 880 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 881 } 882 883 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64. 884 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) { 885 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 886 EVT VT = SVT; 887 888 // Do not attempt to promote non-128-bit vectors 889 if (!VT.is128BitVector()) 890 continue; 891 892 setOperationAction(ISD::AND, SVT, Promote); 893 AddPromotedToType (ISD::AND, SVT, MVT::v2i64); 894 setOperationAction(ISD::OR, SVT, Promote); 895 AddPromotedToType (ISD::OR, SVT, MVT::v2i64); 896 setOperationAction(ISD::XOR, SVT, Promote); 897 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64); 898 setOperationAction(ISD::LOAD, SVT, Promote); 899 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64); 900 setOperationAction(ISD::SELECT, SVT, Promote); 901 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64); 902 } 903 904 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 905 906 // Custom lower v2i64 and v2f64 selects. 907 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 908 setOperationAction(ISD::LOAD, MVT::v2i64, Legal); 909 setOperationAction(ISD::SELECT, MVT::v2f64, Custom); 910 setOperationAction(ISD::SELECT, MVT::v2i64, Custom); 911 912 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 913 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 914 } 915 916 if (Subtarget->hasSSE41()) { 917 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 918 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 919 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 920 setOperationAction(ISD::FRINT, MVT::f32, Legal); 921 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 922 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 923 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 924 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 925 setOperationAction(ISD::FRINT, MVT::f64, Legal); 926 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 927 928 // FIXME: Do we need to handle scalar-to-vector here? 929 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 930 931 // Can turn SHL into an integer multiply. 932 setOperationAction(ISD::SHL, MVT::v4i32, Custom); 933 setOperationAction(ISD::SHL, MVT::v16i8, Custom); 934 935 // i8 and i16 vectors are custom , because the source register and source 936 // source memory operand types are not the same width. f32 vectors are 937 // custom since the immediate controlling the insert encodes additional 938 // information. 939 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 940 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 941 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 942 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 943 944 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom); 945 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom); 946 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom); 947 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 948 949 if (Subtarget->is64Bit()) { 950 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal); 951 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 952 } 953 } 954 955 if (Subtarget->hasSSE2()) { 956 setOperationAction(ISD::SRL, MVT::v2i64, Custom); 957 setOperationAction(ISD::SRL, MVT::v4i32, Custom); 958 setOperationAction(ISD::SRL, MVT::v16i8, Custom); 959 960 setOperationAction(ISD::SHL, MVT::v2i64, Custom); 961 setOperationAction(ISD::SHL, MVT::v4i32, Custom); 962 setOperationAction(ISD::SHL, MVT::v8i16, Custom); 963 964 setOperationAction(ISD::SRA, MVT::v4i32, Custom); 965 setOperationAction(ISD::SRA, MVT::v8i16, Custom); 966 } 967 968 if (Subtarget->hasSSE42()) 969 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom); 970 971 if (!UseSoftFloat && Subtarget->hasAVX()) { 972 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass); 973 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass); 974 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass); 975 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass); 976 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass); 977 978 setOperationAction(ISD::LOAD, MVT::v8f32, Legal); 979 setOperationAction(ISD::LOAD, MVT::v8i32, Legal); 980 setOperationAction(ISD::LOAD, MVT::v4f64, Legal); 981 setOperationAction(ISD::LOAD, MVT::v4i64, Legal); 982 983 setOperationAction(ISD::FADD, MVT::v8f32, Legal); 984 setOperationAction(ISD::FSUB, MVT::v8f32, Legal); 985 setOperationAction(ISD::FMUL, MVT::v8f32, Legal); 986 setOperationAction(ISD::FDIV, MVT::v8f32, Legal); 987 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal); 988 setOperationAction(ISD::FNEG, MVT::v8f32, Custom); 989 990 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 991 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 992 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 993 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 994 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 995 setOperationAction(ISD::FNEG, MVT::v4f64, Custom); 996 997 // Custom lower build_vector, vector_shuffle, scalar_to_vector, 998 // insert_vector_elt extract_subvector and extract_vector_elt for 999 // 256-bit types. 1000 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 1001 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; 1002 ++i) { 1003 MVT::SimpleValueType VT = (MVT::SimpleValueType)i; 1004 // Do not attempt to custom lower non-256-bit vectors 1005 if (!isPowerOf2_32(MVT(VT).getVectorNumElements()) 1006 || (MVT(VT).getSizeInBits() < 256)) 1007 continue; 1008 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 1009 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 1010 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 1012 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom); 1013 } 1014 // Custom-lower insert_subvector and extract_subvector based on 1015 // the result type. 1016 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 1017 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; 1018 ++i) { 1019 MVT::SimpleValueType VT = (MVT::SimpleValueType)i; 1020 // Do not attempt to custom lower non-256-bit vectors 1021 if (!isPowerOf2_32(MVT(VT).getVectorNumElements())) 1022 continue; 1023 1024 if (MVT(VT).getSizeInBits() == 128) { 1025 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1026 } 1027 else if (MVT(VT).getSizeInBits() == 256) { 1028 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1029 } 1030 } 1031 1032 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64. 1033 // Don't promote loads because we need them for VPERM vector index versions. 1034 1035 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 1036 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; 1037 VT++) { 1038 if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements()) 1039 || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256)) 1040 continue; 1041 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote); 1042 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v4i64); 1043 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote); 1044 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v4i64); 1045 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote); 1046 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v4i64); 1047 //setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote); 1048 //AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v4i64); 1049 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote); 1050 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64); 1051 } 1052 } 1053 1054 // We want to custom lower some of our intrinsics. 1055 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1056 1057 1058 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't 1059 // handle type legalization for these operations here. 1060 // 1061 // FIXME: We really should do custom legalization for addition and 1062 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better 1063 // than generic legalization for 64-bit multiplication-with-overflow, though. 1064 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) { 1065 // Add/Sub/Mul with overflow operations are custom lowered. 1066 MVT VT = IntVTs[i]; 1067 setOperationAction(ISD::SADDO, VT, Custom); 1068 setOperationAction(ISD::UADDO, VT, Custom); 1069 setOperationAction(ISD::SSUBO, VT, Custom); 1070 setOperationAction(ISD::USUBO, VT, Custom); 1071 setOperationAction(ISD::SMULO, VT, Custom); 1072 setOperationAction(ISD::UMULO, VT, Custom); 1073 } 1074 1075 // There are no 8-bit 3-address imul/mul instructions 1076 setOperationAction(ISD::SMULO, MVT::i8, Expand); 1077 setOperationAction(ISD::UMULO, MVT::i8, Expand); 1078 1079 if (!Subtarget->is64Bit()) { 1080 // These libcalls are not available in 32-bit. 1081 setLibcallName(RTLIB::SHL_I128, 0); 1082 setLibcallName(RTLIB::SRL_I128, 0); 1083 setLibcallName(RTLIB::SRA_I128, 0); 1084 } 1085 1086 // We have target-specific dag combine patterns for the following nodes: 1087 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1088 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 1089 setTargetDAGCombine(ISD::BUILD_VECTOR); 1090 setTargetDAGCombine(ISD::SELECT); 1091 setTargetDAGCombine(ISD::SHL); 1092 setTargetDAGCombine(ISD::SRA); 1093 setTargetDAGCombine(ISD::SRL); 1094 setTargetDAGCombine(ISD::OR); 1095 setTargetDAGCombine(ISD::AND); 1096 setTargetDAGCombine(ISD::ADD); 1097 setTargetDAGCombine(ISD::SUB); 1098 setTargetDAGCombine(ISD::STORE); 1099 setTargetDAGCombine(ISD::ZERO_EXTEND); 1100 setTargetDAGCombine(ISD::SINT_TO_FP); 1101 if (Subtarget->is64Bit()) 1102 setTargetDAGCombine(ISD::MUL); 1103 1104 computeRegisterProperties(); 1105 1106 // On Darwin, -Os means optimize for size without hurting performance, 1107 // do not reduce the limit. 1108 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores 1109 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8; 1110 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores 1111 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1112 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores 1113 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1114 setPrefLoopAlignment(16); 1115 benefitFromCodePlacementOpt = true; 1116 1117 setPrefFunctionAlignment(4); 1118} 1119 1120 1121MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const { 1122 return MVT::i8; 1123} 1124 1125 1126/// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1127/// the desired ByVal argument alignment. 1128static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) { 1129 if (MaxAlign == 16) 1130 return; 1131 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1132 if (VTy->getBitWidth() == 128) 1133 MaxAlign = 16; 1134 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1135 unsigned EltAlign = 0; 1136 getMaxByValAlign(ATy->getElementType(), EltAlign); 1137 if (EltAlign > MaxAlign) 1138 MaxAlign = EltAlign; 1139 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) { 1140 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1141 unsigned EltAlign = 0; 1142 getMaxByValAlign(STy->getElementType(i), EltAlign); 1143 if (EltAlign > MaxAlign) 1144 MaxAlign = EltAlign; 1145 if (MaxAlign == 16) 1146 break; 1147 } 1148 } 1149 return; 1150} 1151 1152/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1153/// function arguments in the caller parameter area. For X86, aggregates 1154/// that contain SSE vectors are placed at 16-byte boundaries while the rest 1155/// are at 4-byte boundaries. 1156unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const { 1157 if (Subtarget->is64Bit()) { 1158 // Max of 8 and alignment of type. 1159 unsigned TyAlign = TD->getABITypeAlignment(Ty); 1160 if (TyAlign > 8) 1161 return TyAlign; 1162 return 8; 1163 } 1164 1165 unsigned Align = 4; 1166 if (Subtarget->hasXMM()) 1167 getMaxByValAlign(Ty, Align); 1168 return Align; 1169} 1170 1171/// getOptimalMemOpType - Returns the target specific optimal type for load 1172/// and store operations as a result of memset, memcpy, and memmove 1173/// lowering. If DstAlign is zero that means it's safe to destination 1174/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 1175/// means there isn't a need to check it against alignment requirement, 1176/// probably because the source does not need to be loaded. If 1177/// 'NonScalarIntSafe' is true, that means it's safe to return a 1178/// non-scalar-integer type, e.g. empty string source, constant, or loaded 1179/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is 1180/// constant so it does not need to be loaded. 1181/// It returns EVT::Other if the type should be determined using generic 1182/// target-independent logic. 1183EVT 1184X86TargetLowering::getOptimalMemOpType(uint64_t Size, 1185 unsigned DstAlign, unsigned SrcAlign, 1186 bool NonScalarIntSafe, 1187 bool MemcpyStrSrc, 1188 MachineFunction &MF) const { 1189 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like 1190 // linux. This is because the stack realignment code can't handle certain 1191 // cases like PR2962. This should be removed when PR2962 is fixed. 1192 const Function *F = MF.getFunction(); 1193 if (NonScalarIntSafe && 1194 !F->hasFnAttr(Attribute::NoImplicitFloat)) { 1195 if (Size >= 16 && 1196 (Subtarget->isUnalignedMemAccessFast() || 1197 ((DstAlign == 0 || DstAlign >= 16) && 1198 (SrcAlign == 0 || SrcAlign >= 16))) && 1199 Subtarget->getStackAlignment() >= 16) { 1200 if (Subtarget->hasSSE2()) 1201 return MVT::v4i32; 1202 if (Subtarget->hasSSE1()) 1203 return MVT::v4f32; 1204 } else if (!MemcpyStrSrc && Size >= 8 && 1205 !Subtarget->is64Bit() && 1206 Subtarget->getStackAlignment() >= 8 && 1207 Subtarget->hasXMMInt()) { 1208 // Do not use f64 to lower memcpy if source is string constant. It's 1209 // better to use i32 to avoid the loads. 1210 return MVT::f64; 1211 } 1212 } 1213 if (Subtarget->is64Bit() && Size >= 8) 1214 return MVT::i64; 1215 return MVT::i32; 1216} 1217 1218/// getJumpTableEncoding - Return the entry encoding for a jump table in the 1219/// current function. The returned value is a member of the 1220/// MachineJumpTableInfo::JTEntryKind enum. 1221unsigned X86TargetLowering::getJumpTableEncoding() const { 1222 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF 1223 // symbol. 1224 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1225 Subtarget->isPICStyleGOT()) 1226 return MachineJumpTableInfo::EK_Custom32; 1227 1228 // Otherwise, use the normal jump table encoding heuristics. 1229 return TargetLowering::getJumpTableEncoding(); 1230} 1231 1232const MCExpr * 1233X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, 1234 const MachineBasicBlock *MBB, 1235 unsigned uid,MCContext &Ctx) const{ 1236 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1237 Subtarget->isPICStyleGOT()); 1238 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF 1239 // entries. 1240 return MCSymbolRefExpr::Create(MBB->getSymbol(), 1241 MCSymbolRefExpr::VK_GOTOFF, Ctx); 1242} 1243 1244/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC 1245/// jumptable. 1246SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table, 1247 SelectionDAG &DAG) const { 1248 if (!Subtarget->is64Bit()) 1249 // This doesn't have DebugLoc associated with it, but is not really the 1250 // same as a Register. 1251 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy()); 1252 return Table; 1253} 1254 1255/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the 1256/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an 1257/// MCExpr. 1258const MCExpr *X86TargetLowering:: 1259getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, 1260 MCContext &Ctx) const { 1261 // X86-64 uses RIP relative addressing based on the jump table label. 1262 if (Subtarget->isPICStyleRIPRel()) 1263 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 1264 1265 // Otherwise, the reference is relative to the PIC base. 1266 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx); 1267} 1268 1269// FIXME: Why this routine is here? Move to RegInfo! 1270std::pair<const TargetRegisterClass*, uint8_t> 1271X86TargetLowering::findRepresentativeClass(EVT VT) const{ 1272 const TargetRegisterClass *RRC = 0; 1273 uint8_t Cost = 1; 1274 switch (VT.getSimpleVT().SimpleTy) { 1275 default: 1276 return TargetLowering::findRepresentativeClass(VT); 1277 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64: 1278 RRC = (Subtarget->is64Bit() 1279 ? X86::GR64RegisterClass : X86::GR32RegisterClass); 1280 break; 1281 case MVT::x86mmx: 1282 RRC = X86::VR64RegisterClass; 1283 break; 1284 case MVT::f32: case MVT::f64: 1285 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1286 case MVT::v4f32: case MVT::v2f64: 1287 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32: 1288 case MVT::v4f64: 1289 RRC = X86::VR128RegisterClass; 1290 break; 1291 } 1292 return std::make_pair(RRC, Cost); 1293} 1294 1295bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace, 1296 unsigned &Offset) const { 1297 if (!Subtarget->isTargetLinux()) 1298 return false; 1299 1300 if (Subtarget->is64Bit()) { 1301 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs: 1302 Offset = 0x28; 1303 if (getTargetMachine().getCodeModel() == CodeModel::Kernel) 1304 AddressSpace = 256; 1305 else 1306 AddressSpace = 257; 1307 } else { 1308 // %gs:0x14 on i386 1309 Offset = 0x14; 1310 AddressSpace = 256; 1311 } 1312 return true; 1313} 1314 1315 1316//===----------------------------------------------------------------------===// 1317// Return Value Calling Convention Implementation 1318//===----------------------------------------------------------------------===// 1319 1320#include "X86GenCallingConv.inc" 1321 1322bool 1323X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, 1324 MachineFunction &MF, bool isVarArg, 1325 const SmallVectorImpl<ISD::OutputArg> &Outs, 1326 LLVMContext &Context) const { 1327 SmallVector<CCValAssign, 16> RVLocs; 1328 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1329 RVLocs, Context); 1330 return CCInfo.CheckReturn(Outs, RetCC_X86); 1331} 1332 1333SDValue 1334X86TargetLowering::LowerReturn(SDValue Chain, 1335 CallingConv::ID CallConv, bool isVarArg, 1336 const SmallVectorImpl<ISD::OutputArg> &Outs, 1337 const SmallVectorImpl<SDValue> &OutVals, 1338 DebugLoc dl, SelectionDAG &DAG) const { 1339 MachineFunction &MF = DAG.getMachineFunction(); 1340 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1341 1342 SmallVector<CCValAssign, 16> RVLocs; 1343 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1344 RVLocs, *DAG.getContext()); 1345 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 1346 1347 // Add the regs to the liveout set for the function. 1348 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1349 for (unsigned i = 0; i != RVLocs.size(); ++i) 1350 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg())) 1351 MRI.addLiveOut(RVLocs[i].getLocReg()); 1352 1353 SDValue Flag; 1354 1355 SmallVector<SDValue, 6> RetOps; 1356 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1357 // Operand #1 = Bytes To Pop 1358 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), 1359 MVT::i16)); 1360 1361 // Copy the result values into the output registers. 1362 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1363 CCValAssign &VA = RVLocs[i]; 1364 assert(VA.isRegLoc() && "Can only return in registers!"); 1365 SDValue ValToCopy = OutVals[i]; 1366 EVT ValVT = ValToCopy.getValueType(); 1367 1368 // If this is x86-64, and we disabled SSE, we can't return FP values, 1369 // or SSE or MMX vectors. 1370 if ((ValVT == MVT::f32 || ValVT == MVT::f64 || 1371 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) && 1372 (Subtarget->is64Bit() && !Subtarget->hasXMM())) { 1373 report_fatal_error("SSE register return with SSE disabled"); 1374 } 1375 // Likewise we can't return F64 values with SSE1 only. gcc does so, but 1376 // llvm-gcc has never done it right and no one has noticed, so this 1377 // should be OK for now. 1378 if (ValVT == MVT::f64 && 1379 (Subtarget->is64Bit() && !Subtarget->hasXMMInt())) 1380 report_fatal_error("SSE2 register return with SSE2 disabled"); 1381 1382 // Returns in ST0/ST1 are handled specially: these are pushed as operands to 1383 // the RET instruction and handled by the FP Stackifier. 1384 if (VA.getLocReg() == X86::ST0 || 1385 VA.getLocReg() == X86::ST1) { 1386 // If this is a copy from an xmm register to ST(0), use an FPExtend to 1387 // change the value to the FP stack register class. 1388 if (isScalarFPTypeInSSEReg(VA.getValVT())) 1389 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy); 1390 RetOps.push_back(ValToCopy); 1391 // Don't emit a copytoreg. 1392 continue; 1393 } 1394 1395 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64 1396 // which is returned in RAX / RDX. 1397 if (Subtarget->is64Bit()) { 1398 if (ValVT == MVT::x86mmx) { 1399 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) { 1400 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy); 1401 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 1402 ValToCopy); 1403 // If we don't have SSE2 available, convert to v4f32 so the generated 1404 // register is legal. 1405 if (!Subtarget->hasSSE2()) 1406 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy); 1407 } 1408 } 1409 } 1410 1411 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag); 1412 Flag = Chain.getValue(1); 1413 } 1414 1415 // The x86-64 ABI for returning structs by value requires that we copy 1416 // the sret argument into %rax for the return. We saved the argument into 1417 // a virtual register in the entry block, so now we copy the value out 1418 // and into %rax. 1419 if (Subtarget->is64Bit() && 1420 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) { 1421 MachineFunction &MF = DAG.getMachineFunction(); 1422 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1423 unsigned Reg = FuncInfo->getSRetReturnReg(); 1424 assert(Reg && 1425 "SRetReturnReg should have been set in LowerFormalArguments()."); 1426 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy()); 1427 1428 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag); 1429 Flag = Chain.getValue(1); 1430 1431 // RAX now acts like a return value. 1432 MRI.addLiveOut(X86::RAX); 1433 } 1434 1435 RetOps[0] = Chain; // Update chain. 1436 1437 // Add the flag if we have it. 1438 if (Flag.getNode()) 1439 RetOps.push_back(Flag); 1440 1441 return DAG.getNode(X86ISD::RET_FLAG, dl, 1442 MVT::Other, &RetOps[0], RetOps.size()); 1443} 1444 1445bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const { 1446 if (N->getNumValues() != 1) 1447 return false; 1448 if (!N->hasNUsesOfValue(1, 0)) 1449 return false; 1450 1451 SDNode *Copy = *N->use_begin(); 1452 if (Copy->getOpcode() != ISD::CopyToReg && 1453 Copy->getOpcode() != ISD::FP_EXTEND) 1454 return false; 1455 1456 bool HasRet = false; 1457 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 1458 UI != UE; ++UI) { 1459 if (UI->getOpcode() != X86ISD::RET_FLAG) 1460 return false; 1461 HasRet = true; 1462 } 1463 1464 return HasRet; 1465} 1466 1467EVT 1468X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT, 1469 ISD::NodeType ExtendKind) const { 1470 MVT ReturnMVT; 1471 // TODO: Is this also valid on 32-bit? 1472 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND) 1473 ReturnMVT = MVT::i8; 1474 else 1475 ReturnMVT = MVT::i32; 1476 1477 EVT MinVT = getRegisterType(Context, ReturnMVT); 1478 return VT.bitsLT(MinVT) ? MinVT : VT; 1479} 1480 1481/// LowerCallResult - Lower the result values of a call into the 1482/// appropriate copies out of appropriate physical registers. 1483/// 1484SDValue 1485X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1486 CallingConv::ID CallConv, bool isVarArg, 1487 const SmallVectorImpl<ISD::InputArg> &Ins, 1488 DebugLoc dl, SelectionDAG &DAG, 1489 SmallVectorImpl<SDValue> &InVals) const { 1490 1491 // Assign locations to each value returned by this call. 1492 SmallVector<CCValAssign, 16> RVLocs; 1493 bool Is64Bit = Subtarget->is64Bit(); 1494 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 1495 getTargetMachine(), RVLocs, *DAG.getContext()); 1496 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 1497 1498 // Copy all of the result registers out of their specified physreg. 1499 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1500 CCValAssign &VA = RVLocs[i]; 1501 EVT CopyVT = VA.getValVT(); 1502 1503 // If this is x86-64, and we disabled SSE, we can't return FP values 1504 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 1505 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) { 1506 report_fatal_error("SSE register return with SSE disabled"); 1507 } 1508 1509 SDValue Val; 1510 1511 // If this is a call to a function that returns an fp value on the floating 1512 // point stack, we must guarantee the the value is popped from the stack, so 1513 // a CopyFromReg is not good enough - the copy instruction may be eliminated 1514 // if the return value is not used. We use the FpGET_ST0 instructions 1515 // instead. 1516 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) { 1517 // If we prefer to use the value in xmm registers, copy it out as f80 and 1518 // use a truncate to move it from fp stack reg to xmm reg. 1519 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80; 1520 bool isST0 = VA.getLocReg() == X86::ST0; 1521 unsigned Opc = 0; 1522 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32; 1523 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64; 1524 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80; 1525 SDValue Ops[] = { Chain, InFlag }; 1526 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue, 1527 Ops, 2), 1); 1528 Val = Chain.getValue(0); 1529 1530 // Round the f80 to the right size, which also moves it to the appropriate 1531 // xmm register. 1532 if (CopyVT != VA.getValVT()) 1533 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val, 1534 // This truncation won't change the value. 1535 DAG.getIntPtrConstant(1)); 1536 } else { 1537 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1538 CopyVT, InFlag).getValue(1); 1539 Val = Chain.getValue(0); 1540 } 1541 InFlag = Chain.getValue(2); 1542 InVals.push_back(Val); 1543 } 1544 1545 return Chain; 1546} 1547 1548 1549//===----------------------------------------------------------------------===// 1550// C & StdCall & Fast Calling Convention implementation 1551//===----------------------------------------------------------------------===// 1552// StdCall calling convention seems to be standard for many Windows' API 1553// routines and around. It differs from C calling convention just a little: 1554// callee should clean up the stack, not caller. Symbols should be also 1555// decorated in some fancy way :) It doesn't support any vector arguments. 1556// For info on fast calling convention see Fast Calling Convention (tail call) 1557// implementation LowerX86_32FastCCCallTo. 1558 1559/// CallIsStructReturn - Determines whether a call uses struct return 1560/// semantics. 1561static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) { 1562 if (Outs.empty()) 1563 return false; 1564 1565 return Outs[0].Flags.isSRet(); 1566} 1567 1568/// ArgsAreStructReturn - Determines whether a function uses struct 1569/// return semantics. 1570static bool 1571ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) { 1572 if (Ins.empty()) 1573 return false; 1574 1575 return Ins[0].Flags.isSRet(); 1576} 1577 1578/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 1579/// by "Src" to address "Dst" with size and alignment information specified by 1580/// the specific parameter attribute. The copy will be passed as a byval 1581/// function parameter. 1582static SDValue 1583CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 1584 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 1585 DebugLoc dl) { 1586 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 1587 1588 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 1589 /*isVolatile*/false, /*AlwaysInline=*/true, 1590 MachinePointerInfo(), MachinePointerInfo()); 1591} 1592 1593/// IsTailCallConvention - Return true if the calling convention is one that 1594/// supports tail call optimization. 1595static bool IsTailCallConvention(CallingConv::ID CC) { 1596 return (CC == CallingConv::Fast || CC == CallingConv::GHC); 1597} 1598 1599bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 1600 if (!CI->isTailCall()) 1601 return false; 1602 1603 CallSite CS(CI); 1604 CallingConv::ID CalleeCC = CS.getCallingConv(); 1605 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C) 1606 return false; 1607 1608 return true; 1609} 1610 1611/// FuncIsMadeTailCallSafe - Return true if the function is being made into 1612/// a tailcall target by changing its ABI. 1613static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) { 1614 return GuaranteedTailCallOpt && IsTailCallConvention(CC); 1615} 1616 1617SDValue 1618X86TargetLowering::LowerMemArgument(SDValue Chain, 1619 CallingConv::ID CallConv, 1620 const SmallVectorImpl<ISD::InputArg> &Ins, 1621 DebugLoc dl, SelectionDAG &DAG, 1622 const CCValAssign &VA, 1623 MachineFrameInfo *MFI, 1624 unsigned i) const { 1625 // Create the nodes corresponding to a load from this parameter slot. 1626 ISD::ArgFlagsTy Flags = Ins[i].Flags; 1627 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv); 1628 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal(); 1629 EVT ValVT; 1630 1631 // If value is passed by pointer we have address passed instead of the value 1632 // itself. 1633 if (VA.getLocInfo() == CCValAssign::Indirect) 1634 ValVT = VA.getLocVT(); 1635 else 1636 ValVT = VA.getValVT(); 1637 1638 // FIXME: For now, all byval parameter objects are marked mutable. This can be 1639 // changed with more analysis. 1640 // In case of tail call optimization mark all arguments mutable. Since they 1641 // could be overwritten by lowering of arguments in case of a tail call. 1642 if (Flags.isByVal()) { 1643 unsigned Bytes = Flags.getByValSize(); 1644 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects. 1645 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable); 1646 return DAG.getFrameIndex(FI, getPointerTy()); 1647 } else { 1648 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8, 1649 VA.getLocMemOffset(), isImmutable); 1650 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 1651 return DAG.getLoad(ValVT, dl, Chain, FIN, 1652 MachinePointerInfo::getFixedStack(FI), 1653 false, false, 0); 1654 } 1655} 1656 1657SDValue 1658X86TargetLowering::LowerFormalArguments(SDValue Chain, 1659 CallingConv::ID CallConv, 1660 bool isVarArg, 1661 const SmallVectorImpl<ISD::InputArg> &Ins, 1662 DebugLoc dl, 1663 SelectionDAG &DAG, 1664 SmallVectorImpl<SDValue> &InVals) 1665 const { 1666 MachineFunction &MF = DAG.getMachineFunction(); 1667 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1668 1669 const Function* Fn = MF.getFunction(); 1670 if (Fn->hasExternalLinkage() && 1671 Subtarget->isTargetCygMing() && 1672 Fn->getName() == "main") 1673 FuncInfo->setForceFramePointer(true); 1674 1675 MachineFrameInfo *MFI = MF.getFrameInfo(); 1676 bool Is64Bit = Subtarget->is64Bit(); 1677 bool IsWin64 = Subtarget->isTargetWin64(); 1678 1679 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 1680 "Var args not supported with calling convention fastcc or ghc"); 1681 1682 // Assign locations to all of the incoming arguments. 1683 SmallVector<CCValAssign, 16> ArgLocs; 1684 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1685 ArgLocs, *DAG.getContext()); 1686 1687 // Allocate shadow area for Win64 1688 if (IsWin64) { 1689 CCInfo.AllocateStack(32, 8); 1690 } 1691 1692 CCInfo.AnalyzeFormalArguments(Ins, CC_X86); 1693 1694 unsigned LastVal = ~0U; 1695 SDValue ArgValue; 1696 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 1697 CCValAssign &VA = ArgLocs[i]; 1698 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later 1699 // places. 1700 assert(VA.getValNo() != LastVal && 1701 "Don't support value assigned to multiple locs yet"); 1702 LastVal = VA.getValNo(); 1703 1704 if (VA.isRegLoc()) { 1705 EVT RegVT = VA.getLocVT(); 1706 TargetRegisterClass *RC = NULL; 1707 if (RegVT == MVT::i32) 1708 RC = X86::GR32RegisterClass; 1709 else if (Is64Bit && RegVT == MVT::i64) 1710 RC = X86::GR64RegisterClass; 1711 else if (RegVT == MVT::f32) 1712 RC = X86::FR32RegisterClass; 1713 else if (RegVT == MVT::f64) 1714 RC = X86::FR64RegisterClass; 1715 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256) 1716 RC = X86::VR256RegisterClass; 1717 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128) 1718 RC = X86::VR128RegisterClass; 1719 else if (RegVT == MVT::x86mmx) 1720 RC = X86::VR64RegisterClass; 1721 else 1722 llvm_unreachable("Unknown argument type!"); 1723 1724 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 1725 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 1726 1727 // If this is an 8 or 16-bit value, it is really passed promoted to 32 1728 // bits. Insert an assert[sz]ext to capture this, then truncate to the 1729 // right size. 1730 if (VA.getLocInfo() == CCValAssign::SExt) 1731 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 1732 DAG.getValueType(VA.getValVT())); 1733 else if (VA.getLocInfo() == CCValAssign::ZExt) 1734 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 1735 DAG.getValueType(VA.getValVT())); 1736 else if (VA.getLocInfo() == CCValAssign::BCvt) 1737 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 1738 1739 if (VA.isExtInLoc()) { 1740 // Handle MMX values passed in XMM regs. 1741 if (RegVT.isVector()) { 1742 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), 1743 ArgValue); 1744 } else 1745 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 1746 } 1747 } else { 1748 assert(VA.isMemLoc()); 1749 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i); 1750 } 1751 1752 // If value is passed via pointer - do a load. 1753 if (VA.getLocInfo() == CCValAssign::Indirect) 1754 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, 1755 MachinePointerInfo(), false, false, 0); 1756 1757 InVals.push_back(ArgValue); 1758 } 1759 1760 // The x86-64 ABI for returning structs by value requires that we copy 1761 // the sret argument into %rax for the return. Save the argument into 1762 // a virtual register so that we can access it from the return points. 1763 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) { 1764 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1765 unsigned Reg = FuncInfo->getSRetReturnReg(); 1766 if (!Reg) { 1767 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64)); 1768 FuncInfo->setSRetReturnReg(Reg); 1769 } 1770 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]); 1771 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain); 1772 } 1773 1774 unsigned StackSize = CCInfo.getNextStackOffset(); 1775 // Align stack specially for tail calls. 1776 if (FuncIsMadeTailCallSafe(CallConv)) 1777 StackSize = GetAlignedArgumentStackSize(StackSize, DAG); 1778 1779 // If the function takes variable number of arguments, make a frame index for 1780 // the start of the first vararg value... for expansion of llvm.va_start. 1781 if (isVarArg) { 1782 if (Is64Bit || (CallConv != CallingConv::X86_FastCall && 1783 CallConv != CallingConv::X86_ThisCall)) { 1784 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true)); 1785 } 1786 if (Is64Bit) { 1787 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0; 1788 1789 // FIXME: We should really autogenerate these arrays 1790 static const unsigned GPR64ArgRegsWin64[] = { 1791 X86::RCX, X86::RDX, X86::R8, X86::R9 1792 }; 1793 static const unsigned GPR64ArgRegs64Bit[] = { 1794 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9 1795 }; 1796 static const unsigned XMMArgRegs64Bit[] = { 1797 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 1798 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 1799 }; 1800 const unsigned *GPR64ArgRegs; 1801 unsigned NumXMMRegs = 0; 1802 1803 if (IsWin64) { 1804 // The XMM registers which might contain var arg parameters are shadowed 1805 // in their paired GPR. So we only need to save the GPR to their home 1806 // slots. 1807 TotalNumIntRegs = 4; 1808 GPR64ArgRegs = GPR64ArgRegsWin64; 1809 } else { 1810 TotalNumIntRegs = 6; TotalNumXMMRegs = 8; 1811 GPR64ArgRegs = GPR64ArgRegs64Bit; 1812 1813 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs); 1814 } 1815 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 1816 TotalNumIntRegs); 1817 1818 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat); 1819 assert(!(NumXMMRegs && !Subtarget->hasXMM()) && 1820 "SSE register cannot be used when SSE is disabled!"); 1821 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) && 1822 "SSE register cannot be used when SSE is disabled!"); 1823 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM()) 1824 // Kernel mode asks for SSE to be disabled, so don't push them 1825 // on the stack. 1826 TotalNumXMMRegs = 0; 1827 1828 if (IsWin64) { 1829 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering(); 1830 // Get to the caller-allocated home save location. Add 8 to account 1831 // for the return address. 1832 int HomeOffset = TFI.getOffsetOfLocalArea() + 8; 1833 FuncInfo->setRegSaveFrameIndex( 1834 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false)); 1835 // Fixup to set vararg frame on shadow area (4 x i64). 1836 if (NumIntRegs < 4) 1837 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex()); 1838 } else { 1839 // For X86-64, if there are vararg parameters that are passed via 1840 // registers, then we must store them to their spots on the stack so they 1841 // may be loaded by deferencing the result of va_next. 1842 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8); 1843 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16); 1844 FuncInfo->setRegSaveFrameIndex( 1845 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16, 1846 false)); 1847 } 1848 1849 // Store the integer parameter registers. 1850 SmallVector<SDValue, 8> MemOps; 1851 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 1852 getPointerTy()); 1853 unsigned Offset = FuncInfo->getVarArgsGPOffset(); 1854 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) { 1855 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN, 1856 DAG.getIntPtrConstant(Offset)); 1857 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs], 1858 X86::GR64RegisterClass); 1859 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 1860 SDValue Store = 1861 DAG.getStore(Val.getValue(1), dl, Val, FIN, 1862 MachinePointerInfo::getFixedStack( 1863 FuncInfo->getRegSaveFrameIndex(), Offset), 1864 false, false, 0); 1865 MemOps.push_back(Store); 1866 Offset += 8; 1867 } 1868 1869 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) { 1870 // Now store the XMM (fp + vector) parameter registers. 1871 SmallVector<SDValue, 11> SaveXMMOps; 1872 SaveXMMOps.push_back(Chain); 1873 1874 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass); 1875 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8); 1876 SaveXMMOps.push_back(ALVal); 1877 1878 SaveXMMOps.push_back(DAG.getIntPtrConstant( 1879 FuncInfo->getRegSaveFrameIndex())); 1880 SaveXMMOps.push_back(DAG.getIntPtrConstant( 1881 FuncInfo->getVarArgsFPOffset())); 1882 1883 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) { 1884 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs], 1885 X86::VR128RegisterClass); 1886 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32); 1887 SaveXMMOps.push_back(Val); 1888 } 1889 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl, 1890 MVT::Other, 1891 &SaveXMMOps[0], SaveXMMOps.size())); 1892 } 1893 1894 if (!MemOps.empty()) 1895 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 1896 &MemOps[0], MemOps.size()); 1897 } 1898 } 1899 1900 // Some CCs need callee pop. 1901 if (Subtarget->IsCalleePop(isVarArg, CallConv)) { 1902 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything. 1903 } else { 1904 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing. 1905 // If this is an sret function, the return should pop the hidden pointer. 1906 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins)) 1907 FuncInfo->setBytesToPopOnReturn(4); 1908 } 1909 1910 if (!Is64Bit) { 1911 // RegSaveFrameIndex is X86-64 only. 1912 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA); 1913 if (CallConv == CallingConv::X86_FastCall || 1914 CallConv == CallingConv::X86_ThisCall) 1915 // fastcc functions can't have varargs. 1916 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA); 1917 } 1918 1919 return Chain; 1920} 1921 1922SDValue 1923X86TargetLowering::LowerMemOpCallTo(SDValue Chain, 1924 SDValue StackPtr, SDValue Arg, 1925 DebugLoc dl, SelectionDAG &DAG, 1926 const CCValAssign &VA, 1927 ISD::ArgFlagsTy Flags) const { 1928 unsigned LocMemOffset = VA.getLocMemOffset(); 1929 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 1930 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 1931 if (Flags.isByVal()) 1932 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl); 1933 1934 return DAG.getStore(Chain, dl, Arg, PtrOff, 1935 MachinePointerInfo::getStack(LocMemOffset), 1936 false, false, 0); 1937} 1938 1939/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call 1940/// optimization is performed and it is required. 1941SDValue 1942X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 1943 SDValue &OutRetAddr, SDValue Chain, 1944 bool IsTailCall, bool Is64Bit, 1945 int FPDiff, DebugLoc dl) const { 1946 // Adjust the Return address stack slot. 1947 EVT VT = getPointerTy(); 1948 OutRetAddr = getReturnAddressFrameIndex(DAG); 1949 1950 // Load the "old" Return address. 1951 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(), 1952 false, false, 0); 1953 return SDValue(OutRetAddr.getNode(), 1); 1954} 1955 1956/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call 1957/// optimization is performed and it is required (FPDiff!=0). 1958static SDValue 1959EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 1960 SDValue Chain, SDValue RetAddrFrIdx, 1961 bool Is64Bit, int FPDiff, DebugLoc dl) { 1962 // Store the return address to the appropriate stack slot. 1963 if (!FPDiff) return Chain; 1964 // Calculate the new stack slot for the return address. 1965 int SlotSize = Is64Bit ? 8 : 4; 1966 int NewReturnAddrFI = 1967 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false); 1968 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 1969 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT); 1970 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx, 1971 MachinePointerInfo::getFixedStack(NewReturnAddrFI), 1972 false, false, 0); 1973 return Chain; 1974} 1975 1976SDValue 1977X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee, 1978 CallingConv::ID CallConv, bool isVarArg, 1979 bool &isTailCall, 1980 const SmallVectorImpl<ISD::OutputArg> &Outs, 1981 const SmallVectorImpl<SDValue> &OutVals, 1982 const SmallVectorImpl<ISD::InputArg> &Ins, 1983 DebugLoc dl, SelectionDAG &DAG, 1984 SmallVectorImpl<SDValue> &InVals) const { 1985 MachineFunction &MF = DAG.getMachineFunction(); 1986 bool Is64Bit = Subtarget->is64Bit(); 1987 bool IsWin64 = Subtarget->isTargetWin64(); 1988 bool IsStructRet = CallIsStructReturn(Outs); 1989 bool IsSibcall = false; 1990 1991 if (isTailCall) { 1992 // Check if it's really possible to do a tail call. 1993 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1994 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(), 1995 Outs, OutVals, Ins, DAG); 1996 1997 // Sibcalls are automatically detected tailcalls which do not require 1998 // ABI changes. 1999 if (!GuaranteedTailCallOpt && isTailCall) 2000 IsSibcall = true; 2001 2002 if (isTailCall) 2003 ++NumTailCalls; 2004 } 2005 2006 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 2007 "Var args not supported with calling convention fastcc or ghc"); 2008 2009 // Analyze operands of the call, assigning locations to each operand. 2010 SmallVector<CCValAssign, 16> ArgLocs; 2011 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 2012 ArgLocs, *DAG.getContext()); 2013 2014 // Allocate shadow area for Win64 2015 if (IsWin64) { 2016 CCInfo.AllocateStack(32, 8); 2017 } 2018 2019 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2020 2021 // Get a count of how many bytes are to be pushed on the stack. 2022 unsigned NumBytes = CCInfo.getNextStackOffset(); 2023 if (IsSibcall) 2024 // This is a sibcall. The memory operands are available in caller's 2025 // own caller's stack. 2026 NumBytes = 0; 2027 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv)) 2028 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG); 2029 2030 int FPDiff = 0; 2031 if (isTailCall && !IsSibcall) { 2032 // Lower arguments at fp - stackoffset + fpdiff. 2033 unsigned NumBytesCallerPushed = 2034 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn(); 2035 FPDiff = NumBytesCallerPushed - NumBytes; 2036 2037 // Set the delta of movement of the returnaddr stackslot. 2038 // But only set if delta is greater than previous delta. 2039 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta())) 2040 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff); 2041 } 2042 2043 if (!IsSibcall) 2044 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true)); 2045 2046 SDValue RetAddrFrIdx; 2047 // Load return address for tail calls. 2048 if (isTailCall && FPDiff) 2049 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, 2050 Is64Bit, FPDiff, dl); 2051 2052 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2053 SmallVector<SDValue, 8> MemOpChains; 2054 SDValue StackPtr; 2055 2056 // Walk the register/memloc assignments, inserting copies/loads. In the case 2057 // of tail call optimization arguments are handle later. 2058 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2059 CCValAssign &VA = ArgLocs[i]; 2060 EVT RegVT = VA.getLocVT(); 2061 SDValue Arg = OutVals[i]; 2062 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2063 bool isByVal = Flags.isByVal(); 2064 2065 // Promote the value if needed. 2066 switch (VA.getLocInfo()) { 2067 default: llvm_unreachable("Unknown loc info!"); 2068 case CCValAssign::Full: break; 2069 case CCValAssign::SExt: 2070 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg); 2071 break; 2072 case CCValAssign::ZExt: 2073 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg); 2074 break; 2075 case CCValAssign::AExt: 2076 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) { 2077 // Special case: passing MMX values in XMM registers. 2078 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 2079 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg); 2080 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg); 2081 } else 2082 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg); 2083 break; 2084 case CCValAssign::BCvt: 2085 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg); 2086 break; 2087 case CCValAssign::Indirect: { 2088 // Store the argument. 2089 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT()); 2090 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 2091 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot, 2092 MachinePointerInfo::getFixedStack(FI), 2093 false, false, 0); 2094 Arg = SpillSlot; 2095 break; 2096 } 2097 } 2098 2099 if (VA.isRegLoc()) { 2100 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2101 if (isVarArg && IsWin64) { 2102 // Win64 ABI requires argument XMM reg to be copied to the corresponding 2103 // shadow reg if callee is a varargs function. 2104 unsigned ShadowReg = 0; 2105 switch (VA.getLocReg()) { 2106 case X86::XMM0: ShadowReg = X86::RCX; break; 2107 case X86::XMM1: ShadowReg = X86::RDX; break; 2108 case X86::XMM2: ShadowReg = X86::R8; break; 2109 case X86::XMM3: ShadowReg = X86::R9; break; 2110 } 2111 if (ShadowReg) 2112 RegsToPass.push_back(std::make_pair(ShadowReg, Arg)); 2113 } 2114 } else if (!IsSibcall && (!isTailCall || isByVal)) { 2115 assert(VA.isMemLoc()); 2116 if (StackPtr.getNode() == 0) 2117 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy()); 2118 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2119 dl, DAG, VA, Flags)); 2120 } 2121 } 2122 2123 if (!MemOpChains.empty()) 2124 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2125 &MemOpChains[0], MemOpChains.size()); 2126 2127 // Build a sequence of copy-to-reg nodes chained together with token chain 2128 // and flag operands which copy the outgoing args into registers. 2129 SDValue InFlag; 2130 // Tail call byval lowering might overwrite argument registers so in case of 2131 // tail call optimization the copies to registers are lowered later. 2132 if (!isTailCall) 2133 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2134 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2135 RegsToPass[i].second, InFlag); 2136 InFlag = Chain.getValue(1); 2137 } 2138 2139 if (Subtarget->isPICStyleGOT()) { 2140 // ELF / PIC requires GOT in the EBX register before function calls via PLT 2141 // GOT pointer. 2142 if (!isTailCall) { 2143 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX, 2144 DAG.getNode(X86ISD::GlobalBaseReg, 2145 DebugLoc(), getPointerTy()), 2146 InFlag); 2147 InFlag = Chain.getValue(1); 2148 } else { 2149 // If we are tail calling and generating PIC/GOT style code load the 2150 // address of the callee into ECX. The value in ecx is used as target of 2151 // the tail jump. This is done to circumvent the ebx/callee-saved problem 2152 // for tail calls on PIC/GOT architectures. Normally we would just put the 2153 // address of GOT into ebx and then call target@PLT. But for tail calls 2154 // ebx would be restored (since ebx is callee saved) before jumping to the 2155 // target@PLT. 2156 2157 // Note: The actual moving to ECX is done further down. 2158 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 2159 if (G && !G->getGlobal()->hasHiddenVisibility() && 2160 !G->getGlobal()->hasProtectedVisibility()) 2161 Callee = LowerGlobalAddress(Callee, DAG); 2162 else if (isa<ExternalSymbolSDNode>(Callee)) 2163 Callee = LowerExternalSymbol(Callee, DAG); 2164 } 2165 } 2166 2167 if (Is64Bit && isVarArg && !IsWin64) { 2168 // From AMD64 ABI document: 2169 // For calls that may call functions that use varargs or stdargs 2170 // (prototype-less calls or calls to functions containing ellipsis (...) in 2171 // the declaration) %al is used as hidden argument to specify the number 2172 // of SSE registers used. The contents of %al do not need to match exactly 2173 // the number of registers, but must be an ubound on the number of SSE 2174 // registers used and is in the range 0 - 8 inclusive. 2175 2176 // Count the number of XMM registers allocated. 2177 static const unsigned XMMArgRegs[] = { 2178 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2179 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2180 }; 2181 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8); 2182 assert((Subtarget->hasXMM() || !NumXMMRegs) 2183 && "SSE registers cannot be used when SSE is disabled"); 2184 2185 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, 2186 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag); 2187 InFlag = Chain.getValue(1); 2188 } 2189 2190 2191 // For tail calls lower the arguments to the 'real' stack slot. 2192 if (isTailCall) { 2193 // Force all the incoming stack arguments to be loaded from the stack 2194 // before any new outgoing arguments are stored to the stack, because the 2195 // outgoing stack slots may alias the incoming argument stack slots, and 2196 // the alias isn't otherwise explicit. This is slightly more conservative 2197 // than necessary, because it means that each store effectively depends 2198 // on every argument instead of just those arguments it would clobber. 2199 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain); 2200 2201 SmallVector<SDValue, 8> MemOpChains2; 2202 SDValue FIN; 2203 int FI = 0; 2204 // Do not flag preceding copytoreg stuff together with the following stuff. 2205 InFlag = SDValue(); 2206 if (GuaranteedTailCallOpt) { 2207 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2208 CCValAssign &VA = ArgLocs[i]; 2209 if (VA.isRegLoc()) 2210 continue; 2211 assert(VA.isMemLoc()); 2212 SDValue Arg = OutVals[i]; 2213 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2214 // Create frame index. 2215 int32_t Offset = VA.getLocMemOffset()+FPDiff; 2216 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8; 2217 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 2218 FIN = DAG.getFrameIndex(FI, getPointerTy()); 2219 2220 if (Flags.isByVal()) { 2221 // Copy relative to framepointer. 2222 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset()); 2223 if (StackPtr.getNode() == 0) 2224 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, 2225 getPointerTy()); 2226 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source); 2227 2228 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, 2229 ArgChain, 2230 Flags, DAG, dl)); 2231 } else { 2232 // Store relative to framepointer. 2233 MemOpChains2.push_back( 2234 DAG.getStore(ArgChain, dl, Arg, FIN, 2235 MachinePointerInfo::getFixedStack(FI), 2236 false, false, 0)); 2237 } 2238 } 2239 } 2240 2241 if (!MemOpChains2.empty()) 2242 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2243 &MemOpChains2[0], MemOpChains2.size()); 2244 2245 // Copy arguments to their registers. 2246 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2247 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2248 RegsToPass[i].second, InFlag); 2249 InFlag = Chain.getValue(1); 2250 } 2251 InFlag =SDValue(); 2252 2253 // Store the return address to the appropriate stack slot. 2254 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit, 2255 FPDiff, dl); 2256 } 2257 2258 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 2259 assert(Is64Bit && "Large code model is only legal in 64-bit mode."); 2260 // In the 64-bit large code model, we have to make all calls 2261 // through a register, since the call instruction's 32-bit 2262 // pc-relative offset may not be large enough to hold the whole 2263 // address. 2264 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2265 // If the callee is a GlobalAddress node (quite common, every direct call 2266 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack 2267 // it. 2268 2269 // We should use extra load for direct calls to dllimported functions in 2270 // non-JIT mode. 2271 const GlobalValue *GV = G->getGlobal(); 2272 if (!GV->hasDLLImportLinkage()) { 2273 unsigned char OpFlags = 0; 2274 2275 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to 2276 // external symbols most go through the PLT in PIC mode. If the symbol 2277 // has hidden or protected visibility, or if it is static or local, then 2278 // we don't need to use the PLT - we can directly call it. 2279 if (Subtarget->isTargetELF() && 2280 getTargetMachine().getRelocationModel() == Reloc::PIC_ && 2281 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) { 2282 OpFlags = X86II::MO_PLT; 2283 } else if (Subtarget->isPICStyleStubAny() && 2284 (GV->isDeclaration() || GV->isWeakForLinker()) && 2285 (!Subtarget->getTargetTriple().isMacOSX() || 2286 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2287 // PC-relative references to external symbols should go through $stub, 2288 // unless we're building with the leopard linker or later, which 2289 // automatically synthesizes these stubs. 2290 OpFlags = X86II::MO_DARWIN_STUB; 2291 } 2292 2293 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 2294 G->getOffset(), OpFlags); 2295 } 2296 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2297 unsigned char OpFlags = 0; 2298 2299 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to 2300 // external symbols should go through the PLT. 2301 if (Subtarget->isTargetELF() && 2302 getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2303 OpFlags = X86II::MO_PLT; 2304 } else if (Subtarget->isPICStyleStubAny() && 2305 (!Subtarget->getTargetTriple().isMacOSX() || 2306 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2307 // PC-relative references to external symbols should go through $stub, 2308 // unless we're building with the leopard linker or later, which 2309 // automatically synthesizes these stubs. 2310 OpFlags = X86II::MO_DARWIN_STUB; 2311 } 2312 2313 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(), 2314 OpFlags); 2315 } 2316 2317 // Returns a chain & a flag for retval copy to use. 2318 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2319 SmallVector<SDValue, 8> Ops; 2320 2321 if (!IsSibcall && isTailCall) { 2322 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 2323 DAG.getIntPtrConstant(0, true), InFlag); 2324 InFlag = Chain.getValue(1); 2325 } 2326 2327 Ops.push_back(Chain); 2328 Ops.push_back(Callee); 2329 2330 if (isTailCall) 2331 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32)); 2332 2333 // Add argument registers to the end of the list so that they are known live 2334 // into the call. 2335 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2336 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2337 RegsToPass[i].second.getValueType())); 2338 2339 // Add an implicit use GOT pointer in EBX. 2340 if (!isTailCall && Subtarget->isPICStyleGOT()) 2341 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy())); 2342 2343 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions. 2344 if (Is64Bit && isVarArg && !IsWin64) 2345 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8)); 2346 2347 if (InFlag.getNode()) 2348 Ops.push_back(InFlag); 2349 2350 if (isTailCall) { 2351 // We used to do: 2352 //// If this is the first return lowered for this function, add the regs 2353 //// to the liveout set for the function. 2354 // This isn't right, although it's probably harmless on x86; liveouts 2355 // should be computed from returns not tail calls. Consider a void 2356 // function making a tail call to a function returning int. 2357 return DAG.getNode(X86ISD::TC_RETURN, dl, 2358 NodeTys, &Ops[0], Ops.size()); 2359 } 2360 2361 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size()); 2362 InFlag = Chain.getValue(1); 2363 2364 // Create the CALLSEQ_END node. 2365 unsigned NumBytesForCalleeToPush; 2366 if (Subtarget->IsCalleePop(isVarArg, CallConv)) 2367 NumBytesForCalleeToPush = NumBytes; // Callee pops everything 2368 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet) 2369 // If this is a call to a struct-return function, the callee 2370 // pops the hidden struct pointer, so we have to push it back. 2371 // This is common for Darwin/X86, Linux & Mingw32 targets. 2372 NumBytesForCalleeToPush = 4; 2373 else 2374 NumBytesForCalleeToPush = 0; // Callee pops nothing. 2375 2376 // Returns a flag for retval copy to use. 2377 if (!IsSibcall) { 2378 Chain = DAG.getCALLSEQ_END(Chain, 2379 DAG.getIntPtrConstant(NumBytes, true), 2380 DAG.getIntPtrConstant(NumBytesForCalleeToPush, 2381 true), 2382 InFlag); 2383 InFlag = Chain.getValue(1); 2384 } 2385 2386 // Handle result values, copying them out of physregs into vregs that we 2387 // return. 2388 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 2389 Ins, dl, DAG, InVals); 2390} 2391 2392 2393//===----------------------------------------------------------------------===// 2394// Fast Calling Convention (tail call) implementation 2395//===----------------------------------------------------------------------===// 2396 2397// Like std call, callee cleans arguments, convention except that ECX is 2398// reserved for storing the tail called function address. Only 2 registers are 2399// free for argument passing (inreg). Tail call optimization is performed 2400// provided: 2401// * tailcallopt is enabled 2402// * caller/callee are fastcc 2403// On X86_64 architecture with GOT-style position independent code only local 2404// (within module) calls are supported at the moment. 2405// To keep the stack aligned according to platform abi the function 2406// GetAlignedArgumentStackSize ensures that argument delta is always multiples 2407// of stack alignment. (Dynamic linkers need this - darwin's dyld for example) 2408// If a tail called function callee has more arguments than the caller the 2409// caller needs to make sure that there is room to move the RETADDR to. This is 2410// achieved by reserving an area the size of the argument delta right after the 2411// original REtADDR, but before the saved framepointer or the spilled registers 2412// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4) 2413// stack layout: 2414// arg1 2415// arg2 2416// RETADDR 2417// [ new RETADDR 2418// move area ] 2419// (possible EBP) 2420// ESI 2421// EDI 2422// local1 .. 2423 2424/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned 2425/// for a 16 byte align requirement. 2426unsigned 2427X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 2428 SelectionDAG& DAG) const { 2429 MachineFunction &MF = DAG.getMachineFunction(); 2430 const TargetMachine &TM = MF.getTarget(); 2431 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 2432 unsigned StackAlignment = TFI.getStackAlignment(); 2433 uint64_t AlignMask = StackAlignment - 1; 2434 int64_t Offset = StackSize; 2435 uint64_t SlotSize = TD->getPointerSize(); 2436 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) { 2437 // Number smaller than 12 so just add the difference. 2438 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask)); 2439 } else { 2440 // Mask out lower bits, add stackalignment once plus the 12 bytes. 2441 Offset = ((~AlignMask) & Offset) + StackAlignment + 2442 (StackAlignment-SlotSize); 2443 } 2444 return Offset; 2445} 2446 2447/// MatchingStackOffset - Return true if the given stack call argument is 2448/// already available in the same position (relatively) of the caller's 2449/// incoming argument stack. 2450static 2451bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2452 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2453 const X86InstrInfo *TII) { 2454 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2455 int FI = INT_MAX; 2456 if (Arg.getOpcode() == ISD::CopyFromReg) { 2457 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2458 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2459 return false; 2460 MachineInstr *Def = MRI->getVRegDef(VR); 2461 if (!Def) 2462 return false; 2463 if (!Flags.isByVal()) { 2464 if (!TII->isLoadFromStackSlot(Def, FI)) 2465 return false; 2466 } else { 2467 unsigned Opcode = Def->getOpcode(); 2468 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) && 2469 Def->getOperand(1).isFI()) { 2470 FI = Def->getOperand(1).getIndex(); 2471 Bytes = Flags.getByValSize(); 2472 } else 2473 return false; 2474 } 2475 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2476 if (Flags.isByVal()) 2477 // ByVal argument is passed in as a pointer but it's now being 2478 // dereferenced. e.g. 2479 // define @foo(%struct.X* %A) { 2480 // tail call @bar(%struct.X* byval %A) 2481 // } 2482 return false; 2483 SDValue Ptr = Ld->getBasePtr(); 2484 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2485 if (!FINode) 2486 return false; 2487 FI = FINode->getIndex(); 2488 } else 2489 return false; 2490 2491 assert(FI != INT_MAX); 2492 if (!MFI->isFixedObjectIndex(FI)) 2493 return false; 2494 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2495} 2496 2497/// IsEligibleForTailCallOptimization - Check whether the call is eligible 2498/// for tail call optimization. Targets which want to do tail call 2499/// optimization should implement this function. 2500bool 2501X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2502 CallingConv::ID CalleeCC, 2503 bool isVarArg, 2504 bool isCalleeStructRet, 2505 bool isCallerStructRet, 2506 const SmallVectorImpl<ISD::OutputArg> &Outs, 2507 const SmallVectorImpl<SDValue> &OutVals, 2508 const SmallVectorImpl<ISD::InputArg> &Ins, 2509 SelectionDAG& DAG) const { 2510 if (!IsTailCallConvention(CalleeCC) && 2511 CalleeCC != CallingConv::C) 2512 return false; 2513 2514 // If -tailcallopt is specified, make fastcc functions tail-callable. 2515 const MachineFunction &MF = DAG.getMachineFunction(); 2516 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2517 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2518 bool CCMatch = CallerCC == CalleeCC; 2519 2520 if (GuaranteedTailCallOpt) { 2521 if (IsTailCallConvention(CalleeCC) && CCMatch) 2522 return true; 2523 return false; 2524 } 2525 2526 // Look for obvious safe cases to perform tail call optimization that do not 2527 // require ABI changes. This is what gcc calls sibcall. 2528 2529 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to 2530 // emit a special epilogue. 2531 if (RegInfo->needsStackRealignment(MF)) 2532 return false; 2533 2534 // Also avoid sibcall optimization if either caller or callee uses struct 2535 // return semantics. 2536 if (isCalleeStructRet || isCallerStructRet) 2537 return false; 2538 2539 // Do not sibcall optimize vararg calls unless all arguments are passed via 2540 // registers. 2541 if (isVarArg && !Outs.empty()) { 2542 2543 // Optimizing for varargs on Win64 is unlikely to be safe without 2544 // additional testing. 2545 if (Subtarget->isTargetWin64()) 2546 return false; 2547 2548 SmallVector<CCValAssign, 16> ArgLocs; 2549 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2550 getTargetMachine(), ArgLocs, *DAG.getContext()); 2551 2552 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2553 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) 2554 if (!ArgLocs[i].isRegLoc()) 2555 return false; 2556 } 2557 2558 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack. 2559 // Therefore if it's not used by the call it is not safe to optimize this into 2560 // a sibcall. 2561 bool Unused = false; 2562 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 2563 if (!Ins[i].Used) { 2564 Unused = true; 2565 break; 2566 } 2567 } 2568 if (Unused) { 2569 SmallVector<CCValAssign, 16> RVLocs; 2570 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), 2571 getTargetMachine(), RVLocs, *DAG.getContext()); 2572 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 2573 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 2574 CCValAssign &VA = RVLocs[i]; 2575 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) 2576 return false; 2577 } 2578 } 2579 2580 // If the calling conventions do not match, then we'd better make sure the 2581 // results are returned in the same way as what the caller expects. 2582 if (!CCMatch) { 2583 SmallVector<CCValAssign, 16> RVLocs1; 2584 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), 2585 getTargetMachine(), RVLocs1, *DAG.getContext()); 2586 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86); 2587 2588 SmallVector<CCValAssign, 16> RVLocs2; 2589 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), 2590 getTargetMachine(), RVLocs2, *DAG.getContext()); 2591 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86); 2592 2593 if (RVLocs1.size() != RVLocs2.size()) 2594 return false; 2595 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2596 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2597 return false; 2598 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2599 return false; 2600 if (RVLocs1[i].isRegLoc()) { 2601 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2602 return false; 2603 } else { 2604 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2605 return false; 2606 } 2607 } 2608 } 2609 2610 // If the callee takes no arguments then go on to check the results of the 2611 // call. 2612 if (!Outs.empty()) { 2613 // Check if stack adjustment is needed. For now, do not do this if any 2614 // argument is passed on the stack. 2615 SmallVector<CCValAssign, 16> ArgLocs; 2616 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2617 getTargetMachine(), ArgLocs, *DAG.getContext()); 2618 2619 // Allocate shadow area for Win64 2620 if (Subtarget->isTargetWin64()) { 2621 CCInfo.AllocateStack(32, 8); 2622 } 2623 2624 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2625 if (CCInfo.getNextStackOffset()) { 2626 MachineFunction &MF = DAG.getMachineFunction(); 2627 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) 2628 return false; 2629 2630 // Check if the arguments are already laid out in the right way as 2631 // the caller's fixed stack objects. 2632 MachineFrameInfo *MFI = MF.getFrameInfo(); 2633 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2634 const X86InstrInfo *TII = 2635 ((X86TargetMachine&)getTargetMachine()).getInstrInfo(); 2636 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2637 CCValAssign &VA = ArgLocs[i]; 2638 SDValue Arg = OutVals[i]; 2639 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2640 if (VA.getLocInfo() == CCValAssign::Indirect) 2641 return false; 2642 if (!VA.isRegLoc()) { 2643 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2644 MFI, MRI, TII)) 2645 return false; 2646 } 2647 } 2648 } 2649 2650 // If the tailcall address may be in a register, then make sure it's 2651 // possible to register allocate for it. In 32-bit, the call address can 2652 // only target EAX, EDX, or ECX since the tail call must be scheduled after 2653 // callee-saved registers are restored. These happen to be the same 2654 // registers used to pass 'inreg' arguments so watch out for those. 2655 if (!Subtarget->is64Bit() && 2656 !isa<GlobalAddressSDNode>(Callee) && 2657 !isa<ExternalSymbolSDNode>(Callee)) { 2658 unsigned NumInRegs = 0; 2659 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2660 CCValAssign &VA = ArgLocs[i]; 2661 if (!VA.isRegLoc()) 2662 continue; 2663 unsigned Reg = VA.getLocReg(); 2664 switch (Reg) { 2665 default: break; 2666 case X86::EAX: case X86::EDX: case X86::ECX: 2667 if (++NumInRegs == 3) 2668 return false; 2669 break; 2670 } 2671 } 2672 } 2673 } 2674 2675 // An stdcall caller is expected to clean up its arguments; the callee 2676 // isn't going to do that. 2677 if (!CCMatch && CallerCC==CallingConv::X86_StdCall) 2678 return false; 2679 2680 return true; 2681} 2682 2683FastISel * 2684X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const { 2685 return X86::createFastISel(funcInfo); 2686} 2687 2688 2689//===----------------------------------------------------------------------===// 2690// Other Lowering Hooks 2691//===----------------------------------------------------------------------===// 2692 2693static bool MayFoldLoad(SDValue Op) { 2694 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode()); 2695} 2696 2697static bool MayFoldIntoStore(SDValue Op) { 2698 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin()); 2699} 2700 2701static bool isTargetShuffle(unsigned Opcode) { 2702 switch(Opcode) { 2703 default: return false; 2704 case X86ISD::PSHUFD: 2705 case X86ISD::PSHUFHW: 2706 case X86ISD::PSHUFLW: 2707 case X86ISD::SHUFPD: 2708 case X86ISD::PALIGN: 2709 case X86ISD::SHUFPS: 2710 case X86ISD::MOVLHPS: 2711 case X86ISD::MOVLHPD: 2712 case X86ISD::MOVHLPS: 2713 case X86ISD::MOVLPS: 2714 case X86ISD::MOVLPD: 2715 case X86ISD::MOVSHDUP: 2716 case X86ISD::MOVSLDUP: 2717 case X86ISD::MOVDDUP: 2718 case X86ISD::MOVSS: 2719 case X86ISD::MOVSD: 2720 case X86ISD::UNPCKLPS: 2721 case X86ISD::UNPCKLPD: 2722 case X86ISD::VUNPCKLPS: 2723 case X86ISD::VUNPCKLPD: 2724 case X86ISD::VUNPCKLPSY: 2725 case X86ISD::VUNPCKLPDY: 2726 case X86ISD::PUNPCKLWD: 2727 case X86ISD::PUNPCKLBW: 2728 case X86ISD::PUNPCKLDQ: 2729 case X86ISD::PUNPCKLQDQ: 2730 case X86ISD::UNPCKHPS: 2731 case X86ISD::UNPCKHPD: 2732 case X86ISD::PUNPCKHWD: 2733 case X86ISD::PUNPCKHBW: 2734 case X86ISD::PUNPCKHDQ: 2735 case X86ISD::PUNPCKHQDQ: 2736 return true; 2737 } 2738 return false; 2739} 2740 2741static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2742 SDValue V1, SelectionDAG &DAG) { 2743 switch(Opc) { 2744 default: llvm_unreachable("Unknown x86 shuffle node"); 2745 case X86ISD::MOVSHDUP: 2746 case X86ISD::MOVSLDUP: 2747 case X86ISD::MOVDDUP: 2748 return DAG.getNode(Opc, dl, VT, V1); 2749 } 2750 2751 return SDValue(); 2752} 2753 2754static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2755 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) { 2756 switch(Opc) { 2757 default: llvm_unreachable("Unknown x86 shuffle node"); 2758 case X86ISD::PSHUFD: 2759 case X86ISD::PSHUFHW: 2760 case X86ISD::PSHUFLW: 2761 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8)); 2762 } 2763 2764 return SDValue(); 2765} 2766 2767static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2768 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) { 2769 switch(Opc) { 2770 default: llvm_unreachable("Unknown x86 shuffle node"); 2771 case X86ISD::PALIGN: 2772 case X86ISD::SHUFPD: 2773 case X86ISD::SHUFPS: 2774 return DAG.getNode(Opc, dl, VT, V1, V2, 2775 DAG.getConstant(TargetMask, MVT::i8)); 2776 } 2777 return SDValue(); 2778} 2779 2780static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2781 SDValue V1, SDValue V2, SelectionDAG &DAG) { 2782 switch(Opc) { 2783 default: llvm_unreachable("Unknown x86 shuffle node"); 2784 case X86ISD::MOVLHPS: 2785 case X86ISD::MOVLHPD: 2786 case X86ISD::MOVHLPS: 2787 case X86ISD::MOVLPS: 2788 case X86ISD::MOVLPD: 2789 case X86ISD::MOVSS: 2790 case X86ISD::MOVSD: 2791 case X86ISD::UNPCKLPS: 2792 case X86ISD::UNPCKLPD: 2793 case X86ISD::VUNPCKLPS: 2794 case X86ISD::VUNPCKLPD: 2795 case X86ISD::VUNPCKLPSY: 2796 case X86ISD::VUNPCKLPDY: 2797 case X86ISD::PUNPCKLWD: 2798 case X86ISD::PUNPCKLBW: 2799 case X86ISD::PUNPCKLDQ: 2800 case X86ISD::PUNPCKLQDQ: 2801 case X86ISD::UNPCKHPS: 2802 case X86ISD::UNPCKHPD: 2803 case X86ISD::PUNPCKHWD: 2804 case X86ISD::PUNPCKHBW: 2805 case X86ISD::PUNPCKHDQ: 2806 case X86ISD::PUNPCKHQDQ: 2807 return DAG.getNode(Opc, dl, VT, V1, V2); 2808 } 2809 return SDValue(); 2810} 2811 2812SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const { 2813 MachineFunction &MF = DAG.getMachineFunction(); 2814 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 2815 int ReturnAddrIndex = FuncInfo->getRAIndex(); 2816 2817 if (ReturnAddrIndex == 0) { 2818 // Set up a frame object for the return address. 2819 uint64_t SlotSize = TD->getPointerSize(); 2820 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize, 2821 false); 2822 FuncInfo->setRAIndex(ReturnAddrIndex); 2823 } 2824 2825 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy()); 2826} 2827 2828 2829bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M, 2830 bool hasSymbolicDisplacement) { 2831 // Offset should fit into 32 bit immediate field. 2832 if (!isInt<32>(Offset)) 2833 return false; 2834 2835 // If we don't have a symbolic displacement - we don't have any extra 2836 // restrictions. 2837 if (!hasSymbolicDisplacement) 2838 return true; 2839 2840 // FIXME: Some tweaks might be needed for medium code model. 2841 if (M != CodeModel::Small && M != CodeModel::Kernel) 2842 return false; 2843 2844 // For small code model we assume that latest object is 16MB before end of 31 2845 // bits boundary. We may also accept pretty large negative constants knowing 2846 // that all objects are in the positive half of address space. 2847 if (M == CodeModel::Small && Offset < 16*1024*1024) 2848 return true; 2849 2850 // For kernel code model we know that all object resist in the negative half 2851 // of 32bits address space. We may not accept negative offsets, since they may 2852 // be just off and we may accept pretty large positive ones. 2853 if (M == CodeModel::Kernel && Offset > 0) 2854 return true; 2855 2856 return false; 2857} 2858 2859/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86 2860/// specific condition code, returning the condition code and the LHS/RHS of the 2861/// comparison to make. 2862static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP, 2863 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) { 2864 if (!isFP) { 2865 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 2866 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) { 2867 // X > -1 -> X == 0, jump !sign. 2868 RHS = DAG.getConstant(0, RHS.getValueType()); 2869 return X86::COND_NS; 2870 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) { 2871 // X < 0 -> X == 0, jump on sign. 2872 return X86::COND_S; 2873 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) { 2874 // X < 1 -> X <= 0 2875 RHS = DAG.getConstant(0, RHS.getValueType()); 2876 return X86::COND_LE; 2877 } 2878 } 2879 2880 switch (SetCCOpcode) { 2881 default: llvm_unreachable("Invalid integer condition!"); 2882 case ISD::SETEQ: return X86::COND_E; 2883 case ISD::SETGT: return X86::COND_G; 2884 case ISD::SETGE: return X86::COND_GE; 2885 case ISD::SETLT: return X86::COND_L; 2886 case ISD::SETLE: return X86::COND_LE; 2887 case ISD::SETNE: return X86::COND_NE; 2888 case ISD::SETULT: return X86::COND_B; 2889 case ISD::SETUGT: return X86::COND_A; 2890 case ISD::SETULE: return X86::COND_BE; 2891 case ISD::SETUGE: return X86::COND_AE; 2892 } 2893 } 2894 2895 // First determine if it is required or is profitable to flip the operands. 2896 2897 // If LHS is a foldable load, but RHS is not, flip the condition. 2898 if (ISD::isNON_EXTLoad(LHS.getNode()) && 2899 !ISD::isNON_EXTLoad(RHS.getNode())) { 2900 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode); 2901 std::swap(LHS, RHS); 2902 } 2903 2904 switch (SetCCOpcode) { 2905 default: break; 2906 case ISD::SETOLT: 2907 case ISD::SETOLE: 2908 case ISD::SETUGT: 2909 case ISD::SETUGE: 2910 std::swap(LHS, RHS); 2911 break; 2912 } 2913 2914 // On a floating point condition, the flags are set as follows: 2915 // ZF PF CF op 2916 // 0 | 0 | 0 | X > Y 2917 // 0 | 0 | 1 | X < Y 2918 // 1 | 0 | 0 | X == Y 2919 // 1 | 1 | 1 | unordered 2920 switch (SetCCOpcode) { 2921 default: llvm_unreachable("Condcode should be pre-legalized away"); 2922 case ISD::SETUEQ: 2923 case ISD::SETEQ: return X86::COND_E; 2924 case ISD::SETOLT: // flipped 2925 case ISD::SETOGT: 2926 case ISD::SETGT: return X86::COND_A; 2927 case ISD::SETOLE: // flipped 2928 case ISD::SETOGE: 2929 case ISD::SETGE: return X86::COND_AE; 2930 case ISD::SETUGT: // flipped 2931 case ISD::SETULT: 2932 case ISD::SETLT: return X86::COND_B; 2933 case ISD::SETUGE: // flipped 2934 case ISD::SETULE: 2935 case ISD::SETLE: return X86::COND_BE; 2936 case ISD::SETONE: 2937 case ISD::SETNE: return X86::COND_NE; 2938 case ISD::SETUO: return X86::COND_P; 2939 case ISD::SETO: return X86::COND_NP; 2940 case ISD::SETOEQ: 2941 case ISD::SETUNE: return X86::COND_INVALID; 2942 } 2943} 2944 2945/// hasFPCMov - is there a floating point cmov for the specific X86 condition 2946/// code. Current x86 isa includes the following FP cmov instructions: 2947/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu. 2948static bool hasFPCMov(unsigned X86CC) { 2949 switch (X86CC) { 2950 default: 2951 return false; 2952 case X86::COND_B: 2953 case X86::COND_BE: 2954 case X86::COND_E: 2955 case X86::COND_P: 2956 case X86::COND_A: 2957 case X86::COND_AE: 2958 case X86::COND_NE: 2959 case X86::COND_NP: 2960 return true; 2961 } 2962} 2963 2964/// isFPImmLegal - Returns true if the target can instruction select the 2965/// specified FP immediate natively. If false, the legalizer will 2966/// materialize the FP immediate as a load from a constant pool. 2967bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 2968 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) { 2969 if (Imm.bitwiseIsEqual(LegalFPImmediates[i])) 2970 return true; 2971 } 2972 return false; 2973} 2974 2975/// isUndefOrInRange - Return true if Val is undef or if its value falls within 2976/// the specified range (L, H]. 2977static bool isUndefOrInRange(int Val, int Low, int Hi) { 2978 return (Val < 0) || (Val >= Low && Val < Hi); 2979} 2980 2981/// isUndefOrEqual - Val is either less than zero (undef) or equal to the 2982/// specified value. 2983static bool isUndefOrEqual(int Val, int CmpVal) { 2984 if (Val < 0 || Val == CmpVal) 2985 return true; 2986 return false; 2987} 2988 2989/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that 2990/// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference 2991/// the second operand. 2992static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) { 2993 if (VT == MVT::v4f32 || VT == MVT::v4i32 ) 2994 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4); 2995 if (VT == MVT::v2f64 || VT == MVT::v2i64) 2996 return (Mask[0] < 2 && Mask[1] < 2); 2997 return false; 2998} 2999 3000bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) { 3001 SmallVector<int, 8> M; 3002 N->getMask(M); 3003 return ::isPSHUFDMask(M, N->getValueType(0)); 3004} 3005 3006/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that 3007/// is suitable for input to PSHUFHW. 3008static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3009 if (VT != MVT::v8i16) 3010 return false; 3011 3012 // Lower quadword copied in order or undef. 3013 for (int i = 0; i != 4; ++i) 3014 if (Mask[i] >= 0 && Mask[i] != i) 3015 return false; 3016 3017 // Upper quadword shuffled. 3018 for (int i = 4; i != 8; ++i) 3019 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7)) 3020 return false; 3021 3022 return true; 3023} 3024 3025bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) { 3026 SmallVector<int, 8> M; 3027 N->getMask(M); 3028 return ::isPSHUFHWMask(M, N->getValueType(0)); 3029} 3030 3031/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that 3032/// is suitable for input to PSHUFLW. 3033static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3034 if (VT != MVT::v8i16) 3035 return false; 3036 3037 // Upper quadword copied in order. 3038 for (int i = 4; i != 8; ++i) 3039 if (Mask[i] >= 0 && Mask[i] != i) 3040 return false; 3041 3042 // Lower quadword shuffled. 3043 for (int i = 0; i != 4; ++i) 3044 if (Mask[i] >= 4) 3045 return false; 3046 3047 return true; 3048} 3049 3050bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) { 3051 SmallVector<int, 8> M; 3052 N->getMask(M); 3053 return ::isPSHUFLWMask(M, N->getValueType(0)); 3054} 3055 3056/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that 3057/// is suitable for input to PALIGNR. 3058static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT, 3059 bool hasSSSE3) { 3060 int i, e = VT.getVectorNumElements(); 3061 3062 // Do not handle v2i64 / v2f64 shuffles with palignr. 3063 if (e < 4 || !hasSSSE3) 3064 return false; 3065 3066 for (i = 0; i != e; ++i) 3067 if (Mask[i] >= 0) 3068 break; 3069 3070 // All undef, not a palignr. 3071 if (i == e) 3072 return false; 3073 3074 // Determine if it's ok to perform a palignr with only the LHS, since we 3075 // don't have access to the actual shuffle elements to see if RHS is undef. 3076 bool Unary = Mask[i] < (int)e; 3077 bool NeedsUnary = false; 3078 3079 int s = Mask[i] - i; 3080 3081 // Check the rest of the elements to see if they are consecutive. 3082 for (++i; i != e; ++i) { 3083 int m = Mask[i]; 3084 if (m < 0) 3085 continue; 3086 3087 Unary = Unary && (m < (int)e); 3088 NeedsUnary = NeedsUnary || (m < s); 3089 3090 if (NeedsUnary && !Unary) 3091 return false; 3092 if (Unary && m != ((s+i) & (e-1))) 3093 return false; 3094 if (!Unary && m != (s+i)) 3095 return false; 3096 } 3097 return true; 3098} 3099 3100bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) { 3101 SmallVector<int, 8> M; 3102 N->getMask(M); 3103 return ::isPALIGNRMask(M, N->getValueType(0), true); 3104} 3105 3106/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand 3107/// specifies a shuffle of elements that is suitable for input to SHUFP*. 3108static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3109 int NumElems = VT.getVectorNumElements(); 3110 if (NumElems != 2 && NumElems != 4) 3111 return false; 3112 3113 int Half = NumElems / 2; 3114 for (int i = 0; i < Half; ++i) 3115 if (!isUndefOrInRange(Mask[i], 0, NumElems)) 3116 return false; 3117 for (int i = Half; i < NumElems; ++i) 3118 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2)) 3119 return false; 3120 3121 return true; 3122} 3123 3124bool X86::isSHUFPMask(ShuffleVectorSDNode *N) { 3125 SmallVector<int, 8> M; 3126 N->getMask(M); 3127 return ::isSHUFPMask(M, N->getValueType(0)); 3128} 3129 3130/// isCommutedSHUFP - Returns true if the shuffle mask is exactly 3131/// the reverse of what x86 shuffles want. x86 shuffles requires the lower 3132/// half elements to come from vector 1 (which would equal the dest.) and 3133/// the upper half to come from vector 2. 3134static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3135 int NumElems = VT.getVectorNumElements(); 3136 3137 if (NumElems != 2 && NumElems != 4) 3138 return false; 3139 3140 int Half = NumElems / 2; 3141 for (int i = 0; i < Half; ++i) 3142 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2)) 3143 return false; 3144 for (int i = Half; i < NumElems; ++i) 3145 if (!isUndefOrInRange(Mask[i], 0, NumElems)) 3146 return false; 3147 return true; 3148} 3149 3150static bool isCommutedSHUFP(ShuffleVectorSDNode *N) { 3151 SmallVector<int, 8> M; 3152 N->getMask(M); 3153 return isCommutedSHUFPMask(M, N->getValueType(0)); 3154} 3155 3156/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand 3157/// specifies a shuffle of elements that is suitable for input to MOVHLPS. 3158bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) { 3159 if (N->getValueType(0).getVectorNumElements() != 4) 3160 return false; 3161 3162 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3 3163 return isUndefOrEqual(N->getMaskElt(0), 6) && 3164 isUndefOrEqual(N->getMaskElt(1), 7) && 3165 isUndefOrEqual(N->getMaskElt(2), 2) && 3166 isUndefOrEqual(N->getMaskElt(3), 3); 3167} 3168 3169/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form 3170/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef, 3171/// <2, 3, 2, 3> 3172bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) { 3173 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3174 3175 if (NumElems != 4) 3176 return false; 3177 3178 return isUndefOrEqual(N->getMaskElt(0), 2) && 3179 isUndefOrEqual(N->getMaskElt(1), 3) && 3180 isUndefOrEqual(N->getMaskElt(2), 2) && 3181 isUndefOrEqual(N->getMaskElt(3), 3); 3182} 3183 3184/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand 3185/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}. 3186bool X86::isMOVLPMask(ShuffleVectorSDNode *N) { 3187 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3188 3189 if (NumElems != 2 && NumElems != 4) 3190 return false; 3191 3192 for (unsigned i = 0; i < NumElems/2; ++i) 3193 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems)) 3194 return false; 3195 3196 for (unsigned i = NumElems/2; i < NumElems; ++i) 3197 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3198 return false; 3199 3200 return true; 3201} 3202 3203/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand 3204/// specifies a shuffle of elements that is suitable for input to MOVLHPS. 3205bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) { 3206 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3207 3208 if ((NumElems != 2 && NumElems != 4) 3209 || N->getValueType(0).getSizeInBits() > 128) 3210 return false; 3211 3212 for (unsigned i = 0; i < NumElems/2; ++i) 3213 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3214 return false; 3215 3216 for (unsigned i = 0; i < NumElems/2; ++i) 3217 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems)) 3218 return false; 3219 3220 return true; 3221} 3222 3223/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand 3224/// specifies a shuffle of elements that is suitable for input to UNPCKL. 3225static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT, 3226 bool V2IsSplat = false) { 3227 int NumElts = VT.getVectorNumElements(); 3228 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16) 3229 return false; 3230 3231 // Handle vector lengths > 128 bits. Define a "section" as a set of 3232 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit 3233 // sections. 3234 unsigned NumSections = VT.getSizeInBits() / 128; 3235 if (NumSections == 0 ) NumSections = 1; // Handle MMX 3236 unsigned NumSectionElts = NumElts / NumSections; 3237 3238 unsigned Start = 0; 3239 unsigned End = NumSectionElts; 3240 for (unsigned s = 0; s < NumSections; ++s) { 3241 for (unsigned i = Start, j = s * NumSectionElts; 3242 i != End; 3243 i += 2, ++j) { 3244 int BitI = Mask[i]; 3245 int BitI1 = Mask[i+1]; 3246 if (!isUndefOrEqual(BitI, j)) 3247 return false; 3248 if (V2IsSplat) { 3249 if (!isUndefOrEqual(BitI1, NumElts)) 3250 return false; 3251 } else { 3252 if (!isUndefOrEqual(BitI1, j + NumElts)) 3253 return false; 3254 } 3255 } 3256 // Process the next 128 bits. 3257 Start += NumSectionElts; 3258 End += NumSectionElts; 3259 } 3260 3261 return true; 3262} 3263 3264bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) { 3265 SmallVector<int, 8> M; 3266 N->getMask(M); 3267 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat); 3268} 3269 3270/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand 3271/// specifies a shuffle of elements that is suitable for input to UNPCKH. 3272static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT, 3273 bool V2IsSplat = false) { 3274 int NumElts = VT.getVectorNumElements(); 3275 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16) 3276 return false; 3277 3278 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) { 3279 int BitI = Mask[i]; 3280 int BitI1 = Mask[i+1]; 3281 if (!isUndefOrEqual(BitI, j + NumElts/2)) 3282 return false; 3283 if (V2IsSplat) { 3284 if (isUndefOrEqual(BitI1, NumElts)) 3285 return false; 3286 } else { 3287 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts)) 3288 return false; 3289 } 3290 } 3291 return true; 3292} 3293 3294bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) { 3295 SmallVector<int, 8> M; 3296 N->getMask(M); 3297 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat); 3298} 3299 3300/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form 3301/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef, 3302/// <0, 0, 1, 1> 3303static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) { 3304 int NumElems = VT.getVectorNumElements(); 3305 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16) 3306 return false; 3307 3308 // Handle vector lengths > 128 bits. Define a "section" as a set of 3309 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit 3310 // sections. 3311 unsigned NumSections = VT.getSizeInBits() / 128; 3312 if (NumSections == 0 ) NumSections = 1; // Handle MMX 3313 unsigned NumSectionElts = NumElems / NumSections; 3314 3315 for (unsigned s = 0; s < NumSections; ++s) { 3316 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts; 3317 i != NumSectionElts * (s + 1); 3318 i += 2, ++j) { 3319 int BitI = Mask[i]; 3320 int BitI1 = Mask[i+1]; 3321 3322 if (!isUndefOrEqual(BitI, j)) 3323 return false; 3324 if (!isUndefOrEqual(BitI1, j)) 3325 return false; 3326 } 3327 } 3328 3329 return true; 3330} 3331 3332bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) { 3333 SmallVector<int, 8> M; 3334 N->getMask(M); 3335 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0)); 3336} 3337 3338/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form 3339/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef, 3340/// <2, 2, 3, 3> 3341static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) { 3342 int NumElems = VT.getVectorNumElements(); 3343 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16) 3344 return false; 3345 3346 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) { 3347 int BitI = Mask[i]; 3348 int BitI1 = Mask[i+1]; 3349 if (!isUndefOrEqual(BitI, j)) 3350 return false; 3351 if (!isUndefOrEqual(BitI1, j)) 3352 return false; 3353 } 3354 return true; 3355} 3356 3357bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) { 3358 SmallVector<int, 8> M; 3359 N->getMask(M); 3360 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0)); 3361} 3362 3363/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand 3364/// specifies a shuffle of elements that is suitable for input to MOVSS, 3365/// MOVSD, and MOVD, i.e. setting the lowest element. 3366static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3367 if (VT.getVectorElementType().getSizeInBits() < 32) 3368 return false; 3369 3370 int NumElts = VT.getVectorNumElements(); 3371 3372 if (!isUndefOrEqual(Mask[0], NumElts)) 3373 return false; 3374 3375 for (int i = 1; i < NumElts; ++i) 3376 if (!isUndefOrEqual(Mask[i], i)) 3377 return false; 3378 3379 return true; 3380} 3381 3382bool X86::isMOVLMask(ShuffleVectorSDNode *N) { 3383 SmallVector<int, 8> M; 3384 N->getMask(M); 3385 return ::isMOVLMask(M, N->getValueType(0)); 3386} 3387 3388/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse 3389/// of what x86 movss want. X86 movs requires the lowest element to be lowest 3390/// element of vector 2 and the other elements to come from vector 1 in order. 3391static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT, 3392 bool V2IsSplat = false, bool V2IsUndef = false) { 3393 int NumOps = VT.getVectorNumElements(); 3394 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16) 3395 return false; 3396 3397 if (!isUndefOrEqual(Mask[0], 0)) 3398 return false; 3399 3400 for (int i = 1; i < NumOps; ++i) 3401 if (!(isUndefOrEqual(Mask[i], i+NumOps) || 3402 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) || 3403 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps)))) 3404 return false; 3405 3406 return true; 3407} 3408 3409static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false, 3410 bool V2IsUndef = false) { 3411 SmallVector<int, 8> M; 3412 N->getMask(M); 3413 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef); 3414} 3415 3416/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3417/// specifies a shuffle of elements that is suitable for input to MOVSHDUP. 3418bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) { 3419 if (N->getValueType(0).getVectorNumElements() != 4) 3420 return false; 3421 3422 // Expect 1, 1, 3, 3 3423 for (unsigned i = 0; i < 2; ++i) { 3424 int Elt = N->getMaskElt(i); 3425 if (Elt >= 0 && Elt != 1) 3426 return false; 3427 } 3428 3429 bool HasHi = false; 3430 for (unsigned i = 2; i < 4; ++i) { 3431 int Elt = N->getMaskElt(i); 3432 if (Elt >= 0 && Elt != 3) 3433 return false; 3434 if (Elt == 3) 3435 HasHi = true; 3436 } 3437 // Don't use movshdup if it can be done with a shufps. 3438 // FIXME: verify that matching u, u, 3, 3 is what we want. 3439 return HasHi; 3440} 3441 3442/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3443/// specifies a shuffle of elements that is suitable for input to MOVSLDUP. 3444bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) { 3445 if (N->getValueType(0).getVectorNumElements() != 4) 3446 return false; 3447 3448 // Expect 0, 0, 2, 2 3449 for (unsigned i = 0; i < 2; ++i) 3450 if (N->getMaskElt(i) > 0) 3451 return false; 3452 3453 bool HasHi = false; 3454 for (unsigned i = 2; i < 4; ++i) { 3455 int Elt = N->getMaskElt(i); 3456 if (Elt >= 0 && Elt != 2) 3457 return false; 3458 if (Elt == 2) 3459 HasHi = true; 3460 } 3461 // Don't use movsldup if it can be done with a shufps. 3462 return HasHi; 3463} 3464 3465/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3466/// specifies a shuffle of elements that is suitable for input to MOVDDUP. 3467bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) { 3468 int e = N->getValueType(0).getVectorNumElements() / 2; 3469 3470 for (int i = 0; i < e; ++i) 3471 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3472 return false; 3473 for (int i = 0; i < e; ++i) 3474 if (!isUndefOrEqual(N->getMaskElt(e+i), i)) 3475 return false; 3476 return true; 3477} 3478 3479/// isVEXTRACTF128Index - Return true if the specified 3480/// EXTRACT_SUBVECTOR operand specifies a vector extract that is 3481/// suitable for input to VEXTRACTF128. 3482bool X86::isVEXTRACTF128Index(SDNode *N) { 3483 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 3484 return false; 3485 3486 // The index should be aligned on a 128-bit boundary. 3487 uint64_t Index = 3488 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 3489 3490 unsigned VL = N->getValueType(0).getVectorNumElements(); 3491 unsigned VBits = N->getValueType(0).getSizeInBits(); 3492 unsigned ElSize = VBits / VL; 3493 bool Result = (Index * ElSize) % 128 == 0; 3494 3495 return Result; 3496} 3497 3498/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR 3499/// operand specifies a subvector insert that is suitable for input to 3500/// VINSERTF128. 3501bool X86::isVINSERTF128Index(SDNode *N) { 3502 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 3503 return false; 3504 3505 // The index should be aligned on a 128-bit boundary. 3506 uint64_t Index = 3507 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 3508 3509 unsigned VL = N->getValueType(0).getVectorNumElements(); 3510 unsigned VBits = N->getValueType(0).getSizeInBits(); 3511 unsigned ElSize = VBits / VL; 3512 bool Result = (Index * ElSize) % 128 == 0; 3513 3514 return Result; 3515} 3516 3517/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle 3518/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions. 3519unsigned X86::getShuffleSHUFImmediate(SDNode *N) { 3520 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3521 int NumOperands = SVOp->getValueType(0).getVectorNumElements(); 3522 3523 unsigned Shift = (NumOperands == 4) ? 2 : 1; 3524 unsigned Mask = 0; 3525 for (int i = 0; i < NumOperands; ++i) { 3526 int Val = SVOp->getMaskElt(NumOperands-i-1); 3527 if (Val < 0) Val = 0; 3528 if (Val >= NumOperands) Val -= NumOperands; 3529 Mask |= Val; 3530 if (i != NumOperands - 1) 3531 Mask <<= Shift; 3532 } 3533 return Mask; 3534} 3535 3536/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle 3537/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction. 3538unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) { 3539 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3540 unsigned Mask = 0; 3541 // 8 nodes, but we only care about the last 4. 3542 for (unsigned i = 7; i >= 4; --i) { 3543 int Val = SVOp->getMaskElt(i); 3544 if (Val >= 0) 3545 Mask |= (Val - 4); 3546 if (i != 4) 3547 Mask <<= 2; 3548 } 3549 return Mask; 3550} 3551 3552/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle 3553/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction. 3554unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) { 3555 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3556 unsigned Mask = 0; 3557 // 8 nodes, but we only care about the first 4. 3558 for (int i = 3; i >= 0; --i) { 3559 int Val = SVOp->getMaskElt(i); 3560 if (Val >= 0) 3561 Mask |= Val; 3562 if (i != 0) 3563 Mask <<= 2; 3564 } 3565 return Mask; 3566} 3567 3568/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle 3569/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction. 3570unsigned X86::getShufflePALIGNRImmediate(SDNode *N) { 3571 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3572 EVT VVT = N->getValueType(0); 3573 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3; 3574 int Val = 0; 3575 3576 unsigned i, e; 3577 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) { 3578 Val = SVOp->getMaskElt(i); 3579 if (Val >= 0) 3580 break; 3581 } 3582 return (Val - i) * EltSize; 3583} 3584 3585/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate 3586/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128 3587/// instructions. 3588unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) { 3589 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 3590 llvm_unreachable("Illegal extract subvector for VEXTRACTF128"); 3591 3592 uint64_t Index = 3593 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 3594 3595 EVT VecVT = N->getOperand(0).getValueType(); 3596 EVT ElVT = VecVT.getVectorElementType(); 3597 3598 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 3599 3600 return Index / NumElemsPerChunk; 3601} 3602 3603/// getInsertVINSERTF128Immediate - Return the appropriate immediate 3604/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128 3605/// instructions. 3606unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) { 3607 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 3608 llvm_unreachable("Illegal insert subvector for VINSERTF128"); 3609 3610 uint64_t Index = 3611 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 3612 3613 EVT VecVT = N->getValueType(0); 3614 EVT ElVT = VecVT.getVectorElementType(); 3615 3616 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 3617 3618 return Index / NumElemsPerChunk; 3619} 3620 3621/// isZeroNode - Returns true if Elt is a constant zero or a floating point 3622/// constant +0.0. 3623bool X86::isZeroNode(SDValue Elt) { 3624 return ((isa<ConstantSDNode>(Elt) && 3625 cast<ConstantSDNode>(Elt)->isNullValue()) || 3626 (isa<ConstantFPSDNode>(Elt) && 3627 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero())); 3628} 3629 3630/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in 3631/// their permute mask. 3632static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp, 3633 SelectionDAG &DAG) { 3634 EVT VT = SVOp->getValueType(0); 3635 unsigned NumElems = VT.getVectorNumElements(); 3636 SmallVector<int, 8> MaskVec; 3637 3638 for (unsigned i = 0; i != NumElems; ++i) { 3639 int idx = SVOp->getMaskElt(i); 3640 if (idx < 0) 3641 MaskVec.push_back(idx); 3642 else if (idx < (int)NumElems) 3643 MaskVec.push_back(idx + NumElems); 3644 else 3645 MaskVec.push_back(idx - NumElems); 3646 } 3647 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1), 3648 SVOp->getOperand(0), &MaskVec[0]); 3649} 3650 3651/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming 3652/// the two vector operands have swapped position. 3653static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) { 3654 unsigned NumElems = VT.getVectorNumElements(); 3655 for (unsigned i = 0; i != NumElems; ++i) { 3656 int idx = Mask[i]; 3657 if (idx < 0) 3658 continue; 3659 else if (idx < (int)NumElems) 3660 Mask[i] = idx + NumElems; 3661 else 3662 Mask[i] = idx - NumElems; 3663 } 3664} 3665 3666/// ShouldXformToMOVHLPS - Return true if the node should be transformed to 3667/// match movhlps. The lower half elements should come from upper half of 3668/// V1 (and in order), and the upper half elements should come from the upper 3669/// half of V2 (and in order). 3670static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) { 3671 if (Op->getValueType(0).getVectorNumElements() != 4) 3672 return false; 3673 for (unsigned i = 0, e = 2; i != e; ++i) 3674 if (!isUndefOrEqual(Op->getMaskElt(i), i+2)) 3675 return false; 3676 for (unsigned i = 2; i != 4; ++i) 3677 if (!isUndefOrEqual(Op->getMaskElt(i), i+4)) 3678 return false; 3679 return true; 3680} 3681 3682/// isScalarLoadToVector - Returns true if the node is a scalar load that 3683/// is promoted to a vector. It also returns the LoadSDNode by reference if 3684/// required. 3685static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) { 3686 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR) 3687 return false; 3688 N = N->getOperand(0).getNode(); 3689 if (!ISD::isNON_EXTLoad(N)) 3690 return false; 3691 if (LD) 3692 *LD = cast<LoadSDNode>(N); 3693 return true; 3694} 3695 3696/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to 3697/// match movlp{s|d}. The lower half elements should come from lower half of 3698/// V1 (and in order), and the upper half elements should come from the upper 3699/// half of V2 (and in order). And since V1 will become the source of the 3700/// MOVLP, it must be either a vector load or a scalar load to vector. 3701static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, 3702 ShuffleVectorSDNode *Op) { 3703 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1)) 3704 return false; 3705 // Is V2 is a vector load, don't do this transformation. We will try to use 3706 // load folding shufps op. 3707 if (ISD::isNON_EXTLoad(V2)) 3708 return false; 3709 3710 unsigned NumElems = Op->getValueType(0).getVectorNumElements(); 3711 3712 if (NumElems != 2 && NumElems != 4) 3713 return false; 3714 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3715 if (!isUndefOrEqual(Op->getMaskElt(i), i)) 3716 return false; 3717 for (unsigned i = NumElems/2; i != NumElems; ++i) 3718 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems)) 3719 return false; 3720 return true; 3721} 3722 3723/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are 3724/// all the same. 3725static bool isSplatVector(SDNode *N) { 3726 if (N->getOpcode() != ISD::BUILD_VECTOR) 3727 return false; 3728 3729 SDValue SplatValue = N->getOperand(0); 3730 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i) 3731 if (N->getOperand(i) != SplatValue) 3732 return false; 3733 return true; 3734} 3735 3736/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved 3737/// to an zero vector. 3738/// FIXME: move to dag combiner / method on ShuffleVectorSDNode 3739static bool isZeroShuffle(ShuffleVectorSDNode *N) { 3740 SDValue V1 = N->getOperand(0); 3741 SDValue V2 = N->getOperand(1); 3742 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3743 for (unsigned i = 0; i != NumElems; ++i) { 3744 int Idx = N->getMaskElt(i); 3745 if (Idx >= (int)NumElems) { 3746 unsigned Opc = V2.getOpcode(); 3747 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode())) 3748 continue; 3749 if (Opc != ISD::BUILD_VECTOR || 3750 !X86::isZeroNode(V2.getOperand(Idx-NumElems))) 3751 return false; 3752 } else if (Idx >= 0) { 3753 unsigned Opc = V1.getOpcode(); 3754 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode())) 3755 continue; 3756 if (Opc != ISD::BUILD_VECTOR || 3757 !X86::isZeroNode(V1.getOperand(Idx))) 3758 return false; 3759 } 3760 } 3761 return true; 3762} 3763 3764/// getZeroVector - Returns a vector of specified type with all zero elements. 3765/// 3766static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG, 3767 DebugLoc dl) { 3768 assert(VT.isVector() && "Expected a vector type"); 3769 3770 // Always build SSE zero vectors as <4 x i32> bitcasted 3771 // to their dest type. This ensures they get CSE'd. 3772 SDValue Vec; 3773 if (VT.getSizeInBits() == 128) { // SSE 3774 if (HasSSE2) { // SSE2 3775 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 3776 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 3777 } else { // SSE1 3778 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 3779 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst); 3780 } 3781 } else if (VT.getSizeInBits() == 256) { // AVX 3782 // 256-bit logic and arithmetic instructions in AVX are 3783 // all floating-point, no support for integer ops. Default 3784 // to emitting fp zeroed vectors then. 3785 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 3786 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 3787 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8); 3788 } 3789 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 3790} 3791 3792/// getOnesVector - Returns a vector of specified type with all bits set. 3793/// 3794static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) { 3795 assert(VT.isVector() && "Expected a vector type"); 3796 3797 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest 3798 // type. This ensures they get CSE'd. 3799 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32); 3800 SDValue Vec; 3801 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 3802 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 3803} 3804 3805 3806/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements 3807/// that point to V2 points to its first element. 3808static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 3809 EVT VT = SVOp->getValueType(0); 3810 unsigned NumElems = VT.getVectorNumElements(); 3811 3812 bool Changed = false; 3813 SmallVector<int, 8> MaskVec; 3814 SVOp->getMask(MaskVec); 3815 3816 for (unsigned i = 0; i != NumElems; ++i) { 3817 if (MaskVec[i] > (int)NumElems) { 3818 MaskVec[i] = NumElems; 3819 Changed = true; 3820 } 3821 } 3822 if (Changed) 3823 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0), 3824 SVOp->getOperand(1), &MaskVec[0]); 3825 return SDValue(SVOp, 0); 3826} 3827 3828/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd 3829/// operation of specified width. 3830static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 3831 SDValue V2) { 3832 unsigned NumElems = VT.getVectorNumElements(); 3833 SmallVector<int, 8> Mask; 3834 Mask.push_back(NumElems); 3835 for (unsigned i = 1; i != NumElems; ++i) 3836 Mask.push_back(i); 3837 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 3838} 3839 3840/// getUnpackl - Returns a vector_shuffle node for an unpackl operation. 3841static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 3842 SDValue V2) { 3843 unsigned NumElems = VT.getVectorNumElements(); 3844 SmallVector<int, 8> Mask; 3845 for (unsigned i = 0, e = NumElems/2; i != e; ++i) { 3846 Mask.push_back(i); 3847 Mask.push_back(i + NumElems); 3848 } 3849 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 3850} 3851 3852/// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation. 3853static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 3854 SDValue V2) { 3855 unsigned NumElems = VT.getVectorNumElements(); 3856 unsigned Half = NumElems/2; 3857 SmallVector<int, 8> Mask; 3858 for (unsigned i = 0; i != Half; ++i) { 3859 Mask.push_back(i + Half); 3860 Mask.push_back(i + NumElems + Half); 3861 } 3862 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 3863} 3864 3865/// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32. 3866static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) { 3867 EVT PVT = MVT::v4f32; 3868 EVT VT = SV->getValueType(0); 3869 DebugLoc dl = SV->getDebugLoc(); 3870 SDValue V1 = SV->getOperand(0); 3871 int NumElems = VT.getVectorNumElements(); 3872 int EltNo = SV->getSplatIndex(); 3873 3874 // unpack elements to the correct location 3875 while (NumElems > 4) { 3876 if (EltNo < NumElems/2) { 3877 V1 = getUnpackl(DAG, dl, VT, V1, V1); 3878 } else { 3879 V1 = getUnpackh(DAG, dl, VT, V1, V1); 3880 EltNo -= NumElems/2; 3881 } 3882 NumElems >>= 1; 3883 } 3884 3885 // Perform the splat. 3886 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo }; 3887 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1); 3888 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]); 3889 return DAG.getNode(ISD::BITCAST, dl, VT, V1); 3890} 3891 3892/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified 3893/// vector of zero or undef vector. This produces a shuffle where the low 3894/// element of V2 is swizzled into the zero/undef vector, landing at element 3895/// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3). 3896static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx, 3897 bool isZero, bool HasSSE2, 3898 SelectionDAG &DAG) { 3899 EVT VT = V2.getValueType(); 3900 SDValue V1 = isZero 3901 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT); 3902 unsigned NumElems = VT.getVectorNumElements(); 3903 SmallVector<int, 16> MaskVec; 3904 for (unsigned i = 0; i != NumElems; ++i) 3905 // If this is the insertion idx, put the low elt of V2 here. 3906 MaskVec.push_back(i == Idx ? NumElems : i); 3907 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]); 3908} 3909 3910/// getShuffleScalarElt - Returns the scalar element that will make up the ith 3911/// element of the result of the vector shuffle. 3912static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG, 3913 unsigned Depth) { 3914 if (Depth == 6) 3915 return SDValue(); // Limit search depth. 3916 3917 SDValue V = SDValue(N, 0); 3918 EVT VT = V.getValueType(); 3919 unsigned Opcode = V.getOpcode(); 3920 3921 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars. 3922 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) { 3923 Index = SV->getMaskElt(Index); 3924 3925 if (Index < 0) 3926 return DAG.getUNDEF(VT.getVectorElementType()); 3927 3928 int NumElems = VT.getVectorNumElements(); 3929 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1); 3930 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1); 3931 } 3932 3933 // Recurse into target specific vector shuffles to find scalars. 3934 if (isTargetShuffle(Opcode)) { 3935 int NumElems = VT.getVectorNumElements(); 3936 SmallVector<unsigned, 16> ShuffleMask; 3937 SDValue ImmN; 3938 3939 switch(Opcode) { 3940 case X86ISD::SHUFPS: 3941 case X86ISD::SHUFPD: 3942 ImmN = N->getOperand(N->getNumOperands()-1); 3943 DecodeSHUFPSMask(NumElems, 3944 cast<ConstantSDNode>(ImmN)->getZExtValue(), 3945 ShuffleMask); 3946 break; 3947 case X86ISD::PUNPCKHBW: 3948 case X86ISD::PUNPCKHWD: 3949 case X86ISD::PUNPCKHDQ: 3950 case X86ISD::PUNPCKHQDQ: 3951 DecodePUNPCKHMask(NumElems, ShuffleMask); 3952 break; 3953 case X86ISD::UNPCKHPS: 3954 case X86ISD::UNPCKHPD: 3955 DecodeUNPCKHPMask(NumElems, ShuffleMask); 3956 break; 3957 case X86ISD::PUNPCKLBW: 3958 case X86ISD::PUNPCKLWD: 3959 case X86ISD::PUNPCKLDQ: 3960 case X86ISD::PUNPCKLQDQ: 3961 DecodePUNPCKLMask(VT, ShuffleMask); 3962 break; 3963 case X86ISD::UNPCKLPS: 3964 case X86ISD::UNPCKLPD: 3965 case X86ISD::VUNPCKLPS: 3966 case X86ISD::VUNPCKLPD: 3967 case X86ISD::VUNPCKLPSY: 3968 case X86ISD::VUNPCKLPDY: 3969 DecodeUNPCKLPMask(VT, ShuffleMask); 3970 break; 3971 case X86ISD::MOVHLPS: 3972 DecodeMOVHLPSMask(NumElems, ShuffleMask); 3973 break; 3974 case X86ISD::MOVLHPS: 3975 DecodeMOVLHPSMask(NumElems, ShuffleMask); 3976 break; 3977 case X86ISD::PSHUFD: 3978 ImmN = N->getOperand(N->getNumOperands()-1); 3979 DecodePSHUFMask(NumElems, 3980 cast<ConstantSDNode>(ImmN)->getZExtValue(), 3981 ShuffleMask); 3982 break; 3983 case X86ISD::PSHUFHW: 3984 ImmN = N->getOperand(N->getNumOperands()-1); 3985 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), 3986 ShuffleMask); 3987 break; 3988 case X86ISD::PSHUFLW: 3989 ImmN = N->getOperand(N->getNumOperands()-1); 3990 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), 3991 ShuffleMask); 3992 break; 3993 case X86ISD::MOVSS: 3994 case X86ISD::MOVSD: { 3995 // The index 0 always comes from the first element of the second source, 3996 // this is why MOVSS and MOVSD are used in the first place. The other 3997 // elements come from the other positions of the first source vector. 3998 unsigned OpNum = (Index == 0) ? 1 : 0; 3999 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG, 4000 Depth+1); 4001 } 4002 default: 4003 assert("not implemented for target shuffle node"); 4004 return SDValue(); 4005 } 4006 4007 Index = ShuffleMask[Index]; 4008 if (Index < 0) 4009 return DAG.getUNDEF(VT.getVectorElementType()); 4010 4011 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1); 4012 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, 4013 Depth+1); 4014 } 4015 4016 // Actual nodes that may contain scalar elements 4017 if (Opcode == ISD::BITCAST) { 4018 V = V.getOperand(0); 4019 EVT SrcVT = V.getValueType(); 4020 unsigned NumElems = VT.getVectorNumElements(); 4021 4022 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems) 4023 return SDValue(); 4024 } 4025 4026 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 4027 return (Index == 0) ? V.getOperand(0) 4028 : DAG.getUNDEF(VT.getVectorElementType()); 4029 4030 if (V.getOpcode() == ISD::BUILD_VECTOR) 4031 return V.getOperand(Index); 4032 4033 return SDValue(); 4034} 4035 4036/// getNumOfConsecutiveZeros - Return the number of elements of a vector 4037/// shuffle operation which come from a consecutively from a zero. The 4038/// search can start in two different directions, from left or right. 4039static 4040unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems, 4041 bool ZerosFromLeft, SelectionDAG &DAG) { 4042 int i = 0; 4043 4044 while (i < NumElems) { 4045 unsigned Index = ZerosFromLeft ? i : NumElems-i-1; 4046 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0); 4047 if (!(Elt.getNode() && 4048 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt)))) 4049 break; 4050 ++i; 4051 } 4052 4053 return i; 4054} 4055 4056/// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to 4057/// MaskE correspond consecutively to elements from one of the vector operands, 4058/// starting from its index OpIdx. Also tell OpNum which source vector operand. 4059static 4060bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE, 4061 int OpIdx, int NumElems, unsigned &OpNum) { 4062 bool SeenV1 = false; 4063 bool SeenV2 = false; 4064 4065 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) { 4066 int Idx = SVOp->getMaskElt(i); 4067 // Ignore undef indicies 4068 if (Idx < 0) 4069 continue; 4070 4071 if (Idx < NumElems) 4072 SeenV1 = true; 4073 else 4074 SeenV2 = true; 4075 4076 // Only accept consecutive elements from the same vector 4077 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2)) 4078 return false; 4079 } 4080 4081 OpNum = SeenV1 ? 0 : 1; 4082 return true; 4083} 4084 4085/// isVectorShiftRight - Returns true if the shuffle can be implemented as a 4086/// logical left shift of a vector. 4087static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4088 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4089 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4090 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4091 false /* check zeros from right */, DAG); 4092 unsigned OpSrc; 4093 4094 if (!NumZeros) 4095 return false; 4096 4097 // Considering the elements in the mask that are not consecutive zeros, 4098 // check if they consecutively come from only one of the source vectors. 4099 // 4100 // V1 = {X, A, B, C} 0 4101 // \ \ \ / 4102 // vector_shuffle V1, V2 <1, 2, 3, X> 4103 // 4104 if (!isShuffleMaskConsecutive(SVOp, 4105 0, // Mask Start Index 4106 NumElems-NumZeros-1, // Mask End Index 4107 NumZeros, // Where to start looking in the src vector 4108 NumElems, // Number of elements in vector 4109 OpSrc)) // Which source operand ? 4110 return false; 4111 4112 isLeft = false; 4113 ShAmt = NumZeros; 4114 ShVal = SVOp->getOperand(OpSrc); 4115 return true; 4116} 4117 4118/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a 4119/// logical left shift of a vector. 4120static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4121 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4122 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4123 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4124 true /* check zeros from left */, DAG); 4125 unsigned OpSrc; 4126 4127 if (!NumZeros) 4128 return false; 4129 4130 // Considering the elements in the mask that are not consecutive zeros, 4131 // check if they consecutively come from only one of the source vectors. 4132 // 4133 // 0 { A, B, X, X } = V2 4134 // / \ / / 4135 // vector_shuffle V1, V2 <X, X, 4, 5> 4136 // 4137 if (!isShuffleMaskConsecutive(SVOp, 4138 NumZeros, // Mask Start Index 4139 NumElems-1, // Mask End Index 4140 0, // Where to start looking in the src vector 4141 NumElems, // Number of elements in vector 4142 OpSrc)) // Which source operand ? 4143 return false; 4144 4145 isLeft = true; 4146 ShAmt = NumZeros; 4147 ShVal = SVOp->getOperand(OpSrc); 4148 return true; 4149} 4150 4151/// isVectorShift - Returns true if the shuffle can be implemented as a 4152/// logical left or right shift of a vector. 4153static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4154 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4155 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) || 4156 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt)) 4157 return true; 4158 4159 return false; 4160} 4161 4162/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8. 4163/// 4164static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros, 4165 unsigned NumNonZero, unsigned NumZero, 4166 SelectionDAG &DAG, 4167 const TargetLowering &TLI) { 4168 if (NumNonZero > 8) 4169 return SDValue(); 4170 4171 DebugLoc dl = Op.getDebugLoc(); 4172 SDValue V(0, 0); 4173 bool First = true; 4174 for (unsigned i = 0; i < 16; ++i) { 4175 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0; 4176 if (ThisIsNonZero && First) { 4177 if (NumZero) 4178 V = getZeroVector(MVT::v8i16, true, DAG, dl); 4179 else 4180 V = DAG.getUNDEF(MVT::v8i16); 4181 First = false; 4182 } 4183 4184 if ((i & 1) != 0) { 4185 SDValue ThisElt(0, 0), LastElt(0, 0); 4186 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0; 4187 if (LastIsNonZero) { 4188 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl, 4189 MVT::i16, Op.getOperand(i-1)); 4190 } 4191 if (ThisIsNonZero) { 4192 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i)); 4193 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16, 4194 ThisElt, DAG.getConstant(8, MVT::i8)); 4195 if (LastIsNonZero) 4196 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt); 4197 } else 4198 ThisElt = LastElt; 4199 4200 if (ThisElt.getNode()) 4201 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt, 4202 DAG.getIntPtrConstant(i/2)); 4203 } 4204 } 4205 4206 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V); 4207} 4208 4209/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16. 4210/// 4211static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros, 4212 unsigned NumNonZero, unsigned NumZero, 4213 SelectionDAG &DAG, 4214 const TargetLowering &TLI) { 4215 if (NumNonZero > 4) 4216 return SDValue(); 4217 4218 DebugLoc dl = Op.getDebugLoc(); 4219 SDValue V(0, 0); 4220 bool First = true; 4221 for (unsigned i = 0; i < 8; ++i) { 4222 bool isNonZero = (NonZeros & (1 << i)) != 0; 4223 if (isNonZero) { 4224 if (First) { 4225 if (NumZero) 4226 V = getZeroVector(MVT::v8i16, true, DAG, dl); 4227 else 4228 V = DAG.getUNDEF(MVT::v8i16); 4229 First = false; 4230 } 4231 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, 4232 MVT::v8i16, V, Op.getOperand(i), 4233 DAG.getIntPtrConstant(i)); 4234 } 4235 } 4236 4237 return V; 4238} 4239 4240/// getVShift - Return a vector logical shift node. 4241/// 4242static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, 4243 unsigned NumBits, SelectionDAG &DAG, 4244 const TargetLowering &TLI, DebugLoc dl) { 4245 EVT ShVT = MVT::v2i64; 4246 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL; 4247 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp); 4248 return DAG.getNode(ISD::BITCAST, dl, VT, 4249 DAG.getNode(Opc, dl, ShVT, SrcOp, 4250 DAG.getConstant(NumBits, 4251 TLI.getShiftAmountTy(SrcOp.getValueType())))); 4252} 4253 4254SDValue 4255X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl, 4256 SelectionDAG &DAG) const { 4257 4258 // Check if the scalar load can be widened into a vector load. And if 4259 // the address is "base + cst" see if the cst can be "absorbed" into 4260 // the shuffle mask. 4261 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) { 4262 SDValue Ptr = LD->getBasePtr(); 4263 if (!ISD::isNormalLoad(LD) || LD->isVolatile()) 4264 return SDValue(); 4265 EVT PVT = LD->getValueType(0); 4266 if (PVT != MVT::i32 && PVT != MVT::f32) 4267 return SDValue(); 4268 4269 int FI = -1; 4270 int64_t Offset = 0; 4271 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) { 4272 FI = FINode->getIndex(); 4273 Offset = 0; 4274 } else if (DAG.isBaseWithConstantOffset(Ptr) && 4275 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 4276 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 4277 Offset = Ptr.getConstantOperandVal(1); 4278 Ptr = Ptr.getOperand(0); 4279 } else { 4280 return SDValue(); 4281 } 4282 4283 SDValue Chain = LD->getChain(); 4284 // Make sure the stack object alignment is at least 16. 4285 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4286 if (DAG.InferPtrAlignment(Ptr) < 16) { 4287 if (MFI->isFixedObjectIndex(FI)) { 4288 // Can't change the alignment. FIXME: It's possible to compute 4289 // the exact stack offset and reference FI + adjust offset instead. 4290 // If someone *really* cares about this. That's the way to implement it. 4291 return SDValue(); 4292 } else { 4293 MFI->setObjectAlignment(FI, 16); 4294 } 4295 } 4296 4297 // (Offset % 16) must be multiple of 4. Then address is then 4298 // Ptr + (Offset & ~15). 4299 if (Offset < 0) 4300 return SDValue(); 4301 if ((Offset % 16) & 3) 4302 return SDValue(); 4303 int64_t StartOffset = Offset & ~15; 4304 if (StartOffset) 4305 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(), 4306 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType())); 4307 4308 int EltNo = (Offset - StartOffset) >> 2; 4309 int Mask[4] = { EltNo, EltNo, EltNo, EltNo }; 4310 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32; 4311 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr, 4312 LD->getPointerInfo().getWithOffset(StartOffset), 4313 false, false, 0); 4314 // Canonicalize it to a v4i32 shuffle. 4315 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 4316 return DAG.getNode(ISD::BITCAST, dl, VT, 4317 DAG.getVectorShuffle(MVT::v4i32, dl, V1, 4318 DAG.getUNDEF(MVT::v4i32),&Mask[0])); 4319 } 4320 4321 return SDValue(); 4322} 4323 4324/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 4325/// vector of type 'VT', see if the elements can be replaced by a single large 4326/// load which has the same value as a build_vector whose operands are 'elts'. 4327/// 4328/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a 4329/// 4330/// FIXME: we'd also like to handle the case where the last elements are zero 4331/// rather than undef via VZEXT_LOAD, but we do not detect that case today. 4332/// There's even a handy isZeroNode for that purpose. 4333static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts, 4334 DebugLoc &DL, SelectionDAG &DAG) { 4335 EVT EltVT = VT.getVectorElementType(); 4336 unsigned NumElems = Elts.size(); 4337 4338 LoadSDNode *LDBase = NULL; 4339 unsigned LastLoadedElt = -1U; 4340 4341 // For each element in the initializer, see if we've found a load or an undef. 4342 // If we don't find an initial load element, or later load elements are 4343 // non-consecutive, bail out. 4344 for (unsigned i = 0; i < NumElems; ++i) { 4345 SDValue Elt = Elts[i]; 4346 4347 if (!Elt.getNode() || 4348 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode()))) 4349 return SDValue(); 4350 if (!LDBase) { 4351 if (Elt.getNode()->getOpcode() == ISD::UNDEF) 4352 return SDValue(); 4353 LDBase = cast<LoadSDNode>(Elt.getNode()); 4354 LastLoadedElt = i; 4355 continue; 4356 } 4357 if (Elt.getOpcode() == ISD::UNDEF) 4358 continue; 4359 4360 LoadSDNode *LD = cast<LoadSDNode>(Elt); 4361 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i)) 4362 return SDValue(); 4363 LastLoadedElt = i; 4364 } 4365 4366 // If we have found an entire vector of loads and undefs, then return a large 4367 // load of the entire vector width starting at the base pointer. If we found 4368 // consecutive loads for the low half, generate a vzext_load node. 4369 if (LastLoadedElt == NumElems - 1) { 4370 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16) 4371 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 4372 LDBase->getPointerInfo(), 4373 LDBase->isVolatile(), LDBase->isNonTemporal(), 0); 4374 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 4375 LDBase->getPointerInfo(), 4376 LDBase->isVolatile(), LDBase->isNonTemporal(), 4377 LDBase->getAlignment()); 4378 } else if (NumElems == 4 && LastLoadedElt == 1) { 4379 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other); 4380 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() }; 4381 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, 4382 Ops, 2, MVT::i32, 4383 LDBase->getMemOperand()); 4384 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode); 4385 } 4386 return SDValue(); 4387} 4388 4389SDValue 4390X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const { 4391 DebugLoc dl = Op.getDebugLoc(); 4392 4393 EVT VT = Op.getValueType(); 4394 EVT ExtVT = VT.getVectorElementType(); 4395 4396 unsigned NumElems = Op.getNumOperands(); 4397 4398 // For AVX-length vectors, build the individual 128-bit pieces and 4399 // use shuffles to put them in place. 4400 if (VT.getSizeInBits() > 256 && 4401 Subtarget->hasAVX() && 4402 !ISD::isBuildVectorAllZeros(Op.getNode())) { 4403 SmallVector<SDValue, 8> V; 4404 V.resize(NumElems); 4405 for (unsigned i = 0; i < NumElems; ++i) { 4406 V[i] = Op.getOperand(i); 4407 } 4408 4409 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2); 4410 4411 // Build the lower subvector. 4412 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2); 4413 // Build the upper subvector. 4414 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2], 4415 NumElems/2); 4416 4417 return ConcatVectors(Lower, Upper, DAG); 4418 } 4419 4420 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1. 4421 // All one's are handled with pcmpeqd. In AVX, zero's are handled with 4422 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd 4423 // is present, so AllOnes is ignored. 4424 if (ISD::isBuildVectorAllZeros(Op.getNode()) || 4425 (Op.getValueType().getSizeInBits() != 256 && 4426 ISD::isBuildVectorAllOnes(Op.getNode()))) { 4427 // Canonicalize this to <4 x i32> (SSE) to 4428 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are 4429 // eliminated on x86-32 hosts. 4430 if (Op.getValueType() == MVT::v4i32) 4431 return Op; 4432 4433 if (ISD::isBuildVectorAllOnes(Op.getNode())) 4434 return getOnesVector(Op.getValueType(), DAG, dl); 4435 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl); 4436 } 4437 4438 unsigned EVTBits = ExtVT.getSizeInBits(); 4439 4440 unsigned NumZero = 0; 4441 unsigned NumNonZero = 0; 4442 unsigned NonZeros = 0; 4443 bool IsAllConstants = true; 4444 SmallSet<SDValue, 8> Values; 4445 for (unsigned i = 0; i < NumElems; ++i) { 4446 SDValue Elt = Op.getOperand(i); 4447 if (Elt.getOpcode() == ISD::UNDEF) 4448 continue; 4449 Values.insert(Elt); 4450 if (Elt.getOpcode() != ISD::Constant && 4451 Elt.getOpcode() != ISD::ConstantFP) 4452 IsAllConstants = false; 4453 if (X86::isZeroNode(Elt)) 4454 NumZero++; 4455 else { 4456 NonZeros |= (1 << i); 4457 NumNonZero++; 4458 } 4459 } 4460 4461 // All undef vector. Return an UNDEF. All zero vectors were handled above. 4462 if (NumNonZero == 0) 4463 return DAG.getUNDEF(VT); 4464 4465 // Special case for single non-zero, non-undef, element. 4466 if (NumNonZero == 1) { 4467 unsigned Idx = CountTrailingZeros_32(NonZeros); 4468 SDValue Item = Op.getOperand(Idx); 4469 4470 // If this is an insertion of an i64 value on x86-32, and if the top bits of 4471 // the value are obviously zero, truncate the value to i32 and do the 4472 // insertion that way. Only do this if the value is non-constant or if the 4473 // value is a constant being inserted into element 0. It is cheaper to do 4474 // a constant pool load than it is to do a movd + shuffle. 4475 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() && 4476 (!IsAllConstants || Idx == 0)) { 4477 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) { 4478 // Handle SSE only. 4479 assert(VT == MVT::v2i64 && "Expected an SSE value type!"); 4480 EVT VecVT = MVT::v4i32; 4481 unsigned VecElts = 4; 4482 4483 // Truncate the value (which may itself be a constant) to i32, and 4484 // convert it to a vector with movd (S2V+shuffle to zero extend). 4485 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item); 4486 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item); 4487 Item = getShuffleVectorZeroOrUndef(Item, 0, true, 4488 Subtarget->hasSSE2(), DAG); 4489 4490 // Now we have our 32-bit value zero extended in the low element of 4491 // a vector. If Idx != 0, swizzle it into place. 4492 if (Idx != 0) { 4493 SmallVector<int, 4> Mask; 4494 Mask.push_back(Idx); 4495 for (unsigned i = 1; i != VecElts; ++i) 4496 Mask.push_back(i); 4497 Item = DAG.getVectorShuffle(VecVT, dl, Item, 4498 DAG.getUNDEF(Item.getValueType()), 4499 &Mask[0]); 4500 } 4501 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item); 4502 } 4503 } 4504 4505 // If we have a constant or non-constant insertion into the low element of 4506 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into 4507 // the rest of the elements. This will be matched as movd/movq/movss/movsd 4508 // depending on what the source datatype is. 4509 if (Idx == 0) { 4510 if (NumZero == 0) { 4511 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 4512 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 || 4513 (ExtVT == MVT::i64 && Subtarget->is64Bit())) { 4514 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 4515 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector. 4516 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(), 4517 DAG); 4518 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) { 4519 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item); 4520 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!"); 4521 EVT MiddleVT = MVT::v4i32; 4522 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item); 4523 Item = getShuffleVectorZeroOrUndef(Item, 0, true, 4524 Subtarget->hasSSE2(), DAG); 4525 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 4526 } 4527 } 4528 4529 // Is it a vector logical left shift? 4530 if (NumElems == 2 && Idx == 1 && 4531 X86::isZeroNode(Op.getOperand(0)) && 4532 !X86::isZeroNode(Op.getOperand(1))) { 4533 unsigned NumBits = VT.getSizeInBits(); 4534 return getVShift(true, VT, 4535 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 4536 VT, Op.getOperand(1)), 4537 NumBits/2, DAG, *this, dl); 4538 } 4539 4540 if (IsAllConstants) // Otherwise, it's better to do a constpool load. 4541 return SDValue(); 4542 4543 // Otherwise, if this is a vector with i32 or f32 elements, and the element 4544 // is a non-constant being inserted into an element other than the low one, 4545 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka 4546 // movd/movss) to move this into the low element, then shuffle it into 4547 // place. 4548 if (EVTBits == 32) { 4549 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 4550 4551 // Turn it into a shuffle of zero and zero-extended scalar to vector. 4552 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, 4553 Subtarget->hasSSE2(), DAG); 4554 SmallVector<int, 8> MaskVec; 4555 for (unsigned i = 0; i < NumElems; i++) 4556 MaskVec.push_back(i == Idx ? 0 : 1); 4557 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]); 4558 } 4559 } 4560 4561 // Splat is obviously ok. Let legalizer expand it to a shuffle. 4562 if (Values.size() == 1) { 4563 if (EVTBits == 32) { 4564 // Instead of a shuffle like this: 4565 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0> 4566 // Check if it's possible to issue this instead. 4567 // shuffle (vload ptr)), undef, <1, 1, 1, 1> 4568 unsigned Idx = CountTrailingZeros_32(NonZeros); 4569 SDValue Item = Op.getOperand(Idx); 4570 if (Op.getNode()->isOnlyUserOf(Item.getNode())) 4571 return LowerAsSplatVectorLoad(Item, VT, dl, DAG); 4572 } 4573 return SDValue(); 4574 } 4575 4576 // A vector full of immediates; various special cases are already 4577 // handled, so this is best done with a single constant-pool load. 4578 if (IsAllConstants) 4579 return SDValue(); 4580 4581 // Let legalizer expand 2-wide build_vectors. 4582 if (EVTBits == 64) { 4583 if (NumNonZero == 1) { 4584 // One half is zero or undef. 4585 unsigned Idx = CountTrailingZeros_32(NonZeros); 4586 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, 4587 Op.getOperand(Idx)); 4588 return getShuffleVectorZeroOrUndef(V2, Idx, true, 4589 Subtarget->hasSSE2(), DAG); 4590 } 4591 return SDValue(); 4592 } 4593 4594 // If element VT is < 32 bits, convert it to inserts into a zero vector. 4595 if (EVTBits == 8 && NumElems == 16) { 4596 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG, 4597 *this); 4598 if (V.getNode()) return V; 4599 } 4600 4601 if (EVTBits == 16 && NumElems == 8) { 4602 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG, 4603 *this); 4604 if (V.getNode()) return V; 4605 } 4606 4607 // If element VT is == 32 bits, turn it into a number of shuffles. 4608 SmallVector<SDValue, 8> V; 4609 V.resize(NumElems); 4610 if (NumElems == 4 && NumZero > 0) { 4611 for (unsigned i = 0; i < 4; ++i) { 4612 bool isZero = !(NonZeros & (1 << i)); 4613 if (isZero) 4614 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl); 4615 else 4616 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 4617 } 4618 4619 for (unsigned i = 0; i < 2; ++i) { 4620 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) { 4621 default: break; 4622 case 0: 4623 V[i] = V[i*2]; // Must be a zero vector. 4624 break; 4625 case 1: 4626 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]); 4627 break; 4628 case 2: 4629 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]); 4630 break; 4631 case 3: 4632 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]); 4633 break; 4634 } 4635 } 4636 4637 SmallVector<int, 8> MaskVec; 4638 bool Reverse = (NonZeros & 0x3) == 2; 4639 for (unsigned i = 0; i < 2; ++i) 4640 MaskVec.push_back(Reverse ? 1-i : i); 4641 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2; 4642 for (unsigned i = 0; i < 2; ++i) 4643 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems); 4644 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]); 4645 } 4646 4647 if (Values.size() > 1 && VT.getSizeInBits() == 128) { 4648 // Check for a build vector of consecutive loads. 4649 for (unsigned i = 0; i < NumElems; ++i) 4650 V[i] = Op.getOperand(i); 4651 4652 // Check for elements which are consecutive loads. 4653 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG); 4654 if (LD.getNode()) 4655 return LD; 4656 4657 // For SSE 4.1, use insertps to put the high elements into the low element. 4658 if (getSubtarget()->hasSSE41()) { 4659 SDValue Result; 4660 if (Op.getOperand(0).getOpcode() != ISD::UNDEF) 4661 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0)); 4662 else 4663 Result = DAG.getUNDEF(VT); 4664 4665 for (unsigned i = 1; i < NumElems; ++i) { 4666 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue; 4667 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result, 4668 Op.getOperand(i), DAG.getIntPtrConstant(i)); 4669 } 4670 return Result; 4671 } 4672 4673 // Otherwise, expand into a number of unpckl*, start by extending each of 4674 // our (non-undef) elements to the full vector width with the element in the 4675 // bottom slot of the vector (which generates no code for SSE). 4676 for (unsigned i = 0; i < NumElems; ++i) { 4677 if (Op.getOperand(i).getOpcode() != ISD::UNDEF) 4678 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 4679 else 4680 V[i] = DAG.getUNDEF(VT); 4681 } 4682 4683 // Next, we iteratively mix elements, e.g. for v4f32: 4684 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0> 4685 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1> 4686 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0> 4687 unsigned EltStride = NumElems >> 1; 4688 while (EltStride != 0) { 4689 for (unsigned i = 0; i < EltStride; ++i) { 4690 // If V[i+EltStride] is undef and this is the first round of mixing, 4691 // then it is safe to just drop this shuffle: V[i] is already in the 4692 // right place, the one element (since it's the first round) being 4693 // inserted as undef can be dropped. This isn't safe for successive 4694 // rounds because they will permute elements within both vectors. 4695 if (V[i+EltStride].getOpcode() == ISD::UNDEF && 4696 EltStride == NumElems/2) 4697 continue; 4698 4699 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]); 4700 } 4701 EltStride >>= 1; 4702 } 4703 return V[0]; 4704 } 4705 return SDValue(); 4706} 4707 4708SDValue 4709X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const { 4710 // We support concatenate two MMX registers and place them in a MMX 4711 // register. This is better than doing a stack convert. 4712 DebugLoc dl = Op.getDebugLoc(); 4713 EVT ResVT = Op.getValueType(); 4714 assert(Op.getNumOperands() == 2); 4715 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 || 4716 ResVT == MVT::v8i16 || ResVT == MVT::v16i8); 4717 int Mask[2]; 4718 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0)); 4719 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 4720 InVec = Op.getOperand(1); 4721 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 4722 unsigned NumElts = ResVT.getVectorNumElements(); 4723 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 4724 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp, 4725 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1)); 4726 } else { 4727 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec); 4728 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 4729 Mask[0] = 0; Mask[1] = 2; 4730 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask); 4731 } 4732 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 4733} 4734 4735// v8i16 shuffles - Prefer shuffles in the following order: 4736// 1. [all] pshuflw, pshufhw, optional move 4737// 2. [ssse3] 1 x pshufb 4738// 3. [ssse3] 2 x pshufb + 1 x por 4739// 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw) 4740SDValue 4741X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op, 4742 SelectionDAG &DAG) const { 4743 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 4744 SDValue V1 = SVOp->getOperand(0); 4745 SDValue V2 = SVOp->getOperand(1); 4746 DebugLoc dl = SVOp->getDebugLoc(); 4747 SmallVector<int, 8> MaskVals; 4748 4749 // Determine if more than 1 of the words in each of the low and high quadwords 4750 // of the result come from the same quadword of one of the two inputs. Undef 4751 // mask values count as coming from any quadword, for better codegen. 4752 SmallVector<unsigned, 4> LoQuad(4); 4753 SmallVector<unsigned, 4> HiQuad(4); 4754 BitVector InputQuads(4); 4755 for (unsigned i = 0; i < 8; ++i) { 4756 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad; 4757 int EltIdx = SVOp->getMaskElt(i); 4758 MaskVals.push_back(EltIdx); 4759 if (EltIdx < 0) { 4760 ++Quad[0]; 4761 ++Quad[1]; 4762 ++Quad[2]; 4763 ++Quad[3]; 4764 continue; 4765 } 4766 ++Quad[EltIdx / 4]; 4767 InputQuads.set(EltIdx / 4); 4768 } 4769 4770 int BestLoQuad = -1; 4771 unsigned MaxQuad = 1; 4772 for (unsigned i = 0; i < 4; ++i) { 4773 if (LoQuad[i] > MaxQuad) { 4774 BestLoQuad = i; 4775 MaxQuad = LoQuad[i]; 4776 } 4777 } 4778 4779 int BestHiQuad = -1; 4780 MaxQuad = 1; 4781 for (unsigned i = 0; i < 4; ++i) { 4782 if (HiQuad[i] > MaxQuad) { 4783 BestHiQuad = i; 4784 MaxQuad = HiQuad[i]; 4785 } 4786 } 4787 4788 // For SSSE3, If all 8 words of the result come from only 1 quadword of each 4789 // of the two input vectors, shuffle them into one input vector so only a 4790 // single pshufb instruction is necessary. If There are more than 2 input 4791 // quads, disable the next transformation since it does not help SSSE3. 4792 bool V1Used = InputQuads[0] || InputQuads[1]; 4793 bool V2Used = InputQuads[2] || InputQuads[3]; 4794 if (Subtarget->hasSSSE3()) { 4795 if (InputQuads.count() == 2 && V1Used && V2Used) { 4796 BestLoQuad = InputQuads.find_first(); 4797 BestHiQuad = InputQuads.find_next(BestLoQuad); 4798 } 4799 if (InputQuads.count() > 2) { 4800 BestLoQuad = -1; 4801 BestHiQuad = -1; 4802 } 4803 } 4804 4805 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update 4806 // the shuffle mask. If a quad is scored as -1, that means that it contains 4807 // words from all 4 input quadwords. 4808 SDValue NewV; 4809 if (BestLoQuad >= 0 || BestHiQuad >= 0) { 4810 SmallVector<int, 8> MaskV; 4811 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad); 4812 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad); 4813 NewV = DAG.getVectorShuffle(MVT::v2i64, dl, 4814 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1), 4815 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]); 4816 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV); 4817 4818 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the 4819 // source words for the shuffle, to aid later transformations. 4820 bool AllWordsInNewV = true; 4821 bool InOrder[2] = { true, true }; 4822 for (unsigned i = 0; i != 8; ++i) { 4823 int idx = MaskVals[i]; 4824 if (idx != (int)i) 4825 InOrder[i/4] = false; 4826 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad) 4827 continue; 4828 AllWordsInNewV = false; 4829 break; 4830 } 4831 4832 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV; 4833 if (AllWordsInNewV) { 4834 for (int i = 0; i != 8; ++i) { 4835 int idx = MaskVals[i]; 4836 if (idx < 0) 4837 continue; 4838 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4; 4839 if ((idx != i) && idx < 4) 4840 pshufhw = false; 4841 if ((idx != i) && idx > 3) 4842 pshuflw = false; 4843 } 4844 V1 = NewV; 4845 V2Used = false; 4846 BestLoQuad = 0; 4847 BestHiQuad = 1; 4848 } 4849 4850 // If we've eliminated the use of V2, and the new mask is a pshuflw or 4851 // pshufhw, that's as cheap as it gets. Return the new shuffle. 4852 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) { 4853 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW; 4854 unsigned TargetMask = 0; 4855 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, 4856 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]); 4857 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()): 4858 X86::getShufflePSHUFLWImmediate(NewV.getNode()); 4859 V1 = NewV.getOperand(0); 4860 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG); 4861 } 4862 } 4863 4864 // If we have SSSE3, and all words of the result are from 1 input vector, 4865 // case 2 is generated, otherwise case 3 is generated. If no SSSE3 4866 // is present, fall back to case 4. 4867 if (Subtarget->hasSSSE3()) { 4868 SmallVector<SDValue,16> pshufbMask; 4869 4870 // If we have elements from both input vectors, set the high bit of the 4871 // shuffle mask element to zero out elements that come from V2 in the V1 4872 // mask, and elements that come from V1 in the V2 mask, so that the two 4873 // results can be OR'd together. 4874 bool TwoInputs = V1Used && V2Used; 4875 for (unsigned i = 0; i != 8; ++i) { 4876 int EltIdx = MaskVals[i] * 2; 4877 if (TwoInputs && (EltIdx >= 16)) { 4878 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 4879 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 4880 continue; 4881 } 4882 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 4883 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8)); 4884 } 4885 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1); 4886 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 4887 DAG.getNode(ISD::BUILD_VECTOR, dl, 4888 MVT::v16i8, &pshufbMask[0], 16)); 4889 if (!TwoInputs) 4890 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 4891 4892 // Calculate the shuffle mask for the second input, shuffle it, and 4893 // OR it with the first shuffled input. 4894 pshufbMask.clear(); 4895 for (unsigned i = 0; i != 8; ++i) { 4896 int EltIdx = MaskVals[i] * 2; 4897 if (EltIdx < 16) { 4898 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 4899 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 4900 continue; 4901 } 4902 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8)); 4903 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8)); 4904 } 4905 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2); 4906 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 4907 DAG.getNode(ISD::BUILD_VECTOR, dl, 4908 MVT::v16i8, &pshufbMask[0], 16)); 4909 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 4910 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 4911 } 4912 4913 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order, 4914 // and update MaskVals with new element order. 4915 BitVector InOrder(8); 4916 if (BestLoQuad >= 0) { 4917 SmallVector<int, 8> MaskV; 4918 for (int i = 0; i != 4; ++i) { 4919 int idx = MaskVals[i]; 4920 if (idx < 0) { 4921 MaskV.push_back(-1); 4922 InOrder.set(i); 4923 } else if ((idx / 4) == BestLoQuad) { 4924 MaskV.push_back(idx & 3); 4925 InOrder.set(i); 4926 } else { 4927 MaskV.push_back(-1); 4928 } 4929 } 4930 for (unsigned i = 4; i != 8; ++i) 4931 MaskV.push_back(i); 4932 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 4933 &MaskV[0]); 4934 4935 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) 4936 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16, 4937 NewV.getOperand(0), 4938 X86::getShufflePSHUFLWImmediate(NewV.getNode()), 4939 DAG); 4940 } 4941 4942 // If BestHi >= 0, generate a pshufhw to put the high elements in order, 4943 // and update MaskVals with the new element order. 4944 if (BestHiQuad >= 0) { 4945 SmallVector<int, 8> MaskV; 4946 for (unsigned i = 0; i != 4; ++i) 4947 MaskV.push_back(i); 4948 for (unsigned i = 4; i != 8; ++i) { 4949 int idx = MaskVals[i]; 4950 if (idx < 0) { 4951 MaskV.push_back(-1); 4952 InOrder.set(i); 4953 } else if ((idx / 4) == BestHiQuad) { 4954 MaskV.push_back((idx & 3) + 4); 4955 InOrder.set(i); 4956 } else { 4957 MaskV.push_back(-1); 4958 } 4959 } 4960 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 4961 &MaskV[0]); 4962 4963 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) 4964 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16, 4965 NewV.getOperand(0), 4966 X86::getShufflePSHUFHWImmediate(NewV.getNode()), 4967 DAG); 4968 } 4969 4970 // In case BestHi & BestLo were both -1, which means each quadword has a word 4971 // from each of the four input quadwords, calculate the InOrder bitvector now 4972 // before falling through to the insert/extract cleanup. 4973 if (BestLoQuad == -1 && BestHiQuad == -1) { 4974 NewV = V1; 4975 for (int i = 0; i != 8; ++i) 4976 if (MaskVals[i] < 0 || MaskVals[i] == i) 4977 InOrder.set(i); 4978 } 4979 4980 // The other elements are put in the right place using pextrw and pinsrw. 4981 for (unsigned i = 0; i != 8; ++i) { 4982 if (InOrder[i]) 4983 continue; 4984 int EltIdx = MaskVals[i]; 4985 if (EltIdx < 0) 4986 continue; 4987 SDValue ExtOp = (EltIdx < 8) 4988 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1, 4989 DAG.getIntPtrConstant(EltIdx)) 4990 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2, 4991 DAG.getIntPtrConstant(EltIdx - 8)); 4992 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp, 4993 DAG.getIntPtrConstant(i)); 4994 } 4995 return NewV; 4996} 4997 4998// v16i8 shuffles - Prefer shuffles in the following order: 4999// 1. [ssse3] 1 x pshufb 5000// 2. [ssse3] 2 x pshufb + 1 x por 5001// 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw 5002static 5003SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp, 5004 SelectionDAG &DAG, 5005 const X86TargetLowering &TLI) { 5006 SDValue V1 = SVOp->getOperand(0); 5007 SDValue V2 = SVOp->getOperand(1); 5008 DebugLoc dl = SVOp->getDebugLoc(); 5009 SmallVector<int, 16> MaskVals; 5010 SVOp->getMask(MaskVals); 5011 5012 // If we have SSSE3, case 1 is generated when all result bytes come from 5013 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is 5014 // present, fall back to case 3. 5015 // FIXME: kill V2Only once shuffles are canonizalized by getNode. 5016 bool V1Only = true; 5017 bool V2Only = true; 5018 for (unsigned i = 0; i < 16; ++i) { 5019 int EltIdx = MaskVals[i]; 5020 if (EltIdx < 0) 5021 continue; 5022 if (EltIdx < 16) 5023 V2Only = false; 5024 else 5025 V1Only = false; 5026 } 5027 5028 // If SSSE3, use 1 pshufb instruction per vector with elements in the result. 5029 if (TLI.getSubtarget()->hasSSSE3()) { 5030 SmallVector<SDValue,16> pshufbMask; 5031 5032 // If all result elements are from one input vector, then only translate 5033 // undef mask values to 0x80 (zero out result) in the pshufb mask. 5034 // 5035 // Otherwise, we have elements from both input vectors, and must zero out 5036 // elements that come from V2 in the first mask, and V1 in the second mask 5037 // so that we can OR them together. 5038 bool TwoInputs = !(V1Only || V2Only); 5039 for (unsigned i = 0; i != 16; ++i) { 5040 int EltIdx = MaskVals[i]; 5041 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) { 5042 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5043 continue; 5044 } 5045 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 5046 } 5047 // If all the elements are from V2, assign it to V1 and return after 5048 // building the first pshufb. 5049 if (V2Only) 5050 V1 = V2; 5051 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 5052 DAG.getNode(ISD::BUILD_VECTOR, dl, 5053 MVT::v16i8, &pshufbMask[0], 16)); 5054 if (!TwoInputs) 5055 return V1; 5056 5057 // Calculate the shuffle mask for the second input, shuffle it, and 5058 // OR it with the first shuffled input. 5059 pshufbMask.clear(); 5060 for (unsigned i = 0; i != 16; ++i) { 5061 int EltIdx = MaskVals[i]; 5062 if (EltIdx < 16) { 5063 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5064 continue; 5065 } 5066 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8)); 5067 } 5068 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 5069 DAG.getNode(ISD::BUILD_VECTOR, dl, 5070 MVT::v16i8, &pshufbMask[0], 16)); 5071 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 5072 } 5073 5074 // No SSSE3 - Calculate in place words and then fix all out of place words 5075 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from 5076 // the 16 different words that comprise the two doublequadword input vectors. 5077 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5078 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 5079 SDValue NewV = V2Only ? V2 : V1; 5080 for (int i = 0; i != 8; ++i) { 5081 int Elt0 = MaskVals[i*2]; 5082 int Elt1 = MaskVals[i*2+1]; 5083 5084 // This word of the result is all undef, skip it. 5085 if (Elt0 < 0 && Elt1 < 0) 5086 continue; 5087 5088 // This word of the result is already in the correct place, skip it. 5089 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1)) 5090 continue; 5091 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17)) 5092 continue; 5093 5094 SDValue Elt0Src = Elt0 < 16 ? V1 : V2; 5095 SDValue Elt1Src = Elt1 < 16 ? V1 : V2; 5096 SDValue InsElt; 5097 5098 // If Elt0 and Elt1 are defined, are consecutive, and can be load 5099 // using a single extract together, load it and store it. 5100 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) { 5101 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5102 DAG.getIntPtrConstant(Elt1 / 2)); 5103 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5104 DAG.getIntPtrConstant(i)); 5105 continue; 5106 } 5107 5108 // If Elt1 is defined, extract it from the appropriate source. If the 5109 // source byte is not also odd, shift the extracted word left 8 bits 5110 // otherwise clear the bottom 8 bits if we need to do an or. 5111 if (Elt1 >= 0) { 5112 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5113 DAG.getIntPtrConstant(Elt1 / 2)); 5114 if ((Elt1 & 1) == 0) 5115 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt, 5116 DAG.getConstant(8, 5117 TLI.getShiftAmountTy(InsElt.getValueType()))); 5118 else if (Elt0 >= 0) 5119 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt, 5120 DAG.getConstant(0xFF00, MVT::i16)); 5121 } 5122 // If Elt0 is defined, extract it from the appropriate source. If the 5123 // source byte is not also even, shift the extracted word right 8 bits. If 5124 // Elt1 was also defined, OR the extracted values together before 5125 // inserting them in the result. 5126 if (Elt0 >= 0) { 5127 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, 5128 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2)); 5129 if ((Elt0 & 1) != 0) 5130 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0, 5131 DAG.getConstant(8, 5132 TLI.getShiftAmountTy(InsElt0.getValueType()))); 5133 else if (Elt1 >= 0) 5134 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0, 5135 DAG.getConstant(0x00FF, MVT::i16)); 5136 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0) 5137 : InsElt0; 5138 } 5139 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5140 DAG.getIntPtrConstant(i)); 5141 } 5142 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV); 5143} 5144 5145/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide 5146/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be 5147/// done when every pair / quad of shuffle mask elements point to elements in 5148/// the right sequence. e.g. 5149/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15> 5150static 5151SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp, 5152 SelectionDAG &DAG, DebugLoc dl) { 5153 EVT VT = SVOp->getValueType(0); 5154 SDValue V1 = SVOp->getOperand(0); 5155 SDValue V2 = SVOp->getOperand(1); 5156 unsigned NumElems = VT.getVectorNumElements(); 5157 unsigned NewWidth = (NumElems == 4) ? 2 : 4; 5158 EVT NewVT; 5159 switch (VT.getSimpleVT().SimpleTy) { 5160 default: assert(false && "Unexpected!"); 5161 case MVT::v4f32: NewVT = MVT::v2f64; break; 5162 case MVT::v4i32: NewVT = MVT::v2i64; break; 5163 case MVT::v8i16: NewVT = MVT::v4i32; break; 5164 case MVT::v16i8: NewVT = MVT::v4i32; break; 5165 } 5166 5167 int Scale = NumElems / NewWidth; 5168 SmallVector<int, 8> MaskVec; 5169 for (unsigned i = 0; i < NumElems; i += Scale) { 5170 int StartIdx = -1; 5171 for (int j = 0; j < Scale; ++j) { 5172 int EltIdx = SVOp->getMaskElt(i+j); 5173 if (EltIdx < 0) 5174 continue; 5175 if (StartIdx == -1) 5176 StartIdx = EltIdx - (EltIdx % Scale); 5177 if (EltIdx != StartIdx + j) 5178 return SDValue(); 5179 } 5180 if (StartIdx == -1) 5181 MaskVec.push_back(-1); 5182 else 5183 MaskVec.push_back(StartIdx / Scale); 5184 } 5185 5186 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1); 5187 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2); 5188 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]); 5189} 5190 5191/// getVZextMovL - Return a zero-extending vector move low node. 5192/// 5193static SDValue getVZextMovL(EVT VT, EVT OpVT, 5194 SDValue SrcOp, SelectionDAG &DAG, 5195 const X86Subtarget *Subtarget, DebugLoc dl) { 5196 if (VT == MVT::v2f64 || VT == MVT::v4f32) { 5197 LoadSDNode *LD = NULL; 5198 if (!isScalarLoadToVector(SrcOp.getNode(), &LD)) 5199 LD = dyn_cast<LoadSDNode>(SrcOp); 5200 if (!LD) { 5201 // movssrr and movsdrr do not clear top bits. Try to use movd, movq 5202 // instead. 5203 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32; 5204 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) && 5205 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR && 5206 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST && 5207 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) { 5208 // PR2108 5209 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32; 5210 return DAG.getNode(ISD::BITCAST, dl, VT, 5211 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 5212 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 5213 OpVT, 5214 SrcOp.getOperand(0) 5215 .getOperand(0)))); 5216 } 5217 } 5218 } 5219 5220 return DAG.getNode(ISD::BITCAST, dl, VT, 5221 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 5222 DAG.getNode(ISD::BITCAST, dl, 5223 OpVT, SrcOp))); 5224} 5225 5226/// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of 5227/// shuffles. 5228static SDValue 5229LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 5230 SDValue V1 = SVOp->getOperand(0); 5231 SDValue V2 = SVOp->getOperand(1); 5232 DebugLoc dl = SVOp->getDebugLoc(); 5233 EVT VT = SVOp->getValueType(0); 5234 5235 SmallVector<std::pair<int, int>, 8> Locs; 5236 Locs.resize(4); 5237 SmallVector<int, 8> Mask1(4U, -1); 5238 SmallVector<int, 8> PermMask; 5239 SVOp->getMask(PermMask); 5240 5241 unsigned NumHi = 0; 5242 unsigned NumLo = 0; 5243 for (unsigned i = 0; i != 4; ++i) { 5244 int Idx = PermMask[i]; 5245 if (Idx < 0) { 5246 Locs[i] = std::make_pair(-1, -1); 5247 } else { 5248 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!"); 5249 if (Idx < 4) { 5250 Locs[i] = std::make_pair(0, NumLo); 5251 Mask1[NumLo] = Idx; 5252 NumLo++; 5253 } else { 5254 Locs[i] = std::make_pair(1, NumHi); 5255 if (2+NumHi < 4) 5256 Mask1[2+NumHi] = Idx; 5257 NumHi++; 5258 } 5259 } 5260 } 5261 5262 if (NumLo <= 2 && NumHi <= 2) { 5263 // If no more than two elements come from either vector. This can be 5264 // implemented with two shuffles. First shuffle gather the elements. 5265 // The second shuffle, which takes the first shuffle as both of its 5266 // vector operands, put the elements into the right order. 5267 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 5268 5269 SmallVector<int, 8> Mask2(4U, -1); 5270 5271 for (unsigned i = 0; i != 4; ++i) { 5272 if (Locs[i].first == -1) 5273 continue; 5274 else { 5275 unsigned Idx = (i < 2) ? 0 : 4; 5276 Idx += Locs[i].first * 2 + Locs[i].second; 5277 Mask2[i] = Idx; 5278 } 5279 } 5280 5281 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]); 5282 } else if (NumLo == 3 || NumHi == 3) { 5283 // Otherwise, we must have three elements from one vector, call it X, and 5284 // one element from the other, call it Y. First, use a shufps to build an 5285 // intermediate vector with the one element from Y and the element from X 5286 // that will be in the same half in the final destination (the indexes don't 5287 // matter). Then, use a shufps to build the final vector, taking the half 5288 // containing the element from Y from the intermediate, and the other half 5289 // from X. 5290 if (NumHi == 3) { 5291 // Normalize it so the 3 elements come from V1. 5292 CommuteVectorShuffleMask(PermMask, VT); 5293 std::swap(V1, V2); 5294 } 5295 5296 // Find the element from V2. 5297 unsigned HiIndex; 5298 for (HiIndex = 0; HiIndex < 3; ++HiIndex) { 5299 int Val = PermMask[HiIndex]; 5300 if (Val < 0) 5301 continue; 5302 if (Val >= 4) 5303 break; 5304 } 5305 5306 Mask1[0] = PermMask[HiIndex]; 5307 Mask1[1] = -1; 5308 Mask1[2] = PermMask[HiIndex^1]; 5309 Mask1[3] = -1; 5310 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 5311 5312 if (HiIndex >= 2) { 5313 Mask1[0] = PermMask[0]; 5314 Mask1[1] = PermMask[1]; 5315 Mask1[2] = HiIndex & 1 ? 6 : 4; 5316 Mask1[3] = HiIndex & 1 ? 4 : 6; 5317 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 5318 } else { 5319 Mask1[0] = HiIndex & 1 ? 2 : 0; 5320 Mask1[1] = HiIndex & 1 ? 0 : 2; 5321 Mask1[2] = PermMask[2]; 5322 Mask1[3] = PermMask[3]; 5323 if (Mask1[2] >= 0) 5324 Mask1[2] += 4; 5325 if (Mask1[3] >= 0) 5326 Mask1[3] += 4; 5327 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]); 5328 } 5329 } 5330 5331 // Break it into (shuffle shuffle_hi, shuffle_lo). 5332 Locs.clear(); 5333 Locs.resize(4); 5334 SmallVector<int,8> LoMask(4U, -1); 5335 SmallVector<int,8> HiMask(4U, -1); 5336 5337 SmallVector<int,8> *MaskPtr = &LoMask; 5338 unsigned MaskIdx = 0; 5339 unsigned LoIdx = 0; 5340 unsigned HiIdx = 2; 5341 for (unsigned i = 0; i != 4; ++i) { 5342 if (i == 2) { 5343 MaskPtr = &HiMask; 5344 MaskIdx = 1; 5345 LoIdx = 0; 5346 HiIdx = 2; 5347 } 5348 int Idx = PermMask[i]; 5349 if (Idx < 0) { 5350 Locs[i] = std::make_pair(-1, -1); 5351 } else if (Idx < 4) { 5352 Locs[i] = std::make_pair(MaskIdx, LoIdx); 5353 (*MaskPtr)[LoIdx] = Idx; 5354 LoIdx++; 5355 } else { 5356 Locs[i] = std::make_pair(MaskIdx, HiIdx); 5357 (*MaskPtr)[HiIdx] = Idx; 5358 HiIdx++; 5359 } 5360 } 5361 5362 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]); 5363 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]); 5364 SmallVector<int, 8> MaskOps; 5365 for (unsigned i = 0; i != 4; ++i) { 5366 if (Locs[i].first == -1) { 5367 MaskOps.push_back(-1); 5368 } else { 5369 unsigned Idx = Locs[i].first * 4 + Locs[i].second; 5370 MaskOps.push_back(Idx); 5371 } 5372 } 5373 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]); 5374} 5375 5376static bool MayFoldVectorLoad(SDValue V) { 5377 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 5378 V = V.getOperand(0); 5379 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 5380 V = V.getOperand(0); 5381 if (MayFoldLoad(V)) 5382 return true; 5383 return false; 5384} 5385 5386// FIXME: the version above should always be used. Since there's 5387// a bug where several vector shuffles can't be folded because the 5388// DAG is not updated during lowering and a node claims to have two 5389// uses while it only has one, use this version, and let isel match 5390// another instruction if the load really happens to have more than 5391// one use. Remove this version after this bug get fixed. 5392// rdar://8434668, PR8156 5393static bool RelaxedMayFoldVectorLoad(SDValue V) { 5394 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 5395 V = V.getOperand(0); 5396 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 5397 V = V.getOperand(0); 5398 if (ISD::isNormalLoad(V.getNode())) 5399 return true; 5400 return false; 5401} 5402 5403/// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by 5404/// a vector extract, and if both can be later optimized into a single load. 5405/// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked 5406/// here because otherwise a target specific shuffle node is going to be 5407/// emitted for this shuffle, and the optimization not done. 5408/// FIXME: This is probably not the best approach, but fix the problem 5409/// until the right path is decided. 5410static 5411bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG, 5412 const TargetLowering &TLI) { 5413 EVT VT = V.getValueType(); 5414 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V); 5415 5416 // Be sure that the vector shuffle is present in a pattern like this: 5417 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr) 5418 if (!V.hasOneUse()) 5419 return false; 5420 5421 SDNode *N = *V.getNode()->use_begin(); 5422 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 5423 return false; 5424 5425 SDValue EltNo = N->getOperand(1); 5426 if (!isa<ConstantSDNode>(EltNo)) 5427 return false; 5428 5429 // If the bit convert changed the number of elements, it is unsafe 5430 // to examine the mask. 5431 bool HasShuffleIntoBitcast = false; 5432 if (V.getOpcode() == ISD::BITCAST) { 5433 EVT SrcVT = V.getOperand(0).getValueType(); 5434 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements()) 5435 return false; 5436 V = V.getOperand(0); 5437 HasShuffleIntoBitcast = true; 5438 } 5439 5440 // Select the input vector, guarding against out of range extract vector. 5441 unsigned NumElems = VT.getVectorNumElements(); 5442 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 5443 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt); 5444 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1); 5445 5446 // Skip one more bit_convert if necessary 5447 if (V.getOpcode() == ISD::BITCAST) 5448 V = V.getOperand(0); 5449 5450 if (ISD::isNormalLoad(V.getNode())) { 5451 // Is the original load suitable? 5452 LoadSDNode *LN0 = cast<LoadSDNode>(V); 5453 5454 // FIXME: avoid the multi-use bug that is preventing lots of 5455 // of foldings to be detected, this is still wrong of course, but 5456 // give the temporary desired behavior, and if it happens that 5457 // the load has real more uses, during isel it will not fold, and 5458 // will generate poor code. 5459 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse() 5460 return false; 5461 5462 if (!HasShuffleIntoBitcast) 5463 return true; 5464 5465 // If there's a bitcast before the shuffle, check if the load type and 5466 // alignment is valid. 5467 unsigned Align = LN0->getAlignment(); 5468 unsigned NewAlign = 5469 TLI.getTargetData()->getABITypeAlignment( 5470 VT.getTypeForEVT(*DAG.getContext())); 5471 5472 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT)) 5473 return false; 5474 } 5475 5476 return true; 5477} 5478 5479static 5480SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) { 5481 EVT VT = Op.getValueType(); 5482 5483 // Canonizalize to v2f64. 5484 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 5485 return DAG.getNode(ISD::BITCAST, dl, VT, 5486 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64, 5487 V1, DAG)); 5488} 5489 5490static 5491SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, 5492 bool HasSSE2) { 5493 SDValue V1 = Op.getOperand(0); 5494 SDValue V2 = Op.getOperand(1); 5495 EVT VT = Op.getValueType(); 5496 5497 assert(VT != MVT::v2i64 && "unsupported shuffle type"); 5498 5499 if (HasSSE2 && VT == MVT::v2f64) 5500 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG); 5501 5502 // v4f32 or v4i32 5503 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG); 5504} 5505 5506static 5507SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) { 5508 SDValue V1 = Op.getOperand(0); 5509 SDValue V2 = Op.getOperand(1); 5510 EVT VT = Op.getValueType(); 5511 5512 assert((VT == MVT::v4i32 || VT == MVT::v4f32) && 5513 "unsupported shuffle type"); 5514 5515 if (V2.getOpcode() == ISD::UNDEF) 5516 V2 = V1; 5517 5518 // v4i32 or v4f32 5519 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG); 5520} 5521 5522static 5523SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) { 5524 SDValue V1 = Op.getOperand(0); 5525 SDValue V2 = Op.getOperand(1); 5526 EVT VT = Op.getValueType(); 5527 unsigned NumElems = VT.getVectorNumElements(); 5528 5529 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second 5530 // operand of these instructions is only memory, so check if there's a 5531 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the 5532 // same masks. 5533 bool CanFoldLoad = false; 5534 5535 // Trivial case, when V2 comes from a load. 5536 if (MayFoldVectorLoad(V2)) 5537 CanFoldLoad = true; 5538 5539 // When V1 is a load, it can be folded later into a store in isel, example: 5540 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1) 5541 // turns into: 5542 // (MOVLPSmr addr:$src1, VR128:$src2) 5543 // So, recognize this potential and also use MOVLPS or MOVLPD 5544 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op)) 5545 CanFoldLoad = true; 5546 5547 // Both of them can't be memory operations though. 5548 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2)) 5549 CanFoldLoad = false; 5550 5551 if (CanFoldLoad) { 5552 if (HasSSE2 && NumElems == 2) 5553 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG); 5554 5555 if (NumElems == 4) 5556 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG); 5557 } 5558 5559 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5560 // movl and movlp will both match v2i64, but v2i64 is never matched by 5561 // movl earlier because we make it strict to avoid messing with the movlp load 5562 // folding logic (see the code above getMOVLP call). Match it here then, 5563 // this is horrible, but will stay like this until we move all shuffle 5564 // matching to x86 specific nodes. Note that for the 1st condition all 5565 // types are matched with movsd. 5566 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp)) 5567 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 5568 else if (HasSSE2) 5569 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 5570 5571 5572 assert(VT != MVT::v4i32 && "unsupported shuffle type"); 5573 5574 // Invert the operand order and use SHUFPS to match it. 5575 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1, 5576 X86::getShuffleSHUFImmediate(SVOp), DAG); 5577} 5578 5579static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) { 5580 switch(VT.getSimpleVT().SimpleTy) { 5581 case MVT::v4i32: return X86ISD::PUNPCKLDQ; 5582 case MVT::v2i64: return X86ISD::PUNPCKLQDQ; 5583 case MVT::v4f32: 5584 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS; 5585 case MVT::v2f64: 5586 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD; 5587 case MVT::v8f32: return X86ISD::VUNPCKLPSY; 5588 case MVT::v4f64: return X86ISD::VUNPCKLPDY; 5589 case MVT::v16i8: return X86ISD::PUNPCKLBW; 5590 case MVT::v8i16: return X86ISD::PUNPCKLWD; 5591 default: 5592 llvm_unreachable("Unknown type for unpckl"); 5593 } 5594 return 0; 5595} 5596 5597static inline unsigned getUNPCKHOpcode(EVT VT) { 5598 switch(VT.getSimpleVT().SimpleTy) { 5599 case MVT::v4i32: return X86ISD::PUNPCKHDQ; 5600 case MVT::v2i64: return X86ISD::PUNPCKHQDQ; 5601 case MVT::v4f32: return X86ISD::UNPCKHPS; 5602 case MVT::v2f64: return X86ISD::UNPCKHPD; 5603 case MVT::v16i8: return X86ISD::PUNPCKHBW; 5604 case MVT::v8i16: return X86ISD::PUNPCKHWD; 5605 default: 5606 llvm_unreachable("Unknown type for unpckh"); 5607 } 5608 return 0; 5609} 5610 5611static 5612SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG, 5613 const TargetLowering &TLI, 5614 const X86Subtarget *Subtarget) { 5615 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5616 EVT VT = Op.getValueType(); 5617 DebugLoc dl = Op.getDebugLoc(); 5618 SDValue V1 = Op.getOperand(0); 5619 SDValue V2 = Op.getOperand(1); 5620 5621 if (isZeroShuffle(SVOp)) 5622 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl); 5623 5624 // Handle splat operations 5625 if (SVOp->isSplat()) { 5626 // Special case, this is the only place now where it's 5627 // allowed to return a vector_shuffle operation without 5628 // using a target specific node, because *hopefully* it 5629 // will be optimized away by the dag combiner. 5630 if (VT.getVectorNumElements() <= 4 && 5631 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI)) 5632 return Op; 5633 5634 // Handle splats by matching through known masks 5635 if (VT.getVectorNumElements() <= 4) 5636 return SDValue(); 5637 5638 // Canonicalize all of the remaining to v4f32. 5639 return PromoteSplat(SVOp, DAG); 5640 } 5641 5642 // If the shuffle can be profitably rewritten as a narrower shuffle, then 5643 // do it! 5644 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 5645 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 5646 if (NewOp.getNode()) 5647 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp); 5648 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) { 5649 // FIXME: Figure out a cleaner way to do this. 5650 // Try to make use of movq to zero out the top part. 5651 if (ISD::isBuildVectorAllZeros(V2.getNode())) { 5652 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 5653 if (NewOp.getNode()) { 5654 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false)) 5655 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0), 5656 DAG, Subtarget, dl); 5657 } 5658 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) { 5659 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 5660 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp))) 5661 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1), 5662 DAG, Subtarget, dl); 5663 } 5664 } 5665 return SDValue(); 5666} 5667 5668SDValue 5669X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const { 5670 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5671 SDValue V1 = Op.getOperand(0); 5672 SDValue V2 = Op.getOperand(1); 5673 EVT VT = Op.getValueType(); 5674 DebugLoc dl = Op.getDebugLoc(); 5675 unsigned NumElems = VT.getVectorNumElements(); 5676 bool isMMX = VT.getSizeInBits() == 64; 5677 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF; 5678 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 5679 bool V1IsSplat = false; 5680 bool V2IsSplat = false; 5681 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX(); 5682 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX(); 5683 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX(); 5684 MachineFunction &MF = DAG.getMachineFunction(); 5685 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize); 5686 5687 // Shuffle operations on MMX not supported. 5688 if (isMMX) 5689 return Op; 5690 5691 // Vector shuffle lowering takes 3 steps: 5692 // 5693 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable 5694 // narrowing and commutation of operands should be handled. 5695 // 2) Matching of shuffles with known shuffle masks to x86 target specific 5696 // shuffle nodes. 5697 // 3) Rewriting of unmatched masks into new generic shuffle operations, 5698 // so the shuffle can be broken into other shuffles and the legalizer can 5699 // try the lowering again. 5700 // 5701 // The general ideia is that no vector_shuffle operation should be left to 5702 // be matched during isel, all of them must be converted to a target specific 5703 // node here. 5704 5705 // Normalize the input vectors. Here splats, zeroed vectors, profitable 5706 // narrowing and commutation of operands should be handled. The actual code 5707 // doesn't include all of those, work in progress... 5708 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget); 5709 if (NewOp.getNode()) 5710 return NewOp; 5711 5712 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and 5713 // unpckh_undef). Only use pshufd if speed is more important than size. 5714 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp)) 5715 if (VT != MVT::v2i64 && VT != MVT::v2f64) 5716 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG); 5717 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp)) 5718 if (VT != MVT::v2i64 && VT != MVT::v2f64) 5719 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 5720 5721 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef && 5722 RelaxedMayFoldVectorLoad(V1)) 5723 return getMOVDDup(Op, dl, V1, DAG); 5724 5725 if (X86::isMOVHLPS_v_undef_Mask(SVOp)) 5726 return getMOVHighToLow(Op, dl, DAG); 5727 5728 // Use to match splats 5729 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef && 5730 (VT == MVT::v2f64 || VT == MVT::v2i64)) 5731 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 5732 5733 if (X86::isPSHUFDMask(SVOp)) { 5734 // The actual implementation will match the mask in the if above and then 5735 // during isel it can match several different instructions, not only pshufd 5736 // as its name says, sad but true, emulate the behavior for now... 5737 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64))) 5738 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG); 5739 5740 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp); 5741 5742 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32)) 5743 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG); 5744 5745 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64)) 5746 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1, 5747 TargetMask, DAG); 5748 5749 if (VT == MVT::v4f32) 5750 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1, 5751 TargetMask, DAG); 5752 } 5753 5754 // Check if this can be converted into a logical shift. 5755 bool isLeft = false; 5756 unsigned ShAmt = 0; 5757 SDValue ShVal; 5758 bool isShift = getSubtarget()->hasSSE2() && 5759 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt); 5760 if (isShift && ShVal.hasOneUse()) { 5761 // If the shifted value has multiple uses, it may be cheaper to use 5762 // v_set0 + movlhps or movhlps, etc. 5763 EVT EltVT = VT.getVectorElementType(); 5764 ShAmt *= EltVT.getSizeInBits(); 5765 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 5766 } 5767 5768 if (X86::isMOVLMask(SVOp)) { 5769 if (V1IsUndef) 5770 return V2; 5771 if (ISD::isBuildVectorAllZeros(V1.getNode())) 5772 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl); 5773 if (!X86::isMOVLPMask(SVOp)) { 5774 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64)) 5775 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 5776 5777 if (VT == MVT::v4i32 || VT == MVT::v4f32) 5778 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 5779 } 5780 } 5781 5782 // FIXME: fold these into legal mask. 5783 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp)) 5784 return getMOVLowToHigh(Op, dl, DAG, HasSSE2); 5785 5786 if (X86::isMOVHLPSMask(SVOp)) 5787 return getMOVHighToLow(Op, dl, DAG); 5788 5789 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4) 5790 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG); 5791 5792 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4) 5793 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG); 5794 5795 if (X86::isMOVLPMask(SVOp)) 5796 return getMOVLP(Op, dl, DAG, HasSSE2); 5797 5798 if (ShouldXformToMOVHLPS(SVOp) || 5799 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp)) 5800 return CommuteVectorShuffle(SVOp, DAG); 5801 5802 if (isShift) { 5803 // No better options. Use a vshl / vsrl. 5804 EVT EltVT = VT.getVectorElementType(); 5805 ShAmt *= EltVT.getSizeInBits(); 5806 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 5807 } 5808 5809 bool Commuted = false; 5810 // FIXME: This should also accept a bitcast of a splat? Be careful, not 5811 // 1,1,1,1 -> v8i16 though. 5812 V1IsSplat = isSplatVector(V1.getNode()); 5813 V2IsSplat = isSplatVector(V2.getNode()); 5814 5815 // Canonicalize the splat or undef, if present, to be on the RHS. 5816 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) { 5817 Op = CommuteVectorShuffle(SVOp, DAG); 5818 SVOp = cast<ShuffleVectorSDNode>(Op); 5819 V1 = SVOp->getOperand(0); 5820 V2 = SVOp->getOperand(1); 5821 std::swap(V1IsSplat, V2IsSplat); 5822 std::swap(V1IsUndef, V2IsUndef); 5823 Commuted = true; 5824 } 5825 5826 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) { 5827 // Shuffling low element of v1 into undef, just return v1. 5828 if (V2IsUndef) 5829 return V1; 5830 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which 5831 // the instruction selector will not match, so get a canonical MOVL with 5832 // swapped operands to undo the commute. 5833 return getMOVL(DAG, dl, VT, V2, V1); 5834 } 5835 5836 if (X86::isUNPCKLMask(SVOp)) 5837 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), 5838 dl, VT, V1, V2, DAG); 5839 5840 if (X86::isUNPCKHMask(SVOp)) 5841 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG); 5842 5843 if (V2IsSplat) { 5844 // Normalize mask so all entries that point to V2 points to its first 5845 // element then try to match unpck{h|l} again. If match, return a 5846 // new vector_shuffle with the corrected mask. 5847 SDValue NewMask = NormalizeMask(SVOp, DAG); 5848 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask); 5849 if (NSVOp != SVOp) { 5850 if (X86::isUNPCKLMask(NSVOp, true)) { 5851 return NewMask; 5852 } else if (X86::isUNPCKHMask(NSVOp, true)) { 5853 return NewMask; 5854 } 5855 } 5856 } 5857 5858 if (Commuted) { 5859 // Commute is back and try unpck* again. 5860 // FIXME: this seems wrong. 5861 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG); 5862 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp); 5863 5864 if (X86::isUNPCKLMask(NewSVOp)) 5865 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), 5866 dl, VT, V2, V1, DAG); 5867 5868 if (X86::isUNPCKHMask(NewSVOp)) 5869 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG); 5870 } 5871 5872 // Normalize the node to match x86 shuffle ops if needed 5873 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp)) 5874 return CommuteVectorShuffle(SVOp, DAG); 5875 5876 // The checks below are all present in isShuffleMaskLegal, but they are 5877 // inlined here right now to enable us to directly emit target specific 5878 // nodes, and remove one by one until they don't return Op anymore. 5879 SmallVector<int, 16> M; 5880 SVOp->getMask(M); 5881 5882 if (isPALIGNRMask(M, VT, HasSSSE3)) 5883 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2, 5884 X86::getShufflePALIGNRImmediate(SVOp), 5885 DAG); 5886 5887 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) && 5888 SVOp->getSplatIndex() == 0 && V2IsUndef) { 5889 if (VT == MVT::v2f64) { 5890 X86ISD::NodeType Opcode = 5891 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD; 5892 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG); 5893 } 5894 if (VT == MVT::v2i64) 5895 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG); 5896 } 5897 5898 if (isPSHUFHWMask(M, VT)) 5899 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1, 5900 X86::getShufflePSHUFHWImmediate(SVOp), 5901 DAG); 5902 5903 if (isPSHUFLWMask(M, VT)) 5904 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1, 5905 X86::getShufflePSHUFLWImmediate(SVOp), 5906 DAG); 5907 5908 if (isSHUFPMask(M, VT)) { 5909 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp); 5910 if (VT == MVT::v4f32 || VT == MVT::v4i32) 5911 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2, 5912 TargetMask, DAG); 5913 if (VT == MVT::v2f64 || VT == MVT::v2i64) 5914 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2, 5915 TargetMask, DAG); 5916 } 5917 5918 if (X86::isUNPCKL_v_undef_Mask(SVOp)) 5919 if (VT != MVT::v2i64 && VT != MVT::v2f64) 5920 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), 5921 dl, VT, V1, V1, DAG); 5922 if (X86::isUNPCKH_v_undef_Mask(SVOp)) 5923 if (VT != MVT::v2i64 && VT != MVT::v2f64) 5924 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 5925 5926 // Handle v8i16 specifically since SSE can do byte extraction and insertion. 5927 if (VT == MVT::v8i16) { 5928 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG); 5929 if (NewOp.getNode()) 5930 return NewOp; 5931 } 5932 5933 if (VT == MVT::v16i8) { 5934 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this); 5935 if (NewOp.getNode()) 5936 return NewOp; 5937 } 5938 5939 // Handle all 4 wide cases with a number of shuffles. 5940 if (NumElems == 4) 5941 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG); 5942 5943 return SDValue(); 5944} 5945 5946SDValue 5947X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, 5948 SelectionDAG &DAG) const { 5949 EVT VT = Op.getValueType(); 5950 DebugLoc dl = Op.getDebugLoc(); 5951 if (VT.getSizeInBits() == 8) { 5952 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, 5953 Op.getOperand(0), Op.getOperand(1)); 5954 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 5955 DAG.getValueType(VT)); 5956 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 5957 } else if (VT.getSizeInBits() == 16) { 5958 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 5959 // If Idx is 0, it's cheaper to do a move instead of a pextrw. 5960 if (Idx == 0) 5961 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 5962 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 5963 DAG.getNode(ISD::BITCAST, dl, 5964 MVT::v4i32, 5965 Op.getOperand(0)), 5966 Op.getOperand(1))); 5967 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, 5968 Op.getOperand(0), Op.getOperand(1)); 5969 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 5970 DAG.getValueType(VT)); 5971 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 5972 } else if (VT == MVT::f32) { 5973 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy 5974 // the result back to FR32 register. It's only worth matching if the 5975 // result has a single use which is a store or a bitcast to i32. And in 5976 // the case of a store, it's not worth it if the index is a constant 0, 5977 // because a MOVSSmr can be used instead, which is smaller and faster. 5978 if (!Op.hasOneUse()) 5979 return SDValue(); 5980 SDNode *User = *Op.getNode()->use_begin(); 5981 if ((User->getOpcode() != ISD::STORE || 5982 (isa<ConstantSDNode>(Op.getOperand(1)) && 5983 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) && 5984 (User->getOpcode() != ISD::BITCAST || 5985 User->getValueType(0) != MVT::i32)) 5986 return SDValue(); 5987 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 5988 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, 5989 Op.getOperand(0)), 5990 Op.getOperand(1)); 5991 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract); 5992 } else if (VT == MVT::i32) { 5993 // ExtractPS works with constant index. 5994 if (isa<ConstantSDNode>(Op.getOperand(1))) 5995 return Op; 5996 } 5997 return SDValue(); 5998} 5999 6000 6001SDValue 6002X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 6003 SelectionDAG &DAG) const { 6004 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6005 return SDValue(); 6006 6007 SDValue Vec = Op.getOperand(0); 6008 EVT VecVT = Vec.getValueType(); 6009 6010 // If this is a 256-bit vector result, first extract the 128-bit 6011 // vector and then extract from the 128-bit vector. 6012 if (VecVT.getSizeInBits() > 128) { 6013 DebugLoc dl = Op.getNode()->getDebugLoc(); 6014 unsigned NumElems = VecVT.getVectorNumElements(); 6015 SDValue Idx = Op.getOperand(1); 6016 6017 if (!isa<ConstantSDNode>(Idx)) 6018 return SDValue(); 6019 6020 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128); 6021 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 6022 6023 // Get the 128-bit vector. 6024 bool Upper = IdxVal >= ExtractNumElems; 6025 Vec = Extract128BitVector(Vec, Idx, DAG, dl); 6026 6027 // Extract from it. 6028 SDValue ScaledIdx = Idx; 6029 if (Upper) 6030 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx, 6031 DAG.getConstant(ExtractNumElems, 6032 Idx.getValueType())); 6033 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec, 6034 ScaledIdx); 6035 } 6036 6037 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length"); 6038 6039 if (Subtarget->hasSSE41()) { 6040 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG); 6041 if (Res.getNode()) 6042 return Res; 6043 } 6044 6045 EVT VT = Op.getValueType(); 6046 DebugLoc dl = Op.getDebugLoc(); 6047 // TODO: handle v16i8. 6048 if (VT.getSizeInBits() == 16) { 6049 SDValue Vec = Op.getOperand(0); 6050 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6051 if (Idx == 0) 6052 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 6053 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 6054 DAG.getNode(ISD::BITCAST, dl, 6055 MVT::v4i32, Vec), 6056 Op.getOperand(1))); 6057 // Transform it so it match pextrw which produces a 32-bit result. 6058 EVT EltVT = MVT::i32; 6059 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT, 6060 Op.getOperand(0), Op.getOperand(1)); 6061 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract, 6062 DAG.getValueType(VT)); 6063 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6064 } else if (VT.getSizeInBits() == 32) { 6065 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6066 if (Idx == 0) 6067 return Op; 6068 6069 // SHUFPS the element to the lowest double word, then movss. 6070 int Mask[4] = { Idx, -1, -1, -1 }; 6071 EVT VVT = Op.getOperand(0).getValueType(); 6072 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 6073 DAG.getUNDEF(VVT), Mask); 6074 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 6075 DAG.getIntPtrConstant(0)); 6076 } else if (VT.getSizeInBits() == 64) { 6077 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b 6078 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught 6079 // to match extract_elt for f64. 6080 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6081 if (Idx == 0) 6082 return Op; 6083 6084 // UNPCKHPD the element to the lowest double word, then movsd. 6085 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored 6086 // to a f64mem, the whole operation is folded into a single MOVHPDmr. 6087 int Mask[2] = { 1, -1 }; 6088 EVT VVT = Op.getOperand(0).getValueType(); 6089 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 6090 DAG.getUNDEF(VVT), Mask); 6091 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 6092 DAG.getIntPtrConstant(0)); 6093 } 6094 6095 return SDValue(); 6096} 6097 6098SDValue 6099X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, 6100 SelectionDAG &DAG) const { 6101 EVT VT = Op.getValueType(); 6102 EVT EltVT = VT.getVectorElementType(); 6103 DebugLoc dl = Op.getDebugLoc(); 6104 6105 SDValue N0 = Op.getOperand(0); 6106 SDValue N1 = Op.getOperand(1); 6107 SDValue N2 = Op.getOperand(2); 6108 6109 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) && 6110 isa<ConstantSDNode>(N2)) { 6111 unsigned Opc; 6112 if (VT == MVT::v8i16) 6113 Opc = X86ISD::PINSRW; 6114 else if (VT == MVT::v16i8) 6115 Opc = X86ISD::PINSRB; 6116 else 6117 Opc = X86ISD::PINSRB; 6118 6119 // Transform it so it match pinsr{b,w} which expects a GR32 as its second 6120 // argument. 6121 if (N1.getValueType() != MVT::i32) 6122 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 6123 if (N2.getValueType() != MVT::i32) 6124 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 6125 return DAG.getNode(Opc, dl, VT, N0, N1, N2); 6126 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) { 6127 // Bits [7:6] of the constant are the source select. This will always be 6128 // zero here. The DAG Combiner may combine an extract_elt index into these 6129 // bits. For example (insert (extract, 3), 2) could be matched by putting 6130 // the '3' into bits [7:6] of X86ISD::INSERTPS. 6131 // Bits [5:4] of the constant are the destination select. This is the 6132 // value of the incoming immediate. 6133 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may 6134 // combine either bitwise AND or insert of float 0.0 to set these bits. 6135 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4); 6136 // Create this as a scalar to vector.. 6137 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1); 6138 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2); 6139 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) { 6140 // PINSR* works with constant index. 6141 return Op; 6142 } 6143 return SDValue(); 6144} 6145 6146SDValue 6147X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { 6148 EVT VT = Op.getValueType(); 6149 EVT EltVT = VT.getVectorElementType(); 6150 6151 DebugLoc dl = Op.getDebugLoc(); 6152 SDValue N0 = Op.getOperand(0); 6153 SDValue N1 = Op.getOperand(1); 6154 SDValue N2 = Op.getOperand(2); 6155 6156 // If this is a 256-bit vector result, first insert into a 128-bit 6157 // vector and then insert into the 256-bit vector. 6158 if (VT.getSizeInBits() > 128) { 6159 if (!isa<ConstantSDNode>(N2)) 6160 return SDValue(); 6161 6162 // Get the 128-bit vector. 6163 unsigned NumElems = VT.getVectorNumElements(); 6164 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue(); 6165 bool Upper = IdxVal >= NumElems / 2; 6166 6167 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl); 6168 6169 // Insert into it. 6170 SDValue ScaledN2 = N2; 6171 if (Upper) 6172 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2, 6173 DAG.getConstant(NumElems / 6174 (VT.getSizeInBits() / 128), 6175 N2.getValueType())); 6176 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0, 6177 N1, ScaledN2); 6178 6179 // Insert the 128-bit vector 6180 // FIXME: Why UNDEF? 6181 return Insert128BitVector(N0, Op, N2, DAG, dl); 6182 } 6183 6184 if (Subtarget->hasSSE41()) 6185 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG); 6186 6187 if (EltVT == MVT::i8) 6188 return SDValue(); 6189 6190 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) { 6191 // Transform it so it match pinsrw which expects a 16-bit value in a GR32 6192 // as its second argument. 6193 if (N1.getValueType() != MVT::i32) 6194 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 6195 if (N2.getValueType() != MVT::i32) 6196 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 6197 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2); 6198 } 6199 return SDValue(); 6200} 6201 6202SDValue 6203X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const { 6204 LLVMContext *Context = DAG.getContext(); 6205 DebugLoc dl = Op.getDebugLoc(); 6206 EVT OpVT = Op.getValueType(); 6207 6208 // If this is a 256-bit vector result, first insert into a 128-bit 6209 // vector and then insert into the 256-bit vector. 6210 if (OpVT.getSizeInBits() > 128) { 6211 // Insert into a 128-bit vector. 6212 EVT VT128 = EVT::getVectorVT(*Context, 6213 OpVT.getVectorElementType(), 6214 OpVT.getVectorNumElements() / 2); 6215 6216 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0)); 6217 6218 // Insert the 128-bit vector. 6219 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op, 6220 DAG.getConstant(0, MVT::i32), 6221 DAG, dl); 6222 } 6223 6224 if (Op.getValueType() == MVT::v1i64 && 6225 Op.getOperand(0).getValueType() == MVT::i64) 6226 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0)); 6227 6228 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0)); 6229 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 && 6230 "Expected an SSE type!"); 6231 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), 6232 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt)); 6233} 6234 6235// Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in 6236// a simple subregister reference or explicit instructions to grab 6237// upper bits of a vector. 6238SDValue 6239X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 6240 if (Subtarget->hasAVX()) { 6241 DebugLoc dl = Op.getNode()->getDebugLoc(); 6242 SDValue Vec = Op.getNode()->getOperand(0); 6243 SDValue Idx = Op.getNode()->getOperand(1); 6244 6245 if (Op.getNode()->getValueType(0).getSizeInBits() == 128 6246 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) { 6247 return Extract128BitVector(Vec, Idx, DAG, dl); 6248 } 6249 } 6250 return SDValue(); 6251} 6252 6253// Lower a node with an INSERT_SUBVECTOR opcode. This may result in a 6254// simple superregister reference or explicit instructions to insert 6255// the upper bits of a vector. 6256SDValue 6257X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 6258 if (Subtarget->hasAVX()) { 6259 DebugLoc dl = Op.getNode()->getDebugLoc(); 6260 SDValue Vec = Op.getNode()->getOperand(0); 6261 SDValue SubVec = Op.getNode()->getOperand(1); 6262 SDValue Idx = Op.getNode()->getOperand(2); 6263 6264 if (Op.getNode()->getValueType(0).getSizeInBits() == 256 6265 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) { 6266 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl); 6267 } 6268 } 6269 return SDValue(); 6270} 6271 6272// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 6273// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is 6274// one of the above mentioned nodes. It has to be wrapped because otherwise 6275// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 6276// be used to form addressing mode. These wrapped nodes will be selected 6277// into MOV32ri. 6278SDValue 6279X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const { 6280 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 6281 6282 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 6283 // global base reg. 6284 unsigned char OpFlag = 0; 6285 unsigned WrapperKind = X86ISD::Wrapper; 6286 CodeModel::Model M = getTargetMachine().getCodeModel(); 6287 6288 if (Subtarget->isPICStyleRIPRel() && 6289 (M == CodeModel::Small || M == CodeModel::Kernel)) 6290 WrapperKind = X86ISD::WrapperRIP; 6291 else if (Subtarget->isPICStyleGOT()) 6292 OpFlag = X86II::MO_GOTOFF; 6293 else if (Subtarget->isPICStyleStubPIC()) 6294 OpFlag = X86II::MO_PIC_BASE_OFFSET; 6295 6296 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(), 6297 CP->getAlignment(), 6298 CP->getOffset(), OpFlag); 6299 DebugLoc DL = CP->getDebugLoc(); 6300 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 6301 // With PIC, the address is actually $g + Offset. 6302 if (OpFlag) { 6303 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 6304 DAG.getNode(X86ISD::GlobalBaseReg, 6305 DebugLoc(), getPointerTy()), 6306 Result); 6307 } 6308 6309 return Result; 6310} 6311 6312SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 6313 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 6314 6315 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 6316 // global base reg. 6317 unsigned char OpFlag = 0; 6318 unsigned WrapperKind = X86ISD::Wrapper; 6319 CodeModel::Model M = getTargetMachine().getCodeModel(); 6320 6321 if (Subtarget->isPICStyleRIPRel() && 6322 (M == CodeModel::Small || M == CodeModel::Kernel)) 6323 WrapperKind = X86ISD::WrapperRIP; 6324 else if (Subtarget->isPICStyleGOT()) 6325 OpFlag = X86II::MO_GOTOFF; 6326 else if (Subtarget->isPICStyleStubPIC()) 6327 OpFlag = X86II::MO_PIC_BASE_OFFSET; 6328 6329 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(), 6330 OpFlag); 6331 DebugLoc DL = JT->getDebugLoc(); 6332 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 6333 6334 // With PIC, the address is actually $g + Offset. 6335 if (OpFlag) 6336 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 6337 DAG.getNode(X86ISD::GlobalBaseReg, 6338 DebugLoc(), getPointerTy()), 6339 Result); 6340 6341 return Result; 6342} 6343 6344SDValue 6345X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const { 6346 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 6347 6348 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 6349 // global base reg. 6350 unsigned char OpFlag = 0; 6351 unsigned WrapperKind = X86ISD::Wrapper; 6352 CodeModel::Model M = getTargetMachine().getCodeModel(); 6353 6354 if (Subtarget->isPICStyleRIPRel() && 6355 (M == CodeModel::Small || M == CodeModel::Kernel)) 6356 WrapperKind = X86ISD::WrapperRIP; 6357 else if (Subtarget->isPICStyleGOT()) 6358 OpFlag = X86II::MO_GOTOFF; 6359 else if (Subtarget->isPICStyleStubPIC()) 6360 OpFlag = X86II::MO_PIC_BASE_OFFSET; 6361 6362 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag); 6363 6364 DebugLoc DL = Op.getDebugLoc(); 6365 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 6366 6367 6368 // With PIC, the address is actually $g + Offset. 6369 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 6370 !Subtarget->is64Bit()) { 6371 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 6372 DAG.getNode(X86ISD::GlobalBaseReg, 6373 DebugLoc(), getPointerTy()), 6374 Result); 6375 } 6376 6377 return Result; 6378} 6379 6380SDValue 6381X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const { 6382 // Create the TargetBlockAddressAddress node. 6383 unsigned char OpFlags = 6384 Subtarget->ClassifyBlockAddressReference(); 6385 CodeModel::Model M = getTargetMachine().getCodeModel(); 6386 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 6387 DebugLoc dl = Op.getDebugLoc(); 6388 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), 6389 /*isTarget=*/true, OpFlags); 6390 6391 if (Subtarget->isPICStyleRIPRel() && 6392 (M == CodeModel::Small || M == CodeModel::Kernel)) 6393 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 6394 else 6395 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 6396 6397 // With PIC, the address is actually $g + Offset. 6398 if (isGlobalRelativeToPICBase(OpFlags)) { 6399 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 6400 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 6401 Result); 6402 } 6403 6404 return Result; 6405} 6406 6407SDValue 6408X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl, 6409 int64_t Offset, 6410 SelectionDAG &DAG) const { 6411 // Create the TargetGlobalAddress node, folding in the constant 6412 // offset if it is legal. 6413 unsigned char OpFlags = 6414 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 6415 CodeModel::Model M = getTargetMachine().getCodeModel(); 6416 SDValue Result; 6417 if (OpFlags == X86II::MO_NO_FLAG && 6418 X86::isOffsetSuitableForCodeModel(Offset, M)) { 6419 // A direct static reference to a global. 6420 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset); 6421 Offset = 0; 6422 } else { 6423 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags); 6424 } 6425 6426 if (Subtarget->isPICStyleRIPRel() && 6427 (M == CodeModel::Small || M == CodeModel::Kernel)) 6428 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 6429 else 6430 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 6431 6432 // With PIC, the address is actually $g + Offset. 6433 if (isGlobalRelativeToPICBase(OpFlags)) { 6434 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 6435 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 6436 Result); 6437 } 6438 6439 // For globals that require a load from a stub to get the address, emit the 6440 // load. 6441 if (isGlobalStubReference(OpFlags)) 6442 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result, 6443 MachinePointerInfo::getGOT(), false, false, 0); 6444 6445 // If there was a non-zero offset that we didn't fold, create an explicit 6446 // addition for it. 6447 if (Offset != 0) 6448 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result, 6449 DAG.getConstant(Offset, getPointerTy())); 6450 6451 return Result; 6452} 6453 6454SDValue 6455X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const { 6456 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 6457 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset(); 6458 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG); 6459} 6460 6461static SDValue 6462GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA, 6463 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg, 6464 unsigned char OperandFlags) { 6465 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 6466 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6467 DebugLoc dl = GA->getDebugLoc(); 6468 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 6469 GA->getValueType(0), 6470 GA->getOffset(), 6471 OperandFlags); 6472 if (InFlag) { 6473 SDValue Ops[] = { Chain, TGA, *InFlag }; 6474 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3); 6475 } else { 6476 SDValue Ops[] = { Chain, TGA }; 6477 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2); 6478 } 6479 6480 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 6481 MFI->setAdjustsStack(true); 6482 6483 SDValue Flag = Chain.getValue(1); 6484 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag); 6485} 6486 6487// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit 6488static SDValue 6489LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG, 6490 const EVT PtrVT) { 6491 SDValue InFlag; 6492 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better 6493 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 6494 DAG.getNode(X86ISD::GlobalBaseReg, 6495 DebugLoc(), PtrVT), InFlag); 6496 InFlag = Chain.getValue(1); 6497 6498 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD); 6499} 6500 6501// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit 6502static SDValue 6503LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG, 6504 const EVT PtrVT) { 6505 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, 6506 X86::RAX, X86II::MO_TLSGD); 6507} 6508 6509// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or 6510// "local exec" model. 6511static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG, 6512 const EVT PtrVT, TLSModel::Model model, 6513 bool is64Bit) { 6514 DebugLoc dl = GA->getDebugLoc(); 6515 6516 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit). 6517 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(), 6518 is64Bit ? 257 : 256)); 6519 6520 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 6521 DAG.getIntPtrConstant(0), 6522 MachinePointerInfo(Ptr), false, false, 0); 6523 6524 unsigned char OperandFlags = 0; 6525 // Most TLS accesses are not RIP relative, even on x86-64. One exception is 6526 // initialexec. 6527 unsigned WrapperKind = X86ISD::Wrapper; 6528 if (model == TLSModel::LocalExec) { 6529 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF; 6530 } else if (is64Bit) { 6531 assert(model == TLSModel::InitialExec); 6532 OperandFlags = X86II::MO_GOTTPOFF; 6533 WrapperKind = X86ISD::WrapperRIP; 6534 } else { 6535 assert(model == TLSModel::InitialExec); 6536 OperandFlags = X86II::MO_INDNTPOFF; 6537 } 6538 6539 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial 6540 // exec) 6541 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 6542 GA->getValueType(0), 6543 GA->getOffset(), OperandFlags); 6544 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 6545 6546 if (model == TLSModel::InitialExec) 6547 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset, 6548 MachinePointerInfo::getGOT(), false, false, 0); 6549 6550 // The address of the thread local variable is the add of the thread 6551 // pointer with the offset of the variable. 6552 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 6553} 6554 6555SDValue 6556X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 6557 6558 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 6559 const GlobalValue *GV = GA->getGlobal(); 6560 6561 if (Subtarget->isTargetELF()) { 6562 // TODO: implement the "local dynamic" model 6563 // TODO: implement the "initial exec"model for pic executables 6564 6565 // If GV is an alias then use the aliasee for determining 6566 // thread-localness. 6567 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 6568 GV = GA->resolveAliasedGlobal(false); 6569 6570 TLSModel::Model model 6571 = getTLSModel(GV, getTargetMachine().getRelocationModel()); 6572 6573 switch (model) { 6574 case TLSModel::GeneralDynamic: 6575 case TLSModel::LocalDynamic: // not implemented 6576 if (Subtarget->is64Bit()) 6577 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy()); 6578 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy()); 6579 6580 case TLSModel::InitialExec: 6581 case TLSModel::LocalExec: 6582 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, 6583 Subtarget->is64Bit()); 6584 } 6585 } else if (Subtarget->isTargetDarwin()) { 6586 // Darwin only has one model of TLS. Lower to that. 6587 unsigned char OpFlag = 0; 6588 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ? 6589 X86ISD::WrapperRIP : X86ISD::Wrapper; 6590 6591 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 6592 // global base reg. 6593 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) && 6594 !Subtarget->is64Bit(); 6595 if (PIC32) 6596 OpFlag = X86II::MO_TLVP_PIC_BASE; 6597 else 6598 OpFlag = X86II::MO_TLVP; 6599 DebugLoc DL = Op.getDebugLoc(); 6600 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL, 6601 GA->getValueType(0), 6602 GA->getOffset(), OpFlag); 6603 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 6604 6605 // With PIC32, the address is actually $g + Offset. 6606 if (PIC32) 6607 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(), 6608 DAG.getNode(X86ISD::GlobalBaseReg, 6609 DebugLoc(), getPointerTy()), 6610 Offset); 6611 6612 // Lowering the machine isd will make sure everything is in the right 6613 // location. 6614 SDValue Chain = DAG.getEntryNode(); 6615 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6616 SDValue Args[] = { Chain, Offset }; 6617 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2); 6618 6619 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls. 6620 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 6621 MFI->setAdjustsStack(true); 6622 6623 // And our return value (tls address) is in the standard call return value 6624 // location. 6625 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 6626 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy()); 6627 } 6628 6629 assert(false && 6630 "TLS not implemented for this target."); 6631 6632 llvm_unreachable("Unreachable"); 6633 return SDValue(); 6634} 6635 6636 6637/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and 6638/// take a 2 x i32 value to shift plus a shift amount. 6639SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const { 6640 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6641 EVT VT = Op.getValueType(); 6642 unsigned VTBits = VT.getSizeInBits(); 6643 DebugLoc dl = Op.getDebugLoc(); 6644 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS; 6645 SDValue ShOpLo = Op.getOperand(0); 6646 SDValue ShOpHi = Op.getOperand(1); 6647 SDValue ShAmt = Op.getOperand(2); 6648 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 6649 DAG.getConstant(VTBits - 1, MVT::i8)) 6650 : DAG.getConstant(0, VT); 6651 6652 SDValue Tmp2, Tmp3; 6653 if (Op.getOpcode() == ISD::SHL_PARTS) { 6654 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt); 6655 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 6656 } else { 6657 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt); 6658 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt); 6659 } 6660 6661 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt, 6662 DAG.getConstant(VTBits, MVT::i8)); 6663 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 6664 AndNode, DAG.getConstant(0, MVT::i8)); 6665 6666 SDValue Hi, Lo; 6667 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8); 6668 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond }; 6669 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond }; 6670 6671 if (Op.getOpcode() == ISD::SHL_PARTS) { 6672 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 6673 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 6674 } else { 6675 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 6676 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 6677 } 6678 6679 SDValue Ops[2] = { Lo, Hi }; 6680 return DAG.getMergeValues(Ops, 2, dl); 6681} 6682 6683SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, 6684 SelectionDAG &DAG) const { 6685 EVT SrcVT = Op.getOperand(0).getValueType(); 6686 6687 if (SrcVT.isVector()) 6688 return SDValue(); 6689 6690 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 && 6691 "Unknown SINT_TO_FP to lower!"); 6692 6693 // These are really Legal; return the operand so the caller accepts it as 6694 // Legal. 6695 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType())) 6696 return Op; 6697 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) && 6698 Subtarget->is64Bit()) { 6699 return Op; 6700 } 6701 6702 DebugLoc dl = Op.getDebugLoc(); 6703 unsigned Size = SrcVT.getSizeInBits()/8; 6704 MachineFunction &MF = DAG.getMachineFunction(); 6705 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false); 6706 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 6707 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 6708 StackSlot, 6709 MachinePointerInfo::getFixedStack(SSFI), 6710 false, false, 0); 6711 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG); 6712} 6713 6714SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain, 6715 SDValue StackSlot, 6716 SelectionDAG &DAG) const { 6717 // Build the FILD 6718 DebugLoc DL = Op.getDebugLoc(); 6719 SDVTList Tys; 6720 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType()); 6721 if (useSSE) 6722 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue); 6723 else 6724 Tys = DAG.getVTList(Op.getValueType(), MVT::Other); 6725 6726 unsigned ByteSize = SrcVT.getSizeInBits()/8; 6727 6728 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot); 6729 MachineMemOperand *MMO; 6730 if (FI) { 6731 int SSFI = FI->getIndex(); 6732 MMO = 6733 DAG.getMachineFunction() 6734 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 6735 MachineMemOperand::MOLoad, ByteSize, ByteSize); 6736 } else { 6737 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand(); 6738 StackSlot = StackSlot.getOperand(1); 6739 } 6740 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) }; 6741 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG : 6742 X86ISD::FILD, DL, 6743 Tys, Ops, array_lengthof(Ops), 6744 SrcVT, MMO); 6745 6746 if (useSSE) { 6747 Chain = Result.getValue(1); 6748 SDValue InFlag = Result.getValue(2); 6749 6750 // FIXME: Currently the FST is flagged to the FILD_FLAG. This 6751 // shouldn't be necessary except that RFP cannot be live across 6752 // multiple blocks. When stackifier is fixed, they can be uncoupled. 6753 MachineFunction &MF = DAG.getMachineFunction(); 6754 unsigned SSFISize = Op.getValueType().getSizeInBits()/8; 6755 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false); 6756 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 6757 Tys = DAG.getVTList(MVT::Other); 6758 SDValue Ops[] = { 6759 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag 6760 }; 6761 MachineMemOperand *MMO = 6762 DAG.getMachineFunction() 6763 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 6764 MachineMemOperand::MOStore, SSFISize, SSFISize); 6765 6766 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, 6767 Ops, array_lengthof(Ops), 6768 Op.getValueType(), MMO); 6769 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot, 6770 MachinePointerInfo::getFixedStack(SSFI), 6771 false, false, 0); 6772 } 6773 6774 return Result; 6775} 6776 6777// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion. 6778SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, 6779 SelectionDAG &DAG) const { 6780 // This algorithm is not obvious. Here it is in C code, more or less: 6781 /* 6782 double uint64_to_double( uint32_t hi, uint32_t lo ) { 6783 static const __m128i exp = { 0x4330000045300000ULL, 0 }; 6784 static const __m128d bias = { 0x1.0p84, 0x1.0p52 }; 6785 6786 // Copy ints to xmm registers. 6787 __m128i xh = _mm_cvtsi32_si128( hi ); 6788 __m128i xl = _mm_cvtsi32_si128( lo ); 6789 6790 // Combine into low half of a single xmm register. 6791 __m128i x = _mm_unpacklo_epi32( xh, xl ); 6792 __m128d d; 6793 double sd; 6794 6795 // Merge in appropriate exponents to give the integer bits the right 6796 // magnitude. 6797 x = _mm_unpacklo_epi32( x, exp ); 6798 6799 // Subtract away the biases to deal with the IEEE-754 double precision 6800 // implicit 1. 6801 d = _mm_sub_pd( (__m128d) x, bias ); 6802 6803 // All conversions up to here are exact. The correctly rounded result is 6804 // calculated using the current rounding mode using the following 6805 // horizontal add. 6806 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) ); 6807 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this 6808 // store doesn't really need to be here (except 6809 // maybe to zero the other double) 6810 return sd; 6811 } 6812 */ 6813 6814 DebugLoc dl = Op.getDebugLoc(); 6815 LLVMContext *Context = DAG.getContext(); 6816 6817 // Build some magic constants. 6818 std::vector<Constant*> CV0; 6819 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000))); 6820 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000))); 6821 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0))); 6822 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0))); 6823 Constant *C0 = ConstantVector::get(CV0); 6824 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16); 6825 6826 std::vector<Constant*> CV1; 6827 CV1.push_back( 6828 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL)))); 6829 CV1.push_back( 6830 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL)))); 6831 Constant *C1 = ConstantVector::get(CV1); 6832 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16); 6833 6834 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 6835 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 6836 Op.getOperand(0), 6837 DAG.getIntPtrConstant(1))); 6838 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 6839 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 6840 Op.getOperand(0), 6841 DAG.getIntPtrConstant(0))); 6842 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2); 6843 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0, 6844 MachinePointerInfo::getConstantPool(), 6845 false, false, 16); 6846 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0); 6847 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2); 6848 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1, 6849 MachinePointerInfo::getConstantPool(), 6850 false, false, 16); 6851 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1); 6852 6853 // Add the halves; easiest way is to swap them into another reg first. 6854 int ShufMask[2] = { 1, -1 }; 6855 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, 6856 DAG.getUNDEF(MVT::v2f64), ShufMask); 6857 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub); 6858 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add, 6859 DAG.getIntPtrConstant(0)); 6860} 6861 6862// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion. 6863SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, 6864 SelectionDAG &DAG) const { 6865 DebugLoc dl = Op.getDebugLoc(); 6866 // FP constant to bias correct the final result. 6867 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), 6868 MVT::f64); 6869 6870 // Load the 32-bit value into an XMM register. 6871 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 6872 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 6873 Op.getOperand(0), 6874 DAG.getIntPtrConstant(0))); 6875 6876 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 6877 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load), 6878 DAG.getIntPtrConstant(0)); 6879 6880 // Or the load with the bias. 6881 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, 6882 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 6883 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 6884 MVT::v2f64, Load)), 6885 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 6886 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 6887 MVT::v2f64, Bias))); 6888 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 6889 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or), 6890 DAG.getIntPtrConstant(0)); 6891 6892 // Subtract the bias. 6893 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias); 6894 6895 // Handle final rounding. 6896 EVT DestVT = Op.getValueType(); 6897 6898 if (DestVT.bitsLT(MVT::f64)) { 6899 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub, 6900 DAG.getIntPtrConstant(0)); 6901 } else if (DestVT.bitsGT(MVT::f64)) { 6902 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub); 6903 } 6904 6905 // Handle final rounding. 6906 return Sub; 6907} 6908 6909SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, 6910 SelectionDAG &DAG) const { 6911 SDValue N0 = Op.getOperand(0); 6912 DebugLoc dl = Op.getDebugLoc(); 6913 6914 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't 6915 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform 6916 // the optimization here. 6917 if (DAG.SignBitIsZero(N0)) 6918 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0); 6919 6920 EVT SrcVT = N0.getValueType(); 6921 EVT DstVT = Op.getValueType(); 6922 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64) 6923 return LowerUINT_TO_FP_i64(Op, DAG); 6924 else if (SrcVT == MVT::i32 && X86ScalarSSEf64) 6925 return LowerUINT_TO_FP_i32(Op, DAG); 6926 6927 // Make a 64-bit buffer, and use it to build an FILD. 6928 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64); 6929 if (SrcVT == MVT::i32) { 6930 SDValue WordOff = DAG.getConstant(4, getPointerTy()); 6931 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, 6932 getPointerTy(), StackSlot, WordOff); 6933 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 6934 StackSlot, MachinePointerInfo(), 6935 false, false, 0); 6936 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32), 6937 OffsetSlot, MachinePointerInfo(), 6938 false, false, 0); 6939 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG); 6940 return Fild; 6941 } 6942 6943 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP"); 6944 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 6945 StackSlot, MachinePointerInfo(), 6946 false, false, 0); 6947 // For i64 source, we need to add the appropriate power of 2 if the input 6948 // was negative. This is the same as the optimization in 6949 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here, 6950 // we must be careful to do the computation in x87 extended precision, not 6951 // in SSE. (The generic code can't know it's OK to do this, or how to.) 6952 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex(); 6953 MachineMemOperand *MMO = 6954 DAG.getMachineFunction() 6955 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 6956 MachineMemOperand::MOLoad, 8, 8); 6957 6958 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other); 6959 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) }; 6960 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3, 6961 MVT::i64, MMO); 6962 6963 APInt FF(32, 0x5F800000ULL); 6964 6965 // Check whether the sign bit is set. 6966 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), 6967 Op.getOperand(0), DAG.getConstant(0, MVT::i64), 6968 ISD::SETLT); 6969 6970 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits. 6971 SDValue FudgePtr = DAG.getConstantPool( 6972 ConstantInt::get(*DAG.getContext(), FF.zext(64)), 6973 getPointerTy()); 6974 6975 // Get a pointer to FF if the sign bit was set, or to 0 otherwise. 6976 SDValue Zero = DAG.getIntPtrConstant(0); 6977 SDValue Four = DAG.getIntPtrConstant(4); 6978 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet, 6979 Zero, Four); 6980 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset); 6981 6982 // Load the value out, extending it from f32 to f80. 6983 // FIXME: Avoid the extend by constructing the right constant pool? 6984 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), 6985 FudgePtr, MachinePointerInfo::getConstantPool(), 6986 MVT::f32, false, false, 4); 6987 // Extend everything to 80 bits to force it to be done on x87. 6988 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge); 6989 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0)); 6990} 6991 6992std::pair<SDValue,SDValue> X86TargetLowering:: 6993FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const { 6994 DebugLoc DL = Op.getDebugLoc(); 6995 6996 EVT DstTy = Op.getValueType(); 6997 6998 if (!IsSigned) { 6999 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT"); 7000 DstTy = MVT::i64; 7001 } 7002 7003 assert(DstTy.getSimpleVT() <= MVT::i64 && 7004 DstTy.getSimpleVT() >= MVT::i16 && 7005 "Unknown FP_TO_SINT to lower!"); 7006 7007 // These are really Legal. 7008 if (DstTy == MVT::i32 && 7009 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 7010 return std::make_pair(SDValue(), SDValue()); 7011 if (Subtarget->is64Bit() && 7012 DstTy == MVT::i64 && 7013 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 7014 return std::make_pair(SDValue(), SDValue()); 7015 7016 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary 7017 // stack slot. 7018 MachineFunction &MF = DAG.getMachineFunction(); 7019 unsigned MemSize = DstTy.getSizeInBits()/8; 7020 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 7021 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7022 7023 7024 7025 unsigned Opc; 7026 switch (DstTy.getSimpleVT().SimpleTy) { 7027 default: llvm_unreachable("Invalid FP_TO_SINT to lower!"); 7028 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break; 7029 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break; 7030 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break; 7031 } 7032 7033 SDValue Chain = DAG.getEntryNode(); 7034 SDValue Value = Op.getOperand(0); 7035 EVT TheVT = Op.getOperand(0).getValueType(); 7036 if (isScalarFPTypeInSSEReg(TheVT)) { 7037 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!"); 7038 Chain = DAG.getStore(Chain, DL, Value, StackSlot, 7039 MachinePointerInfo::getFixedStack(SSFI), 7040 false, false, 0); 7041 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other); 7042 SDValue Ops[] = { 7043 Chain, StackSlot, DAG.getValueType(TheVT) 7044 }; 7045 7046 MachineMemOperand *MMO = 7047 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7048 MachineMemOperand::MOLoad, MemSize, MemSize); 7049 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3, 7050 DstTy, MMO); 7051 Chain = Value.getValue(1); 7052 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 7053 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7054 } 7055 7056 MachineMemOperand *MMO = 7057 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7058 MachineMemOperand::MOStore, MemSize, MemSize); 7059 7060 // Build the FP_TO_INT*_IN_MEM 7061 SDValue Ops[] = { Chain, Value, StackSlot }; 7062 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other), 7063 Ops, 3, DstTy, MMO); 7064 7065 return std::make_pair(FIST, StackSlot); 7066} 7067 7068SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, 7069 SelectionDAG &DAG) const { 7070 if (Op.getValueType().isVector()) 7071 return SDValue(); 7072 7073 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true); 7074 SDValue FIST = Vals.first, StackSlot = Vals.second; 7075 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal. 7076 if (FIST.getNode() == 0) return Op; 7077 7078 // Load the result. 7079 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 7080 FIST, StackSlot, MachinePointerInfo(), false, false, 0); 7081} 7082 7083SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, 7084 SelectionDAG &DAG) const { 7085 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false); 7086 SDValue FIST = Vals.first, StackSlot = Vals.second; 7087 assert(FIST.getNode() && "Unexpected failure"); 7088 7089 // Load the result. 7090 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 7091 FIST, StackSlot, MachinePointerInfo(), false, false, 0); 7092} 7093 7094SDValue X86TargetLowering::LowerFABS(SDValue Op, 7095 SelectionDAG &DAG) const { 7096 LLVMContext *Context = DAG.getContext(); 7097 DebugLoc dl = Op.getDebugLoc(); 7098 EVT VT = Op.getValueType(); 7099 EVT EltVT = VT; 7100 if (VT.isVector()) 7101 EltVT = VT.getVectorElementType(); 7102 std::vector<Constant*> CV; 7103 if (EltVT == MVT::f64) { 7104 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))); 7105 CV.push_back(C); 7106 CV.push_back(C); 7107 } else { 7108 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))); 7109 CV.push_back(C); 7110 CV.push_back(C); 7111 CV.push_back(C); 7112 CV.push_back(C); 7113 } 7114 Constant *C = ConstantVector::get(CV); 7115 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 7116 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 7117 MachinePointerInfo::getConstantPool(), 7118 false, false, 16); 7119 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask); 7120} 7121 7122SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const { 7123 LLVMContext *Context = DAG.getContext(); 7124 DebugLoc dl = Op.getDebugLoc(); 7125 EVT VT = Op.getValueType(); 7126 EVT EltVT = VT; 7127 if (VT.isVector()) 7128 EltVT = VT.getVectorElementType(); 7129 std::vector<Constant*> CV; 7130 if (EltVT == MVT::f64) { 7131 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))); 7132 CV.push_back(C); 7133 CV.push_back(C); 7134 } else { 7135 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))); 7136 CV.push_back(C); 7137 CV.push_back(C); 7138 CV.push_back(C); 7139 CV.push_back(C); 7140 } 7141 Constant *C = ConstantVector::get(CV); 7142 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 7143 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 7144 MachinePointerInfo::getConstantPool(), 7145 false, false, 16); 7146 if (VT.isVector()) { 7147 return DAG.getNode(ISD::BITCAST, dl, VT, 7148 DAG.getNode(ISD::XOR, dl, MVT::v2i64, 7149 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 7150 Op.getOperand(0)), 7151 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask))); 7152 } else { 7153 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask); 7154 } 7155} 7156 7157SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 7158 LLVMContext *Context = DAG.getContext(); 7159 SDValue Op0 = Op.getOperand(0); 7160 SDValue Op1 = Op.getOperand(1); 7161 DebugLoc dl = Op.getDebugLoc(); 7162 EVT VT = Op.getValueType(); 7163 EVT SrcVT = Op1.getValueType(); 7164 7165 // If second operand is smaller, extend it first. 7166 if (SrcVT.bitsLT(VT)) { 7167 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1); 7168 SrcVT = VT; 7169 } 7170 // And if it is bigger, shrink it first. 7171 if (SrcVT.bitsGT(VT)) { 7172 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1)); 7173 SrcVT = VT; 7174 } 7175 7176 // At this point the operands and the result should have the same 7177 // type, and that won't be f80 since that is not custom lowered. 7178 7179 // First get the sign bit of second operand. 7180 std::vector<Constant*> CV; 7181 if (SrcVT == MVT::f64) { 7182 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)))); 7183 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 7184 } else { 7185 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)))); 7186 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7187 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7188 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7189 } 7190 Constant *C = ConstantVector::get(CV); 7191 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 7192 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx, 7193 MachinePointerInfo::getConstantPool(), 7194 false, false, 16); 7195 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1); 7196 7197 // Shift sign bit right or left if the two operands have different types. 7198 if (SrcVT.bitsGT(VT)) { 7199 // Op0 is MVT::f32, Op1 is MVT::f64. 7200 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit); 7201 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit, 7202 DAG.getConstant(32, MVT::i32)); 7203 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit); 7204 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit, 7205 DAG.getIntPtrConstant(0)); 7206 } 7207 7208 // Clear first operand sign bit. 7209 CV.clear(); 7210 if (VT == MVT::f64) { 7211 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))))); 7212 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 7213 } else { 7214 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))))); 7215 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7216 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7217 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7218 } 7219 C = ConstantVector::get(CV); 7220 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 7221 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 7222 MachinePointerInfo::getConstantPool(), 7223 false, false, 16); 7224 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2); 7225 7226 // Or the value with the sign bit. 7227 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit); 7228} 7229 7230SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const { 7231 SDValue N0 = Op.getOperand(0); 7232 DebugLoc dl = Op.getDebugLoc(); 7233 EVT VT = Op.getValueType(); 7234 7235 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1). 7236 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0, 7237 DAG.getConstant(1, VT)); 7238 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT)); 7239} 7240 7241/// Emit nodes that will be selected as "test Op0,Op0", or something 7242/// equivalent. 7243SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, 7244 SelectionDAG &DAG) const { 7245 DebugLoc dl = Op.getDebugLoc(); 7246 7247 // CF and OF aren't always set the way we want. Determine which 7248 // of these we need. 7249 bool NeedCF = false; 7250 bool NeedOF = false; 7251 switch (X86CC) { 7252 default: break; 7253 case X86::COND_A: case X86::COND_AE: 7254 case X86::COND_B: case X86::COND_BE: 7255 NeedCF = true; 7256 break; 7257 case X86::COND_G: case X86::COND_GE: 7258 case X86::COND_L: case X86::COND_LE: 7259 case X86::COND_O: case X86::COND_NO: 7260 NeedOF = true; 7261 break; 7262 } 7263 7264 // See if we can use the EFLAGS value from the operand instead of 7265 // doing a separate TEST. TEST always sets OF and CF to 0, so unless 7266 // we prove that the arithmetic won't overflow, we can't use OF or CF. 7267 if (Op.getResNo() != 0 || NeedOF || NeedCF) 7268 // Emit a CMP with 0, which is the TEST pattern. 7269 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 7270 DAG.getConstant(0, Op.getValueType())); 7271 7272 unsigned Opcode = 0; 7273 unsigned NumOperands = 0; 7274 switch (Op.getNode()->getOpcode()) { 7275 case ISD::ADD: 7276 // Due to an isel shortcoming, be conservative if this add is likely to be 7277 // selected as part of a load-modify-store instruction. When the root node 7278 // in a match is a store, isel doesn't know how to remap non-chain non-flag 7279 // uses of other nodes in the match, such as the ADD in this case. This 7280 // leads to the ADD being left around and reselected, with the result being 7281 // two adds in the output. Alas, even if none our users are stores, that 7282 // doesn't prove we're O.K. Ergo, if we have any parents that aren't 7283 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require 7284 // climbing the DAG back to the root, and it doesn't seem to be worth the 7285 // effort. 7286 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 7287 UE = Op.getNode()->use_end(); UI != UE; ++UI) 7288 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC) 7289 goto default_case; 7290 7291 if (ConstantSDNode *C = 7292 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) { 7293 // An add of one will be selected as an INC. 7294 if (C->getAPIntValue() == 1) { 7295 Opcode = X86ISD::INC; 7296 NumOperands = 1; 7297 break; 7298 } 7299 7300 // An add of negative one (subtract of one) will be selected as a DEC. 7301 if (C->getAPIntValue().isAllOnesValue()) { 7302 Opcode = X86ISD::DEC; 7303 NumOperands = 1; 7304 break; 7305 } 7306 } 7307 7308 // Otherwise use a regular EFLAGS-setting add. 7309 Opcode = X86ISD::ADD; 7310 NumOperands = 2; 7311 break; 7312 case ISD::AND: { 7313 // If the primary and result isn't used, don't bother using X86ISD::AND, 7314 // because a TEST instruction will be better. 7315 bool NonFlagUse = false; 7316 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 7317 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 7318 SDNode *User = *UI; 7319 unsigned UOpNo = UI.getOperandNo(); 7320 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) { 7321 // Look pass truncate. 7322 UOpNo = User->use_begin().getOperandNo(); 7323 User = *User->use_begin(); 7324 } 7325 7326 if (User->getOpcode() != ISD::BRCOND && 7327 User->getOpcode() != ISD::SETCC && 7328 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) { 7329 NonFlagUse = true; 7330 break; 7331 } 7332 } 7333 7334 if (!NonFlagUse) 7335 break; 7336 } 7337 // FALL THROUGH 7338 case ISD::SUB: 7339 case ISD::OR: 7340 case ISD::XOR: 7341 // Due to the ISEL shortcoming noted above, be conservative if this op is 7342 // likely to be selected as part of a load-modify-store instruction. 7343 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 7344 UE = Op.getNode()->use_end(); UI != UE; ++UI) 7345 if (UI->getOpcode() == ISD::STORE) 7346 goto default_case; 7347 7348 // Otherwise use a regular EFLAGS-setting instruction. 7349 switch (Op.getNode()->getOpcode()) { 7350 default: llvm_unreachable("unexpected operator!"); 7351 case ISD::SUB: Opcode = X86ISD::SUB; break; 7352 case ISD::OR: Opcode = X86ISD::OR; break; 7353 case ISD::XOR: Opcode = X86ISD::XOR; break; 7354 case ISD::AND: Opcode = X86ISD::AND; break; 7355 } 7356 7357 NumOperands = 2; 7358 break; 7359 case X86ISD::ADD: 7360 case X86ISD::SUB: 7361 case X86ISD::INC: 7362 case X86ISD::DEC: 7363 case X86ISD::OR: 7364 case X86ISD::XOR: 7365 case X86ISD::AND: 7366 return SDValue(Op.getNode(), 1); 7367 default: 7368 default_case: 7369 break; 7370 } 7371 7372 if (Opcode == 0) 7373 // Emit a CMP with 0, which is the TEST pattern. 7374 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 7375 DAG.getConstant(0, Op.getValueType())); 7376 7377 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 7378 SmallVector<SDValue, 4> Ops; 7379 for (unsigned i = 0; i != NumOperands; ++i) 7380 Ops.push_back(Op.getOperand(i)); 7381 7382 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands); 7383 DAG.ReplaceAllUsesWith(Op, New); 7384 return SDValue(New.getNode(), 1); 7385} 7386 7387/// Emit nodes that will be selected as "cmp Op0,Op1", or something 7388/// equivalent. 7389SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC, 7390 SelectionDAG &DAG) const { 7391 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) 7392 if (C->getAPIntValue() == 0) 7393 return EmitTest(Op0, X86CC, DAG); 7394 7395 DebugLoc dl = Op0.getDebugLoc(); 7396 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1); 7397} 7398 7399/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node 7400/// if it's possible. 7401SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC, 7402 DebugLoc dl, SelectionDAG &DAG) const { 7403 SDValue Op0 = And.getOperand(0); 7404 SDValue Op1 = And.getOperand(1); 7405 if (Op0.getOpcode() == ISD::TRUNCATE) 7406 Op0 = Op0.getOperand(0); 7407 if (Op1.getOpcode() == ISD::TRUNCATE) 7408 Op1 = Op1.getOperand(0); 7409 7410 SDValue LHS, RHS; 7411 if (Op1.getOpcode() == ISD::SHL) 7412 std::swap(Op0, Op1); 7413 if (Op0.getOpcode() == ISD::SHL) { 7414 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0))) 7415 if (And00C->getZExtValue() == 1) { 7416 // If we looked past a truncate, check that it's only truncating away 7417 // known zeros. 7418 unsigned BitWidth = Op0.getValueSizeInBits(); 7419 unsigned AndBitWidth = And.getValueSizeInBits(); 7420 if (BitWidth > AndBitWidth) { 7421 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones; 7422 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones); 7423 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth) 7424 return SDValue(); 7425 } 7426 LHS = Op1; 7427 RHS = Op0.getOperand(1); 7428 } 7429 } else if (Op1.getOpcode() == ISD::Constant) { 7430 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1); 7431 SDValue AndLHS = Op0; 7432 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) { 7433 LHS = AndLHS.getOperand(0); 7434 RHS = AndLHS.getOperand(1); 7435 } 7436 } 7437 7438 if (LHS.getNode()) { 7439 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT 7440 // instruction. Since the shift amount is in-range-or-undefined, we know 7441 // that doing a bittest on the i32 value is ok. We extend to i32 because 7442 // the encoding for the i16 version is larger than the i32 version. 7443 // Also promote i16 to i32 for performance / code size reason. 7444 if (LHS.getValueType() == MVT::i8 || 7445 LHS.getValueType() == MVT::i16) 7446 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 7447 7448 // If the operand types disagree, extend the shift amount to match. Since 7449 // BT ignores high bits (like shifts) we can use anyextend. 7450 if (LHS.getValueType() != RHS.getValueType()) 7451 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS); 7452 7453 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS); 7454 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B; 7455 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 7456 DAG.getConstant(Cond, MVT::i8), BT); 7457 } 7458 7459 return SDValue(); 7460} 7461 7462SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 7463 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer"); 7464 SDValue Op0 = Op.getOperand(0); 7465 SDValue Op1 = Op.getOperand(1); 7466 DebugLoc dl = Op.getDebugLoc(); 7467 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 7468 7469 // Optimize to BT if possible. 7470 // Lower (X & (1 << N)) == 0 to BT(X, N). 7471 // Lower ((X >>u N) & 1) != 0 to BT(X, N). 7472 // Lower ((X >>s N) & 1) != 0 to BT(X, N). 7473 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && 7474 Op1.getOpcode() == ISD::Constant && 7475 cast<ConstantSDNode>(Op1)->isNullValue() && 7476 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 7477 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG); 7478 if (NewSetCC.getNode()) 7479 return NewSetCC; 7480 } 7481 7482 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of 7483 // these. 7484 if (Op1.getOpcode() == ISD::Constant && 7485 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 || 7486 cast<ConstantSDNode>(Op1)->isNullValue()) && 7487 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 7488 7489 // If the input is a setcc, then reuse the input setcc or use a new one with 7490 // the inverted condition. 7491 if (Op0.getOpcode() == X86ISD::SETCC) { 7492 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0); 7493 bool Invert = (CC == ISD::SETNE) ^ 7494 cast<ConstantSDNode>(Op1)->isNullValue(); 7495 if (!Invert) return Op0; 7496 7497 CCode = X86::GetOppositeBranchCondition(CCode); 7498 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 7499 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1)); 7500 } 7501 } 7502 7503 bool isFP = Op1.getValueType().isFloatingPoint(); 7504 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG); 7505 if (X86CC == X86::COND_INVALID) 7506 return SDValue(); 7507 7508 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG); 7509 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 7510 DAG.getConstant(X86CC, MVT::i8), EFLAGS); 7511} 7512 7513SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const { 7514 SDValue Cond; 7515 SDValue Op0 = Op.getOperand(0); 7516 SDValue Op1 = Op.getOperand(1); 7517 SDValue CC = Op.getOperand(2); 7518 EVT VT = Op.getValueType(); 7519 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 7520 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint(); 7521 DebugLoc dl = Op.getDebugLoc(); 7522 7523 if (isFP) { 7524 unsigned SSECC = 8; 7525 EVT VT0 = Op0.getValueType(); 7526 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64); 7527 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD; 7528 bool Swap = false; 7529 7530 switch (SetCCOpcode) { 7531 default: break; 7532 case ISD::SETOEQ: 7533 case ISD::SETEQ: SSECC = 0; break; 7534 case ISD::SETOGT: 7535 case ISD::SETGT: Swap = true; // Fallthrough 7536 case ISD::SETLT: 7537 case ISD::SETOLT: SSECC = 1; break; 7538 case ISD::SETOGE: 7539 case ISD::SETGE: Swap = true; // Fallthrough 7540 case ISD::SETLE: 7541 case ISD::SETOLE: SSECC = 2; break; 7542 case ISD::SETUO: SSECC = 3; break; 7543 case ISD::SETUNE: 7544 case ISD::SETNE: SSECC = 4; break; 7545 case ISD::SETULE: Swap = true; 7546 case ISD::SETUGE: SSECC = 5; break; 7547 case ISD::SETULT: Swap = true; 7548 case ISD::SETUGT: SSECC = 6; break; 7549 case ISD::SETO: SSECC = 7; break; 7550 } 7551 if (Swap) 7552 std::swap(Op0, Op1); 7553 7554 // In the two special cases we can't handle, emit two comparisons. 7555 if (SSECC == 8) { 7556 if (SetCCOpcode == ISD::SETUEQ) { 7557 SDValue UNORD, EQ; 7558 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8)); 7559 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8)); 7560 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ); 7561 } 7562 else if (SetCCOpcode == ISD::SETONE) { 7563 SDValue ORD, NEQ; 7564 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8)); 7565 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8)); 7566 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ); 7567 } 7568 llvm_unreachable("Illegal FP comparison"); 7569 } 7570 // Handle all other FP comparisons here. 7571 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8)); 7572 } 7573 7574 // We are handling one of the integer comparisons here. Since SSE only has 7575 // GT and EQ comparisons for integer, swapping operands and multiple 7576 // operations may be required for some comparisons. 7577 unsigned Opc = 0, EQOpc = 0, GTOpc = 0; 7578 bool Swap = false, Invert = false, FlipSigns = false; 7579 7580 switch (VT.getSimpleVT().SimpleTy) { 7581 default: break; 7582 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break; 7583 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break; 7584 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break; 7585 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break; 7586 } 7587 7588 switch (SetCCOpcode) { 7589 default: break; 7590 case ISD::SETNE: Invert = true; 7591 case ISD::SETEQ: Opc = EQOpc; break; 7592 case ISD::SETLT: Swap = true; 7593 case ISD::SETGT: Opc = GTOpc; break; 7594 case ISD::SETGE: Swap = true; 7595 case ISD::SETLE: Opc = GTOpc; Invert = true; break; 7596 case ISD::SETULT: Swap = true; 7597 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break; 7598 case ISD::SETUGE: Swap = true; 7599 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break; 7600 } 7601 if (Swap) 7602 std::swap(Op0, Op1); 7603 7604 // Since SSE has no unsigned integer comparisons, we need to flip the sign 7605 // bits of the inputs before performing those operations. 7606 if (FlipSigns) { 7607 EVT EltVT = VT.getVectorElementType(); 7608 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), 7609 EltVT); 7610 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit); 7611 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0], 7612 SignBits.size()); 7613 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec); 7614 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec); 7615 } 7616 7617 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 7618 7619 // If the logical-not of the result is required, perform that now. 7620 if (Invert) 7621 Result = DAG.getNOT(dl, Result, VT); 7622 7623 return Result; 7624} 7625 7626// isX86LogicalCmp - Return true if opcode is a X86 logical comparison. 7627static bool isX86LogicalCmp(SDValue Op) { 7628 unsigned Opc = Op.getNode()->getOpcode(); 7629 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) 7630 return true; 7631 if (Op.getResNo() == 1 && 7632 (Opc == X86ISD::ADD || 7633 Opc == X86ISD::SUB || 7634 Opc == X86ISD::ADC || 7635 Opc == X86ISD::SBB || 7636 Opc == X86ISD::SMUL || 7637 Opc == X86ISD::UMUL || 7638 Opc == X86ISD::INC || 7639 Opc == X86ISD::DEC || 7640 Opc == X86ISD::OR || 7641 Opc == X86ISD::XOR || 7642 Opc == X86ISD::AND)) 7643 return true; 7644 7645 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL) 7646 return true; 7647 7648 return false; 7649} 7650 7651static bool isZero(SDValue V) { 7652 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 7653 return C && C->isNullValue(); 7654} 7655 7656static bool isAllOnes(SDValue V) { 7657 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 7658 return C && C->isAllOnesValue(); 7659} 7660 7661SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7662 bool addTest = true; 7663 SDValue Cond = Op.getOperand(0); 7664 SDValue Op1 = Op.getOperand(1); 7665 SDValue Op2 = Op.getOperand(2); 7666 DebugLoc DL = Op.getDebugLoc(); 7667 SDValue CC; 7668 7669 if (Cond.getOpcode() == ISD::SETCC) { 7670 SDValue NewCond = LowerSETCC(Cond, DAG); 7671 if (NewCond.getNode()) 7672 Cond = NewCond; 7673 } 7674 7675 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y 7676 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y 7677 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y 7678 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y 7679 if (Cond.getOpcode() == X86ISD::SETCC && 7680 Cond.getOperand(1).getOpcode() == X86ISD::CMP && 7681 isZero(Cond.getOperand(1).getOperand(1))) { 7682 SDValue Cmp = Cond.getOperand(1); 7683 7684 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue(); 7685 7686 if ((isAllOnes(Op1) || isAllOnes(Op2)) && 7687 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) { 7688 SDValue Y = isAllOnes(Op2) ? Op1 : Op2; 7689 7690 SDValue CmpOp0 = Cmp.getOperand(0); 7691 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, 7692 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType())); 7693 7694 SDValue Res = // Res = 0 or -1. 7695 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 7696 DAG.getConstant(X86::COND_B, MVT::i8), Cmp); 7697 7698 if (isAllOnes(Op1) != (CondCode == X86::COND_E)) 7699 Res = DAG.getNOT(DL, Res, Res.getValueType()); 7700 7701 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2); 7702 if (N2C == 0 || !N2C->isNullValue()) 7703 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y); 7704 return Res; 7705 } 7706 } 7707 7708 // Look past (and (setcc_carry (cmp ...)), 1). 7709 if (Cond.getOpcode() == ISD::AND && 7710 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 7711 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 7712 if (C && C->getAPIntValue() == 1) 7713 Cond = Cond.getOperand(0); 7714 } 7715 7716 // If condition flag is set by a X86ISD::CMP, then use it as the condition 7717 // setting operand in place of the X86ISD::SETCC. 7718 if (Cond.getOpcode() == X86ISD::SETCC || 7719 Cond.getOpcode() == X86ISD::SETCC_CARRY) { 7720 CC = Cond.getOperand(0); 7721 7722 SDValue Cmp = Cond.getOperand(1); 7723 unsigned Opc = Cmp.getOpcode(); 7724 EVT VT = Op.getValueType(); 7725 7726 bool IllegalFPCMov = false; 7727 if (VT.isFloatingPoint() && !VT.isVector() && 7728 !isScalarFPTypeInSSEReg(VT)) // FPStack? 7729 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue()); 7730 7731 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) || 7732 Opc == X86ISD::BT) { // FIXME 7733 Cond = Cmp; 7734 addTest = false; 7735 } 7736 } 7737 7738 if (addTest) { 7739 // Look pass the truncate. 7740 if (Cond.getOpcode() == ISD::TRUNCATE) 7741 Cond = Cond.getOperand(0); 7742 7743 // We know the result of AND is compared against zero. Try to match 7744 // it to BT. 7745 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 7746 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG); 7747 if (NewSetCC.getNode()) { 7748 CC = NewSetCC.getOperand(0); 7749 Cond = NewSetCC.getOperand(1); 7750 addTest = false; 7751 } 7752 } 7753 } 7754 7755 if (addTest) { 7756 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 7757 Cond = EmitTest(Cond, X86::COND_NE, DAG); 7758 } 7759 7760 // a < b ? -1 : 0 -> RES = ~setcc_carry 7761 // a < b ? 0 : -1 -> RES = setcc_carry 7762 // a >= b ? -1 : 0 -> RES = setcc_carry 7763 // a >= b ? 0 : -1 -> RES = ~setcc_carry 7764 if (Cond.getOpcode() == X86ISD::CMP) { 7765 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue(); 7766 7767 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) && 7768 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) { 7769 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 7770 DAG.getConstant(X86::COND_B, MVT::i8), Cond); 7771 if (isAllOnes(Op1) != (CondCode == X86::COND_B)) 7772 return DAG.getNOT(DL, Res, Res.getValueType()); 7773 return Res; 7774 } 7775 } 7776 7777 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if 7778 // condition is true. 7779 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 7780 SDValue Ops[] = { Op2, Op1, CC, Cond }; 7781 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops)); 7782} 7783 7784// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or 7785// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart 7786// from the AND / OR. 7787static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) { 7788 Opc = Op.getOpcode(); 7789 if (Opc != ISD::OR && Opc != ISD::AND) 7790 return false; 7791 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC && 7792 Op.getOperand(0).hasOneUse() && 7793 Op.getOperand(1).getOpcode() == X86ISD::SETCC && 7794 Op.getOperand(1).hasOneUse()); 7795} 7796 7797// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and 7798// 1 and that the SETCC node has a single use. 7799static bool isXor1OfSetCC(SDValue Op) { 7800 if (Op.getOpcode() != ISD::XOR) 7801 return false; 7802 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7803 if (N1C && N1C->getAPIntValue() == 1) { 7804 return Op.getOperand(0).getOpcode() == X86ISD::SETCC && 7805 Op.getOperand(0).hasOneUse(); 7806 } 7807 return false; 7808} 7809 7810SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 7811 bool addTest = true; 7812 SDValue Chain = Op.getOperand(0); 7813 SDValue Cond = Op.getOperand(1); 7814 SDValue Dest = Op.getOperand(2); 7815 DebugLoc dl = Op.getDebugLoc(); 7816 SDValue CC; 7817 7818 if (Cond.getOpcode() == ISD::SETCC) { 7819 SDValue NewCond = LowerSETCC(Cond, DAG); 7820 if (NewCond.getNode()) 7821 Cond = NewCond; 7822 } 7823#if 0 7824 // FIXME: LowerXALUO doesn't handle these!! 7825 else if (Cond.getOpcode() == X86ISD::ADD || 7826 Cond.getOpcode() == X86ISD::SUB || 7827 Cond.getOpcode() == X86ISD::SMUL || 7828 Cond.getOpcode() == X86ISD::UMUL) 7829 Cond = LowerXALUO(Cond, DAG); 7830#endif 7831 7832 // Look pass (and (setcc_carry (cmp ...)), 1). 7833 if (Cond.getOpcode() == ISD::AND && 7834 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 7835 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 7836 if (C && C->getAPIntValue() == 1) 7837 Cond = Cond.getOperand(0); 7838 } 7839 7840 // If condition flag is set by a X86ISD::CMP, then use it as the condition 7841 // setting operand in place of the X86ISD::SETCC. 7842 if (Cond.getOpcode() == X86ISD::SETCC || 7843 Cond.getOpcode() == X86ISD::SETCC_CARRY) { 7844 CC = Cond.getOperand(0); 7845 7846 SDValue Cmp = Cond.getOperand(1); 7847 unsigned Opc = Cmp.getOpcode(); 7848 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp?? 7849 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) { 7850 Cond = Cmp; 7851 addTest = false; 7852 } else { 7853 switch (cast<ConstantSDNode>(CC)->getZExtValue()) { 7854 default: break; 7855 case X86::COND_O: 7856 case X86::COND_B: 7857 // These can only come from an arithmetic instruction with overflow, 7858 // e.g. SADDO, UADDO. 7859 Cond = Cond.getNode()->getOperand(1); 7860 addTest = false; 7861 break; 7862 } 7863 } 7864 } else { 7865 unsigned CondOpc; 7866 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) { 7867 SDValue Cmp = Cond.getOperand(0).getOperand(1); 7868 if (CondOpc == ISD::OR) { 7869 // Also, recognize the pattern generated by an FCMP_UNE. We can emit 7870 // two branches instead of an explicit OR instruction with a 7871 // separate test. 7872 if (Cmp == Cond.getOperand(1).getOperand(1) && 7873 isX86LogicalCmp(Cmp)) { 7874 CC = Cond.getOperand(0).getOperand(0); 7875 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 7876 Chain, Dest, CC, Cmp); 7877 CC = Cond.getOperand(1).getOperand(0); 7878 Cond = Cmp; 7879 addTest = false; 7880 } 7881 } else { // ISD::AND 7882 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit 7883 // two branches instead of an explicit AND instruction with a 7884 // separate test. However, we only do this if this block doesn't 7885 // have a fall-through edge, because this requires an explicit 7886 // jmp when the condition is false. 7887 if (Cmp == Cond.getOperand(1).getOperand(1) && 7888 isX86LogicalCmp(Cmp) && 7889 Op.getNode()->hasOneUse()) { 7890 X86::CondCode CCode = 7891 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 7892 CCode = X86::GetOppositeBranchCondition(CCode); 7893 CC = DAG.getConstant(CCode, MVT::i8); 7894 SDNode *User = *Op.getNode()->use_begin(); 7895 // Look for an unconditional branch following this conditional branch. 7896 // We need this because we need to reverse the successors in order 7897 // to implement FCMP_OEQ. 7898 if (User->getOpcode() == ISD::BR) { 7899 SDValue FalseBB = User->getOperand(1); 7900 SDNode *NewBR = 7901 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 7902 assert(NewBR == User); 7903 (void)NewBR; 7904 Dest = FalseBB; 7905 7906 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 7907 Chain, Dest, CC, Cmp); 7908 X86::CondCode CCode = 7909 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0); 7910 CCode = X86::GetOppositeBranchCondition(CCode); 7911 CC = DAG.getConstant(CCode, MVT::i8); 7912 Cond = Cmp; 7913 addTest = false; 7914 } 7915 } 7916 } 7917 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) { 7918 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition. 7919 // It should be transformed during dag combiner except when the condition 7920 // is set by a arithmetics with overflow node. 7921 X86::CondCode CCode = 7922 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 7923 CCode = X86::GetOppositeBranchCondition(CCode); 7924 CC = DAG.getConstant(CCode, MVT::i8); 7925 Cond = Cond.getOperand(0).getOperand(1); 7926 addTest = false; 7927 } 7928 } 7929 7930 if (addTest) { 7931 // Look pass the truncate. 7932 if (Cond.getOpcode() == ISD::TRUNCATE) 7933 Cond = Cond.getOperand(0); 7934 7935 // We know the result of AND is compared against zero. Try to match 7936 // it to BT. 7937 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 7938 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG); 7939 if (NewSetCC.getNode()) { 7940 CC = NewSetCC.getOperand(0); 7941 Cond = NewSetCC.getOperand(1); 7942 addTest = false; 7943 } 7944 } 7945 } 7946 7947 if (addTest) { 7948 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 7949 Cond = EmitTest(Cond, X86::COND_NE, DAG); 7950 } 7951 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 7952 Chain, Dest, CC, Cond); 7953} 7954 7955 7956// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets. 7957// Calls to _alloca is needed to probe the stack when allocating more than 4k 7958// bytes in one go. Touching the stack at 4K increments is necessary to ensure 7959// that the guard pages used by the OS virtual memory manager are allocated in 7960// correct sequence. 7961SDValue 7962X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7963 SelectionDAG &DAG) const { 7964 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) && 7965 "This should be used only on Windows targets"); 7966 assert(!Subtarget->isTargetEnvMacho()); 7967 DebugLoc dl = Op.getDebugLoc(); 7968 7969 // Get the inputs. 7970 SDValue Chain = Op.getOperand(0); 7971 SDValue Size = Op.getOperand(1); 7972 // FIXME: Ensure alignment here 7973 7974 SDValue Flag; 7975 7976 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32; 7977 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX); 7978 7979 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag); 7980 Flag = Chain.getValue(1); 7981 7982 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7983 7984 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag); 7985 Flag = Chain.getValue(1); 7986 7987 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1); 7988 7989 SDValue Ops1[2] = { Chain.getValue(0), Chain }; 7990 return DAG.getMergeValues(Ops1, 2, dl); 7991} 7992 7993SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 7994 MachineFunction &MF = DAG.getMachineFunction(); 7995 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 7996 7997 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7998 DebugLoc DL = Op.getDebugLoc(); 7999 8000 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) { 8001 // vastart just stores the address of the VarArgsFrameIndex slot into the 8002 // memory location argument. 8003 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 8004 getPointerTy()); 8005 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 8006 MachinePointerInfo(SV), false, false, 0); 8007 } 8008 8009 // __va_list_tag: 8010 // gp_offset (0 - 6 * 8) 8011 // fp_offset (48 - 48 + 8 * 16) 8012 // overflow_arg_area (point to parameters coming in memory). 8013 // reg_save_area 8014 SmallVector<SDValue, 8> MemOps; 8015 SDValue FIN = Op.getOperand(1); 8016 // Store gp_offset 8017 SDValue Store = DAG.getStore(Op.getOperand(0), DL, 8018 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), 8019 MVT::i32), 8020 FIN, MachinePointerInfo(SV), false, false, 0); 8021 MemOps.push_back(Store); 8022 8023 // Store fp_offset 8024 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 8025 FIN, DAG.getIntPtrConstant(4)); 8026 Store = DAG.getStore(Op.getOperand(0), DL, 8027 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), 8028 MVT::i32), 8029 FIN, MachinePointerInfo(SV, 4), false, false, 0); 8030 MemOps.push_back(Store); 8031 8032 // Store ptr to overflow_arg_area 8033 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 8034 FIN, DAG.getIntPtrConstant(4)); 8035 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 8036 getPointerTy()); 8037 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, 8038 MachinePointerInfo(SV, 8), 8039 false, false, 0); 8040 MemOps.push_back(Store); 8041 8042 // Store ptr to reg_save_area. 8043 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 8044 FIN, DAG.getIntPtrConstant(8)); 8045 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 8046 getPointerTy()); 8047 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, 8048 MachinePointerInfo(SV, 16), false, false, 0); 8049 MemOps.push_back(Store); 8050 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 8051 &MemOps[0], MemOps.size()); 8052} 8053 8054SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 8055 assert(Subtarget->is64Bit() && 8056 "LowerVAARG only handles 64-bit va_arg!"); 8057 assert((Subtarget->isTargetLinux() || 8058 Subtarget->isTargetDarwin()) && 8059 "Unhandled target in LowerVAARG"); 8060 assert(Op.getNode()->getNumOperands() == 4); 8061 SDValue Chain = Op.getOperand(0); 8062 SDValue SrcPtr = Op.getOperand(1); 8063 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 8064 unsigned Align = Op.getConstantOperandVal(3); 8065 DebugLoc dl = Op.getDebugLoc(); 8066 8067 EVT ArgVT = Op.getNode()->getValueType(0); 8068 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 8069 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy); 8070 uint8_t ArgMode; 8071 8072 // Decide which area this value should be read from. 8073 // TODO: Implement the AMD64 ABI in its entirety. This simple 8074 // selection mechanism works only for the basic types. 8075 if (ArgVT == MVT::f80) { 8076 llvm_unreachable("va_arg for f80 not yet implemented"); 8077 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) { 8078 ArgMode = 2; // Argument passed in XMM register. Use fp_offset. 8079 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) { 8080 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset. 8081 } else { 8082 llvm_unreachable("Unhandled argument type in LowerVAARG"); 8083 } 8084 8085 if (ArgMode == 2) { 8086 // Sanity Check: Make sure using fp_offset makes sense. 8087 assert(!UseSoftFloat && 8088 !(DAG.getMachineFunction() 8089 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) && 8090 Subtarget->hasXMM()); 8091 } 8092 8093 // Insert VAARG_64 node into the DAG 8094 // VAARG_64 returns two values: Variable Argument Address, Chain 8095 SmallVector<SDValue, 11> InstOps; 8096 InstOps.push_back(Chain); 8097 InstOps.push_back(SrcPtr); 8098 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32)); 8099 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8)); 8100 InstOps.push_back(DAG.getConstant(Align, MVT::i32)); 8101 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other); 8102 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl, 8103 VTs, &InstOps[0], InstOps.size(), 8104 MVT::i64, 8105 MachinePointerInfo(SV), 8106 /*Align=*/0, 8107 /*Volatile=*/false, 8108 /*ReadMem=*/true, 8109 /*WriteMem=*/true); 8110 Chain = VAARG.getValue(1); 8111 8112 // Load the next argument and return it 8113 return DAG.getLoad(ArgVT, dl, 8114 Chain, 8115 VAARG, 8116 MachinePointerInfo(), 8117 false, false, 0); 8118} 8119 8120SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 8121 // X86-64 va_list is a struct { i32, i32, i8*, i8* }. 8122 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!"); 8123 SDValue Chain = Op.getOperand(0); 8124 SDValue DstPtr = Op.getOperand(1); 8125 SDValue SrcPtr = Op.getOperand(2); 8126 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 8127 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 8128 DebugLoc DL = Op.getDebugLoc(); 8129 8130 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, 8131 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false, 8132 false, 8133 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV)); 8134} 8135 8136SDValue 8137X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const { 8138 DebugLoc dl = Op.getDebugLoc(); 8139 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8140 switch (IntNo) { 8141 default: return SDValue(); // Don't custom lower most intrinsics. 8142 // Comparison intrinsics. 8143 case Intrinsic::x86_sse_comieq_ss: 8144 case Intrinsic::x86_sse_comilt_ss: 8145 case Intrinsic::x86_sse_comile_ss: 8146 case Intrinsic::x86_sse_comigt_ss: 8147 case Intrinsic::x86_sse_comige_ss: 8148 case Intrinsic::x86_sse_comineq_ss: 8149 case Intrinsic::x86_sse_ucomieq_ss: 8150 case Intrinsic::x86_sse_ucomilt_ss: 8151 case Intrinsic::x86_sse_ucomile_ss: 8152 case Intrinsic::x86_sse_ucomigt_ss: 8153 case Intrinsic::x86_sse_ucomige_ss: 8154 case Intrinsic::x86_sse_ucomineq_ss: 8155 case Intrinsic::x86_sse2_comieq_sd: 8156 case Intrinsic::x86_sse2_comilt_sd: 8157 case Intrinsic::x86_sse2_comile_sd: 8158 case Intrinsic::x86_sse2_comigt_sd: 8159 case Intrinsic::x86_sse2_comige_sd: 8160 case Intrinsic::x86_sse2_comineq_sd: 8161 case Intrinsic::x86_sse2_ucomieq_sd: 8162 case Intrinsic::x86_sse2_ucomilt_sd: 8163 case Intrinsic::x86_sse2_ucomile_sd: 8164 case Intrinsic::x86_sse2_ucomigt_sd: 8165 case Intrinsic::x86_sse2_ucomige_sd: 8166 case Intrinsic::x86_sse2_ucomineq_sd: { 8167 unsigned Opc = 0; 8168 ISD::CondCode CC = ISD::SETCC_INVALID; 8169 switch (IntNo) { 8170 default: break; 8171 case Intrinsic::x86_sse_comieq_ss: 8172 case Intrinsic::x86_sse2_comieq_sd: 8173 Opc = X86ISD::COMI; 8174 CC = ISD::SETEQ; 8175 break; 8176 case Intrinsic::x86_sse_comilt_ss: 8177 case Intrinsic::x86_sse2_comilt_sd: 8178 Opc = X86ISD::COMI; 8179 CC = ISD::SETLT; 8180 break; 8181 case Intrinsic::x86_sse_comile_ss: 8182 case Intrinsic::x86_sse2_comile_sd: 8183 Opc = X86ISD::COMI; 8184 CC = ISD::SETLE; 8185 break; 8186 case Intrinsic::x86_sse_comigt_ss: 8187 case Intrinsic::x86_sse2_comigt_sd: 8188 Opc = X86ISD::COMI; 8189 CC = ISD::SETGT; 8190 break; 8191 case Intrinsic::x86_sse_comige_ss: 8192 case Intrinsic::x86_sse2_comige_sd: 8193 Opc = X86ISD::COMI; 8194 CC = ISD::SETGE; 8195 break; 8196 case Intrinsic::x86_sse_comineq_ss: 8197 case Intrinsic::x86_sse2_comineq_sd: 8198 Opc = X86ISD::COMI; 8199 CC = ISD::SETNE; 8200 break; 8201 case Intrinsic::x86_sse_ucomieq_ss: 8202 case Intrinsic::x86_sse2_ucomieq_sd: 8203 Opc = X86ISD::UCOMI; 8204 CC = ISD::SETEQ; 8205 break; 8206 case Intrinsic::x86_sse_ucomilt_ss: 8207 case Intrinsic::x86_sse2_ucomilt_sd: 8208 Opc = X86ISD::UCOMI; 8209 CC = ISD::SETLT; 8210 break; 8211 case Intrinsic::x86_sse_ucomile_ss: 8212 case Intrinsic::x86_sse2_ucomile_sd: 8213 Opc = X86ISD::UCOMI; 8214 CC = ISD::SETLE; 8215 break; 8216 case Intrinsic::x86_sse_ucomigt_ss: 8217 case Intrinsic::x86_sse2_ucomigt_sd: 8218 Opc = X86ISD::UCOMI; 8219 CC = ISD::SETGT; 8220 break; 8221 case Intrinsic::x86_sse_ucomige_ss: 8222 case Intrinsic::x86_sse2_ucomige_sd: 8223 Opc = X86ISD::UCOMI; 8224 CC = ISD::SETGE; 8225 break; 8226 case Intrinsic::x86_sse_ucomineq_ss: 8227 case Intrinsic::x86_sse2_ucomineq_sd: 8228 Opc = X86ISD::UCOMI; 8229 CC = ISD::SETNE; 8230 break; 8231 } 8232 8233 SDValue LHS = Op.getOperand(1); 8234 SDValue RHS = Op.getOperand(2); 8235 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG); 8236 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!"); 8237 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS); 8238 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8239 DAG.getConstant(X86CC, MVT::i8), Cond); 8240 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 8241 } 8242 // ptest and testp intrinsics. The intrinsic these come from are designed to 8243 // return an integer value, not just an instruction so lower it to the ptest 8244 // or testp pattern and a setcc for the result. 8245 case Intrinsic::x86_sse41_ptestz: 8246 case Intrinsic::x86_sse41_ptestc: 8247 case Intrinsic::x86_sse41_ptestnzc: 8248 case Intrinsic::x86_avx_ptestz_256: 8249 case Intrinsic::x86_avx_ptestc_256: 8250 case Intrinsic::x86_avx_ptestnzc_256: 8251 case Intrinsic::x86_avx_vtestz_ps: 8252 case Intrinsic::x86_avx_vtestc_ps: 8253 case Intrinsic::x86_avx_vtestnzc_ps: 8254 case Intrinsic::x86_avx_vtestz_pd: 8255 case Intrinsic::x86_avx_vtestc_pd: 8256 case Intrinsic::x86_avx_vtestnzc_pd: 8257 case Intrinsic::x86_avx_vtestz_ps_256: 8258 case Intrinsic::x86_avx_vtestc_ps_256: 8259 case Intrinsic::x86_avx_vtestnzc_ps_256: 8260 case Intrinsic::x86_avx_vtestz_pd_256: 8261 case Intrinsic::x86_avx_vtestc_pd_256: 8262 case Intrinsic::x86_avx_vtestnzc_pd_256: { 8263 bool IsTestPacked = false; 8264 unsigned X86CC = 0; 8265 switch (IntNo) { 8266 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering."); 8267 case Intrinsic::x86_avx_vtestz_ps: 8268 case Intrinsic::x86_avx_vtestz_pd: 8269 case Intrinsic::x86_avx_vtestz_ps_256: 8270 case Intrinsic::x86_avx_vtestz_pd_256: 8271 IsTestPacked = true; // Fallthrough 8272 case Intrinsic::x86_sse41_ptestz: 8273 case Intrinsic::x86_avx_ptestz_256: 8274 // ZF = 1 8275 X86CC = X86::COND_E; 8276 break; 8277 case Intrinsic::x86_avx_vtestc_ps: 8278 case Intrinsic::x86_avx_vtestc_pd: 8279 case Intrinsic::x86_avx_vtestc_ps_256: 8280 case Intrinsic::x86_avx_vtestc_pd_256: 8281 IsTestPacked = true; // Fallthrough 8282 case Intrinsic::x86_sse41_ptestc: 8283 case Intrinsic::x86_avx_ptestc_256: 8284 // CF = 1 8285 X86CC = X86::COND_B; 8286 break; 8287 case Intrinsic::x86_avx_vtestnzc_ps: 8288 case Intrinsic::x86_avx_vtestnzc_pd: 8289 case Intrinsic::x86_avx_vtestnzc_ps_256: 8290 case Intrinsic::x86_avx_vtestnzc_pd_256: 8291 IsTestPacked = true; // Fallthrough 8292 case Intrinsic::x86_sse41_ptestnzc: 8293 case Intrinsic::x86_avx_ptestnzc_256: 8294 // ZF and CF = 0 8295 X86CC = X86::COND_A; 8296 break; 8297 } 8298 8299 SDValue LHS = Op.getOperand(1); 8300 SDValue RHS = Op.getOperand(2); 8301 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST; 8302 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS); 8303 SDValue CC = DAG.getConstant(X86CC, MVT::i8); 8304 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test); 8305 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 8306 } 8307 8308 // Fix vector shift instructions where the last operand is a non-immediate 8309 // i32 value. 8310 case Intrinsic::x86_sse2_pslli_w: 8311 case Intrinsic::x86_sse2_pslli_d: 8312 case Intrinsic::x86_sse2_pslli_q: 8313 case Intrinsic::x86_sse2_psrli_w: 8314 case Intrinsic::x86_sse2_psrli_d: 8315 case Intrinsic::x86_sse2_psrli_q: 8316 case Intrinsic::x86_sse2_psrai_w: 8317 case Intrinsic::x86_sse2_psrai_d: 8318 case Intrinsic::x86_mmx_pslli_w: 8319 case Intrinsic::x86_mmx_pslli_d: 8320 case Intrinsic::x86_mmx_pslli_q: 8321 case Intrinsic::x86_mmx_psrli_w: 8322 case Intrinsic::x86_mmx_psrli_d: 8323 case Intrinsic::x86_mmx_psrli_q: 8324 case Intrinsic::x86_mmx_psrai_w: 8325 case Intrinsic::x86_mmx_psrai_d: { 8326 SDValue ShAmt = Op.getOperand(2); 8327 if (isa<ConstantSDNode>(ShAmt)) 8328 return SDValue(); 8329 8330 unsigned NewIntNo = 0; 8331 EVT ShAmtVT = MVT::v4i32; 8332 switch (IntNo) { 8333 case Intrinsic::x86_sse2_pslli_w: 8334 NewIntNo = Intrinsic::x86_sse2_psll_w; 8335 break; 8336 case Intrinsic::x86_sse2_pslli_d: 8337 NewIntNo = Intrinsic::x86_sse2_psll_d; 8338 break; 8339 case Intrinsic::x86_sse2_pslli_q: 8340 NewIntNo = Intrinsic::x86_sse2_psll_q; 8341 break; 8342 case Intrinsic::x86_sse2_psrli_w: 8343 NewIntNo = Intrinsic::x86_sse2_psrl_w; 8344 break; 8345 case Intrinsic::x86_sse2_psrli_d: 8346 NewIntNo = Intrinsic::x86_sse2_psrl_d; 8347 break; 8348 case Intrinsic::x86_sse2_psrli_q: 8349 NewIntNo = Intrinsic::x86_sse2_psrl_q; 8350 break; 8351 case Intrinsic::x86_sse2_psrai_w: 8352 NewIntNo = Intrinsic::x86_sse2_psra_w; 8353 break; 8354 case Intrinsic::x86_sse2_psrai_d: 8355 NewIntNo = Intrinsic::x86_sse2_psra_d; 8356 break; 8357 default: { 8358 ShAmtVT = MVT::v2i32; 8359 switch (IntNo) { 8360 case Intrinsic::x86_mmx_pslli_w: 8361 NewIntNo = Intrinsic::x86_mmx_psll_w; 8362 break; 8363 case Intrinsic::x86_mmx_pslli_d: 8364 NewIntNo = Intrinsic::x86_mmx_psll_d; 8365 break; 8366 case Intrinsic::x86_mmx_pslli_q: 8367 NewIntNo = Intrinsic::x86_mmx_psll_q; 8368 break; 8369 case Intrinsic::x86_mmx_psrli_w: 8370 NewIntNo = Intrinsic::x86_mmx_psrl_w; 8371 break; 8372 case Intrinsic::x86_mmx_psrli_d: 8373 NewIntNo = Intrinsic::x86_mmx_psrl_d; 8374 break; 8375 case Intrinsic::x86_mmx_psrli_q: 8376 NewIntNo = Intrinsic::x86_mmx_psrl_q; 8377 break; 8378 case Intrinsic::x86_mmx_psrai_w: 8379 NewIntNo = Intrinsic::x86_mmx_psra_w; 8380 break; 8381 case Intrinsic::x86_mmx_psrai_d: 8382 NewIntNo = Intrinsic::x86_mmx_psra_d; 8383 break; 8384 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 8385 } 8386 break; 8387 } 8388 } 8389 8390 // The vector shift intrinsics with scalars uses 32b shift amounts but 8391 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 8392 // to be zero. 8393 SDValue ShOps[4]; 8394 ShOps[0] = ShAmt; 8395 ShOps[1] = DAG.getConstant(0, MVT::i32); 8396 if (ShAmtVT == MVT::v4i32) { 8397 ShOps[2] = DAG.getUNDEF(MVT::i32); 8398 ShOps[3] = DAG.getUNDEF(MVT::i32); 8399 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4); 8400 } else { 8401 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2); 8402// FIXME this must be lowered to get rid of the invalid type. 8403 } 8404 8405 EVT VT = Op.getValueType(); 8406 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt); 8407 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8408 DAG.getConstant(NewIntNo, MVT::i32), 8409 Op.getOperand(1), ShAmt); 8410 } 8411 } 8412} 8413 8414SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, 8415 SelectionDAG &DAG) const { 8416 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 8417 MFI->setReturnAddressIsTaken(true); 8418 8419 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8420 DebugLoc dl = Op.getDebugLoc(); 8421 8422 if (Depth > 0) { 8423 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 8424 SDValue Offset = 8425 DAG.getConstant(TD->getPointerSize(), 8426 Subtarget->is64Bit() ? MVT::i64 : MVT::i32); 8427 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 8428 DAG.getNode(ISD::ADD, dl, getPointerTy(), 8429 FrameAddr, Offset), 8430 MachinePointerInfo(), false, false, 0); 8431 } 8432 8433 // Just load the return address. 8434 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG); 8435 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 8436 RetAddrFI, MachinePointerInfo(), false, false, 0); 8437} 8438 8439SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 8440 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 8441 MFI->setFrameAddressIsTaken(true); 8442 8443 EVT VT = Op.getValueType(); 8444 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful 8445 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8446 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP; 8447 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 8448 while (Depth--) 8449 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 8450 MachinePointerInfo(), 8451 false, false, 0); 8452 return FrameAddr; 8453} 8454 8455SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op, 8456 SelectionDAG &DAG) const { 8457 return DAG.getIntPtrConstant(2*TD->getPointerSize()); 8458} 8459 8460SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const { 8461 MachineFunction &MF = DAG.getMachineFunction(); 8462 SDValue Chain = Op.getOperand(0); 8463 SDValue Offset = Op.getOperand(1); 8464 SDValue Handler = Op.getOperand(2); 8465 DebugLoc dl = Op.getDebugLoc(); 8466 8467 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, 8468 Subtarget->is64Bit() ? X86::RBP : X86::EBP, 8469 getPointerTy()); 8470 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX); 8471 8472 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame, 8473 DAG.getIntPtrConstant(TD->getPointerSize())); 8474 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset); 8475 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(), 8476 false, false, 0); 8477 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr); 8478 MF.getRegInfo().addLiveOut(StoreAddrReg); 8479 8480 return DAG.getNode(X86ISD::EH_RETURN, dl, 8481 MVT::Other, 8482 Chain, DAG.getRegister(StoreAddrReg, getPointerTy())); 8483} 8484 8485SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op, 8486 SelectionDAG &DAG) const { 8487 SDValue Root = Op.getOperand(0); 8488 SDValue Trmp = Op.getOperand(1); // trampoline 8489 SDValue FPtr = Op.getOperand(2); // nested function 8490 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 8491 DebugLoc dl = Op.getDebugLoc(); 8492 8493 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 8494 8495 if (Subtarget->is64Bit()) { 8496 SDValue OutChains[6]; 8497 8498 // Large code-model. 8499 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode. 8500 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode. 8501 8502 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10); 8503 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11); 8504 8505 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix 8506 8507 // Load the pointer to the nested function into R11. 8508 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11 8509 SDValue Addr = Trmp; 8510 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 8511 Addr, MachinePointerInfo(TrmpAddr), 8512 false, false, 0); 8513 8514 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8515 DAG.getConstant(2, MVT::i64)); 8516 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, 8517 MachinePointerInfo(TrmpAddr, 2), 8518 false, false, 2); 8519 8520 // Load the 'nest' parameter value into R10. 8521 // R10 is specified in X86CallingConv.td 8522 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10 8523 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8524 DAG.getConstant(10, MVT::i64)); 8525 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 8526 Addr, MachinePointerInfo(TrmpAddr, 10), 8527 false, false, 0); 8528 8529 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8530 DAG.getConstant(12, MVT::i64)); 8531 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, 8532 MachinePointerInfo(TrmpAddr, 12), 8533 false, false, 2); 8534 8535 // Jump to the nested function. 8536 OpCode = (JMP64r << 8) | REX_WB; // jmpq *... 8537 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8538 DAG.getConstant(20, MVT::i64)); 8539 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 8540 Addr, MachinePointerInfo(TrmpAddr, 20), 8541 false, false, 0); 8542 8543 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11 8544 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8545 DAG.getConstant(22, MVT::i64)); 8546 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr, 8547 MachinePointerInfo(TrmpAddr, 22), 8548 false, false, 0); 8549 8550 SDValue Ops[] = 8551 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) }; 8552 return DAG.getMergeValues(Ops, 2, dl); 8553 } else { 8554 const Function *Func = 8555 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue()); 8556 CallingConv::ID CC = Func->getCallingConv(); 8557 unsigned NestReg; 8558 8559 switch (CC) { 8560 default: 8561 llvm_unreachable("Unsupported calling convention"); 8562 case CallingConv::C: 8563 case CallingConv::X86_StdCall: { 8564 // Pass 'nest' parameter in ECX. 8565 // Must be kept in sync with X86CallingConv.td 8566 NestReg = X86::ECX; 8567 8568 // Check that ECX wasn't needed by an 'inreg' parameter. 8569 const FunctionType *FTy = Func->getFunctionType(); 8570 const AttrListPtr &Attrs = Func->getAttributes(); 8571 8572 if (!Attrs.isEmpty() && !Func->isVarArg()) { 8573 unsigned InRegCount = 0; 8574 unsigned Idx = 1; 8575 8576 for (FunctionType::param_iterator I = FTy->param_begin(), 8577 E = FTy->param_end(); I != E; ++I, ++Idx) 8578 if (Attrs.paramHasAttr(Idx, Attribute::InReg)) 8579 // FIXME: should only count parameters that are lowered to integers. 8580 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32; 8581 8582 if (InRegCount > 2) { 8583 report_fatal_error("Nest register in use - reduce number of inreg" 8584 " parameters!"); 8585 } 8586 } 8587 break; 8588 } 8589 case CallingConv::X86_FastCall: 8590 case CallingConv::X86_ThisCall: 8591 case CallingConv::Fast: 8592 // Pass 'nest' parameter in EAX. 8593 // Must be kept in sync with X86CallingConv.td 8594 NestReg = X86::EAX; 8595 break; 8596 } 8597 8598 SDValue OutChains[4]; 8599 SDValue Addr, Disp; 8600 8601 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 8602 DAG.getConstant(10, MVT::i32)); 8603 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr); 8604 8605 // This is storing the opcode for MOV32ri. 8606 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte. 8607 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg); 8608 OutChains[0] = DAG.getStore(Root, dl, 8609 DAG.getConstant(MOV32ri|N86Reg, MVT::i8), 8610 Trmp, MachinePointerInfo(TrmpAddr), 8611 false, false, 0); 8612 8613 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 8614 DAG.getConstant(1, MVT::i32)); 8615 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, 8616 MachinePointerInfo(TrmpAddr, 1), 8617 false, false, 1); 8618 8619 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode. 8620 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 8621 DAG.getConstant(5, MVT::i32)); 8622 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr, 8623 MachinePointerInfo(TrmpAddr, 5), 8624 false, false, 1); 8625 8626 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 8627 DAG.getConstant(6, MVT::i32)); 8628 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, 8629 MachinePointerInfo(TrmpAddr, 6), 8630 false, false, 1); 8631 8632 SDValue Ops[] = 8633 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) }; 8634 return DAG.getMergeValues(Ops, 2, dl); 8635 } 8636} 8637 8638SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8639 SelectionDAG &DAG) const { 8640 /* 8641 The rounding mode is in bits 11:10 of FPSR, and has the following 8642 settings: 8643 00 Round to nearest 8644 01 Round to -inf 8645 10 Round to +inf 8646 11 Round to 0 8647 8648 FLT_ROUNDS, on the other hand, expects the following: 8649 -1 Undefined 8650 0 Round to 0 8651 1 Round to nearest 8652 2 Round to +inf 8653 3 Round to -inf 8654 8655 To perform the conversion, we do: 8656 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3) 8657 */ 8658 8659 MachineFunction &MF = DAG.getMachineFunction(); 8660 const TargetMachine &TM = MF.getTarget(); 8661 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 8662 unsigned StackAlignment = TFI.getStackAlignment(); 8663 EVT VT = Op.getValueType(); 8664 DebugLoc DL = Op.getDebugLoc(); 8665 8666 // Save FP Control Word to stack slot 8667 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false); 8668 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8669 8670 8671 MachineMemOperand *MMO = 8672 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8673 MachineMemOperand::MOStore, 2, 2); 8674 8675 SDValue Ops[] = { DAG.getEntryNode(), StackSlot }; 8676 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL, 8677 DAG.getVTList(MVT::Other), 8678 Ops, 2, MVT::i16, MMO); 8679 8680 // Load FP Control Word from stack slot 8681 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, 8682 MachinePointerInfo(), false, false, 0); 8683 8684 // Transform as necessary 8685 SDValue CWD1 = 8686 DAG.getNode(ISD::SRL, DL, MVT::i16, 8687 DAG.getNode(ISD::AND, DL, MVT::i16, 8688 CWD, DAG.getConstant(0x800, MVT::i16)), 8689 DAG.getConstant(11, MVT::i8)); 8690 SDValue CWD2 = 8691 DAG.getNode(ISD::SRL, DL, MVT::i16, 8692 DAG.getNode(ISD::AND, DL, MVT::i16, 8693 CWD, DAG.getConstant(0x400, MVT::i16)), 8694 DAG.getConstant(9, MVT::i8)); 8695 8696 SDValue RetVal = 8697 DAG.getNode(ISD::AND, DL, MVT::i16, 8698 DAG.getNode(ISD::ADD, DL, MVT::i16, 8699 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2), 8700 DAG.getConstant(1, MVT::i16)), 8701 DAG.getConstant(3, MVT::i16)); 8702 8703 8704 return DAG.getNode((VT.getSizeInBits() < 16 ? 8705 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal); 8706} 8707 8708SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const { 8709 EVT VT = Op.getValueType(); 8710 EVT OpVT = VT; 8711 unsigned NumBits = VT.getSizeInBits(); 8712 DebugLoc dl = Op.getDebugLoc(); 8713 8714 Op = Op.getOperand(0); 8715 if (VT == MVT::i8) { 8716 // Zero extend to i32 since there is not an i8 bsr. 8717 OpVT = MVT::i32; 8718 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 8719 } 8720 8721 // Issue a bsr (scan bits in reverse) which also sets EFLAGS. 8722 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 8723 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 8724 8725 // If src is zero (i.e. bsr sets ZF), returns NumBits. 8726 SDValue Ops[] = { 8727 Op, 8728 DAG.getConstant(NumBits+NumBits-1, OpVT), 8729 DAG.getConstant(X86::COND_E, MVT::i8), 8730 Op.getValue(1) 8731 }; 8732 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 8733 8734 // Finally xor with NumBits-1. 8735 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 8736 8737 if (VT == MVT::i8) 8738 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 8739 return Op; 8740} 8741 8742SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const { 8743 EVT VT = Op.getValueType(); 8744 EVT OpVT = VT; 8745 unsigned NumBits = VT.getSizeInBits(); 8746 DebugLoc dl = Op.getDebugLoc(); 8747 8748 Op = Op.getOperand(0); 8749 if (VT == MVT::i8) { 8750 OpVT = MVT::i32; 8751 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 8752 } 8753 8754 // Issue a bsf (scan bits forward) which also sets EFLAGS. 8755 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 8756 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op); 8757 8758 // If src is zero (i.e. bsf sets ZF), returns NumBits. 8759 SDValue Ops[] = { 8760 Op, 8761 DAG.getConstant(NumBits, OpVT), 8762 DAG.getConstant(X86::COND_E, MVT::i8), 8763 Op.getValue(1) 8764 }; 8765 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 8766 8767 if (VT == MVT::i8) 8768 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 8769 return Op; 8770} 8771 8772SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const { 8773 EVT VT = Op.getValueType(); 8774 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply"); 8775 DebugLoc dl = Op.getDebugLoc(); 8776 8777 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32); 8778 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32); 8779 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b ); 8780 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi ); 8781 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b ); 8782 // 8783 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 ); 8784 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 ); 8785 // return AloBlo + AloBhi + AhiBlo; 8786 8787 SDValue A = Op.getOperand(0); 8788 SDValue B = Op.getOperand(1); 8789 8790 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8791 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 8792 A, DAG.getConstant(32, MVT::i32)); 8793 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8794 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 8795 B, DAG.getConstant(32, MVT::i32)); 8796 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8797 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 8798 A, B); 8799 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8800 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 8801 A, Bhi); 8802 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8803 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 8804 Ahi, B); 8805 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8806 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 8807 AloBhi, DAG.getConstant(32, MVT::i32)); 8808 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8809 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 8810 AhiBlo, DAG.getConstant(32, MVT::i32)); 8811 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi); 8812 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo); 8813 return Res; 8814} 8815 8816SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const { 8817 8818 EVT VT = Op.getValueType(); 8819 DebugLoc dl = Op.getDebugLoc(); 8820 SDValue R = Op.getOperand(0); 8821 SDValue Amt = Op.getOperand(1); 8822 8823 LLVMContext *Context = DAG.getContext(); 8824 8825 // Must have SSE2. 8826 if (!Subtarget->hasSSE2()) return SDValue(); 8827 8828 // Optimize shl/srl/sra with constant shift amount. 8829 if (isSplatVector(Amt.getNode())) { 8830 SDValue SclrAmt = Amt->getOperand(0); 8831 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) { 8832 uint64_t ShiftAmt = C->getZExtValue(); 8833 8834 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL) 8835 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8836 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 8837 R, DAG.getConstant(ShiftAmt, MVT::i32)); 8838 8839 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL) 8840 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8841 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 8842 R, DAG.getConstant(ShiftAmt, MVT::i32)); 8843 8844 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL) 8845 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8846 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 8847 R, DAG.getConstant(ShiftAmt, MVT::i32)); 8848 8849 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL) 8850 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8851 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 8852 R, DAG.getConstant(ShiftAmt, MVT::i32)); 8853 8854 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL) 8855 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8856 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32), 8857 R, DAG.getConstant(ShiftAmt, MVT::i32)); 8858 8859 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL) 8860 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8861 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32), 8862 R, DAG.getConstant(ShiftAmt, MVT::i32)); 8863 8864 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA) 8865 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8866 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32), 8867 R, DAG.getConstant(ShiftAmt, MVT::i32)); 8868 8869 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA) 8870 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8871 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32), 8872 R, DAG.getConstant(ShiftAmt, MVT::i32)); 8873 } 8874 } 8875 8876 // Lower SHL with variable shift amount. 8877 // Cannot lower SHL without SSE4.1 or later. 8878 if (!Subtarget->hasSSE41()) return SDValue(); 8879 8880 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) { 8881 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8882 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 8883 Op.getOperand(1), DAG.getConstant(23, MVT::i32)); 8884 8885 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U)); 8886 8887 std::vector<Constant*> CV(4, CI); 8888 Constant *C = ConstantVector::get(CV); 8889 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8890 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8891 MachinePointerInfo::getConstantPool(), 8892 false, false, 16); 8893 8894 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend); 8895 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op); 8896 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op); 8897 return DAG.getNode(ISD::MUL, dl, VT, Op, R); 8898 } 8899 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) { 8900 // a = a << 5; 8901 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8902 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 8903 Op.getOperand(1), DAG.getConstant(5, MVT::i32)); 8904 8905 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15)); 8906 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63)); 8907 8908 std::vector<Constant*> CVM1(16, CM1); 8909 std::vector<Constant*> CVM2(16, CM2); 8910 Constant *C = ConstantVector::get(CVM1); 8911 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8912 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8913 MachinePointerInfo::getConstantPool(), 8914 false, false, 16); 8915 8916 // r = pblendv(r, psllw(r & (char16)15, 4), a); 8917 M = DAG.getNode(ISD::AND, dl, VT, R, M); 8918 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8919 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M, 8920 DAG.getConstant(4, MVT::i32)); 8921 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op); 8922 // a += a 8923 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 8924 8925 C = ConstantVector::get(CVM2); 8926 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8927 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8928 MachinePointerInfo::getConstantPool(), 8929 false, false, 16); 8930 8931 // r = pblendv(r, psllw(r & (char16)63, 2), a); 8932 M = DAG.getNode(ISD::AND, dl, VT, R, M); 8933 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8934 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M, 8935 DAG.getConstant(2, MVT::i32)); 8936 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op); 8937 // a += a 8938 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 8939 8940 // return pblendv(r, r+r, a); 8941 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, 8942 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op); 8943 return R; 8944 } 8945 return SDValue(); 8946} 8947 8948SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 8949 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus 8950 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering 8951 // looks for this combo and may remove the "setcc" instruction if the "setcc" 8952 // has only one use. 8953 SDNode *N = Op.getNode(); 8954 SDValue LHS = N->getOperand(0); 8955 SDValue RHS = N->getOperand(1); 8956 unsigned BaseOp = 0; 8957 unsigned Cond = 0; 8958 DebugLoc DL = Op.getDebugLoc(); 8959 switch (Op.getOpcode()) { 8960 default: llvm_unreachable("Unknown ovf instruction!"); 8961 case ISD::SADDO: 8962 // A subtract of one will be selected as a INC. Note that INC doesn't 8963 // set CF, so we can't do this for UADDO. 8964 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 8965 if (C->isOne()) { 8966 BaseOp = X86ISD::INC; 8967 Cond = X86::COND_O; 8968 break; 8969 } 8970 BaseOp = X86ISD::ADD; 8971 Cond = X86::COND_O; 8972 break; 8973 case ISD::UADDO: 8974 BaseOp = X86ISD::ADD; 8975 Cond = X86::COND_B; 8976 break; 8977 case ISD::SSUBO: 8978 // A subtract of one will be selected as a DEC. Note that DEC doesn't 8979 // set CF, so we can't do this for USUBO. 8980 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 8981 if (C->isOne()) { 8982 BaseOp = X86ISD::DEC; 8983 Cond = X86::COND_O; 8984 break; 8985 } 8986 BaseOp = X86ISD::SUB; 8987 Cond = X86::COND_O; 8988 break; 8989 case ISD::USUBO: 8990 BaseOp = X86ISD::SUB; 8991 Cond = X86::COND_B; 8992 break; 8993 case ISD::SMULO: 8994 BaseOp = X86ISD::SMUL; 8995 Cond = X86::COND_O; 8996 break; 8997 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs 8998 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0), 8999 MVT::i32); 9000 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS); 9001 9002 SDValue SetCC = 9003 DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 9004 DAG.getConstant(X86::COND_O, MVT::i32), 9005 SDValue(Sum.getNode(), 2)); 9006 9007 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC); 9008 return Sum; 9009 } 9010 } 9011 9012 // Also sets EFLAGS. 9013 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32); 9014 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS); 9015 9016 SDValue SetCC = 9017 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1), 9018 DAG.getConstant(Cond, MVT::i32), 9019 SDValue(Sum.getNode(), 1)); 9020 9021 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC); 9022 return Sum; 9023} 9024 9025SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{ 9026 DebugLoc dl = Op.getDebugLoc(); 9027 9028 if (!Subtarget->hasSSE2()) { 9029 SDValue Chain = Op.getOperand(0); 9030 SDValue Zero = DAG.getConstant(0, 9031 Subtarget->is64Bit() ? MVT::i64 : MVT::i32); 9032 SDValue Ops[] = { 9033 DAG.getRegister(X86::ESP, MVT::i32), // Base 9034 DAG.getTargetConstant(1, MVT::i8), // Scale 9035 DAG.getRegister(0, MVT::i32), // Index 9036 DAG.getTargetConstant(0, MVT::i32), // Disp 9037 DAG.getRegister(0, MVT::i32), // Segment. 9038 Zero, 9039 Chain 9040 }; 9041 SDNode *Res = 9042 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops, 9043 array_lengthof(Ops)); 9044 return SDValue(Res, 0); 9045 } 9046 9047 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 9048 if (!isDev) 9049 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 9050 9051 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 9052 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 9053 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 9054 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 9055 9056 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>; 9057 if (!Op1 && !Op2 && !Op3 && Op4) 9058 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0)); 9059 9060 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>; 9061 if (Op1 && !Op2 && !Op3 && !Op4) 9062 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0)); 9063 9064 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 9065 // (MFENCE)>; 9066 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 9067} 9068 9069SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 9070 EVT T = Op.getValueType(); 9071 DebugLoc DL = Op.getDebugLoc(); 9072 unsigned Reg = 0; 9073 unsigned size = 0; 9074 switch(T.getSimpleVT().SimpleTy) { 9075 default: 9076 assert(false && "Invalid value type!"); 9077 case MVT::i8: Reg = X86::AL; size = 1; break; 9078 case MVT::i16: Reg = X86::AX; size = 2; break; 9079 case MVT::i32: Reg = X86::EAX; size = 4; break; 9080 case MVT::i64: 9081 assert(Subtarget->is64Bit() && "Node not type legal!"); 9082 Reg = X86::RAX; size = 8; 9083 break; 9084 } 9085 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg, 9086 Op.getOperand(2), SDValue()); 9087 SDValue Ops[] = { cpIn.getValue(0), 9088 Op.getOperand(1), 9089 Op.getOperand(3), 9090 DAG.getTargetConstant(size, MVT::i8), 9091 cpIn.getValue(1) }; 9092 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 9093 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand(); 9094 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys, 9095 Ops, 5, T, MMO); 9096 SDValue cpOut = 9097 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1)); 9098 return cpOut; 9099} 9100 9101SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op, 9102 SelectionDAG &DAG) const { 9103 assert(Subtarget->is64Bit() && "Result not type legalized?"); 9104 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 9105 SDValue TheChain = Op.getOperand(0); 9106 DebugLoc dl = Op.getDebugLoc(); 9107 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 9108 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1)); 9109 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64, 9110 rax.getValue(2)); 9111 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx, 9112 DAG.getConstant(32, MVT::i8)); 9113 SDValue Ops[] = { 9114 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp), 9115 rdx.getValue(1) 9116 }; 9117 return DAG.getMergeValues(Ops, 2, dl); 9118} 9119 9120SDValue X86TargetLowering::LowerBITCAST(SDValue Op, 9121 SelectionDAG &DAG) const { 9122 EVT SrcVT = Op.getOperand(0).getValueType(); 9123 EVT DstVT = Op.getValueType(); 9124 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() && 9125 Subtarget->hasMMX() && "Unexpected custom BITCAST"); 9126 assert((DstVT == MVT::i64 || 9127 (DstVT.isVector() && DstVT.getSizeInBits()==64)) && 9128 "Unexpected custom BITCAST"); 9129 // i64 <=> MMX conversions are Legal. 9130 if (SrcVT==MVT::i64 && DstVT.isVector()) 9131 return Op; 9132 if (DstVT==MVT::i64 && SrcVT.isVector()) 9133 return Op; 9134 // MMX <=> MMX conversions are Legal. 9135 if (SrcVT.isVector() && DstVT.isVector()) 9136 return Op; 9137 // All other conversions need to be expanded. 9138 return SDValue(); 9139} 9140 9141SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const { 9142 SDNode *Node = Op.getNode(); 9143 DebugLoc dl = Node->getDebugLoc(); 9144 EVT T = Node->getValueType(0); 9145 SDValue negOp = DAG.getNode(ISD::SUB, dl, T, 9146 DAG.getConstant(0, T), Node->getOperand(2)); 9147 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, 9148 cast<AtomicSDNode>(Node)->getMemoryVT(), 9149 Node->getOperand(0), 9150 Node->getOperand(1), negOp, 9151 cast<AtomicSDNode>(Node)->getSrcValue(), 9152 cast<AtomicSDNode>(Node)->getAlignment()); 9153} 9154 9155static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 9156 EVT VT = Op.getNode()->getValueType(0); 9157 9158 // Let legalize expand this if it isn't a legal type yet. 9159 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9160 return SDValue(); 9161 9162 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 9163 9164 unsigned Opc; 9165 bool ExtraOp = false; 9166 switch (Op.getOpcode()) { 9167 default: assert(0 && "Invalid code"); 9168 case ISD::ADDC: Opc = X86ISD::ADD; break; 9169 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break; 9170 case ISD::SUBC: Opc = X86ISD::SUB; break; 9171 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break; 9172 } 9173 9174 if (!ExtraOp) 9175 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 9176 Op.getOperand(1)); 9177 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 9178 Op.getOperand(1), Op.getOperand(2)); 9179} 9180 9181/// LowerOperation - Provide custom lowering hooks for some operations. 9182/// 9183SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9184 switch (Op.getOpcode()) { 9185 default: llvm_unreachable("Should not custom lower this!"); 9186 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG); 9187 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG); 9188 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG); 9189 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9190 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 9191 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9192 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9193 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9194 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG); 9195 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG); 9196 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9197 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9198 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9199 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9200 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG); 9201 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9202 case ISD::SHL_PARTS: 9203 case ISD::SRA_PARTS: 9204 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG); 9205 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG); 9206 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG); 9207 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG); 9208 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG); 9209 case ISD::FABS: return LowerFABS(Op, DAG); 9210 case ISD::FNEG: return LowerFNEG(Op, DAG); 9211 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 9212 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG); 9213 case ISD::SETCC: return LowerSETCC(Op, DAG); 9214 case ISD::VSETCC: return LowerVSETCC(Op, DAG); 9215 case ISD::SELECT: return LowerSELECT(Op, DAG); 9216 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 9217 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9218 case ISD::VASTART: return LowerVASTART(Op, DAG); 9219 case ISD::VAARG: return LowerVAARG(Op, DAG); 9220 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9221 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9222 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9223 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9224 case ISD::FRAME_TO_ARGS_OFFSET: 9225 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG); 9226 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9227 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG); 9228 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG); 9229 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9230 case ISD::CTLZ: return LowerCTLZ(Op, DAG); 9231 case ISD::CTTZ: return LowerCTTZ(Op, DAG); 9232 case ISD::MUL: return LowerMUL_V2I64(Op, DAG); 9233 case ISD::SRA: 9234 case ISD::SRL: 9235 case ISD::SHL: return LowerShift(Op, DAG); 9236 case ISD::SADDO: 9237 case ISD::UADDO: 9238 case ISD::SSUBO: 9239 case ISD::USUBO: 9240 case ISD::SMULO: 9241 case ISD::UMULO: return LowerXALUO(Op, DAG); 9242 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG); 9243 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 9244 case ISD::ADDC: 9245 case ISD::ADDE: 9246 case ISD::SUBC: 9247 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 9248 } 9249} 9250 9251void X86TargetLowering:: 9252ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results, 9253 SelectionDAG &DAG, unsigned NewOp) const { 9254 EVT T = Node->getValueType(0); 9255 DebugLoc dl = Node->getDebugLoc(); 9256 assert (T == MVT::i64 && "Only know how to expand i64 atomics"); 9257 9258 SDValue Chain = Node->getOperand(0); 9259 SDValue In1 = Node->getOperand(1); 9260 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9261 Node->getOperand(2), DAG.getIntPtrConstant(0)); 9262 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9263 Node->getOperand(2), DAG.getIntPtrConstant(1)); 9264 SDValue Ops[] = { Chain, In1, In2L, In2H }; 9265 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9266 SDValue Result = 9267 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64, 9268 cast<MemSDNode>(Node)->getMemOperand()); 9269 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)}; 9270 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2)); 9271 Results.push_back(Result.getValue(2)); 9272} 9273 9274/// ReplaceNodeResults - Replace a node with an illegal result type 9275/// with a new node built out of custom code. 9276void X86TargetLowering::ReplaceNodeResults(SDNode *N, 9277 SmallVectorImpl<SDValue>&Results, 9278 SelectionDAG &DAG) const { 9279 DebugLoc dl = N->getDebugLoc(); 9280 switch (N->getOpcode()) { 9281 default: 9282 assert(false && "Do not know how to custom type legalize this operation!"); 9283 return; 9284 case ISD::ADDC: 9285 case ISD::ADDE: 9286 case ISD::SUBC: 9287 case ISD::SUBE: 9288 // We don't want to expand or promote these. 9289 return; 9290 case ISD::FP_TO_SINT: { 9291 std::pair<SDValue,SDValue> Vals = 9292 FP_TO_INTHelper(SDValue(N, 0), DAG, true); 9293 SDValue FIST = Vals.first, StackSlot = Vals.second; 9294 if (FIST.getNode() != 0) { 9295 EVT VT = N->getValueType(0); 9296 // Return a load from the stack slot. 9297 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, 9298 MachinePointerInfo(), false, false, 0)); 9299 } 9300 return; 9301 } 9302 case ISD::READCYCLECOUNTER: { 9303 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 9304 SDValue TheChain = N->getOperand(0); 9305 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 9306 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32, 9307 rd.getValue(1)); 9308 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32, 9309 eax.getValue(2)); 9310 // Use a buildpair to merge the two 32-bit values into a 64-bit one. 9311 SDValue Ops[] = { eax, edx }; 9312 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2)); 9313 Results.push_back(edx.getValue(1)); 9314 return; 9315 } 9316 case ISD::ATOMIC_CMP_SWAP: { 9317 EVT T = N->getValueType(0); 9318 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap"); 9319 SDValue cpInL, cpInH; 9320 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2), 9321 DAG.getConstant(0, MVT::i32)); 9322 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2), 9323 DAG.getConstant(1, MVT::i32)); 9324 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue()); 9325 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH, 9326 cpInL.getValue(1)); 9327 SDValue swapInL, swapInH; 9328 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3), 9329 DAG.getConstant(0, MVT::i32)); 9330 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3), 9331 DAG.getConstant(1, MVT::i32)); 9332 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL, 9333 cpInH.getValue(1)); 9334 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH, 9335 swapInL.getValue(1)); 9336 SDValue Ops[] = { swapInH.getValue(0), 9337 N->getOperand(1), 9338 swapInH.getValue(1) }; 9339 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 9340 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 9341 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, 9342 Ops, 3, T, MMO); 9343 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX, 9344 MVT::i32, Result.getValue(1)); 9345 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX, 9346 MVT::i32, cpOutL.getValue(2)); 9347 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)}; 9348 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2)); 9349 Results.push_back(cpOutH.getValue(1)); 9350 return; 9351 } 9352 case ISD::ATOMIC_LOAD_ADD: 9353 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG); 9354 return; 9355 case ISD::ATOMIC_LOAD_AND: 9356 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG); 9357 return; 9358 case ISD::ATOMIC_LOAD_NAND: 9359 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG); 9360 return; 9361 case ISD::ATOMIC_LOAD_OR: 9362 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG); 9363 return; 9364 case ISD::ATOMIC_LOAD_SUB: 9365 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG); 9366 return; 9367 case ISD::ATOMIC_LOAD_XOR: 9368 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG); 9369 return; 9370 case ISD::ATOMIC_SWAP: 9371 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG); 9372 return; 9373 } 9374} 9375 9376const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const { 9377 switch (Opcode) { 9378 default: return NULL; 9379 case X86ISD::BSF: return "X86ISD::BSF"; 9380 case X86ISD::BSR: return "X86ISD::BSR"; 9381 case X86ISD::SHLD: return "X86ISD::SHLD"; 9382 case X86ISD::SHRD: return "X86ISD::SHRD"; 9383 case X86ISD::FAND: return "X86ISD::FAND"; 9384 case X86ISD::FOR: return "X86ISD::FOR"; 9385 case X86ISD::FXOR: return "X86ISD::FXOR"; 9386 case X86ISD::FSRL: return "X86ISD::FSRL"; 9387 case X86ISD::FILD: return "X86ISD::FILD"; 9388 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG"; 9389 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM"; 9390 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM"; 9391 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM"; 9392 case X86ISD::FLD: return "X86ISD::FLD"; 9393 case X86ISD::FST: return "X86ISD::FST"; 9394 case X86ISD::CALL: return "X86ISD::CALL"; 9395 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG"; 9396 case X86ISD::BT: return "X86ISD::BT"; 9397 case X86ISD::CMP: return "X86ISD::CMP"; 9398 case X86ISD::COMI: return "X86ISD::COMI"; 9399 case X86ISD::UCOMI: return "X86ISD::UCOMI"; 9400 case X86ISD::SETCC: return "X86ISD::SETCC"; 9401 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY"; 9402 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd"; 9403 case X86ISD::FSETCCss: return "X86ISD::FSETCCss"; 9404 case X86ISD::CMOV: return "X86ISD::CMOV"; 9405 case X86ISD::BRCOND: return "X86ISD::BRCOND"; 9406 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG"; 9407 case X86ISD::REP_STOS: return "X86ISD::REP_STOS"; 9408 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS"; 9409 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg"; 9410 case X86ISD::Wrapper: return "X86ISD::Wrapper"; 9411 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP"; 9412 case X86ISD::PEXTRB: return "X86ISD::PEXTRB"; 9413 case X86ISD::PEXTRW: return "X86ISD::PEXTRW"; 9414 case X86ISD::INSERTPS: return "X86ISD::INSERTPS"; 9415 case X86ISD::PINSRB: return "X86ISD::PINSRB"; 9416 case X86ISD::PINSRW: return "X86ISD::PINSRW"; 9417 case X86ISD::PSHUFB: return "X86ISD::PSHUFB"; 9418 case X86ISD::PANDN: return "X86ISD::PANDN"; 9419 case X86ISD::PSIGNB: return "X86ISD::PSIGNB"; 9420 case X86ISD::PSIGNW: return "X86ISD::PSIGNW"; 9421 case X86ISD::PSIGND: return "X86ISD::PSIGND"; 9422 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB"; 9423 case X86ISD::FMAX: return "X86ISD::FMAX"; 9424 case X86ISD::FMIN: return "X86ISD::FMIN"; 9425 case X86ISD::FRSQRT: return "X86ISD::FRSQRT"; 9426 case X86ISD::FRCP: return "X86ISD::FRCP"; 9427 case X86ISD::TLSADDR: return "X86ISD::TLSADDR"; 9428 case X86ISD::TLSCALL: return "X86ISD::TLSCALL"; 9429 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN"; 9430 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN"; 9431 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m"; 9432 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG"; 9433 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG"; 9434 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG"; 9435 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG"; 9436 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG"; 9437 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG"; 9438 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG"; 9439 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG"; 9440 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL"; 9441 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD"; 9442 case X86ISD::VSHL: return "X86ISD::VSHL"; 9443 case X86ISD::VSRL: return "X86ISD::VSRL"; 9444 case X86ISD::CMPPD: return "X86ISD::CMPPD"; 9445 case X86ISD::CMPPS: return "X86ISD::CMPPS"; 9446 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB"; 9447 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW"; 9448 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD"; 9449 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ"; 9450 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB"; 9451 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW"; 9452 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD"; 9453 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ"; 9454 case X86ISD::ADD: return "X86ISD::ADD"; 9455 case X86ISD::SUB: return "X86ISD::SUB"; 9456 case X86ISD::ADC: return "X86ISD::ADC"; 9457 case X86ISD::SBB: return "X86ISD::SBB"; 9458 case X86ISD::SMUL: return "X86ISD::SMUL"; 9459 case X86ISD::UMUL: return "X86ISD::UMUL"; 9460 case X86ISD::INC: return "X86ISD::INC"; 9461 case X86ISD::DEC: return "X86ISD::DEC"; 9462 case X86ISD::OR: return "X86ISD::OR"; 9463 case X86ISD::XOR: return "X86ISD::XOR"; 9464 case X86ISD::AND: return "X86ISD::AND"; 9465 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM"; 9466 case X86ISD::PTEST: return "X86ISD::PTEST"; 9467 case X86ISD::TESTP: return "X86ISD::TESTP"; 9468 case X86ISD::PALIGN: return "X86ISD::PALIGN"; 9469 case X86ISD::PSHUFD: return "X86ISD::PSHUFD"; 9470 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW"; 9471 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD"; 9472 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW"; 9473 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD"; 9474 case X86ISD::SHUFPS: return "X86ISD::SHUFPS"; 9475 case X86ISD::SHUFPD: return "X86ISD::SHUFPD"; 9476 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS"; 9477 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD"; 9478 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS"; 9479 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD"; 9480 case X86ISD::MOVLPS: return "X86ISD::MOVLPS"; 9481 case X86ISD::MOVLPD: return "X86ISD::MOVLPD"; 9482 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP"; 9483 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP"; 9484 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP"; 9485 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD"; 9486 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD"; 9487 case X86ISD::MOVSD: return "X86ISD::MOVSD"; 9488 case X86ISD::MOVSS: return "X86ISD::MOVSS"; 9489 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS"; 9490 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD"; 9491 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS"; 9492 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD"; 9493 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY"; 9494 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY"; 9495 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS"; 9496 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD"; 9497 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW"; 9498 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD"; 9499 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ"; 9500 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ"; 9501 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW"; 9502 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD"; 9503 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ"; 9504 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ"; 9505 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS"; 9506 case X86ISD::VAARG_64: return "X86ISD::VAARG_64"; 9507 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA"; 9508 } 9509} 9510 9511// isLegalAddressingMode - Return true if the addressing mode represented 9512// by AM is legal for this target, for a load/store of the specified type. 9513bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 9514 const Type *Ty) const { 9515 // X86 supports extremely general addressing modes. 9516 CodeModel::Model M = getTargetMachine().getCodeModel(); 9517 Reloc::Model R = getTargetMachine().getRelocationModel(); 9518 9519 // X86 allows a sign-extended 32-bit immediate field as a displacement. 9520 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL)) 9521 return false; 9522 9523 if (AM.BaseGV) { 9524 unsigned GVFlags = 9525 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine()); 9526 9527 // If a reference to this global requires an extra load, we can't fold it. 9528 if (isGlobalStubReference(GVFlags)) 9529 return false; 9530 9531 // If BaseGV requires a register for the PIC base, we cannot also have a 9532 // BaseReg specified. 9533 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags)) 9534 return false; 9535 9536 // If lower 4G is not available, then we must use rip-relative addressing. 9537 if ((M != CodeModel::Small || R != Reloc::Static) && 9538 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1)) 9539 return false; 9540 } 9541 9542 switch (AM.Scale) { 9543 case 0: 9544 case 1: 9545 case 2: 9546 case 4: 9547 case 8: 9548 // These scales always work. 9549 break; 9550 case 3: 9551 case 5: 9552 case 9: 9553 // These scales are formed with basereg+scalereg. Only accept if there is 9554 // no basereg yet. 9555 if (AM.HasBaseReg) 9556 return false; 9557 break; 9558 default: // Other stuff never works. 9559 return false; 9560 } 9561 9562 return true; 9563} 9564 9565 9566bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const { 9567 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 9568 return false; 9569 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 9570 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 9571 if (NumBits1 <= NumBits2) 9572 return false; 9573 return true; 9574} 9575 9576bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 9577 if (!VT1.isInteger() || !VT2.isInteger()) 9578 return false; 9579 unsigned NumBits1 = VT1.getSizeInBits(); 9580 unsigned NumBits2 = VT2.getSizeInBits(); 9581 if (NumBits1 <= NumBits2) 9582 return false; 9583 return true; 9584} 9585 9586bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const { 9587 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 9588 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit(); 9589} 9590 9591bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 9592 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 9593 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit(); 9594} 9595 9596bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const { 9597 // i16 instructions are longer (0x66 prefix) and potentially slower. 9598 return !(VT1 == MVT::i32 && VT2 == MVT::i16); 9599} 9600 9601/// isShuffleMaskLegal - Targets can use this to indicate that they only 9602/// support *some* VECTOR_SHUFFLE operations, those with specific masks. 9603/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 9604/// are assumed to be legal. 9605bool 9606X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 9607 EVT VT) const { 9608 // Very little shuffling can be done for 64-bit vectors right now. 9609 if (VT.getSizeInBits() == 64) 9610 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3()); 9611 9612 // FIXME: pshufb, blends, shifts. 9613 return (VT.getVectorNumElements() == 2 || 9614 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 9615 isMOVLMask(M, VT) || 9616 isSHUFPMask(M, VT) || 9617 isPSHUFDMask(M, VT) || 9618 isPSHUFHWMask(M, VT) || 9619 isPSHUFLWMask(M, VT) || 9620 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) || 9621 isUNPCKLMask(M, VT) || 9622 isUNPCKHMask(M, VT) || 9623 isUNPCKL_v_undef_Mask(M, VT) || 9624 isUNPCKH_v_undef_Mask(M, VT)); 9625} 9626 9627bool 9628X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask, 9629 EVT VT) const { 9630 unsigned NumElts = VT.getVectorNumElements(); 9631 // FIXME: This collection of masks seems suspect. 9632 if (NumElts == 2) 9633 return true; 9634 if (NumElts == 4 && VT.getSizeInBits() == 128) { 9635 return (isMOVLMask(Mask, VT) || 9636 isCommutedMOVLMask(Mask, VT, true) || 9637 isSHUFPMask(Mask, VT) || 9638 isCommutedSHUFPMask(Mask, VT)); 9639 } 9640 return false; 9641} 9642 9643//===----------------------------------------------------------------------===// 9644// X86 Scheduler Hooks 9645//===----------------------------------------------------------------------===// 9646 9647// private utility function 9648MachineBasicBlock * 9649X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr, 9650 MachineBasicBlock *MBB, 9651 unsigned regOpc, 9652 unsigned immOpc, 9653 unsigned LoadOpc, 9654 unsigned CXchgOpc, 9655 unsigned notOpc, 9656 unsigned EAXreg, 9657 TargetRegisterClass *RC, 9658 bool invSrc) const { 9659 // For the atomic bitwise operator, we generate 9660 // thisMBB: 9661 // newMBB: 9662 // ld t1 = [bitinstr.addr] 9663 // op t2 = t1, [bitinstr.val] 9664 // mov EAX = t1 9665 // lcs dest = [bitinstr.addr], t2 [EAX is implicit] 9666 // bz newMBB 9667 // fallthrough -->nextMBB 9668 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9669 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 9670 MachineFunction::iterator MBBIter = MBB; 9671 ++MBBIter; 9672 9673 /// First build the CFG 9674 MachineFunction *F = MBB->getParent(); 9675 MachineBasicBlock *thisMBB = MBB; 9676 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 9677 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 9678 F->insert(MBBIter, newMBB); 9679 F->insert(MBBIter, nextMBB); 9680 9681 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 9682 nextMBB->splice(nextMBB->begin(), thisMBB, 9683 llvm::next(MachineBasicBlock::iterator(bInstr)), 9684 thisMBB->end()); 9685 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 9686 9687 // Update thisMBB to fall through to newMBB 9688 thisMBB->addSuccessor(newMBB); 9689 9690 // newMBB jumps to itself and fall through to nextMBB 9691 newMBB->addSuccessor(nextMBB); 9692 newMBB->addSuccessor(newMBB); 9693 9694 // Insert instructions into newMBB based on incoming instruction 9695 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 && 9696 "unexpected number of operands"); 9697 DebugLoc dl = bInstr->getDebugLoc(); 9698 MachineOperand& destOper = bInstr->getOperand(0); 9699 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 9700 int numArgs = bInstr->getNumOperands() - 1; 9701 for (int i=0; i < numArgs; ++i) 9702 argOpers[i] = &bInstr->getOperand(i+1); 9703 9704 // x86 address has 4 operands: base, index, scale, and displacement 9705 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 9706 int valArgIndx = lastAddrIndx + 1; 9707 9708 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 9709 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1); 9710 for (int i=0; i <= lastAddrIndx; ++i) 9711 (*MIB).addOperand(*argOpers[i]); 9712 9713 unsigned tt = F->getRegInfo().createVirtualRegister(RC); 9714 if (invSrc) { 9715 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1); 9716 } 9717 else 9718 tt = t1; 9719 9720 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 9721 assert((argOpers[valArgIndx]->isReg() || 9722 argOpers[valArgIndx]->isImm()) && 9723 "invalid operand"); 9724 if (argOpers[valArgIndx]->isReg()) 9725 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2); 9726 else 9727 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2); 9728 MIB.addReg(tt); 9729 (*MIB).addOperand(*argOpers[valArgIndx]); 9730 9731 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg); 9732 MIB.addReg(t1); 9733 9734 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc)); 9735 for (int i=0; i <= lastAddrIndx; ++i) 9736 (*MIB).addOperand(*argOpers[i]); 9737 MIB.addReg(t2); 9738 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 9739 (*MIB).setMemRefs(bInstr->memoperands_begin(), 9740 bInstr->memoperands_end()); 9741 9742 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 9743 MIB.addReg(EAXreg); 9744 9745 // insert branch 9746 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 9747 9748 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 9749 return nextMBB; 9750} 9751 9752// private utility function: 64 bit atomics on 32 bit host. 9753MachineBasicBlock * 9754X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr, 9755 MachineBasicBlock *MBB, 9756 unsigned regOpcL, 9757 unsigned regOpcH, 9758 unsigned immOpcL, 9759 unsigned immOpcH, 9760 bool invSrc) const { 9761 // For the atomic bitwise operator, we generate 9762 // thisMBB (instructions are in pairs, except cmpxchg8b) 9763 // ld t1,t2 = [bitinstr.addr] 9764 // newMBB: 9765 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4) 9766 // op t5, t6 <- out1, out2, [bitinstr.val] 9767 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val]) 9768 // mov ECX, EBX <- t5, t6 9769 // mov EAX, EDX <- t1, t2 9770 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit] 9771 // mov t3, t4 <- EAX, EDX 9772 // bz newMBB 9773 // result in out1, out2 9774 // fallthrough -->nextMBB 9775 9776 const TargetRegisterClass *RC = X86::GR32RegisterClass; 9777 const unsigned LoadOpc = X86::MOV32rm; 9778 const unsigned NotOpc = X86::NOT32r; 9779 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9780 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 9781 MachineFunction::iterator MBBIter = MBB; 9782 ++MBBIter; 9783 9784 /// First build the CFG 9785 MachineFunction *F = MBB->getParent(); 9786 MachineBasicBlock *thisMBB = MBB; 9787 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 9788 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 9789 F->insert(MBBIter, newMBB); 9790 F->insert(MBBIter, nextMBB); 9791 9792 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 9793 nextMBB->splice(nextMBB->begin(), thisMBB, 9794 llvm::next(MachineBasicBlock::iterator(bInstr)), 9795 thisMBB->end()); 9796 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 9797 9798 // Update thisMBB to fall through to newMBB 9799 thisMBB->addSuccessor(newMBB); 9800 9801 // newMBB jumps to itself and fall through to nextMBB 9802 newMBB->addSuccessor(nextMBB); 9803 newMBB->addSuccessor(newMBB); 9804 9805 DebugLoc dl = bInstr->getDebugLoc(); 9806 // Insert instructions into newMBB based on incoming instruction 9807 // There are 8 "real" operands plus 9 implicit def/uses, ignored here. 9808 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 && 9809 "unexpected number of operands"); 9810 MachineOperand& dest1Oper = bInstr->getOperand(0); 9811 MachineOperand& dest2Oper = bInstr->getOperand(1); 9812 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 9813 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) { 9814 argOpers[i] = &bInstr->getOperand(i+2); 9815 9816 // We use some of the operands multiple times, so conservatively just 9817 // clear any kill flags that might be present. 9818 if (argOpers[i]->isReg() && argOpers[i]->isUse()) 9819 argOpers[i]->setIsKill(false); 9820 } 9821 9822 // x86 address has 5 operands: base, index, scale, displacement, and segment. 9823 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 9824 9825 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 9826 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1); 9827 for (int i=0; i <= lastAddrIndx; ++i) 9828 (*MIB).addOperand(*argOpers[i]); 9829 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 9830 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2); 9831 // add 4 to displacement. 9832 for (int i=0; i <= lastAddrIndx-2; ++i) 9833 (*MIB).addOperand(*argOpers[i]); 9834 MachineOperand newOp3 = *(argOpers[3]); 9835 if (newOp3.isImm()) 9836 newOp3.setImm(newOp3.getImm()+4); 9837 else 9838 newOp3.setOffset(newOp3.getOffset()+4); 9839 (*MIB).addOperand(newOp3); 9840 (*MIB).addOperand(*argOpers[lastAddrIndx]); 9841 9842 // t3/4 are defined later, at the bottom of the loop 9843 unsigned t3 = F->getRegInfo().createVirtualRegister(RC); 9844 unsigned t4 = F->getRegInfo().createVirtualRegister(RC); 9845 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg()) 9846 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB); 9847 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg()) 9848 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB); 9849 9850 // The subsequent operations should be using the destination registers of 9851 //the PHI instructions. 9852 if (invSrc) { 9853 t1 = F->getRegInfo().createVirtualRegister(RC); 9854 t2 = F->getRegInfo().createVirtualRegister(RC); 9855 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg()); 9856 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg()); 9857 } else { 9858 t1 = dest1Oper.getReg(); 9859 t2 = dest2Oper.getReg(); 9860 } 9861 9862 int valArgIndx = lastAddrIndx + 1; 9863 assert((argOpers[valArgIndx]->isReg() || 9864 argOpers[valArgIndx]->isImm()) && 9865 "invalid operand"); 9866 unsigned t5 = F->getRegInfo().createVirtualRegister(RC); 9867 unsigned t6 = F->getRegInfo().createVirtualRegister(RC); 9868 if (argOpers[valArgIndx]->isReg()) 9869 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5); 9870 else 9871 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5); 9872 if (regOpcL != X86::MOV32rr) 9873 MIB.addReg(t1); 9874 (*MIB).addOperand(*argOpers[valArgIndx]); 9875 assert(argOpers[valArgIndx + 1]->isReg() == 9876 argOpers[valArgIndx]->isReg()); 9877 assert(argOpers[valArgIndx + 1]->isImm() == 9878 argOpers[valArgIndx]->isImm()); 9879 if (argOpers[valArgIndx + 1]->isReg()) 9880 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6); 9881 else 9882 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6); 9883 if (regOpcH != X86::MOV32rr) 9884 MIB.addReg(t2); 9885 (*MIB).addOperand(*argOpers[valArgIndx + 1]); 9886 9887 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 9888 MIB.addReg(t1); 9889 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX); 9890 MIB.addReg(t2); 9891 9892 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX); 9893 MIB.addReg(t5); 9894 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX); 9895 MIB.addReg(t6); 9896 9897 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B)); 9898 for (int i=0; i <= lastAddrIndx; ++i) 9899 (*MIB).addOperand(*argOpers[i]); 9900 9901 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 9902 (*MIB).setMemRefs(bInstr->memoperands_begin(), 9903 bInstr->memoperands_end()); 9904 9905 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3); 9906 MIB.addReg(X86::EAX); 9907 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4); 9908 MIB.addReg(X86::EDX); 9909 9910 // insert branch 9911 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 9912 9913 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 9914 return nextMBB; 9915} 9916 9917// private utility function 9918MachineBasicBlock * 9919X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr, 9920 MachineBasicBlock *MBB, 9921 unsigned cmovOpc) const { 9922 // For the atomic min/max operator, we generate 9923 // thisMBB: 9924 // newMBB: 9925 // ld t1 = [min/max.addr] 9926 // mov t2 = [min/max.val] 9927 // cmp t1, t2 9928 // cmov[cond] t2 = t1 9929 // mov EAX = t1 9930 // lcs dest = [bitinstr.addr], t2 [EAX is implicit] 9931 // bz newMBB 9932 // fallthrough -->nextMBB 9933 // 9934 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9935 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 9936 MachineFunction::iterator MBBIter = MBB; 9937 ++MBBIter; 9938 9939 /// First build the CFG 9940 MachineFunction *F = MBB->getParent(); 9941 MachineBasicBlock *thisMBB = MBB; 9942 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 9943 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 9944 F->insert(MBBIter, newMBB); 9945 F->insert(MBBIter, nextMBB); 9946 9947 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 9948 nextMBB->splice(nextMBB->begin(), thisMBB, 9949 llvm::next(MachineBasicBlock::iterator(mInstr)), 9950 thisMBB->end()); 9951 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 9952 9953 // Update thisMBB to fall through to newMBB 9954 thisMBB->addSuccessor(newMBB); 9955 9956 // newMBB jumps to newMBB and fall through to nextMBB 9957 newMBB->addSuccessor(nextMBB); 9958 newMBB->addSuccessor(newMBB); 9959 9960 DebugLoc dl = mInstr->getDebugLoc(); 9961 // Insert instructions into newMBB based on incoming instruction 9962 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 && 9963 "unexpected number of operands"); 9964 MachineOperand& destOper = mInstr->getOperand(0); 9965 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 9966 int numArgs = mInstr->getNumOperands() - 1; 9967 for (int i=0; i < numArgs; ++i) 9968 argOpers[i] = &mInstr->getOperand(i+1); 9969 9970 // x86 address has 4 operands: base, index, scale, and displacement 9971 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 9972 int valArgIndx = lastAddrIndx + 1; 9973 9974 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 9975 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1); 9976 for (int i=0; i <= lastAddrIndx; ++i) 9977 (*MIB).addOperand(*argOpers[i]); 9978 9979 // We only support register and immediate values 9980 assert((argOpers[valArgIndx]->isReg() || 9981 argOpers[valArgIndx]->isImm()) && 9982 "invalid operand"); 9983 9984 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 9985 if (argOpers[valArgIndx]->isReg()) 9986 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2); 9987 else 9988 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2); 9989 (*MIB).addOperand(*argOpers[valArgIndx]); 9990 9991 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 9992 MIB.addReg(t1); 9993 9994 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr)); 9995 MIB.addReg(t1); 9996 MIB.addReg(t2); 9997 9998 // Generate movc 9999 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 10000 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3); 10001 MIB.addReg(t2); 10002 MIB.addReg(t1); 10003 10004 // Cmp and exchange if none has modified the memory location 10005 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32)); 10006 for (int i=0; i <= lastAddrIndx; ++i) 10007 (*MIB).addOperand(*argOpers[i]); 10008 MIB.addReg(t3); 10009 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 10010 (*MIB).setMemRefs(mInstr->memoperands_begin(), 10011 mInstr->memoperands_end()); 10012 10013 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 10014 MIB.addReg(X86::EAX); 10015 10016 // insert branch 10017 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 10018 10019 mInstr->eraseFromParent(); // The pseudo instruction is gone now. 10020 return nextMBB; 10021} 10022 10023// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8 10024// or XMM0_V32I8 in AVX all of this code can be replaced with that 10025// in the .td file. 10026MachineBasicBlock * 10027X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB, 10028 unsigned numArgs, bool memArg) const { 10029 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) && 10030 "Target must have SSE4.2 or AVX features enabled"); 10031 10032 DebugLoc dl = MI->getDebugLoc(); 10033 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10034 unsigned Opc; 10035 if (!Subtarget->hasAVX()) { 10036 if (memArg) 10037 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm; 10038 else 10039 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr; 10040 } else { 10041 if (memArg) 10042 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm; 10043 else 10044 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr; 10045 } 10046 10047 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc)); 10048 for (unsigned i = 0; i < numArgs; ++i) { 10049 MachineOperand &Op = MI->getOperand(i+1); 10050 if (!(Op.isReg() && Op.isImplicit())) 10051 MIB.addOperand(Op); 10052 } 10053 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg()) 10054 .addReg(X86::XMM0); 10055 10056 MI->eraseFromParent(); 10057 return BB; 10058} 10059 10060MachineBasicBlock * 10061X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const { 10062 DebugLoc dl = MI->getDebugLoc(); 10063 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10064 10065 // Address into RAX/EAX, other two args into ECX, EDX. 10066 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r; 10067 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 10068 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg); 10069 for (int i = 0; i < X86::AddrNumOperands; ++i) 10070 MIB.addOperand(MI->getOperand(i)); 10071 10072 unsigned ValOps = X86::AddrNumOperands; 10073 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 10074 .addReg(MI->getOperand(ValOps).getReg()); 10075 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX) 10076 .addReg(MI->getOperand(ValOps+1).getReg()); 10077 10078 // The instruction doesn't actually take any operands though. 10079 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr)); 10080 10081 MI->eraseFromParent(); // The pseudo is gone now. 10082 return BB; 10083} 10084 10085MachineBasicBlock * 10086X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const { 10087 DebugLoc dl = MI->getDebugLoc(); 10088 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10089 10090 // First arg in ECX, the second in EAX. 10091 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 10092 .addReg(MI->getOperand(0).getReg()); 10093 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX) 10094 .addReg(MI->getOperand(1).getReg()); 10095 10096 // The instruction doesn't actually take any operands though. 10097 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr)); 10098 10099 MI->eraseFromParent(); // The pseudo is gone now. 10100 return BB; 10101} 10102 10103MachineBasicBlock * 10104X86TargetLowering::EmitVAARG64WithCustomInserter( 10105 MachineInstr *MI, 10106 MachineBasicBlock *MBB) const { 10107 // Emit va_arg instruction on X86-64. 10108 10109 // Operands to this pseudo-instruction: 10110 // 0 ) Output : destination address (reg) 10111 // 1-5) Input : va_list address (addr, i64mem) 10112 // 6 ) ArgSize : Size (in bytes) of vararg type 10113 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset 10114 // 8 ) Align : Alignment of type 10115 // 9 ) EFLAGS (implicit-def) 10116 10117 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!"); 10118 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands"); 10119 10120 unsigned DestReg = MI->getOperand(0).getReg(); 10121 MachineOperand &Base = MI->getOperand(1); 10122 MachineOperand &Scale = MI->getOperand(2); 10123 MachineOperand &Index = MI->getOperand(3); 10124 MachineOperand &Disp = MI->getOperand(4); 10125 MachineOperand &Segment = MI->getOperand(5); 10126 unsigned ArgSize = MI->getOperand(6).getImm(); 10127 unsigned ArgMode = MI->getOperand(7).getImm(); 10128 unsigned Align = MI->getOperand(8).getImm(); 10129 10130 // Memory Reference 10131 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand"); 10132 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 10133 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 10134 10135 // Machine Information 10136 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10137 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 10138 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64); 10139 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32); 10140 DebugLoc DL = MI->getDebugLoc(); 10141 10142 // struct va_list { 10143 // i32 gp_offset 10144 // i32 fp_offset 10145 // i64 overflow_area (address) 10146 // i64 reg_save_area (address) 10147 // } 10148 // sizeof(va_list) = 24 10149 // alignment(va_list) = 8 10150 10151 unsigned TotalNumIntRegs = 6; 10152 unsigned TotalNumXMMRegs = 8; 10153 bool UseGPOffset = (ArgMode == 1); 10154 bool UseFPOffset = (ArgMode == 2); 10155 unsigned MaxOffset = TotalNumIntRegs * 8 + 10156 (UseFPOffset ? TotalNumXMMRegs * 16 : 0); 10157 10158 /* Align ArgSize to a multiple of 8 */ 10159 unsigned ArgSizeA8 = (ArgSize + 7) & ~7; 10160 bool NeedsAlign = (Align > 8); 10161 10162 MachineBasicBlock *thisMBB = MBB; 10163 MachineBasicBlock *overflowMBB; 10164 MachineBasicBlock *offsetMBB; 10165 MachineBasicBlock *endMBB; 10166 10167 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB 10168 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB 10169 unsigned OffsetReg = 0; 10170 10171 if (!UseGPOffset && !UseFPOffset) { 10172 // If we only pull from the overflow region, we don't create a branch. 10173 // We don't need to alter control flow. 10174 OffsetDestReg = 0; // unused 10175 OverflowDestReg = DestReg; 10176 10177 offsetMBB = NULL; 10178 overflowMBB = thisMBB; 10179 endMBB = thisMBB; 10180 } else { 10181 // First emit code to check if gp_offset (or fp_offset) is below the bound. 10182 // If so, pull the argument from reg_save_area. (branch to offsetMBB) 10183 // If not, pull from overflow_area. (branch to overflowMBB) 10184 // 10185 // thisMBB 10186 // | . 10187 // | . 10188 // offsetMBB overflowMBB 10189 // | . 10190 // | . 10191 // endMBB 10192 10193 // Registers for the PHI in endMBB 10194 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass); 10195 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass); 10196 10197 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 10198 MachineFunction *MF = MBB->getParent(); 10199 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10200 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10201 endMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10202 10203 MachineFunction::iterator MBBIter = MBB; 10204 ++MBBIter; 10205 10206 // Insert the new basic blocks 10207 MF->insert(MBBIter, offsetMBB); 10208 MF->insert(MBBIter, overflowMBB); 10209 MF->insert(MBBIter, endMBB); 10210 10211 // Transfer the remainder of MBB and its successor edges to endMBB. 10212 endMBB->splice(endMBB->begin(), thisMBB, 10213 llvm::next(MachineBasicBlock::iterator(MI)), 10214 thisMBB->end()); 10215 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 10216 10217 // Make offsetMBB and overflowMBB successors of thisMBB 10218 thisMBB->addSuccessor(offsetMBB); 10219 thisMBB->addSuccessor(overflowMBB); 10220 10221 // endMBB is a successor of both offsetMBB and overflowMBB 10222 offsetMBB->addSuccessor(endMBB); 10223 overflowMBB->addSuccessor(endMBB); 10224 10225 // Load the offset value into a register 10226 OffsetReg = MRI.createVirtualRegister(OffsetRegClass); 10227 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg) 10228 .addOperand(Base) 10229 .addOperand(Scale) 10230 .addOperand(Index) 10231 .addDisp(Disp, UseFPOffset ? 4 : 0) 10232 .addOperand(Segment) 10233 .setMemRefs(MMOBegin, MMOEnd); 10234 10235 // Check if there is enough room left to pull this argument. 10236 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri)) 10237 .addReg(OffsetReg) 10238 .addImm(MaxOffset + 8 - ArgSizeA8); 10239 10240 // Branch to "overflowMBB" if offset >= max 10241 // Fall through to "offsetMBB" otherwise 10242 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE))) 10243 .addMBB(overflowMBB); 10244 } 10245 10246 // In offsetMBB, emit code to use the reg_save_area. 10247 if (offsetMBB) { 10248 assert(OffsetReg != 0); 10249 10250 // Read the reg_save_area address. 10251 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass); 10252 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg) 10253 .addOperand(Base) 10254 .addOperand(Scale) 10255 .addOperand(Index) 10256 .addDisp(Disp, 16) 10257 .addOperand(Segment) 10258 .setMemRefs(MMOBegin, MMOEnd); 10259 10260 // Zero-extend the offset 10261 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass); 10262 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64) 10263 .addImm(0) 10264 .addReg(OffsetReg) 10265 .addImm(X86::sub_32bit); 10266 10267 // Add the offset to the reg_save_area to get the final address. 10268 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg) 10269 .addReg(OffsetReg64) 10270 .addReg(RegSaveReg); 10271 10272 // Compute the offset for the next argument 10273 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass); 10274 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg) 10275 .addReg(OffsetReg) 10276 .addImm(UseFPOffset ? 16 : 8); 10277 10278 // Store it back into the va_list. 10279 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr)) 10280 .addOperand(Base) 10281 .addOperand(Scale) 10282 .addOperand(Index) 10283 .addDisp(Disp, UseFPOffset ? 4 : 0) 10284 .addOperand(Segment) 10285 .addReg(NextOffsetReg) 10286 .setMemRefs(MMOBegin, MMOEnd); 10287 10288 // Jump to endMBB 10289 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4)) 10290 .addMBB(endMBB); 10291 } 10292 10293 // 10294 // Emit code to use overflow area 10295 // 10296 10297 // Load the overflow_area address into a register. 10298 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass); 10299 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg) 10300 .addOperand(Base) 10301 .addOperand(Scale) 10302 .addOperand(Index) 10303 .addDisp(Disp, 8) 10304 .addOperand(Segment) 10305 .setMemRefs(MMOBegin, MMOEnd); 10306 10307 // If we need to align it, do so. Otherwise, just copy the address 10308 // to OverflowDestReg. 10309 if (NeedsAlign) { 10310 // Align the overflow address 10311 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2"); 10312 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass); 10313 10314 // aligned_addr = (addr + (align-1)) & ~(align-1) 10315 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg) 10316 .addReg(OverflowAddrReg) 10317 .addImm(Align-1); 10318 10319 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg) 10320 .addReg(TmpReg) 10321 .addImm(~(uint64_t)(Align-1)); 10322 } else { 10323 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg) 10324 .addReg(OverflowAddrReg); 10325 } 10326 10327 // Compute the next overflow address after this argument. 10328 // (the overflow address should be kept 8-byte aligned) 10329 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass); 10330 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg) 10331 .addReg(OverflowDestReg) 10332 .addImm(ArgSizeA8); 10333 10334 // Store the new overflow address. 10335 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr)) 10336 .addOperand(Base) 10337 .addOperand(Scale) 10338 .addOperand(Index) 10339 .addDisp(Disp, 8) 10340 .addOperand(Segment) 10341 .addReg(NextAddrReg) 10342 .setMemRefs(MMOBegin, MMOEnd); 10343 10344 // If we branched, emit the PHI to the front of endMBB. 10345 if (offsetMBB) { 10346 BuildMI(*endMBB, endMBB->begin(), DL, 10347 TII->get(X86::PHI), DestReg) 10348 .addReg(OffsetDestReg).addMBB(offsetMBB) 10349 .addReg(OverflowDestReg).addMBB(overflowMBB); 10350 } 10351 10352 // Erase the pseudo instruction 10353 MI->eraseFromParent(); 10354 10355 return endMBB; 10356} 10357 10358MachineBasicBlock * 10359X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter( 10360 MachineInstr *MI, 10361 MachineBasicBlock *MBB) const { 10362 // Emit code to save XMM registers to the stack. The ABI says that the 10363 // number of registers to save is given in %al, so it's theoretically 10364 // possible to do an indirect jump trick to avoid saving all of them, 10365 // however this code takes a simpler approach and just executes all 10366 // of the stores if %al is non-zero. It's less code, and it's probably 10367 // easier on the hardware branch predictor, and stores aren't all that 10368 // expensive anyway. 10369 10370 // Create the new basic blocks. One block contains all the XMM stores, 10371 // and one block is the final destination regardless of whether any 10372 // stores were performed. 10373 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 10374 MachineFunction *F = MBB->getParent(); 10375 MachineFunction::iterator MBBIter = MBB; 10376 ++MBBIter; 10377 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB); 10378 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB); 10379 F->insert(MBBIter, XMMSaveMBB); 10380 F->insert(MBBIter, EndMBB); 10381 10382 // Transfer the remainder of MBB and its successor edges to EndMBB. 10383 EndMBB->splice(EndMBB->begin(), MBB, 10384 llvm::next(MachineBasicBlock::iterator(MI)), 10385 MBB->end()); 10386 EndMBB->transferSuccessorsAndUpdatePHIs(MBB); 10387 10388 // The original block will now fall through to the XMM save block. 10389 MBB->addSuccessor(XMMSaveMBB); 10390 // The XMMSaveMBB will fall through to the end block. 10391 XMMSaveMBB->addSuccessor(EndMBB); 10392 10393 // Now add the instructions. 10394 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10395 DebugLoc DL = MI->getDebugLoc(); 10396 10397 unsigned CountReg = MI->getOperand(0).getReg(); 10398 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm(); 10399 int64_t VarArgsFPOffset = MI->getOperand(2).getImm(); 10400 10401 if (!Subtarget->isTargetWin64()) { 10402 // If %al is 0, branch around the XMM save block. 10403 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg); 10404 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB); 10405 MBB->addSuccessor(EndMBB); 10406 } 10407 10408 // In the XMM save block, save all the XMM argument registers. 10409 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) { 10410 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset; 10411 MachineMemOperand *MMO = 10412 F->getMachineMemOperand( 10413 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset), 10414 MachineMemOperand::MOStore, 10415 /*Size=*/16, /*Align=*/16); 10416 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr)) 10417 .addFrameIndex(RegSaveFrameIndex) 10418 .addImm(/*Scale=*/1) 10419 .addReg(/*IndexReg=*/0) 10420 .addImm(/*Disp=*/Offset) 10421 .addReg(/*Segment=*/0) 10422 .addReg(MI->getOperand(i).getReg()) 10423 .addMemOperand(MMO); 10424 } 10425 10426 MI->eraseFromParent(); // The pseudo instruction is gone now. 10427 10428 return EndMBB; 10429} 10430 10431MachineBasicBlock * 10432X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, 10433 MachineBasicBlock *BB) const { 10434 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10435 DebugLoc DL = MI->getDebugLoc(); 10436 10437 // To "insert" a SELECT_CC instruction, we actually have to insert the 10438 // diamond control-flow pattern. The incoming instruction knows the 10439 // destination vreg to set, the condition code register to branch on, the 10440 // true/false values to select between, and a branch opcode to use. 10441 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10442 MachineFunction::iterator It = BB; 10443 ++It; 10444 10445 // thisMBB: 10446 // ... 10447 // TrueVal = ... 10448 // cmpTY ccX, r1, r2 10449 // bCC copy1MBB 10450 // fallthrough --> copy0MBB 10451 MachineBasicBlock *thisMBB = BB; 10452 MachineFunction *F = BB->getParent(); 10453 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10454 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10455 F->insert(It, copy0MBB); 10456 F->insert(It, sinkMBB); 10457 10458 // If the EFLAGS register isn't dead in the terminator, then claim that it's 10459 // live into the sink and copy blocks. 10460 const MachineFunction *MF = BB->getParent(); 10461 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo(); 10462 BitVector ReservedRegs = TRI->getReservedRegs(*MF); 10463 10464 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) { 10465 const MachineOperand &MO = MI->getOperand(I); 10466 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue; 10467 unsigned Reg = MO.getReg(); 10468 if (Reg != X86::EFLAGS) continue; 10469 copy0MBB->addLiveIn(Reg); 10470 sinkMBB->addLiveIn(Reg); 10471 } 10472 10473 // Transfer the remainder of BB and its successor edges to sinkMBB. 10474 sinkMBB->splice(sinkMBB->begin(), BB, 10475 llvm::next(MachineBasicBlock::iterator(MI)), 10476 BB->end()); 10477 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10478 10479 // Add the true and fallthrough blocks as its successors. 10480 BB->addSuccessor(copy0MBB); 10481 BB->addSuccessor(sinkMBB); 10482 10483 // Create the conditional branch instruction. 10484 unsigned Opc = 10485 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm()); 10486 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB); 10487 10488 // copy0MBB: 10489 // %FalseValue = ... 10490 // # fallthrough to sinkMBB 10491 copy0MBB->addSuccessor(sinkMBB); 10492 10493 // sinkMBB: 10494 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10495 // ... 10496 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10497 TII->get(X86::PHI), MI->getOperand(0).getReg()) 10498 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 10499 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 10500 10501 MI->eraseFromParent(); // The pseudo instruction is gone now. 10502 return sinkMBB; 10503} 10504 10505MachineBasicBlock * 10506X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI, 10507 MachineBasicBlock *BB) const { 10508 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10509 DebugLoc DL = MI->getDebugLoc(); 10510 10511 assert(!Subtarget->isTargetEnvMacho()); 10512 10513 // The lowering is pretty easy: we're just emitting the call to _alloca. The 10514 // non-trivial part is impdef of ESP. 10515 10516 if (Subtarget->isTargetWin64()) { 10517 if (Subtarget->isTargetCygMing()) { 10518 // ___chkstk(Mingw64): 10519 // Clobbers R10, R11, RAX and EFLAGS. 10520 // Updates RSP. 10521 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 10522 .addExternalSymbol("___chkstk") 10523 .addReg(X86::RAX, RegState::Implicit) 10524 .addReg(X86::RSP, RegState::Implicit) 10525 .addReg(X86::RAX, RegState::Define | RegState::Implicit) 10526 .addReg(X86::RSP, RegState::Define | RegState::Implicit) 10527 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 10528 } else { 10529 // __chkstk(MSVCRT): does not update stack pointer. 10530 // Clobbers R10, R11 and EFLAGS. 10531 // FIXME: RAX(allocated size) might be reused and not killed. 10532 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 10533 .addExternalSymbol("__chkstk") 10534 .addReg(X86::RAX, RegState::Implicit) 10535 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 10536 // RAX has the offset to subtracted from RSP. 10537 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP) 10538 .addReg(X86::RSP) 10539 .addReg(X86::RAX); 10540 } 10541 } else { 10542 const char *StackProbeSymbol = 10543 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca"; 10544 10545 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32)) 10546 .addExternalSymbol(StackProbeSymbol) 10547 .addReg(X86::EAX, RegState::Implicit) 10548 .addReg(X86::ESP, RegState::Implicit) 10549 .addReg(X86::EAX, RegState::Define | RegState::Implicit) 10550 .addReg(X86::ESP, RegState::Define | RegState::Implicit) 10551 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 10552 } 10553 10554 MI->eraseFromParent(); // The pseudo instruction is gone now. 10555 return BB; 10556} 10557 10558MachineBasicBlock * 10559X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI, 10560 MachineBasicBlock *BB) const { 10561 // This is pretty easy. We're taking the value that we received from 10562 // our load from the relocation, sticking it in either RDI (x86-64) 10563 // or EAX and doing an indirect call. The return value will then 10564 // be in the normal return register. 10565 const X86InstrInfo *TII 10566 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo()); 10567 DebugLoc DL = MI->getDebugLoc(); 10568 MachineFunction *F = BB->getParent(); 10569 10570 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?"); 10571 assert(MI->getOperand(3).isGlobal() && "This should be a global"); 10572 10573 if (Subtarget->is64Bit()) { 10574 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 10575 TII->get(X86::MOV64rm), X86::RDI) 10576 .addReg(X86::RIP) 10577 .addImm(0).addReg(0) 10578 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 10579 MI->getOperand(3).getTargetFlags()) 10580 .addReg(0); 10581 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m)); 10582 addDirectMem(MIB, X86::RDI); 10583 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) { 10584 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 10585 TII->get(X86::MOV32rm), X86::EAX) 10586 .addReg(0) 10587 .addImm(0).addReg(0) 10588 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 10589 MI->getOperand(3).getTargetFlags()) 10590 .addReg(0); 10591 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 10592 addDirectMem(MIB, X86::EAX); 10593 } else { 10594 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 10595 TII->get(X86::MOV32rm), X86::EAX) 10596 .addReg(TII->getGlobalBaseReg(F)) 10597 .addImm(0).addReg(0) 10598 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 10599 MI->getOperand(3).getTargetFlags()) 10600 .addReg(0); 10601 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 10602 addDirectMem(MIB, X86::EAX); 10603 } 10604 10605 MI->eraseFromParent(); // The pseudo instruction is gone now. 10606 return BB; 10607} 10608 10609MachineBasicBlock * 10610X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 10611 MachineBasicBlock *BB) const { 10612 switch (MI->getOpcode()) { 10613 default: assert(false && "Unexpected instr type to insert"); 10614 case X86::TAILJMPd64: 10615 case X86::TAILJMPr64: 10616 case X86::TAILJMPm64: 10617 assert(!"TAILJMP64 would not be touched here."); 10618 case X86::TCRETURNdi64: 10619 case X86::TCRETURNri64: 10620 case X86::TCRETURNmi64: 10621 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset. 10622 // On AMD64, additional defs should be added before register allocation. 10623 if (!Subtarget->isTargetWin64()) { 10624 MI->addRegisterDefined(X86::RSI); 10625 MI->addRegisterDefined(X86::RDI); 10626 MI->addRegisterDefined(X86::XMM6); 10627 MI->addRegisterDefined(X86::XMM7); 10628 MI->addRegisterDefined(X86::XMM8); 10629 MI->addRegisterDefined(X86::XMM9); 10630 MI->addRegisterDefined(X86::XMM10); 10631 MI->addRegisterDefined(X86::XMM11); 10632 MI->addRegisterDefined(X86::XMM12); 10633 MI->addRegisterDefined(X86::XMM13); 10634 MI->addRegisterDefined(X86::XMM14); 10635 MI->addRegisterDefined(X86::XMM15); 10636 } 10637 return BB; 10638 case X86::WIN_ALLOCA: 10639 return EmitLoweredWinAlloca(MI, BB); 10640 case X86::TLSCall_32: 10641 case X86::TLSCall_64: 10642 return EmitLoweredTLSCall(MI, BB); 10643 case X86::CMOV_GR8: 10644 case X86::CMOV_FR32: 10645 case X86::CMOV_FR64: 10646 case X86::CMOV_V4F32: 10647 case X86::CMOV_V2F64: 10648 case X86::CMOV_V2I64: 10649 case X86::CMOV_GR16: 10650 case X86::CMOV_GR32: 10651 case X86::CMOV_RFP32: 10652 case X86::CMOV_RFP64: 10653 case X86::CMOV_RFP80: 10654 return EmitLoweredSelect(MI, BB); 10655 10656 case X86::FP32_TO_INT16_IN_MEM: 10657 case X86::FP32_TO_INT32_IN_MEM: 10658 case X86::FP32_TO_INT64_IN_MEM: 10659 case X86::FP64_TO_INT16_IN_MEM: 10660 case X86::FP64_TO_INT32_IN_MEM: 10661 case X86::FP64_TO_INT64_IN_MEM: 10662 case X86::FP80_TO_INT16_IN_MEM: 10663 case X86::FP80_TO_INT32_IN_MEM: 10664 case X86::FP80_TO_INT64_IN_MEM: { 10665 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10666 DebugLoc DL = MI->getDebugLoc(); 10667 10668 // Change the floating point control register to use "round towards zero" 10669 // mode when truncating to an integer value. 10670 MachineFunction *F = BB->getParent(); 10671 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false); 10672 addFrameReference(BuildMI(*BB, MI, DL, 10673 TII->get(X86::FNSTCW16m)), CWFrameIdx); 10674 10675 // Load the old value of the high byte of the control word... 10676 unsigned OldCW = 10677 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass); 10678 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW), 10679 CWFrameIdx); 10680 10681 // Set the high part to be round to zero... 10682 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx) 10683 .addImm(0xC7F); 10684 10685 // Reload the modified control word now... 10686 addFrameReference(BuildMI(*BB, MI, DL, 10687 TII->get(X86::FLDCW16m)), CWFrameIdx); 10688 10689 // Restore the memory image of control word to original value 10690 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx) 10691 .addReg(OldCW); 10692 10693 // Get the X86 opcode to use. 10694 unsigned Opc; 10695 switch (MI->getOpcode()) { 10696 default: llvm_unreachable("illegal opcode!"); 10697 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break; 10698 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break; 10699 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break; 10700 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break; 10701 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break; 10702 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break; 10703 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break; 10704 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break; 10705 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break; 10706 } 10707 10708 X86AddressMode AM; 10709 MachineOperand &Op = MI->getOperand(0); 10710 if (Op.isReg()) { 10711 AM.BaseType = X86AddressMode::RegBase; 10712 AM.Base.Reg = Op.getReg(); 10713 } else { 10714 AM.BaseType = X86AddressMode::FrameIndexBase; 10715 AM.Base.FrameIndex = Op.getIndex(); 10716 } 10717 Op = MI->getOperand(1); 10718 if (Op.isImm()) 10719 AM.Scale = Op.getImm(); 10720 Op = MI->getOperand(2); 10721 if (Op.isImm()) 10722 AM.IndexReg = Op.getImm(); 10723 Op = MI->getOperand(3); 10724 if (Op.isGlobal()) { 10725 AM.GV = Op.getGlobal(); 10726 } else { 10727 AM.Disp = Op.getImm(); 10728 } 10729 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM) 10730 .addReg(MI->getOperand(X86::AddrNumOperands).getReg()); 10731 10732 // Reload the original control word now. 10733 addFrameReference(BuildMI(*BB, MI, DL, 10734 TII->get(X86::FLDCW16m)), CWFrameIdx); 10735 10736 MI->eraseFromParent(); // The pseudo instruction is gone now. 10737 return BB; 10738 } 10739 // String/text processing lowering. 10740 case X86::PCMPISTRM128REG: 10741 case X86::VPCMPISTRM128REG: 10742 return EmitPCMP(MI, BB, 3, false /* in-mem */); 10743 case X86::PCMPISTRM128MEM: 10744 case X86::VPCMPISTRM128MEM: 10745 return EmitPCMP(MI, BB, 3, true /* in-mem */); 10746 case X86::PCMPESTRM128REG: 10747 case X86::VPCMPESTRM128REG: 10748 return EmitPCMP(MI, BB, 5, false /* in mem */); 10749 case X86::PCMPESTRM128MEM: 10750 case X86::VPCMPESTRM128MEM: 10751 return EmitPCMP(MI, BB, 5, true /* in mem */); 10752 10753 // Thread synchronization. 10754 case X86::MONITOR: 10755 return EmitMonitor(MI, BB); 10756 case X86::MWAIT: 10757 return EmitMwait(MI, BB); 10758 10759 // Atomic Lowering. 10760 case X86::ATOMAND32: 10761 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 10762 X86::AND32ri, X86::MOV32rm, 10763 X86::LCMPXCHG32, 10764 X86::NOT32r, X86::EAX, 10765 X86::GR32RegisterClass); 10766 case X86::ATOMOR32: 10767 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr, 10768 X86::OR32ri, X86::MOV32rm, 10769 X86::LCMPXCHG32, 10770 X86::NOT32r, X86::EAX, 10771 X86::GR32RegisterClass); 10772 case X86::ATOMXOR32: 10773 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr, 10774 X86::XOR32ri, X86::MOV32rm, 10775 X86::LCMPXCHG32, 10776 X86::NOT32r, X86::EAX, 10777 X86::GR32RegisterClass); 10778 case X86::ATOMNAND32: 10779 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 10780 X86::AND32ri, X86::MOV32rm, 10781 X86::LCMPXCHG32, 10782 X86::NOT32r, X86::EAX, 10783 X86::GR32RegisterClass, true); 10784 case X86::ATOMMIN32: 10785 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr); 10786 case X86::ATOMMAX32: 10787 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr); 10788 case X86::ATOMUMIN32: 10789 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr); 10790 case X86::ATOMUMAX32: 10791 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr); 10792 10793 case X86::ATOMAND16: 10794 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 10795 X86::AND16ri, X86::MOV16rm, 10796 X86::LCMPXCHG16, 10797 X86::NOT16r, X86::AX, 10798 X86::GR16RegisterClass); 10799 case X86::ATOMOR16: 10800 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr, 10801 X86::OR16ri, X86::MOV16rm, 10802 X86::LCMPXCHG16, 10803 X86::NOT16r, X86::AX, 10804 X86::GR16RegisterClass); 10805 case X86::ATOMXOR16: 10806 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr, 10807 X86::XOR16ri, X86::MOV16rm, 10808 X86::LCMPXCHG16, 10809 X86::NOT16r, X86::AX, 10810 X86::GR16RegisterClass); 10811 case X86::ATOMNAND16: 10812 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 10813 X86::AND16ri, X86::MOV16rm, 10814 X86::LCMPXCHG16, 10815 X86::NOT16r, X86::AX, 10816 X86::GR16RegisterClass, true); 10817 case X86::ATOMMIN16: 10818 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr); 10819 case X86::ATOMMAX16: 10820 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr); 10821 case X86::ATOMUMIN16: 10822 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr); 10823 case X86::ATOMUMAX16: 10824 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr); 10825 10826 case X86::ATOMAND8: 10827 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 10828 X86::AND8ri, X86::MOV8rm, 10829 X86::LCMPXCHG8, 10830 X86::NOT8r, X86::AL, 10831 X86::GR8RegisterClass); 10832 case X86::ATOMOR8: 10833 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr, 10834 X86::OR8ri, X86::MOV8rm, 10835 X86::LCMPXCHG8, 10836 X86::NOT8r, X86::AL, 10837 X86::GR8RegisterClass); 10838 case X86::ATOMXOR8: 10839 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr, 10840 X86::XOR8ri, X86::MOV8rm, 10841 X86::LCMPXCHG8, 10842 X86::NOT8r, X86::AL, 10843 X86::GR8RegisterClass); 10844 case X86::ATOMNAND8: 10845 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 10846 X86::AND8ri, X86::MOV8rm, 10847 X86::LCMPXCHG8, 10848 X86::NOT8r, X86::AL, 10849 X86::GR8RegisterClass, true); 10850 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way. 10851 // This group is for 64-bit host. 10852 case X86::ATOMAND64: 10853 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 10854 X86::AND64ri32, X86::MOV64rm, 10855 X86::LCMPXCHG64, 10856 X86::NOT64r, X86::RAX, 10857 X86::GR64RegisterClass); 10858 case X86::ATOMOR64: 10859 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr, 10860 X86::OR64ri32, X86::MOV64rm, 10861 X86::LCMPXCHG64, 10862 X86::NOT64r, X86::RAX, 10863 X86::GR64RegisterClass); 10864 case X86::ATOMXOR64: 10865 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr, 10866 X86::XOR64ri32, X86::MOV64rm, 10867 X86::LCMPXCHG64, 10868 X86::NOT64r, X86::RAX, 10869 X86::GR64RegisterClass); 10870 case X86::ATOMNAND64: 10871 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 10872 X86::AND64ri32, X86::MOV64rm, 10873 X86::LCMPXCHG64, 10874 X86::NOT64r, X86::RAX, 10875 X86::GR64RegisterClass, true); 10876 case X86::ATOMMIN64: 10877 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr); 10878 case X86::ATOMMAX64: 10879 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr); 10880 case X86::ATOMUMIN64: 10881 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr); 10882 case X86::ATOMUMAX64: 10883 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr); 10884 10885 // This group does 64-bit operations on a 32-bit host. 10886 case X86::ATOMAND6432: 10887 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10888 X86::AND32rr, X86::AND32rr, 10889 X86::AND32ri, X86::AND32ri, 10890 false); 10891 case X86::ATOMOR6432: 10892 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10893 X86::OR32rr, X86::OR32rr, 10894 X86::OR32ri, X86::OR32ri, 10895 false); 10896 case X86::ATOMXOR6432: 10897 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10898 X86::XOR32rr, X86::XOR32rr, 10899 X86::XOR32ri, X86::XOR32ri, 10900 false); 10901 case X86::ATOMNAND6432: 10902 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10903 X86::AND32rr, X86::AND32rr, 10904 X86::AND32ri, X86::AND32ri, 10905 true); 10906 case X86::ATOMADD6432: 10907 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10908 X86::ADD32rr, X86::ADC32rr, 10909 X86::ADD32ri, X86::ADC32ri, 10910 false); 10911 case X86::ATOMSUB6432: 10912 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10913 X86::SUB32rr, X86::SBB32rr, 10914 X86::SUB32ri, X86::SBB32ri, 10915 false); 10916 case X86::ATOMSWAP6432: 10917 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10918 X86::MOV32rr, X86::MOV32rr, 10919 X86::MOV32ri, X86::MOV32ri, 10920 false); 10921 case X86::VASTART_SAVE_XMM_REGS: 10922 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB); 10923 10924 case X86::VAARG_64: 10925 return EmitVAARG64WithCustomInserter(MI, BB); 10926 } 10927} 10928 10929//===----------------------------------------------------------------------===// 10930// X86 Optimization Hooks 10931//===----------------------------------------------------------------------===// 10932 10933void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 10934 const APInt &Mask, 10935 APInt &KnownZero, 10936 APInt &KnownOne, 10937 const SelectionDAG &DAG, 10938 unsigned Depth) const { 10939 unsigned Opc = Op.getOpcode(); 10940 assert((Opc >= ISD::BUILTIN_OP_END || 10941 Opc == ISD::INTRINSIC_WO_CHAIN || 10942 Opc == ISD::INTRINSIC_W_CHAIN || 10943 Opc == ISD::INTRINSIC_VOID) && 10944 "Should use MaskedValueIsZero if you don't know whether Op" 10945 " is a target node!"); 10946 10947 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything. 10948 switch (Opc) { 10949 default: break; 10950 case X86ISD::ADD: 10951 case X86ISD::SUB: 10952 case X86ISD::ADC: 10953 case X86ISD::SBB: 10954 case X86ISD::SMUL: 10955 case X86ISD::UMUL: 10956 case X86ISD::INC: 10957 case X86ISD::DEC: 10958 case X86ISD::OR: 10959 case X86ISD::XOR: 10960 case X86ISD::AND: 10961 // These nodes' second result is a boolean. 10962 if (Op.getResNo() == 0) 10963 break; 10964 // Fallthrough 10965 case X86ISD::SETCC: 10966 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(), 10967 Mask.getBitWidth() - 1); 10968 break; 10969 } 10970} 10971 10972unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 10973 unsigned Depth) const { 10974 // SETCC_CARRY sets the dest to ~0 for true or 0 for false. 10975 if (Op.getOpcode() == X86ISD::SETCC_CARRY) 10976 return Op.getValueType().getScalarType().getSizeInBits(); 10977 10978 // Fallback case. 10979 return 1; 10980} 10981 10982/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 10983/// node is a GlobalAddress + offset. 10984bool X86TargetLowering::isGAPlusOffset(SDNode *N, 10985 const GlobalValue* &GA, 10986 int64_t &Offset) const { 10987 if (N->getOpcode() == X86ISD::Wrapper) { 10988 if (isa<GlobalAddressSDNode>(N->getOperand(0))) { 10989 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal(); 10990 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset(); 10991 return true; 10992 } 10993 } 10994 return TargetLowering::isGAPlusOffset(N, GA, Offset); 10995} 10996 10997/// PerformShuffleCombine - Combine a vector_shuffle that is equal to 10998/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load 10999/// if the load addresses are consecutive, non-overlapping, and in the right 11000/// order. 11001static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG, 11002 TargetLowering::DAGCombinerInfo &DCI) { 11003 DebugLoc dl = N->getDebugLoc(); 11004 EVT VT = N->getValueType(0); 11005 11006 if (VT.getSizeInBits() != 128) 11007 return SDValue(); 11008 11009 // Don't create instructions with illegal types after legalize types has run. 11010 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11011 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType())) 11012 return SDValue(); 11013 11014 SmallVector<SDValue, 16> Elts; 11015 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 11016 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0)); 11017 11018 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG); 11019} 11020 11021/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index 11022/// generation and convert it from being a bunch of shuffles and extracts 11023/// to a simple store and scalar loads to extract the elements. 11024static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG, 11025 const TargetLowering &TLI) { 11026 SDValue InputVector = N->getOperand(0); 11027 11028 // Only operate on vectors of 4 elements, where the alternative shuffling 11029 // gets to be more expensive. 11030 if (InputVector.getValueType() != MVT::v4i32) 11031 return SDValue(); 11032 11033 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a 11034 // single use which is a sign-extend or zero-extend, and all elements are 11035 // used. 11036 SmallVector<SDNode *, 4> Uses; 11037 unsigned ExtractedElements = 0; 11038 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(), 11039 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) { 11040 if (UI.getUse().getResNo() != InputVector.getResNo()) 11041 return SDValue(); 11042 11043 SDNode *Extract = *UI; 11044 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11045 return SDValue(); 11046 11047 if (Extract->getValueType(0) != MVT::i32) 11048 return SDValue(); 11049 if (!Extract->hasOneUse()) 11050 return SDValue(); 11051 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND && 11052 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND) 11053 return SDValue(); 11054 if (!isa<ConstantSDNode>(Extract->getOperand(1))) 11055 return SDValue(); 11056 11057 // Record which element was extracted. 11058 ExtractedElements |= 11059 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue(); 11060 11061 Uses.push_back(Extract); 11062 } 11063 11064 // If not all the elements were used, this may not be worthwhile. 11065 if (ExtractedElements != 15) 11066 return SDValue(); 11067 11068 // Ok, we've now decided to do the transformation. 11069 DebugLoc dl = InputVector.getDebugLoc(); 11070 11071 // Store the value to a temporary stack slot. 11072 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType()); 11073 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, 11074 MachinePointerInfo(), false, false, 0); 11075 11076 // Replace each use (extract) with a load of the appropriate element. 11077 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(), 11078 UE = Uses.end(); UI != UE; ++UI) { 11079 SDNode *Extract = *UI; 11080 11081 // cOMpute the element's address. 11082 SDValue Idx = Extract->getOperand(1); 11083 unsigned EltSize = 11084 InputVector.getValueType().getVectorElementType().getSizeInBits()/8; 11085 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue(); 11086 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy()); 11087 11088 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), 11089 StackPtr, OffsetVal); 11090 11091 // Load the scalar. 11092 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, 11093 ScalarAddr, MachinePointerInfo(), 11094 false, false, 0); 11095 11096 // Replace the exact with the load. 11097 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar); 11098 } 11099 11100 // The replacement was made in place; don't return anything. 11101 return SDValue(); 11102} 11103 11104/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes. 11105static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG, 11106 const X86Subtarget *Subtarget) { 11107 DebugLoc DL = N->getDebugLoc(); 11108 SDValue Cond = N->getOperand(0); 11109 // Get the LHS/RHS of the select. 11110 SDValue LHS = N->getOperand(1); 11111 SDValue RHS = N->getOperand(2); 11112 11113 // If we have SSE[12] support, try to form min/max nodes. SSE min/max 11114 // instructions match the semantics of the common C idiom x<y?x:y but not 11115 // x<=y?x:y, because of how they handle negative zero (which can be 11116 // ignored in unsafe-math mode). 11117 if (Subtarget->hasSSE2() && 11118 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) && 11119 Cond.getOpcode() == ISD::SETCC) { 11120 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 11121 11122 unsigned Opcode = 0; 11123 // Check for x CC y ? x : y. 11124 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) && 11125 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 11126 switch (CC) { 11127 default: break; 11128 case ISD::SETULT: 11129 // Converting this to a min would handle NaNs incorrectly, and swapping 11130 // the operands would cause it to handle comparisons between positive 11131 // and negative zero incorrectly. 11132 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 11133 if (!UnsafeFPMath && 11134 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 11135 break; 11136 std::swap(LHS, RHS); 11137 } 11138 Opcode = X86ISD::FMIN; 11139 break; 11140 case ISD::SETOLE: 11141 // Converting this to a min would handle comparisons between positive 11142 // and negative zero incorrectly. 11143 if (!UnsafeFPMath && 11144 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 11145 break; 11146 Opcode = X86ISD::FMIN; 11147 break; 11148 case ISD::SETULE: 11149 // Converting this to a min would handle both negative zeros and NaNs 11150 // incorrectly, but we can swap the operands to fix both. 11151 std::swap(LHS, RHS); 11152 case ISD::SETOLT: 11153 case ISD::SETLT: 11154 case ISD::SETLE: 11155 Opcode = X86ISD::FMIN; 11156 break; 11157 11158 case ISD::SETOGE: 11159 // Converting this to a max would handle comparisons between positive 11160 // and negative zero incorrectly. 11161 if (!UnsafeFPMath && 11162 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS)) 11163 break; 11164 Opcode = X86ISD::FMAX; 11165 break; 11166 case ISD::SETUGT: 11167 // Converting this to a max would handle NaNs incorrectly, and swapping 11168 // the operands would cause it to handle comparisons between positive 11169 // and negative zero incorrectly. 11170 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 11171 if (!UnsafeFPMath && 11172 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 11173 break; 11174 std::swap(LHS, RHS); 11175 } 11176 Opcode = X86ISD::FMAX; 11177 break; 11178 case ISD::SETUGE: 11179 // Converting this to a max would handle both negative zeros and NaNs 11180 // incorrectly, but we can swap the operands to fix both. 11181 std::swap(LHS, RHS); 11182 case ISD::SETOGT: 11183 case ISD::SETGT: 11184 case ISD::SETGE: 11185 Opcode = X86ISD::FMAX; 11186 break; 11187 } 11188 // Check for x CC y ? y : x -- a min/max with reversed arms. 11189 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) && 11190 DAG.isEqualTo(RHS, Cond.getOperand(0))) { 11191 switch (CC) { 11192 default: break; 11193 case ISD::SETOGE: 11194 // Converting this to a min would handle comparisons between positive 11195 // and negative zero incorrectly, and swapping the operands would 11196 // cause it to handle NaNs incorrectly. 11197 if (!UnsafeFPMath && 11198 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) { 11199 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 11200 break; 11201 std::swap(LHS, RHS); 11202 } 11203 Opcode = X86ISD::FMIN; 11204 break; 11205 case ISD::SETUGT: 11206 // Converting this to a min would handle NaNs incorrectly. 11207 if (!UnsafeFPMath && 11208 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) 11209 break; 11210 Opcode = X86ISD::FMIN; 11211 break; 11212 case ISD::SETUGE: 11213 // Converting this to a min would handle both negative zeros and NaNs 11214 // incorrectly, but we can swap the operands to fix both. 11215 std::swap(LHS, RHS); 11216 case ISD::SETOGT: 11217 case ISD::SETGT: 11218 case ISD::SETGE: 11219 Opcode = X86ISD::FMIN; 11220 break; 11221 11222 case ISD::SETULT: 11223 // Converting this to a max would handle NaNs incorrectly. 11224 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 11225 break; 11226 Opcode = X86ISD::FMAX; 11227 break; 11228 case ISD::SETOLE: 11229 // Converting this to a max would handle comparisons between positive 11230 // and negative zero incorrectly, and swapping the operands would 11231 // cause it to handle NaNs incorrectly. 11232 if (!UnsafeFPMath && 11233 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) { 11234 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 11235 break; 11236 std::swap(LHS, RHS); 11237 } 11238 Opcode = X86ISD::FMAX; 11239 break; 11240 case ISD::SETULE: 11241 // Converting this to a max would handle both negative zeros and NaNs 11242 // incorrectly, but we can swap the operands to fix both. 11243 std::swap(LHS, RHS); 11244 case ISD::SETOLT: 11245 case ISD::SETLT: 11246 case ISD::SETLE: 11247 Opcode = X86ISD::FMAX; 11248 break; 11249 } 11250 } 11251 11252 if (Opcode) 11253 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS); 11254 } 11255 11256 // If this is a select between two integer constants, try to do some 11257 // optimizations. 11258 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) { 11259 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS)) 11260 // Don't do this for crazy integer types. 11261 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) { 11262 // If this is efficiently invertible, canonicalize the LHSC/RHSC values 11263 // so that TrueC (the true value) is larger than FalseC. 11264 bool NeedsCondInvert = false; 11265 11266 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) && 11267 // Efficiently invertible. 11268 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible. 11269 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible. 11270 isa<ConstantSDNode>(Cond.getOperand(1))))) { 11271 NeedsCondInvert = true; 11272 std::swap(TrueC, FalseC); 11273 } 11274 11275 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0. 11276 if (FalseC->getAPIntValue() == 0 && 11277 TrueC->getAPIntValue().isPowerOf2()) { 11278 if (NeedsCondInvert) // Invert the condition if needed. 11279 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 11280 DAG.getConstant(1, Cond.getValueType())); 11281 11282 // Zero extend the condition if needed. 11283 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond); 11284 11285 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 11286 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond, 11287 DAG.getConstant(ShAmt, MVT::i8)); 11288 } 11289 11290 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. 11291 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 11292 if (NeedsCondInvert) // Invert the condition if needed. 11293 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 11294 DAG.getConstant(1, Cond.getValueType())); 11295 11296 // Zero extend the condition if needed. 11297 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 11298 FalseC->getValueType(0), Cond); 11299 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 11300 SDValue(FalseC, 0)); 11301 } 11302 11303 // Optimize cases that will turn into an LEA instruction. This requires 11304 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 11305 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 11306 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 11307 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 11308 11309 bool isFastMultiplier = false; 11310 if (Diff < 10) { 11311 switch ((unsigned char)Diff) { 11312 default: break; 11313 case 1: // result = add base, cond 11314 case 2: // result = lea base( , cond*2) 11315 case 3: // result = lea base(cond, cond*2) 11316 case 4: // result = lea base( , cond*4) 11317 case 5: // result = lea base(cond, cond*4) 11318 case 8: // result = lea base( , cond*8) 11319 case 9: // result = lea base(cond, cond*8) 11320 isFastMultiplier = true; 11321 break; 11322 } 11323 } 11324 11325 if (isFastMultiplier) { 11326 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 11327 if (NeedsCondInvert) // Invert the condition if needed. 11328 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 11329 DAG.getConstant(1, Cond.getValueType())); 11330 11331 // Zero extend the condition if needed. 11332 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 11333 Cond); 11334 // Scale the condition by the difference. 11335 if (Diff != 1) 11336 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 11337 DAG.getConstant(Diff, Cond.getValueType())); 11338 11339 // Add the base if non-zero. 11340 if (FalseC->getAPIntValue() != 0) 11341 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 11342 SDValue(FalseC, 0)); 11343 return Cond; 11344 } 11345 } 11346 } 11347 } 11348 11349 return SDValue(); 11350} 11351 11352/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL] 11353static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG, 11354 TargetLowering::DAGCombinerInfo &DCI) { 11355 DebugLoc DL = N->getDebugLoc(); 11356 11357 // If the flag operand isn't dead, don't touch this CMOV. 11358 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty()) 11359 return SDValue(); 11360 11361 SDValue FalseOp = N->getOperand(0); 11362 SDValue TrueOp = N->getOperand(1); 11363 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2); 11364 SDValue Cond = N->getOperand(3); 11365 if (CC == X86::COND_E || CC == X86::COND_NE) { 11366 switch (Cond.getOpcode()) { 11367 default: break; 11368 case X86ISD::BSR: 11369 case X86ISD::BSF: 11370 // If operand of BSR / BSF are proven never zero, then ZF cannot be set. 11371 if (DAG.isKnownNeverZero(Cond.getOperand(0))) 11372 return (CC == X86::COND_E) ? FalseOp : TrueOp; 11373 } 11374 } 11375 11376 // If this is a select between two integer constants, try to do some 11377 // optimizations. Note that the operands are ordered the opposite of SELECT 11378 // operands. 11379 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) { 11380 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) { 11381 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is 11382 // larger than FalseC (the false value). 11383 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) { 11384 CC = X86::GetOppositeBranchCondition(CC); 11385 std::swap(TrueC, FalseC); 11386 } 11387 11388 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0. 11389 // This is efficient for any integer data type (including i8/i16) and 11390 // shift amount. 11391 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) { 11392 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 11393 DAG.getConstant(CC, MVT::i8), Cond); 11394 11395 // Zero extend the condition if needed. 11396 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond); 11397 11398 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 11399 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond, 11400 DAG.getConstant(ShAmt, MVT::i8)); 11401 if (N->getNumValues() == 2) // Dead flag value? 11402 return DCI.CombineTo(N, Cond, SDValue()); 11403 return Cond; 11404 } 11405 11406 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient 11407 // for any integer data type, including i8/i16. 11408 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 11409 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 11410 DAG.getConstant(CC, MVT::i8), Cond); 11411 11412 // Zero extend the condition if needed. 11413 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 11414 FalseC->getValueType(0), Cond); 11415 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 11416 SDValue(FalseC, 0)); 11417 11418 if (N->getNumValues() == 2) // Dead flag value? 11419 return DCI.CombineTo(N, Cond, SDValue()); 11420 return Cond; 11421 } 11422 11423 // Optimize cases that will turn into an LEA instruction. This requires 11424 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 11425 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 11426 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 11427 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 11428 11429 bool isFastMultiplier = false; 11430 if (Diff < 10) { 11431 switch ((unsigned char)Diff) { 11432 default: break; 11433 case 1: // result = add base, cond 11434 case 2: // result = lea base( , cond*2) 11435 case 3: // result = lea base(cond, cond*2) 11436 case 4: // result = lea base( , cond*4) 11437 case 5: // result = lea base(cond, cond*4) 11438 case 8: // result = lea base( , cond*8) 11439 case 9: // result = lea base(cond, cond*8) 11440 isFastMultiplier = true; 11441 break; 11442 } 11443 } 11444 11445 if (isFastMultiplier) { 11446 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 11447 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 11448 DAG.getConstant(CC, MVT::i8), Cond); 11449 // Zero extend the condition if needed. 11450 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 11451 Cond); 11452 // Scale the condition by the difference. 11453 if (Diff != 1) 11454 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 11455 DAG.getConstant(Diff, Cond.getValueType())); 11456 11457 // Add the base if non-zero. 11458 if (FalseC->getAPIntValue() != 0) 11459 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 11460 SDValue(FalseC, 0)); 11461 if (N->getNumValues() == 2) // Dead flag value? 11462 return DCI.CombineTo(N, Cond, SDValue()); 11463 return Cond; 11464 } 11465 } 11466 } 11467 } 11468 return SDValue(); 11469} 11470 11471 11472/// PerformMulCombine - Optimize a single multiply with constant into two 11473/// in order to implement it with two cheaper instructions, e.g. 11474/// LEA + SHL, LEA + LEA. 11475static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG, 11476 TargetLowering::DAGCombinerInfo &DCI) { 11477 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11478 return SDValue(); 11479 11480 EVT VT = N->getValueType(0); 11481 if (VT != MVT::i64) 11482 return SDValue(); 11483 11484 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11485 if (!C) 11486 return SDValue(); 11487 uint64_t MulAmt = C->getZExtValue(); 11488 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9) 11489 return SDValue(); 11490 11491 uint64_t MulAmt1 = 0; 11492 uint64_t MulAmt2 = 0; 11493 if ((MulAmt % 9) == 0) { 11494 MulAmt1 = 9; 11495 MulAmt2 = MulAmt / 9; 11496 } else if ((MulAmt % 5) == 0) { 11497 MulAmt1 = 5; 11498 MulAmt2 = MulAmt / 5; 11499 } else if ((MulAmt % 3) == 0) { 11500 MulAmt1 = 3; 11501 MulAmt2 = MulAmt / 3; 11502 } 11503 if (MulAmt2 && 11504 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){ 11505 DebugLoc DL = N->getDebugLoc(); 11506 11507 if (isPowerOf2_64(MulAmt2) && 11508 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD)) 11509 // If second multiplifer is pow2, issue it first. We want the multiply by 11510 // 3, 5, or 9 to be folded into the addressing mode unless the lone use 11511 // is an add. 11512 std::swap(MulAmt1, MulAmt2); 11513 11514 SDValue NewMul; 11515 if (isPowerOf2_64(MulAmt1)) 11516 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 11517 DAG.getConstant(Log2_64(MulAmt1), MVT::i8)); 11518 else 11519 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0), 11520 DAG.getConstant(MulAmt1, VT)); 11521 11522 if (isPowerOf2_64(MulAmt2)) 11523 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul, 11524 DAG.getConstant(Log2_64(MulAmt2), MVT::i8)); 11525 else 11526 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul, 11527 DAG.getConstant(MulAmt2, VT)); 11528 11529 // Do not add new nodes to DAG combiner worklist. 11530 DCI.CombineTo(N, NewMul, false); 11531 } 11532 return SDValue(); 11533} 11534 11535static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) { 11536 SDValue N0 = N->getOperand(0); 11537 SDValue N1 = N->getOperand(1); 11538 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 11539 EVT VT = N0.getValueType(); 11540 11541 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2)) 11542 // since the result of setcc_c is all zero's or all ones. 11543 if (N1C && N0.getOpcode() == ISD::AND && 11544 N0.getOperand(1).getOpcode() == ISD::Constant) { 11545 SDValue N00 = N0.getOperand(0); 11546 if (N00.getOpcode() == X86ISD::SETCC_CARRY || 11547 ((N00.getOpcode() == ISD::ANY_EXTEND || 11548 N00.getOpcode() == ISD::ZERO_EXTEND) && 11549 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) { 11550 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 11551 APInt ShAmt = N1C->getAPIntValue(); 11552 Mask = Mask.shl(ShAmt); 11553 if (Mask != 0) 11554 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 11555 N00, DAG.getConstant(Mask, VT)); 11556 } 11557 } 11558 11559 return SDValue(); 11560} 11561 11562/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts 11563/// when possible. 11564static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG, 11565 const X86Subtarget *Subtarget) { 11566 EVT VT = N->getValueType(0); 11567 if (!VT.isVector() && VT.isInteger() && 11568 N->getOpcode() == ISD::SHL) 11569 return PerformSHLCombine(N, DAG); 11570 11571 // On X86 with SSE2 support, we can transform this to a vector shift if 11572 // all elements are shifted by the same amount. We can't do this in legalize 11573 // because the a constant vector is typically transformed to a constant pool 11574 // so we have no knowledge of the shift amount. 11575 if (!Subtarget->hasSSE2()) 11576 return SDValue(); 11577 11578 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16) 11579 return SDValue(); 11580 11581 SDValue ShAmtOp = N->getOperand(1); 11582 EVT EltVT = VT.getVectorElementType(); 11583 DebugLoc DL = N->getDebugLoc(); 11584 SDValue BaseShAmt = SDValue(); 11585 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) { 11586 unsigned NumElts = VT.getVectorNumElements(); 11587 unsigned i = 0; 11588 for (; i != NumElts; ++i) { 11589 SDValue Arg = ShAmtOp.getOperand(i); 11590 if (Arg.getOpcode() == ISD::UNDEF) continue; 11591 BaseShAmt = Arg; 11592 break; 11593 } 11594 for (; i != NumElts; ++i) { 11595 SDValue Arg = ShAmtOp.getOperand(i); 11596 if (Arg.getOpcode() == ISD::UNDEF) continue; 11597 if (Arg != BaseShAmt) { 11598 return SDValue(); 11599 } 11600 } 11601 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE && 11602 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) { 11603 SDValue InVec = ShAmtOp.getOperand(0); 11604 if (InVec.getOpcode() == ISD::BUILD_VECTOR) { 11605 unsigned NumElts = InVec.getValueType().getVectorNumElements(); 11606 unsigned i = 0; 11607 for (; i != NumElts; ++i) { 11608 SDValue Arg = InVec.getOperand(i); 11609 if (Arg.getOpcode() == ISD::UNDEF) continue; 11610 BaseShAmt = Arg; 11611 break; 11612 } 11613 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) { 11614 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) { 11615 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex(); 11616 if (C->getZExtValue() == SplatIdx) 11617 BaseShAmt = InVec.getOperand(1); 11618 } 11619 } 11620 if (BaseShAmt.getNode() == 0) 11621 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp, 11622 DAG.getIntPtrConstant(0)); 11623 } else 11624 return SDValue(); 11625 11626 // The shift amount is an i32. 11627 if (EltVT.bitsGT(MVT::i32)) 11628 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt); 11629 else if (EltVT.bitsLT(MVT::i32)) 11630 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt); 11631 11632 // The shift amount is identical so we can do a vector shift. 11633 SDValue ValOp = N->getOperand(0); 11634 switch (N->getOpcode()) { 11635 default: 11636 llvm_unreachable("Unknown shift opcode!"); 11637 break; 11638 case ISD::SHL: 11639 if (VT == MVT::v2i64) 11640 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11641 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 11642 ValOp, BaseShAmt); 11643 if (VT == MVT::v4i32) 11644 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11645 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 11646 ValOp, BaseShAmt); 11647 if (VT == MVT::v8i16) 11648 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11649 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 11650 ValOp, BaseShAmt); 11651 break; 11652 case ISD::SRA: 11653 if (VT == MVT::v4i32) 11654 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11655 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32), 11656 ValOp, BaseShAmt); 11657 if (VT == MVT::v8i16) 11658 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11659 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32), 11660 ValOp, BaseShAmt); 11661 break; 11662 case ISD::SRL: 11663 if (VT == MVT::v2i64) 11664 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11665 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 11666 ValOp, BaseShAmt); 11667 if (VT == MVT::v4i32) 11668 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11669 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32), 11670 ValOp, BaseShAmt); 11671 if (VT == MVT::v8i16) 11672 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11673 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32), 11674 ValOp, BaseShAmt); 11675 break; 11676 } 11677 return SDValue(); 11678} 11679 11680 11681// CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..)) 11682// where both setccs reference the same FP CMP, and rewrite for CMPEQSS 11683// and friends. Likewise for OR -> CMPNEQSS. 11684static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG, 11685 TargetLowering::DAGCombinerInfo &DCI, 11686 const X86Subtarget *Subtarget) { 11687 unsigned opcode; 11688 11689 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but 11690 // we're requiring SSE2 for both. 11691 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) { 11692 SDValue N0 = N->getOperand(0); 11693 SDValue N1 = N->getOperand(1); 11694 SDValue CMP0 = N0->getOperand(1); 11695 SDValue CMP1 = N1->getOperand(1); 11696 DebugLoc DL = N->getDebugLoc(); 11697 11698 // The SETCCs should both refer to the same CMP. 11699 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1) 11700 return SDValue(); 11701 11702 SDValue CMP00 = CMP0->getOperand(0); 11703 SDValue CMP01 = CMP0->getOperand(1); 11704 EVT VT = CMP00.getValueType(); 11705 11706 if (VT == MVT::f32 || VT == MVT::f64) { 11707 bool ExpectingFlags = false; 11708 // Check for any users that want flags: 11709 for (SDNode::use_iterator UI = N->use_begin(), 11710 UE = N->use_end(); 11711 !ExpectingFlags && UI != UE; ++UI) 11712 switch (UI->getOpcode()) { 11713 default: 11714 case ISD::BR_CC: 11715 case ISD::BRCOND: 11716 case ISD::SELECT: 11717 ExpectingFlags = true; 11718 break; 11719 case ISD::CopyToReg: 11720 case ISD::SIGN_EXTEND: 11721 case ISD::ZERO_EXTEND: 11722 case ISD::ANY_EXTEND: 11723 break; 11724 } 11725 11726 if (!ExpectingFlags) { 11727 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0); 11728 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0); 11729 11730 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) { 11731 X86::CondCode tmp = cc0; 11732 cc0 = cc1; 11733 cc1 = tmp; 11734 } 11735 11736 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) || 11737 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) { 11738 bool is64BitFP = (CMP00.getValueType() == MVT::f64); 11739 X86ISD::NodeType NTOperator = is64BitFP ? 11740 X86ISD::FSETCCsd : X86ISD::FSETCCss; 11741 // FIXME: need symbolic constants for these magic numbers. 11742 // See X86ATTInstPrinter.cpp:printSSECC(). 11743 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4; 11744 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01, 11745 DAG.getConstant(x86cc, MVT::i8)); 11746 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32, 11747 OnesOrZeroesF); 11748 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI, 11749 DAG.getConstant(1, MVT::i32)); 11750 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed); 11751 return OneBitOfTruth; 11752 } 11753 } 11754 } 11755 } 11756 return SDValue(); 11757} 11758 11759static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG, 11760 TargetLowering::DAGCombinerInfo &DCI, 11761 const X86Subtarget *Subtarget) { 11762 if (DCI.isBeforeLegalizeOps()) 11763 return SDValue(); 11764 11765 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 11766 if (R.getNode()) 11767 return R; 11768 11769 // Want to form PANDN nodes, in the hopes of then easily combining them with 11770 // OR and AND nodes to form PBLEND/PSIGN. 11771 EVT VT = N->getValueType(0); 11772 if (VT != MVT::v2i64) 11773 return SDValue(); 11774 11775 SDValue N0 = N->getOperand(0); 11776 SDValue N1 = N->getOperand(1); 11777 DebugLoc DL = N->getDebugLoc(); 11778 11779 // Check LHS for vnot 11780 if (N0.getOpcode() == ISD::XOR && 11781 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode())) 11782 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1); 11783 11784 // Check RHS for vnot 11785 if (N1.getOpcode() == ISD::XOR && 11786 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode())) 11787 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0); 11788 11789 return SDValue(); 11790} 11791 11792static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG, 11793 TargetLowering::DAGCombinerInfo &DCI, 11794 const X86Subtarget *Subtarget) { 11795 if (DCI.isBeforeLegalizeOps()) 11796 return SDValue(); 11797 11798 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 11799 if (R.getNode()) 11800 return R; 11801 11802 EVT VT = N->getValueType(0); 11803 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64) 11804 return SDValue(); 11805 11806 SDValue N0 = N->getOperand(0); 11807 SDValue N1 = N->getOperand(1); 11808 11809 // look for psign/blend 11810 if (Subtarget->hasSSSE3()) { 11811 if (VT == MVT::v2i64) { 11812 // Canonicalize pandn to RHS 11813 if (N0.getOpcode() == X86ISD::PANDN) 11814 std::swap(N0, N1); 11815 // or (and (m, x), (pandn m, y)) 11816 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) { 11817 SDValue Mask = N1.getOperand(0); 11818 SDValue X = N1.getOperand(1); 11819 SDValue Y; 11820 if (N0.getOperand(0) == Mask) 11821 Y = N0.getOperand(1); 11822 if (N0.getOperand(1) == Mask) 11823 Y = N0.getOperand(0); 11824 11825 // Check to see if the mask appeared in both the AND and PANDN and 11826 if (!Y.getNode()) 11827 return SDValue(); 11828 11829 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them. 11830 if (Mask.getOpcode() != ISD::BITCAST || 11831 X.getOpcode() != ISD::BITCAST || 11832 Y.getOpcode() != ISD::BITCAST) 11833 return SDValue(); 11834 11835 // Look through mask bitcast. 11836 Mask = Mask.getOperand(0); 11837 EVT MaskVT = Mask.getValueType(); 11838 11839 // Validate that the Mask operand is a vector sra node. The sra node 11840 // will be an intrinsic. 11841 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN) 11842 return SDValue(); 11843 11844 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but 11845 // there is no psrai.b 11846 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) { 11847 case Intrinsic::x86_sse2_psrai_w: 11848 case Intrinsic::x86_sse2_psrai_d: 11849 break; 11850 default: return SDValue(); 11851 } 11852 11853 // Check that the SRA is all signbits. 11854 SDValue SraC = Mask.getOperand(2); 11855 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue(); 11856 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits(); 11857 if ((SraAmt + 1) != EltBits) 11858 return SDValue(); 11859 11860 DebugLoc DL = N->getDebugLoc(); 11861 11862 // Now we know we at least have a plendvb with the mask val. See if 11863 // we can form a psignb/w/d. 11864 // psign = x.type == y.type == mask.type && y = sub(0, x); 11865 X = X.getOperand(0); 11866 Y = Y.getOperand(0); 11867 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X && 11868 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) && 11869 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){ 11870 unsigned Opc = 0; 11871 switch (EltBits) { 11872 case 8: Opc = X86ISD::PSIGNB; break; 11873 case 16: Opc = X86ISD::PSIGNW; break; 11874 case 32: Opc = X86ISD::PSIGND; break; 11875 default: break; 11876 } 11877 if (Opc) { 11878 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1)); 11879 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign); 11880 } 11881 } 11882 // PBLENDVB only available on SSE 4.1 11883 if (!Subtarget->hasSSE41()) 11884 return SDValue(); 11885 11886 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X); 11887 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y); 11888 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask); 11889 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask); 11890 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask); 11891 } 11892 } 11893 } 11894 11895 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c) 11896 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 11897 std::swap(N0, N1); 11898 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 11899 return SDValue(); 11900 if (!N0.hasOneUse() || !N1.hasOneUse()) 11901 return SDValue(); 11902 11903 SDValue ShAmt0 = N0.getOperand(1); 11904 if (ShAmt0.getValueType() != MVT::i8) 11905 return SDValue(); 11906 SDValue ShAmt1 = N1.getOperand(1); 11907 if (ShAmt1.getValueType() != MVT::i8) 11908 return SDValue(); 11909 if (ShAmt0.getOpcode() == ISD::TRUNCATE) 11910 ShAmt0 = ShAmt0.getOperand(0); 11911 if (ShAmt1.getOpcode() == ISD::TRUNCATE) 11912 ShAmt1 = ShAmt1.getOperand(0); 11913 11914 DebugLoc DL = N->getDebugLoc(); 11915 unsigned Opc = X86ISD::SHLD; 11916 SDValue Op0 = N0.getOperand(0); 11917 SDValue Op1 = N1.getOperand(0); 11918 if (ShAmt0.getOpcode() == ISD::SUB) { 11919 Opc = X86ISD::SHRD; 11920 std::swap(Op0, Op1); 11921 std::swap(ShAmt0, ShAmt1); 11922 } 11923 11924 unsigned Bits = VT.getSizeInBits(); 11925 if (ShAmt1.getOpcode() == ISD::SUB) { 11926 SDValue Sum = ShAmt1.getOperand(0); 11927 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) { 11928 SDValue ShAmt1Op1 = ShAmt1.getOperand(1); 11929 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE) 11930 ShAmt1Op1 = ShAmt1Op1.getOperand(0); 11931 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0) 11932 return DAG.getNode(Opc, DL, VT, 11933 Op0, Op1, 11934 DAG.getNode(ISD::TRUNCATE, DL, 11935 MVT::i8, ShAmt0)); 11936 } 11937 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) { 11938 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0); 11939 if (ShAmt0C && 11940 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits) 11941 return DAG.getNode(Opc, DL, VT, 11942 N0.getOperand(0), N1.getOperand(0), 11943 DAG.getNode(ISD::TRUNCATE, DL, 11944 MVT::i8, ShAmt0)); 11945 } 11946 11947 return SDValue(); 11948} 11949 11950/// PerformSTORECombine - Do target-specific dag combines on STORE nodes. 11951static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG, 11952 const X86Subtarget *Subtarget) { 11953 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering 11954 // the FP state in cases where an emms may be missing. 11955 // A preferable solution to the general problem is to figure out the right 11956 // places to insert EMMS. This qualifies as a quick hack. 11957 11958 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode. 11959 StoreSDNode *St = cast<StoreSDNode>(N); 11960 EVT VT = St->getValue().getValueType(); 11961 if (VT.getSizeInBits() != 64) 11962 return SDValue(); 11963 11964 const Function *F = DAG.getMachineFunction().getFunction(); 11965 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat); 11966 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps 11967 && Subtarget->hasSSE2(); 11968 if ((VT.isVector() || 11969 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) && 11970 isa<LoadSDNode>(St->getValue()) && 11971 !cast<LoadSDNode>(St->getValue())->isVolatile() && 11972 St->getChain().hasOneUse() && !St->isVolatile()) { 11973 SDNode* LdVal = St->getValue().getNode(); 11974 LoadSDNode *Ld = 0; 11975 int TokenFactorIndex = -1; 11976 SmallVector<SDValue, 8> Ops; 11977 SDNode* ChainVal = St->getChain().getNode(); 11978 // Must be a store of a load. We currently handle two cases: the load 11979 // is a direct child, and it's under an intervening TokenFactor. It is 11980 // possible to dig deeper under nested TokenFactors. 11981 if (ChainVal == LdVal) 11982 Ld = cast<LoadSDNode>(St->getChain()); 11983 else if (St->getValue().hasOneUse() && 11984 ChainVal->getOpcode() == ISD::TokenFactor) { 11985 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) { 11986 if (ChainVal->getOperand(i).getNode() == LdVal) { 11987 TokenFactorIndex = i; 11988 Ld = cast<LoadSDNode>(St->getValue()); 11989 } else 11990 Ops.push_back(ChainVal->getOperand(i)); 11991 } 11992 } 11993 11994 if (!Ld || !ISD::isNormalLoad(Ld)) 11995 return SDValue(); 11996 11997 // If this is not the MMX case, i.e. we are just turning i64 load/store 11998 // into f64 load/store, avoid the transformation if there are multiple 11999 // uses of the loaded value. 12000 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0)) 12001 return SDValue(); 12002 12003 DebugLoc LdDL = Ld->getDebugLoc(); 12004 DebugLoc StDL = N->getDebugLoc(); 12005 // If we are a 64-bit capable x86, lower to a single movq load/store pair. 12006 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store 12007 // pair instead. 12008 if (Subtarget->is64Bit() || F64IsLegal) { 12009 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64; 12010 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(), 12011 Ld->getPointerInfo(), Ld->isVolatile(), 12012 Ld->isNonTemporal(), Ld->getAlignment()); 12013 SDValue NewChain = NewLd.getValue(1); 12014 if (TokenFactorIndex != -1) { 12015 Ops.push_back(NewChain); 12016 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 12017 Ops.size()); 12018 } 12019 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(), 12020 St->getPointerInfo(), 12021 St->isVolatile(), St->isNonTemporal(), 12022 St->getAlignment()); 12023 } 12024 12025 // Otherwise, lower to two pairs of 32-bit loads / stores. 12026 SDValue LoAddr = Ld->getBasePtr(); 12027 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr, 12028 DAG.getConstant(4, MVT::i32)); 12029 12030 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr, 12031 Ld->getPointerInfo(), 12032 Ld->isVolatile(), Ld->isNonTemporal(), 12033 Ld->getAlignment()); 12034 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr, 12035 Ld->getPointerInfo().getWithOffset(4), 12036 Ld->isVolatile(), Ld->isNonTemporal(), 12037 MinAlign(Ld->getAlignment(), 4)); 12038 12039 SDValue NewChain = LoLd.getValue(1); 12040 if (TokenFactorIndex != -1) { 12041 Ops.push_back(LoLd); 12042 Ops.push_back(HiLd); 12043 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 12044 Ops.size()); 12045 } 12046 12047 LoAddr = St->getBasePtr(); 12048 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr, 12049 DAG.getConstant(4, MVT::i32)); 12050 12051 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr, 12052 St->getPointerInfo(), 12053 St->isVolatile(), St->isNonTemporal(), 12054 St->getAlignment()); 12055 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr, 12056 St->getPointerInfo().getWithOffset(4), 12057 St->isVolatile(), 12058 St->isNonTemporal(), 12059 MinAlign(St->getAlignment(), 4)); 12060 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt); 12061 } 12062 return SDValue(); 12063} 12064 12065/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and 12066/// X86ISD::FXOR nodes. 12067static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) { 12068 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR); 12069 // F[X]OR(0.0, x) -> x 12070 // F[X]OR(x, 0.0) -> x 12071 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 12072 if (C->getValueAPF().isPosZero()) 12073 return N->getOperand(1); 12074 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 12075 if (C->getValueAPF().isPosZero()) 12076 return N->getOperand(0); 12077 return SDValue(); 12078} 12079 12080/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes. 12081static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) { 12082 // FAND(0.0, x) -> 0.0 12083 // FAND(x, 0.0) -> 0.0 12084 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 12085 if (C->getValueAPF().isPosZero()) 12086 return N->getOperand(0); 12087 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 12088 if (C->getValueAPF().isPosZero()) 12089 return N->getOperand(1); 12090 return SDValue(); 12091} 12092 12093static SDValue PerformBTCombine(SDNode *N, 12094 SelectionDAG &DAG, 12095 TargetLowering::DAGCombinerInfo &DCI) { 12096 // BT ignores high bits in the bit index operand. 12097 SDValue Op1 = N->getOperand(1); 12098 if (Op1.hasOneUse()) { 12099 unsigned BitWidth = Op1.getValueSizeInBits(); 12100 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth)); 12101 APInt KnownZero, KnownOne; 12102 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 12103 !DCI.isBeforeLegalizeOps()); 12104 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12105 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) || 12106 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO)) 12107 DCI.CommitTargetLoweringOpt(TLO); 12108 } 12109 return SDValue(); 12110} 12111 12112static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) { 12113 SDValue Op = N->getOperand(0); 12114 if (Op.getOpcode() == ISD::BITCAST) 12115 Op = Op.getOperand(0); 12116 EVT VT = N->getValueType(0), OpVT = Op.getValueType(); 12117 if (Op.getOpcode() == X86ISD::VZEXT_LOAD && 12118 VT.getVectorElementType().getSizeInBits() == 12119 OpVT.getVectorElementType().getSizeInBits()) { 12120 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op); 12121 } 12122 return SDValue(); 12123} 12124 12125static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) { 12126 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) -> 12127 // (and (i32 x86isd::setcc_carry), 1) 12128 // This eliminates the zext. This transformation is necessary because 12129 // ISD::SETCC is always legalized to i8. 12130 DebugLoc dl = N->getDebugLoc(); 12131 SDValue N0 = N->getOperand(0); 12132 EVT VT = N->getValueType(0); 12133 if (N0.getOpcode() == ISD::AND && 12134 N0.hasOneUse() && 12135 N0.getOperand(0).hasOneUse()) { 12136 SDValue N00 = N0.getOperand(0); 12137 if (N00.getOpcode() != X86ISD::SETCC_CARRY) 12138 return SDValue(); 12139 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 12140 if (!C || C->getZExtValue() != 1) 12141 return SDValue(); 12142 return DAG.getNode(ISD::AND, dl, VT, 12143 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, 12144 N00.getOperand(0), N00.getOperand(1)), 12145 DAG.getConstant(1, VT)); 12146 } 12147 12148 return SDValue(); 12149} 12150 12151// Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT 12152static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) { 12153 unsigned X86CC = N->getConstantOperandVal(0); 12154 SDValue EFLAG = N->getOperand(1); 12155 DebugLoc DL = N->getDebugLoc(); 12156 12157 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without 12158 // a zext and produces an all-ones bit which is more useful than 0/1 in some 12159 // cases. 12160 if (X86CC == X86::COND_B) 12161 return DAG.getNode(ISD::AND, DL, MVT::i8, 12162 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8, 12163 DAG.getConstant(X86CC, MVT::i8), EFLAG), 12164 DAG.getConstant(1, MVT::i8)); 12165 12166 return SDValue(); 12167} 12168 12169static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG, const X86TargetLowering *XTLI) { 12170 DebugLoc dl = N->getDebugLoc(); 12171 SDValue Op0 = N->getOperand(0); 12172 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have 12173 // a 32-bit target where SSE doesn't support i64->FP operations. 12174 if (Op0.getOpcode() == ISD::LOAD) { 12175 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode()); 12176 EVT VT = Ld->getValueType(0); 12177 if (!Ld->isVolatile() && !N->getValueType(0).isVector() && 12178 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() && 12179 !XTLI->getSubtarget()->is64Bit() && 12180 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 12181 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG); 12182 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1)); 12183 return FILDChain; 12184 } 12185 } 12186 return SDValue(); 12187} 12188 12189// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS 12190static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG, 12191 X86TargetLowering::DAGCombinerInfo &DCI) { 12192 // If the LHS and RHS of the ADC node are zero, then it can't overflow and 12193 // the result is either zero or one (depending on the input carry bit). 12194 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1. 12195 if (X86::isZeroNode(N->getOperand(0)) && 12196 X86::isZeroNode(N->getOperand(1)) && 12197 // We don't have a good way to replace an EFLAGS use, so only do this when 12198 // dead right now. 12199 SDValue(N, 1).use_empty()) { 12200 DebugLoc DL = N->getDebugLoc(); 12201 EVT VT = N->getValueType(0); 12202 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1)); 12203 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT, 12204 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, 12205 DAG.getConstant(X86::COND_B,MVT::i8), 12206 N->getOperand(2)), 12207 DAG.getConstant(1, VT)); 12208 return DCI.CombineTo(N, Res1, CarryOut); 12209 } 12210 12211 return SDValue(); 12212} 12213 12214// fold (add Y, (sete X, 0)) -> adc 0, Y 12215// (add Y, (setne X, 0)) -> sbb -1, Y 12216// (sub (sete X, 0), Y) -> sbb 0, Y 12217// (sub (setne X, 0), Y) -> adc -1, Y 12218static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) { 12219 DebugLoc DL = N->getDebugLoc(); 12220 12221 // Look through ZExts. 12222 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0); 12223 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse()) 12224 return SDValue(); 12225 12226 SDValue SetCC = Ext.getOperand(0); 12227 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse()) 12228 return SDValue(); 12229 12230 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0); 12231 if (CC != X86::COND_E && CC != X86::COND_NE) 12232 return SDValue(); 12233 12234 SDValue Cmp = SetCC.getOperand(1); 12235 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() || 12236 !X86::isZeroNode(Cmp.getOperand(1)) || 12237 !Cmp.getOperand(0).getValueType().isInteger()) 12238 return SDValue(); 12239 12240 SDValue CmpOp0 = Cmp.getOperand(0); 12241 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0, 12242 DAG.getConstant(1, CmpOp0.getValueType())); 12243 12244 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1); 12245 if (CC == X86::COND_NE) 12246 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB, 12247 DL, OtherVal.getValueType(), OtherVal, 12248 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp); 12249 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC, 12250 DL, OtherVal.getValueType(), OtherVal, 12251 DAG.getConstant(0, OtherVal.getValueType()), NewCmp); 12252} 12253 12254SDValue X86TargetLowering::PerformDAGCombine(SDNode *N, 12255 DAGCombinerInfo &DCI) const { 12256 SelectionDAG &DAG = DCI.DAG; 12257 switch (N->getOpcode()) { 12258 default: break; 12259 case ISD::EXTRACT_VECTOR_ELT: 12260 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this); 12261 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget); 12262 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI); 12263 case ISD::ADD: 12264 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG); 12265 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI); 12266 case ISD::MUL: return PerformMulCombine(N, DAG, DCI); 12267 case ISD::SHL: 12268 case ISD::SRA: 12269 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget); 12270 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget); 12271 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget); 12272 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget); 12273 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this); 12274 case X86ISD::FXOR: 12275 case X86ISD::FOR: return PerformFORCombine(N, DAG); 12276 case X86ISD::FAND: return PerformFANDCombine(N, DAG); 12277 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI); 12278 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG); 12279 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG); 12280 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG); 12281 case X86ISD::SHUFPS: // Handle all target specific shuffles 12282 case X86ISD::SHUFPD: 12283 case X86ISD::PALIGN: 12284 case X86ISD::PUNPCKHBW: 12285 case X86ISD::PUNPCKHWD: 12286 case X86ISD::PUNPCKHDQ: 12287 case X86ISD::PUNPCKHQDQ: 12288 case X86ISD::UNPCKHPS: 12289 case X86ISD::UNPCKHPD: 12290 case X86ISD::PUNPCKLBW: 12291 case X86ISD::PUNPCKLWD: 12292 case X86ISD::PUNPCKLDQ: 12293 case X86ISD::PUNPCKLQDQ: 12294 case X86ISD::UNPCKLPS: 12295 case X86ISD::UNPCKLPD: 12296 case X86ISD::VUNPCKLPS: 12297 case X86ISD::VUNPCKLPD: 12298 case X86ISD::VUNPCKLPSY: 12299 case X86ISD::VUNPCKLPDY: 12300 case X86ISD::MOVHLPS: 12301 case X86ISD::MOVLHPS: 12302 case X86ISD::PSHUFD: 12303 case X86ISD::PSHUFHW: 12304 case X86ISD::PSHUFLW: 12305 case X86ISD::MOVSS: 12306 case X86ISD::MOVSD: 12307 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI); 12308 } 12309 12310 return SDValue(); 12311} 12312 12313/// isTypeDesirableForOp - Return true if the target has native support for 12314/// the specified value type and it is 'desirable' to use the type for the 12315/// given node type. e.g. On x86 i16 is legal, but undesirable since i16 12316/// instruction encodings are longer and some i16 instructions are slow. 12317bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const { 12318 if (!isTypeLegal(VT)) 12319 return false; 12320 if (VT != MVT::i16) 12321 return true; 12322 12323 switch (Opc) { 12324 default: 12325 return true; 12326 case ISD::LOAD: 12327 case ISD::SIGN_EXTEND: 12328 case ISD::ZERO_EXTEND: 12329 case ISD::ANY_EXTEND: 12330 case ISD::SHL: 12331 case ISD::SRL: 12332 case ISD::SUB: 12333 case ISD::ADD: 12334 case ISD::MUL: 12335 case ISD::AND: 12336 case ISD::OR: 12337 case ISD::XOR: 12338 return false; 12339 } 12340} 12341 12342/// IsDesirableToPromoteOp - This method query the target whether it is 12343/// beneficial for dag combiner to promote the specified node. If true, it 12344/// should return the desired promotion type by reference. 12345bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const { 12346 EVT VT = Op.getValueType(); 12347 if (VT != MVT::i16) 12348 return false; 12349 12350 bool Promote = false; 12351 bool Commute = false; 12352 switch (Op.getOpcode()) { 12353 default: break; 12354 case ISD::LOAD: { 12355 LoadSDNode *LD = cast<LoadSDNode>(Op); 12356 // If the non-extending load has a single use and it's not live out, then it 12357 // might be folded. 12358 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&& 12359 Op.hasOneUse()*/) { 12360 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 12361 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 12362 // The only case where we'd want to promote LOAD (rather then it being 12363 // promoted as an operand is when it's only use is liveout. 12364 if (UI->getOpcode() != ISD::CopyToReg) 12365 return false; 12366 } 12367 } 12368 Promote = true; 12369 break; 12370 } 12371 case ISD::SIGN_EXTEND: 12372 case ISD::ZERO_EXTEND: 12373 case ISD::ANY_EXTEND: 12374 Promote = true; 12375 break; 12376 case ISD::SHL: 12377 case ISD::SRL: { 12378 SDValue N0 = Op.getOperand(0); 12379 // Look out for (store (shl (load), x)). 12380 if (MayFoldLoad(N0) && MayFoldIntoStore(Op)) 12381 return false; 12382 Promote = true; 12383 break; 12384 } 12385 case ISD::ADD: 12386 case ISD::MUL: 12387 case ISD::AND: 12388 case ISD::OR: 12389 case ISD::XOR: 12390 Commute = true; 12391 // fallthrough 12392 case ISD::SUB: { 12393 SDValue N0 = Op.getOperand(0); 12394 SDValue N1 = Op.getOperand(1); 12395 if (!Commute && MayFoldLoad(N1)) 12396 return false; 12397 // Avoid disabling potential load folding opportunities. 12398 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op))) 12399 return false; 12400 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op))) 12401 return false; 12402 Promote = true; 12403 } 12404 } 12405 12406 PVT = MVT::i32; 12407 return Promote; 12408} 12409 12410//===----------------------------------------------------------------------===// 12411// X86 Inline Assembly Support 12412//===----------------------------------------------------------------------===// 12413 12414bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const { 12415 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 12416 12417 std::string AsmStr = IA->getAsmString(); 12418 12419 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a" 12420 SmallVector<StringRef, 4> AsmPieces; 12421 SplitString(AsmStr, AsmPieces, ";\n"); 12422 12423 switch (AsmPieces.size()) { 12424 default: return false; 12425 case 1: 12426 AsmStr = AsmPieces[0]; 12427 AsmPieces.clear(); 12428 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace. 12429 12430 // FIXME: this should verify that we are targeting a 486 or better. If not, 12431 // we will turn this bswap into something that will be lowered to logical ops 12432 // instead of emitting the bswap asm. For now, we don't support 486 or lower 12433 // so don't worry about this. 12434 // bswap $0 12435 if (AsmPieces.size() == 2 && 12436 (AsmPieces[0] == "bswap" || 12437 AsmPieces[0] == "bswapq" || 12438 AsmPieces[0] == "bswapl") && 12439 (AsmPieces[1] == "$0" || 12440 AsmPieces[1] == "${0:q}")) { 12441 // No need to check constraints, nothing other than the equivalent of 12442 // "=r,0" would be valid here. 12443 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12444 if (!Ty || Ty->getBitWidth() % 16 != 0) 12445 return false; 12446 return IntrinsicLowering::LowerToByteSwap(CI); 12447 } 12448 // rorw $$8, ${0:w} --> llvm.bswap.i16 12449 if (CI->getType()->isIntegerTy(16) && 12450 AsmPieces.size() == 3 && 12451 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") && 12452 AsmPieces[1] == "$$8," && 12453 AsmPieces[2] == "${0:w}" && 12454 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) { 12455 AsmPieces.clear(); 12456 const std::string &ConstraintsStr = IA->getConstraintString(); 12457 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 12458 std::sort(AsmPieces.begin(), AsmPieces.end()); 12459 if (AsmPieces.size() == 4 && 12460 AsmPieces[0] == "~{cc}" && 12461 AsmPieces[1] == "~{dirflag}" && 12462 AsmPieces[2] == "~{flags}" && 12463 AsmPieces[3] == "~{fpsr}") { 12464 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12465 if (!Ty || Ty->getBitWidth() % 16 != 0) 12466 return false; 12467 return IntrinsicLowering::LowerToByteSwap(CI); 12468 } 12469 } 12470 break; 12471 case 3: 12472 if (CI->getType()->isIntegerTy(32) && 12473 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) { 12474 SmallVector<StringRef, 4> Words; 12475 SplitString(AsmPieces[0], Words, " \t,"); 12476 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" && 12477 Words[2] == "${0:w}") { 12478 Words.clear(); 12479 SplitString(AsmPieces[1], Words, " \t,"); 12480 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" && 12481 Words[2] == "$0") { 12482 Words.clear(); 12483 SplitString(AsmPieces[2], Words, " \t,"); 12484 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" && 12485 Words[2] == "${0:w}") { 12486 AsmPieces.clear(); 12487 const std::string &ConstraintsStr = IA->getConstraintString(); 12488 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 12489 std::sort(AsmPieces.begin(), AsmPieces.end()); 12490 if (AsmPieces.size() == 4 && 12491 AsmPieces[0] == "~{cc}" && 12492 AsmPieces[1] == "~{dirflag}" && 12493 AsmPieces[2] == "~{flags}" && 12494 AsmPieces[3] == "~{fpsr}") { 12495 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12496 if (!Ty || Ty->getBitWidth() % 16 != 0) 12497 return false; 12498 return IntrinsicLowering::LowerToByteSwap(CI); 12499 } 12500 } 12501 } 12502 } 12503 } 12504 12505 if (CI->getType()->isIntegerTy(64)) { 12506 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints(); 12507 if (Constraints.size() >= 2 && 12508 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" && 12509 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") { 12510 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64 12511 SmallVector<StringRef, 4> Words; 12512 SplitString(AsmPieces[0], Words, " \t"); 12513 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") { 12514 Words.clear(); 12515 SplitString(AsmPieces[1], Words, " \t"); 12516 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") { 12517 Words.clear(); 12518 SplitString(AsmPieces[2], Words, " \t,"); 12519 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" && 12520 Words[2] == "%edx") { 12521 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12522 if (!Ty || Ty->getBitWidth() % 16 != 0) 12523 return false; 12524 return IntrinsicLowering::LowerToByteSwap(CI); 12525 } 12526 } 12527 } 12528 } 12529 } 12530 break; 12531 } 12532 return false; 12533} 12534 12535 12536 12537/// getConstraintType - Given a constraint letter, return the type of 12538/// constraint it is for this target. 12539X86TargetLowering::ConstraintType 12540X86TargetLowering::getConstraintType(const std::string &Constraint) const { 12541 if (Constraint.size() == 1) { 12542 switch (Constraint[0]) { 12543 case 'R': 12544 case 'q': 12545 case 'Q': 12546 case 'f': 12547 case 't': 12548 case 'u': 12549 case 'y': 12550 case 'x': 12551 case 'Y': 12552 return C_RegisterClass; 12553 case 'a': 12554 case 'b': 12555 case 'c': 12556 case 'd': 12557 case 'S': 12558 case 'D': 12559 case 'A': 12560 return C_Register; 12561 case 'I': 12562 case 'J': 12563 case 'K': 12564 case 'L': 12565 case 'M': 12566 case 'N': 12567 case 'G': 12568 case 'C': 12569 case 'e': 12570 case 'Z': 12571 return C_Other; 12572 default: 12573 break; 12574 } 12575 } 12576 return TargetLowering::getConstraintType(Constraint); 12577} 12578 12579/// Examine constraint type and operand type and determine a weight value. 12580/// This object must already have been set up with the operand type 12581/// and the current alternative constraint selected. 12582TargetLowering::ConstraintWeight 12583 X86TargetLowering::getSingleConstraintMatchWeight( 12584 AsmOperandInfo &info, const char *constraint) const { 12585 ConstraintWeight weight = CW_Invalid; 12586 Value *CallOperandVal = info.CallOperandVal; 12587 // If we don't have a value, we can't do a match, 12588 // but allow it at the lowest weight. 12589 if (CallOperandVal == NULL) 12590 return CW_Default; 12591 const Type *type = CallOperandVal->getType(); 12592 // Look at the constraint type. 12593 switch (*constraint) { 12594 default: 12595 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 12596 case 'R': 12597 case 'q': 12598 case 'Q': 12599 case 'a': 12600 case 'b': 12601 case 'c': 12602 case 'd': 12603 case 'S': 12604 case 'D': 12605 case 'A': 12606 if (CallOperandVal->getType()->isIntegerTy()) 12607 weight = CW_SpecificReg; 12608 break; 12609 case 'f': 12610 case 't': 12611 case 'u': 12612 if (type->isFloatingPointTy()) 12613 weight = CW_SpecificReg; 12614 break; 12615 case 'y': 12616 if (type->isX86_MMXTy() && Subtarget->hasMMX()) 12617 weight = CW_SpecificReg; 12618 break; 12619 case 'x': 12620 case 'Y': 12621 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM()) 12622 weight = CW_Register; 12623 break; 12624 case 'I': 12625 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) { 12626 if (C->getZExtValue() <= 31) 12627 weight = CW_Constant; 12628 } 12629 break; 12630 case 'J': 12631 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12632 if (C->getZExtValue() <= 63) 12633 weight = CW_Constant; 12634 } 12635 break; 12636 case 'K': 12637 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12638 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f)) 12639 weight = CW_Constant; 12640 } 12641 break; 12642 case 'L': 12643 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12644 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff)) 12645 weight = CW_Constant; 12646 } 12647 break; 12648 case 'M': 12649 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12650 if (C->getZExtValue() <= 3) 12651 weight = CW_Constant; 12652 } 12653 break; 12654 case 'N': 12655 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12656 if (C->getZExtValue() <= 0xff) 12657 weight = CW_Constant; 12658 } 12659 break; 12660 case 'G': 12661 case 'C': 12662 if (dyn_cast<ConstantFP>(CallOperandVal)) { 12663 weight = CW_Constant; 12664 } 12665 break; 12666 case 'e': 12667 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12668 if ((C->getSExtValue() >= -0x80000000LL) && 12669 (C->getSExtValue() <= 0x7fffffffLL)) 12670 weight = CW_Constant; 12671 } 12672 break; 12673 case 'Z': 12674 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12675 if (C->getZExtValue() <= 0xffffffff) 12676 weight = CW_Constant; 12677 } 12678 break; 12679 } 12680 return weight; 12681} 12682 12683/// LowerXConstraint - try to replace an X constraint, which matches anything, 12684/// with another that has more specific requirements based on the type of the 12685/// corresponding operand. 12686const char *X86TargetLowering:: 12687LowerXConstraint(EVT ConstraintVT) const { 12688 // FP X constraints get lowered to SSE1/2 registers if available, otherwise 12689 // 'f' like normal targets. 12690 if (ConstraintVT.isFloatingPoint()) { 12691 if (Subtarget->hasXMMInt()) 12692 return "Y"; 12693 if (Subtarget->hasXMM()) 12694 return "x"; 12695 } 12696 12697 return TargetLowering::LowerXConstraint(ConstraintVT); 12698} 12699 12700/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12701/// vector. If it is invalid, don't add anything to Ops. 12702void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12703 std::string &Constraint, 12704 std::vector<SDValue>&Ops, 12705 SelectionDAG &DAG) const { 12706 SDValue Result(0, 0); 12707 12708 // Only support length 1 constraints for now. 12709 if (Constraint.length() > 1) return; 12710 12711 char ConstraintLetter = Constraint[0]; 12712 switch (ConstraintLetter) { 12713 default: break; 12714 case 'I': 12715 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12716 if (C->getZExtValue() <= 31) { 12717 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12718 break; 12719 } 12720 } 12721 return; 12722 case 'J': 12723 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12724 if (C->getZExtValue() <= 63) { 12725 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12726 break; 12727 } 12728 } 12729 return; 12730 case 'K': 12731 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12732 if ((int8_t)C->getSExtValue() == C->getSExtValue()) { 12733 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12734 break; 12735 } 12736 } 12737 return; 12738 case 'N': 12739 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12740 if (C->getZExtValue() <= 255) { 12741 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12742 break; 12743 } 12744 } 12745 return; 12746 case 'e': { 12747 // 32-bit signed value 12748 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12749 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 12750 C->getSExtValue())) { 12751 // Widen to 64 bits here to get it sign extended. 12752 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64); 12753 break; 12754 } 12755 // FIXME gcc accepts some relocatable values here too, but only in certain 12756 // memory models; it's complicated. 12757 } 12758 return; 12759 } 12760 case 'Z': { 12761 // 32-bit unsigned value 12762 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12763 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 12764 C->getZExtValue())) { 12765 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12766 break; 12767 } 12768 } 12769 // FIXME gcc accepts some relocatable values here too, but only in certain 12770 // memory models; it's complicated. 12771 return; 12772 } 12773 case 'i': { 12774 // Literal immediates are always ok. 12775 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) { 12776 // Widen to 64 bits here to get it sign extended. 12777 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64); 12778 break; 12779 } 12780 12781 // In any sort of PIC mode addresses need to be computed at runtime by 12782 // adding in a register or some sort of table lookup. These can't 12783 // be used as immediates. 12784 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC()) 12785 return; 12786 12787 // If we are in non-pic codegen mode, we allow the address of a global (with 12788 // an optional displacement) to be used with 'i'. 12789 GlobalAddressSDNode *GA = 0; 12790 int64_t Offset = 0; 12791 12792 // Match either (GA), (GA+C), (GA+C1+C2), etc. 12793 while (1) { 12794 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) { 12795 Offset += GA->getOffset(); 12796 break; 12797 } else if (Op.getOpcode() == ISD::ADD) { 12798 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 12799 Offset += C->getZExtValue(); 12800 Op = Op.getOperand(0); 12801 continue; 12802 } 12803 } else if (Op.getOpcode() == ISD::SUB) { 12804 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 12805 Offset += -C->getZExtValue(); 12806 Op = Op.getOperand(0); 12807 continue; 12808 } 12809 } 12810 12811 // Otherwise, this isn't something we can handle, reject it. 12812 return; 12813 } 12814 12815 const GlobalValue *GV = GA->getGlobal(); 12816 // If we require an extra load to get this address, as in PIC mode, we 12817 // can't accept it. 12818 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV, 12819 getTargetMachine()))) 12820 return; 12821 12822 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), 12823 GA->getValueType(0), Offset); 12824 break; 12825 } 12826 } 12827 12828 if (Result.getNode()) { 12829 Ops.push_back(Result); 12830 return; 12831 } 12832 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12833} 12834 12835std::vector<unsigned> X86TargetLowering:: 12836getRegClassForInlineAsmConstraint(const std::string &Constraint, 12837 EVT VT) const { 12838 if (Constraint.size() == 1) { 12839 // FIXME: not handling fp-stack yet! 12840 switch (Constraint[0]) { // GCC X86 Constraint Letters 12841 default: break; // Unknown constraint letter 12842 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode. 12843 if (Subtarget->is64Bit()) { 12844 if (VT == MVT::i32) 12845 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 12846 X86::ESI, X86::EDI, X86::R8D, X86::R9D, 12847 X86::R10D,X86::R11D,X86::R12D, 12848 X86::R13D,X86::R14D,X86::R15D, 12849 X86::EBP, X86::ESP, 0); 12850 else if (VT == MVT::i16) 12851 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 12852 X86::SI, X86::DI, X86::R8W,X86::R9W, 12853 X86::R10W,X86::R11W,X86::R12W, 12854 X86::R13W,X86::R14W,X86::R15W, 12855 X86::BP, X86::SP, 0); 12856 else if (VT == MVT::i8) 12857 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 12858 X86::SIL, X86::DIL, X86::R8B,X86::R9B, 12859 X86::R10B,X86::R11B,X86::R12B, 12860 X86::R13B,X86::R14B,X86::R15B, 12861 X86::BPL, X86::SPL, 0); 12862 12863 else if (VT == MVT::i64) 12864 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 12865 X86::RSI, X86::RDI, X86::R8, X86::R9, 12866 X86::R10, X86::R11, X86::R12, 12867 X86::R13, X86::R14, X86::R15, 12868 X86::RBP, X86::RSP, 0); 12869 12870 break; 12871 } 12872 // 32-bit fallthrough 12873 case 'Q': // Q_REGS 12874 if (VT == MVT::i32) 12875 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0); 12876 else if (VT == MVT::i16) 12877 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0); 12878 else if (VT == MVT::i8) 12879 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0); 12880 else if (VT == MVT::i64) 12881 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0); 12882 break; 12883 } 12884 } 12885 12886 return std::vector<unsigned>(); 12887} 12888 12889std::pair<unsigned, const TargetRegisterClass*> 12890X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 12891 EVT VT) const { 12892 // First, see if this is a constraint that directly corresponds to an LLVM 12893 // register class. 12894 if (Constraint.size() == 1) { 12895 // GCC Constraint Letters 12896 switch (Constraint[0]) { 12897 default: break; 12898 case 'r': // GENERAL_REGS 12899 case 'l': // INDEX_REGS 12900 if (VT == MVT::i8) 12901 return std::make_pair(0U, X86::GR8RegisterClass); 12902 if (VT == MVT::i16) 12903 return std::make_pair(0U, X86::GR16RegisterClass); 12904 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit()) 12905 return std::make_pair(0U, X86::GR32RegisterClass); 12906 return std::make_pair(0U, X86::GR64RegisterClass); 12907 case 'R': // LEGACY_REGS 12908 if (VT == MVT::i8) 12909 return std::make_pair(0U, X86::GR8_NOREXRegisterClass); 12910 if (VT == MVT::i16) 12911 return std::make_pair(0U, X86::GR16_NOREXRegisterClass); 12912 if (VT == MVT::i32 || !Subtarget->is64Bit()) 12913 return std::make_pair(0U, X86::GR32_NOREXRegisterClass); 12914 return std::make_pair(0U, X86::GR64_NOREXRegisterClass); 12915 case 'f': // FP Stack registers. 12916 // If SSE is enabled for this VT, use f80 to ensure the isel moves the 12917 // value to the correct fpstack register class. 12918 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT)) 12919 return std::make_pair(0U, X86::RFP32RegisterClass); 12920 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT)) 12921 return std::make_pair(0U, X86::RFP64RegisterClass); 12922 return std::make_pair(0U, X86::RFP80RegisterClass); 12923 case 'y': // MMX_REGS if MMX allowed. 12924 if (!Subtarget->hasMMX()) break; 12925 return std::make_pair(0U, X86::VR64RegisterClass); 12926 case 'Y': // SSE_REGS if SSE2 allowed 12927 if (!Subtarget->hasXMMInt()) break; 12928 // FALL THROUGH. 12929 case 'x': // SSE_REGS if SSE1 allowed 12930 if (!Subtarget->hasXMM()) break; 12931 12932 switch (VT.getSimpleVT().SimpleTy) { 12933 default: break; 12934 // Scalar SSE types. 12935 case MVT::f32: 12936 case MVT::i32: 12937 return std::make_pair(0U, X86::FR32RegisterClass); 12938 case MVT::f64: 12939 case MVT::i64: 12940 return std::make_pair(0U, X86::FR64RegisterClass); 12941 // Vector types. 12942 case MVT::v16i8: 12943 case MVT::v8i16: 12944 case MVT::v4i32: 12945 case MVT::v2i64: 12946 case MVT::v4f32: 12947 case MVT::v2f64: 12948 return std::make_pair(0U, X86::VR128RegisterClass); 12949 } 12950 break; 12951 } 12952 } 12953 12954 // Use the default implementation in TargetLowering to convert the register 12955 // constraint into a member of a register class. 12956 std::pair<unsigned, const TargetRegisterClass*> Res; 12957 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 12958 12959 // Not found as a standard register? 12960 if (Res.second == 0) { 12961 // Map st(0) -> st(7) -> ST0 12962 if (Constraint.size() == 7 && Constraint[0] == '{' && 12963 tolower(Constraint[1]) == 's' && 12964 tolower(Constraint[2]) == 't' && 12965 Constraint[3] == '(' && 12966 (Constraint[4] >= '0' && Constraint[4] <= '7') && 12967 Constraint[5] == ')' && 12968 Constraint[6] == '}') { 12969 12970 Res.first = X86::ST0+Constraint[4]-'0'; 12971 Res.second = X86::RFP80RegisterClass; 12972 return Res; 12973 } 12974 12975 // GCC allows "st(0)" to be called just plain "st". 12976 if (StringRef("{st}").equals_lower(Constraint)) { 12977 Res.first = X86::ST0; 12978 Res.second = X86::RFP80RegisterClass; 12979 return Res; 12980 } 12981 12982 // flags -> EFLAGS 12983 if (StringRef("{flags}").equals_lower(Constraint)) { 12984 Res.first = X86::EFLAGS; 12985 Res.second = X86::CCRRegisterClass; 12986 return Res; 12987 } 12988 12989 // 'A' means EAX + EDX. 12990 if (Constraint == "A") { 12991 Res.first = X86::EAX; 12992 Res.second = X86::GR32_ADRegisterClass; 12993 return Res; 12994 } 12995 return Res; 12996 } 12997 12998 // Otherwise, check to see if this is a register class of the wrong value 12999 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to 13000 // turn into {ax},{dx}. 13001 if (Res.second->hasType(VT)) 13002 return Res; // Correct type already, nothing to do. 13003 13004 // All of the single-register GCC register classes map their values onto 13005 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we 13006 // really want an 8-bit or 32-bit register, map to the appropriate register 13007 // class and return the appropriate register. 13008 if (Res.second == X86::GR16RegisterClass) { 13009 if (VT == MVT::i8) { 13010 unsigned DestReg = 0; 13011 switch (Res.first) { 13012 default: break; 13013 case X86::AX: DestReg = X86::AL; break; 13014 case X86::DX: DestReg = X86::DL; break; 13015 case X86::CX: DestReg = X86::CL; break; 13016 case X86::BX: DestReg = X86::BL; break; 13017 } 13018 if (DestReg) { 13019 Res.first = DestReg; 13020 Res.second = X86::GR8RegisterClass; 13021 } 13022 } else if (VT == MVT::i32) { 13023 unsigned DestReg = 0; 13024 switch (Res.first) { 13025 default: break; 13026 case X86::AX: DestReg = X86::EAX; break; 13027 case X86::DX: DestReg = X86::EDX; break; 13028 case X86::CX: DestReg = X86::ECX; break; 13029 case X86::BX: DestReg = X86::EBX; break; 13030 case X86::SI: DestReg = X86::ESI; break; 13031 case X86::DI: DestReg = X86::EDI; break; 13032 case X86::BP: DestReg = X86::EBP; break; 13033 case X86::SP: DestReg = X86::ESP; break; 13034 } 13035 if (DestReg) { 13036 Res.first = DestReg; 13037 Res.second = X86::GR32RegisterClass; 13038 } 13039 } else if (VT == MVT::i64) { 13040 unsigned DestReg = 0; 13041 switch (Res.first) { 13042 default: break; 13043 case X86::AX: DestReg = X86::RAX; break; 13044 case X86::DX: DestReg = X86::RDX; break; 13045 case X86::CX: DestReg = X86::RCX; break; 13046 case X86::BX: DestReg = X86::RBX; break; 13047 case X86::SI: DestReg = X86::RSI; break; 13048 case X86::DI: DestReg = X86::RDI; break; 13049 case X86::BP: DestReg = X86::RBP; break; 13050 case X86::SP: DestReg = X86::RSP; break; 13051 } 13052 if (DestReg) { 13053 Res.first = DestReg; 13054 Res.second = X86::GR64RegisterClass; 13055 } 13056 } 13057 } else if (Res.second == X86::FR32RegisterClass || 13058 Res.second == X86::FR64RegisterClass || 13059 Res.second == X86::VR128RegisterClass) { 13060 // Handle references to XMM physical registers that got mapped into the 13061 // wrong class. This can happen with constraints like {xmm0} where the 13062 // target independent register mapper will just pick the first match it can 13063 // find, ignoring the required type. 13064 if (VT == MVT::f32) 13065 Res.second = X86::FR32RegisterClass; 13066 else if (VT == MVT::f64) 13067 Res.second = X86::FR64RegisterClass; 13068 else if (X86::VR128RegisterClass->hasType(VT)) 13069 Res.second = X86::VR128RegisterClass; 13070 } 13071 13072 return Res; 13073} 13074