X86ISelLowering.cpp revision 9eac20ac88b82d39aaac9838631f268f3ef69d2c
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 "X86ISelLowering.h" 17#include "X86.h" 18#include "X86InstrBuilder.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/MC/MCAsmInfo.h" 39#include "llvm/MC/MCContext.h" 40#include "llvm/MC/MCExpr.h" 41#include "llvm/MC/MCSymbol.h" 42#include "llvm/ADT/SmallSet.h" 43#include "llvm/ADT/Statistic.h" 44#include "llvm/ADT/StringExtras.h" 45#include "llvm/ADT/VariadicFunction.h" 46#include "llvm/Support/CallSite.h" 47#include "llvm/Support/Debug.h" 48#include "llvm/Support/ErrorHandling.h" 49#include "llvm/Support/MathExtras.h" 50#include "llvm/Target/TargetOptions.h" 51#include <bitset> 52#include <cctype> 53using namespace llvm; 54 55STATISTIC(NumTailCalls, "Number of tail calls"); 56 57// Forward declarations. 58static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 59 SDValue V2); 60 61/// Generate a DAG to grab 128-bits from a vector > 128 bits. This 62/// sets things up to match to an AVX VEXTRACTF128 instruction or a 63/// simple subregister reference. Idx is an index in the 128 bits we 64/// want. It need not be aligned to a 128-bit bounday. That makes 65/// lowering EXTRACT_VECTOR_ELT operations easier. 66static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal, 67 SelectionDAG &DAG, DebugLoc dl) { 68 EVT VT = Vec.getValueType(); 69 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!"); 70 EVT ElVT = VT.getVectorElementType(); 71 unsigned Factor = VT.getSizeInBits()/128; 72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT, 73 VT.getVectorNumElements()/Factor); 74 75 // Extract from UNDEF is UNDEF. 76 if (Vec.getOpcode() == ISD::UNDEF) 77 return DAG.getUNDEF(ResultVT); 78 79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR 80 // we can match to VEXTRACTF128. 81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits(); 82 83 // This is the index of the first element of the 128-bit chunk 84 // we want. 85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128) 86 * ElemsPerChunk); 87 88 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, 90 VecIdx); 91 92 return Result; 93} 94 95/// Generate a DAG to put 128-bits into a vector > 128 bits. This 96/// sets things up to match to an AVX VINSERTF128 instruction or a 97/// simple superregister reference. Idx is an index in the 128 bits 98/// we want. It need not be aligned to a 128-bit bounday. That makes 99/// lowering INSERT_VECTOR_ELT operations easier. 100static SDValue Insert128BitVector(SDValue Result, SDValue Vec, 101 unsigned IdxVal, SelectionDAG &DAG, 102 DebugLoc dl) { 103 // Inserting UNDEF is Result 104 if (Vec.getOpcode() == ISD::UNDEF) 105 return Result; 106 107 EVT VT = Vec.getValueType(); 108 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!"); 109 110 EVT ElVT = VT.getVectorElementType(); 111 EVT ResultVT = Result.getValueType(); 112 113 // Insert the relevant 128 bits. 114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits(); 115 116 // This is the index of the first element of the 128-bit chunk 117 // we want. 118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128) 119 * ElemsPerChunk); 120 121 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 122 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, 123 VecIdx); 124} 125 126/// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128 127/// instructions. This is used because creating CONCAT_VECTOR nodes of 128/// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower 129/// large BUILD_VECTORS. 130static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT, 131 unsigned NumElems, SelectionDAG &DAG, 132 DebugLoc dl) { 133 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl); 134 return Insert128BitVector(V, V2, NumElems/2, DAG, dl); 135} 136 137static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) { 138 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>(); 139 bool is64Bit = Subtarget->is64Bit(); 140 141 if (Subtarget->isTargetEnvMacho()) { 142 if (is64Bit) 143 return new X86_64MachoTargetObjectFile(); 144 return new TargetLoweringObjectFileMachO(); 145 } 146 147 if (Subtarget->isTargetLinux()) 148 return new X86LinuxTargetObjectFile(); 149 if (Subtarget->isTargetELF()) 150 return new TargetLoweringObjectFileELF(); 151 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 152 return new TargetLoweringObjectFileCOFF(); 153 llvm_unreachable("unknown subtarget type"); 154} 155 156X86TargetLowering::X86TargetLowering(X86TargetMachine &TM) 157 : TargetLowering(TM, createTLOF(TM)) { 158 Subtarget = &TM.getSubtarget<X86Subtarget>(); 159 X86ScalarSSEf64 = Subtarget->hasSSE2(); 160 X86ScalarSSEf32 = Subtarget->hasSSE1(); 161 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP; 162 163 RegInfo = TM.getRegisterInfo(); 164 TD = getTargetData(); 165 166 // Set up the TargetLowering object. 167 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }; 168 169 // X86 is weird, it always uses i8 for shift amounts and setcc results. 170 setBooleanContents(ZeroOrOneBooleanContent); 171 // X86-SSE is even stranger. It uses -1 or 0 for vector masks. 172 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 173 174 // For 64-bit since we have so many registers use the ILP scheduler, for 175 // 32-bit code use the register pressure specific scheduling. 176 // For Atom, always use ILP scheduling. 177 if (Subtarget->isAtom()) 178 setSchedulingPreference(Sched::ILP); 179 else if (Subtarget->is64Bit()) 180 setSchedulingPreference(Sched::ILP); 181 else 182 setSchedulingPreference(Sched::RegPressure); 183 setStackPointerRegisterToSaveRestore(X86StackPtr); 184 185 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) { 186 // Setup Windows compiler runtime calls. 187 setLibcallName(RTLIB::SDIV_I64, "_alldiv"); 188 setLibcallName(RTLIB::UDIV_I64, "_aulldiv"); 189 setLibcallName(RTLIB::SREM_I64, "_allrem"); 190 setLibcallName(RTLIB::UREM_I64, "_aullrem"); 191 setLibcallName(RTLIB::MUL_I64, "_allmul"); 192 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall); 193 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall); 194 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall); 195 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall); 196 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall); 197 198 // The _ftol2 runtime function has an unusual calling conv, which 199 // is modeled by a special pseudo-instruction. 200 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0); 201 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0); 202 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0); 203 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0); 204 } 205 206 if (Subtarget->isTargetDarwin()) { 207 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp. 208 setUseUnderscoreSetJmp(false); 209 setUseUnderscoreLongJmp(false); 210 } else if (Subtarget->isTargetMingw()) { 211 // MS runtime is weird: it exports _setjmp, but longjmp! 212 setUseUnderscoreSetJmp(true); 213 setUseUnderscoreLongJmp(false); 214 } else { 215 setUseUnderscoreSetJmp(true); 216 setUseUnderscoreLongJmp(true); 217 } 218 219 // Set up the register classes. 220 addRegisterClass(MVT::i8, &X86::GR8RegClass); 221 addRegisterClass(MVT::i16, &X86::GR16RegClass); 222 addRegisterClass(MVT::i32, &X86::GR32RegClass); 223 if (Subtarget->is64Bit()) 224 addRegisterClass(MVT::i64, &X86::GR64RegClass); 225 226 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 227 228 // We don't accept any truncstore of integer registers. 229 setTruncStoreAction(MVT::i64, MVT::i32, Expand); 230 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 231 setTruncStoreAction(MVT::i64, MVT::i8 , Expand); 232 setTruncStoreAction(MVT::i32, MVT::i16, Expand); 233 setTruncStoreAction(MVT::i32, MVT::i8 , Expand); 234 setTruncStoreAction(MVT::i16, MVT::i8, Expand); 235 236 // SETOEQ and SETUNE require checking two conditions. 237 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand); 238 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand); 239 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand); 240 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand); 241 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand); 242 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand); 243 244 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this 245 // operation. 246 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote); 247 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote); 248 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote); 249 250 if (Subtarget->is64Bit()) { 251 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote); 252 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 253 } else if (!TM.Options.UseSoftFloat) { 254 // We have an algorithm for SSE2->double, and we turn this into a 255 // 64-bit FILD followed by conditional FADD for other targets. 256 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 257 // We have an algorithm for SSE2, and we turn this into a 64-bit 258 // FILD for other targets. 259 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom); 260 } 261 262 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have 263 // this operation. 264 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote); 265 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote); 266 267 if (!TM.Options.UseSoftFloat) { 268 // SSE has no i16 to fp conversion, only i32 269 if (X86ScalarSSEf32) { 270 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 271 // f32 and f64 cases are Legal, f80 case is not 272 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 273 } else { 274 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom); 275 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 276 } 277 } else { 278 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote); 280 } 281 282 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64 283 // are Legal, f80 is custom lowered. 284 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom); 285 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom); 286 287 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have 288 // this operation. 289 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote); 290 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote); 291 292 if (X86ScalarSSEf32) { 293 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote); 294 // f32 and f64 cases are Legal, f80 case is not 295 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 296 } else { 297 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom); 298 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 299 } 300 301 // Handle FP_TO_UINT by promoting the destination to a larger signed 302 // conversion. 303 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote); 304 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote); 305 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote); 306 307 if (Subtarget->is64Bit()) { 308 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand); 309 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote); 310 } else if (!TM.Options.UseSoftFloat) { 311 // Since AVX is a superset of SSE3, only check for SSE here. 312 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3()) 313 // Expand FP_TO_UINT into a select. 314 // FIXME: We would like to use a Custom expander here eventually to do 315 // the optimal thing for SSE vs. the default expansion in the legalizer. 316 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand); 317 else 318 // With SSE3 we can use fisttpll to convert to a signed i64; without 319 // SSE, we're stuck with a fistpll. 320 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom); 321 } 322 323 if (isTargetFTOL()) { 324 // Use the _ftol2 runtime function, which has a pseudo-instruction 325 // to handle its weird calling convention. 326 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom); 327 } 328 329 // TODO: when we have SSE, these could be more efficient, by using movd/movq. 330 if (!X86ScalarSSEf64) { 331 setOperationAction(ISD::BITCAST , MVT::f32 , Expand); 332 setOperationAction(ISD::BITCAST , MVT::i32 , Expand); 333 if (Subtarget->is64Bit()) { 334 setOperationAction(ISD::BITCAST , MVT::f64 , Expand); 335 // Without SSE, i64->f64 goes through memory. 336 setOperationAction(ISD::BITCAST , MVT::i64 , Expand); 337 } 338 } 339 340 // Scalar integer divide and remainder are lowered to use operations that 341 // produce two results, to match the available instructions. This exposes 342 // the two-result form to trivial CSE, which is able to combine x/y and x%y 343 // into a single instruction. 344 // 345 // Scalar integer multiply-high is also lowered to use two-result 346 // operations, to match the available instructions. However, plain multiply 347 // (low) operations are left as Legal, as there are single-result 348 // instructions for this in x86. Using the two-result multiply instructions 349 // when both high and low results are needed must be arranged by dagcombine. 350 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) { 351 MVT VT = IntVTs[i]; 352 setOperationAction(ISD::MULHS, VT, Expand); 353 setOperationAction(ISD::MULHU, VT, Expand); 354 setOperationAction(ISD::SDIV, VT, Expand); 355 setOperationAction(ISD::UDIV, VT, Expand); 356 setOperationAction(ISD::SREM, VT, Expand); 357 setOperationAction(ISD::UREM, VT, Expand); 358 359 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences. 360 setOperationAction(ISD::ADDC, VT, Custom); 361 setOperationAction(ISD::ADDE, VT, Custom); 362 setOperationAction(ISD::SUBC, VT, Custom); 363 setOperationAction(ISD::SUBE, VT, Custom); 364 } 365 366 setOperationAction(ISD::BR_JT , MVT::Other, Expand); 367 setOperationAction(ISD::BRCOND , MVT::Other, Custom); 368 setOperationAction(ISD::BR_CC , MVT::Other, Expand); 369 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand); 370 if (Subtarget->is64Bit()) 371 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal); 372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal); 373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal); 374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand); 375 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand); 376 setOperationAction(ISD::FREM , MVT::f32 , Expand); 377 setOperationAction(ISD::FREM , MVT::f64 , Expand); 378 setOperationAction(ISD::FREM , MVT::f80 , Expand); 379 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom); 380 381 // Promote the i8 variants and force them on up to i32 which has a shorter 382 // encoding. 383 setOperationAction(ISD::CTTZ , MVT::i8 , Promote); 384 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32); 385 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote); 386 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32); 387 if (Subtarget->hasBMI()) { 388 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand); 389 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand); 390 if (Subtarget->is64Bit()) 391 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand); 392 } else { 393 setOperationAction(ISD::CTTZ , MVT::i16 , Custom); 394 setOperationAction(ISD::CTTZ , MVT::i32 , Custom); 395 if (Subtarget->is64Bit()) 396 setOperationAction(ISD::CTTZ , MVT::i64 , Custom); 397 } 398 399 if (Subtarget->hasLZCNT()) { 400 // When promoting the i8 variants, force them to i32 for a shorter 401 // encoding. 402 setOperationAction(ISD::CTLZ , MVT::i8 , Promote); 403 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32); 404 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote); 405 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32); 406 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand); 407 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand); 408 if (Subtarget->is64Bit()) 409 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand); 410 } else { 411 setOperationAction(ISD::CTLZ , MVT::i8 , Custom); 412 setOperationAction(ISD::CTLZ , MVT::i16 , Custom); 413 setOperationAction(ISD::CTLZ , MVT::i32 , Custom); 414 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom); 415 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom); 416 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom); 417 if (Subtarget->is64Bit()) { 418 setOperationAction(ISD::CTLZ , MVT::i64 , Custom); 419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom); 420 } 421 } 422 423 if (Subtarget->hasPOPCNT()) { 424 setOperationAction(ISD::CTPOP , MVT::i8 , Promote); 425 } else { 426 setOperationAction(ISD::CTPOP , MVT::i8 , Expand); 427 setOperationAction(ISD::CTPOP , MVT::i16 , Expand); 428 setOperationAction(ISD::CTPOP , MVT::i32 , Expand); 429 if (Subtarget->is64Bit()) 430 setOperationAction(ISD::CTPOP , MVT::i64 , Expand); 431 } 432 433 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom); 434 setOperationAction(ISD::BSWAP , MVT::i16 , Expand); 435 436 // These should be promoted to a larger select which is supported. 437 setOperationAction(ISD::SELECT , MVT::i1 , Promote); 438 // X86 wants to expand cmov itself. 439 setOperationAction(ISD::SELECT , MVT::i8 , Custom); 440 setOperationAction(ISD::SELECT , MVT::i16 , Custom); 441 setOperationAction(ISD::SELECT , MVT::i32 , Custom); 442 setOperationAction(ISD::SELECT , MVT::f32 , Custom); 443 setOperationAction(ISD::SELECT , MVT::f64 , Custom); 444 setOperationAction(ISD::SELECT , MVT::f80 , Custom); 445 setOperationAction(ISD::SETCC , MVT::i8 , Custom); 446 setOperationAction(ISD::SETCC , MVT::i16 , Custom); 447 setOperationAction(ISD::SETCC , MVT::i32 , Custom); 448 setOperationAction(ISD::SETCC , MVT::f32 , Custom); 449 setOperationAction(ISD::SETCC , MVT::f64 , Custom); 450 setOperationAction(ISD::SETCC , MVT::f80 , Custom); 451 if (Subtarget->is64Bit()) { 452 setOperationAction(ISD::SELECT , MVT::i64 , Custom); 453 setOperationAction(ISD::SETCC , MVT::i64 , Custom); 454 } 455 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom); 456 457 // Darwin ABI issue. 458 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom); 459 setOperationAction(ISD::JumpTable , MVT::i32 , Custom); 460 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom); 461 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom); 462 if (Subtarget->is64Bit()) 463 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 464 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom); 465 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom); 466 if (Subtarget->is64Bit()) { 467 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom); 468 setOperationAction(ISD::JumpTable , MVT::i64 , Custom); 469 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom); 470 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom); 471 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom); 472 } 473 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86) 474 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom); 475 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom); 476 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom); 477 if (Subtarget->is64Bit()) { 478 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom); 479 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom); 480 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom); 481 } 482 483 if (Subtarget->hasSSE1()) 484 setOperationAction(ISD::PREFETCH , MVT::Other, Legal); 485 486 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom); 487 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom); 488 489 // On X86 and X86-64, atomic operations are lowered to locked instructions. 490 // Locked instructions, in turn, have implicit fence semantics (all memory 491 // operations are flushed before issuing the locked instruction, and they 492 // are not buffered), so we can fold away the common pattern of 493 // fence-atomic-fence. 494 setShouldFoldAtomicFences(true); 495 496 // Expand certain atomics 497 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) { 498 MVT VT = IntVTs[i]; 499 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom); 500 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom); 501 setOperationAction(ISD::ATOMIC_STORE, VT, Custom); 502 } 503 504 if (!Subtarget->is64Bit()) { 505 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom); 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 if (Subtarget->hasCmpxchg16b()) { 516 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 517 } 518 519 // FIXME - use subtarget debug flags 520 if (!Subtarget->isTargetDarwin() && 521 !Subtarget->isTargetELF() && 522 !Subtarget->isTargetCygMing()) { 523 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand); 524 } 525 526 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand); 527 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand); 528 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand); 529 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand); 530 if (Subtarget->is64Bit()) { 531 setExceptionPointerRegister(X86::RAX); 532 setExceptionSelectorRegister(X86::RDX); 533 } else { 534 setExceptionPointerRegister(X86::EAX); 535 setExceptionSelectorRegister(X86::EDX); 536 } 537 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom); 538 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom); 539 540 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 541 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 542 543 setOperationAction(ISD::TRAP, MVT::Other, Legal); 544 545 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 546 setOperationAction(ISD::VASTART , MVT::Other, Custom); 547 setOperationAction(ISD::VAEND , MVT::Other, Expand); 548 if (Subtarget->is64Bit()) { 549 setOperationAction(ISD::VAARG , MVT::Other, Custom); 550 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 551 } else { 552 setOperationAction(ISD::VAARG , MVT::Other, Expand); 553 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 554 } 555 556 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 557 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 558 559 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 560 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 561 MVT::i64 : MVT::i32, Custom); 562 else if (TM.Options.EnableSegmentedStacks) 563 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 564 MVT::i64 : MVT::i32, Custom); 565 else 566 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 567 MVT::i64 : MVT::i32, Expand); 568 569 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) { 570 // f32 and f64 use SSE. 571 // Set up the FP register classes. 572 addRegisterClass(MVT::f32, &X86::FR32RegClass); 573 addRegisterClass(MVT::f64, &X86::FR64RegClass); 574 575 // Use ANDPD to simulate FABS. 576 setOperationAction(ISD::FABS , MVT::f64, Custom); 577 setOperationAction(ISD::FABS , MVT::f32, Custom); 578 579 // Use XORP to simulate FNEG. 580 setOperationAction(ISD::FNEG , MVT::f64, Custom); 581 setOperationAction(ISD::FNEG , MVT::f32, Custom); 582 583 // Use ANDPD and ORPD to simulate FCOPYSIGN. 584 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 585 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 586 587 // Lower this to FGETSIGNx86 plus an AND. 588 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom); 589 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom); 590 591 // We don't support sin/cos/fmod 592 setOperationAction(ISD::FSIN , MVT::f64, Expand); 593 setOperationAction(ISD::FCOS , MVT::f64, Expand); 594 setOperationAction(ISD::FSIN , MVT::f32, Expand); 595 setOperationAction(ISD::FCOS , MVT::f32, Expand); 596 597 // Expand FP immediates into loads from the stack, except for the special 598 // cases we handle. 599 addLegalFPImmediate(APFloat(+0.0)); // xorpd 600 addLegalFPImmediate(APFloat(+0.0f)); // xorps 601 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) { 602 // Use SSE for f32, x87 for f64. 603 // Set up the FP register classes. 604 addRegisterClass(MVT::f32, &X86::FR32RegClass); 605 addRegisterClass(MVT::f64, &X86::RFP64RegClass); 606 607 // Use ANDPS to simulate FABS. 608 setOperationAction(ISD::FABS , MVT::f32, Custom); 609 610 // Use XORP to simulate FNEG. 611 setOperationAction(ISD::FNEG , MVT::f32, Custom); 612 613 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 614 615 // Use ANDPS and ORPS to simulate FCOPYSIGN. 616 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 617 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 618 619 // We don't support sin/cos/fmod 620 setOperationAction(ISD::FSIN , MVT::f32, Expand); 621 setOperationAction(ISD::FCOS , MVT::f32, Expand); 622 623 // Special cases we handle for FP constants. 624 addLegalFPImmediate(APFloat(+0.0f)); // xorps 625 addLegalFPImmediate(APFloat(+0.0)); // FLD0 626 addLegalFPImmediate(APFloat(+1.0)); // FLD1 627 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 628 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 629 630 if (!TM.Options.UnsafeFPMath) { 631 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 632 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 633 } 634 } else if (!TM.Options.UseSoftFloat) { 635 // f32 and f64 in x87. 636 // Set up the FP register classes. 637 addRegisterClass(MVT::f64, &X86::RFP64RegClass); 638 addRegisterClass(MVT::f32, &X86::RFP32RegClass); 639 640 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 641 setOperationAction(ISD::UNDEF, MVT::f32, Expand); 642 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 643 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 644 645 if (!TM.Options.UnsafeFPMath) { 646 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 647 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 648 } 649 addLegalFPImmediate(APFloat(+0.0)); // FLD0 650 addLegalFPImmediate(APFloat(+1.0)); // FLD1 651 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 652 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 653 addLegalFPImmediate(APFloat(+0.0f)); // FLD0 654 addLegalFPImmediate(APFloat(+1.0f)); // FLD1 655 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS 656 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS 657 } 658 659 // We don't support FMA. 660 setOperationAction(ISD::FMA, MVT::f64, Expand); 661 setOperationAction(ISD::FMA, MVT::f32, Expand); 662 663 // Long double always uses X87. 664 if (!TM.Options.UseSoftFloat) { 665 addRegisterClass(MVT::f80, &X86::RFP80RegClass); 666 setOperationAction(ISD::UNDEF, MVT::f80, Expand); 667 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand); 668 { 669 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended); 670 addLegalFPImmediate(TmpFlt); // FLD0 671 TmpFlt.changeSign(); 672 addLegalFPImmediate(TmpFlt); // FLD0/FCHS 673 674 bool ignored; 675 APFloat TmpFlt2(+1.0); 676 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, 677 &ignored); 678 addLegalFPImmediate(TmpFlt2); // FLD1 679 TmpFlt2.changeSign(); 680 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS 681 } 682 683 if (!TM.Options.UnsafeFPMath) { 684 setOperationAction(ISD::FSIN , MVT::f80 , Expand); 685 setOperationAction(ISD::FCOS , MVT::f80 , Expand); 686 } 687 688 setOperationAction(ISD::FFLOOR, MVT::f80, Expand); 689 setOperationAction(ISD::FCEIL, MVT::f80, Expand); 690 setOperationAction(ISD::FTRUNC, MVT::f80, Expand); 691 setOperationAction(ISD::FRINT, MVT::f80, Expand); 692 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand); 693 setOperationAction(ISD::FMA, MVT::f80, Expand); 694 } 695 696 // Always use a library call for pow. 697 setOperationAction(ISD::FPOW , MVT::f32 , Expand); 698 setOperationAction(ISD::FPOW , MVT::f64 , Expand); 699 setOperationAction(ISD::FPOW , MVT::f80 , Expand); 700 701 setOperationAction(ISD::FLOG, MVT::f80, Expand); 702 setOperationAction(ISD::FLOG2, MVT::f80, Expand); 703 setOperationAction(ISD::FLOG10, MVT::f80, Expand); 704 setOperationAction(ISD::FEXP, MVT::f80, Expand); 705 setOperationAction(ISD::FEXP2, MVT::f80, Expand); 706 707 // First set operation action for all vector types to either promote 708 // (for widening) or expand (for scalarization). Then we will selectively 709 // turn on ones that can be effectively codegen'd. 710 for (int VT = MVT::FIRST_VECTOR_VALUETYPE; 711 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) { 712 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand); 713 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand); 714 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand); 715 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand); 716 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand); 717 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand); 718 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand); 719 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand); 720 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand); 721 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand); 722 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand); 723 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand); 724 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand); 725 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand); 726 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand); 727 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand); 728 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 729 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 730 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand); 731 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand); 732 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand); 733 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand); 734 setOperationAction(ISD::FMA, (MVT::SimpleValueType)VT, Expand); 735 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand); 736 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand); 737 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand); 738 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 739 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 740 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand); 741 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand); 742 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand); 743 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand); 744 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand); 745 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand); 746 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand); 747 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand); 748 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand); 749 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand); 750 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand); 751 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand); 752 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand); 753 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand); 754 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand); 755 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand); 756 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand); 757 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand); 758 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand); 759 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand); 760 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand); 761 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand); 762 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 763 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 764 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand); 765 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand); 766 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand); 767 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand); 768 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand); 769 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand); 770 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE; 771 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT) 772 setTruncStoreAction((MVT::SimpleValueType)VT, 773 (MVT::SimpleValueType)InnerVT, Expand); 774 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand); 775 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand); 776 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand); 777 } 778 779 // FIXME: In order to prevent SSE instructions being expanded to MMX ones 780 // with -msoft-float, disable use of MMX as well. 781 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) { 782 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass); 783 // No operations on x86mmx supported, everything uses intrinsics. 784 } 785 786 // MMX-sized vectors (other than x86mmx) are expected to be expanded 787 // into smaller operations. 788 setOperationAction(ISD::MULHS, MVT::v8i8, Expand); 789 setOperationAction(ISD::MULHS, MVT::v4i16, Expand); 790 setOperationAction(ISD::MULHS, MVT::v2i32, Expand); 791 setOperationAction(ISD::MULHS, MVT::v1i64, Expand); 792 setOperationAction(ISD::AND, MVT::v8i8, Expand); 793 setOperationAction(ISD::AND, MVT::v4i16, Expand); 794 setOperationAction(ISD::AND, MVT::v2i32, Expand); 795 setOperationAction(ISD::AND, MVT::v1i64, Expand); 796 setOperationAction(ISD::OR, MVT::v8i8, Expand); 797 setOperationAction(ISD::OR, MVT::v4i16, Expand); 798 setOperationAction(ISD::OR, MVT::v2i32, Expand); 799 setOperationAction(ISD::OR, MVT::v1i64, Expand); 800 setOperationAction(ISD::XOR, MVT::v8i8, Expand); 801 setOperationAction(ISD::XOR, MVT::v4i16, Expand); 802 setOperationAction(ISD::XOR, MVT::v2i32, Expand); 803 setOperationAction(ISD::XOR, MVT::v1i64, Expand); 804 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand); 805 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand); 806 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand); 807 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand); 808 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand); 809 setOperationAction(ISD::SELECT, MVT::v8i8, Expand); 810 setOperationAction(ISD::SELECT, MVT::v4i16, Expand); 811 setOperationAction(ISD::SELECT, MVT::v2i32, Expand); 812 setOperationAction(ISD::SELECT, MVT::v1i64, Expand); 813 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand); 814 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand); 815 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand); 816 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand); 817 818 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) { 819 addRegisterClass(MVT::v4f32, &X86::VR128RegClass); 820 821 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 822 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 823 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 824 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 825 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 826 setOperationAction(ISD::FNEG, MVT::v4f32, Custom); 827 setOperationAction(ISD::LOAD, MVT::v4f32, Legal); 828 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 829 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom); 830 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 831 setOperationAction(ISD::SELECT, MVT::v4f32, Custom); 832 setOperationAction(ISD::SETCC, MVT::v4f32, Custom); 833 } 834 835 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) { 836 addRegisterClass(MVT::v2f64, &X86::VR128RegClass); 837 838 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM 839 // registers cannot be used even for integer operations. 840 addRegisterClass(MVT::v16i8, &X86::VR128RegClass); 841 addRegisterClass(MVT::v8i16, &X86::VR128RegClass); 842 addRegisterClass(MVT::v4i32, &X86::VR128RegClass); 843 addRegisterClass(MVT::v2i64, &X86::VR128RegClass); 844 845 setOperationAction(ISD::ADD, MVT::v16i8, Legal); 846 setOperationAction(ISD::ADD, MVT::v8i16, Legal); 847 setOperationAction(ISD::ADD, MVT::v4i32, Legal); 848 setOperationAction(ISD::ADD, MVT::v2i64, Legal); 849 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 850 setOperationAction(ISD::SUB, MVT::v16i8, Legal); 851 setOperationAction(ISD::SUB, MVT::v8i16, Legal); 852 setOperationAction(ISD::SUB, MVT::v4i32, Legal); 853 setOperationAction(ISD::SUB, MVT::v2i64, Legal); 854 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 855 setOperationAction(ISD::FADD, MVT::v2f64, Legal); 856 setOperationAction(ISD::FSUB, MVT::v2f64, Legal); 857 setOperationAction(ISD::FMUL, MVT::v2f64, Legal); 858 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 859 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 860 setOperationAction(ISD::FNEG, MVT::v2f64, Custom); 861 862 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 863 setOperationAction(ISD::SETCC, MVT::v16i8, Custom); 864 setOperationAction(ISD::SETCC, MVT::v8i16, Custom); 865 setOperationAction(ISD::SETCC, MVT::v4i32, Custom); 866 867 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom); 868 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom); 869 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 870 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 871 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 872 873 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom); 874 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom); 875 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom); 876 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom); 877 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom); 878 879 // Custom lower build_vector, vector_shuffle, and extract_vector_elt. 880 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) { 881 EVT VT = (MVT::SimpleValueType)i; 882 // Do not attempt to custom lower non-power-of-2 vectors 883 if (!isPowerOf2_32(VT.getVectorNumElements())) 884 continue; 885 // Do not attempt to custom lower non-128-bit vectors 886 if (!VT.is128BitVector()) 887 continue; 888 setOperationAction(ISD::BUILD_VECTOR, 889 VT.getSimpleVT().SimpleTy, Custom); 890 setOperationAction(ISD::VECTOR_SHUFFLE, 891 VT.getSimpleVT().SimpleTy, Custom); 892 setOperationAction(ISD::EXTRACT_VECTOR_ELT, 893 VT.getSimpleVT().SimpleTy, Custom); 894 } 895 896 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 897 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 898 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 899 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 901 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom); 902 903 if (Subtarget->is64Bit()) { 904 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 906 } 907 908 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64. 909 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) { 910 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 911 EVT VT = SVT; 912 913 // Do not attempt to promote non-128-bit vectors 914 if (!VT.is128BitVector()) 915 continue; 916 917 setOperationAction(ISD::AND, SVT, Promote); 918 AddPromotedToType (ISD::AND, SVT, MVT::v2i64); 919 setOperationAction(ISD::OR, SVT, Promote); 920 AddPromotedToType (ISD::OR, SVT, MVT::v2i64); 921 setOperationAction(ISD::XOR, SVT, Promote); 922 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64); 923 setOperationAction(ISD::LOAD, SVT, Promote); 924 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64); 925 setOperationAction(ISD::SELECT, SVT, Promote); 926 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64); 927 } 928 929 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 930 931 // Custom lower v2i64 and v2f64 selects. 932 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 933 setOperationAction(ISD::LOAD, MVT::v2i64, Legal); 934 setOperationAction(ISD::SELECT, MVT::v2f64, Custom); 935 setOperationAction(ISD::SELECT, MVT::v2i64, Custom); 936 937 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 938 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 939 } 940 941 if (Subtarget->hasSSE41()) { 942 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 943 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 944 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 945 setOperationAction(ISD::FRINT, MVT::f32, Legal); 946 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 947 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 948 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 949 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 950 setOperationAction(ISD::FRINT, MVT::f64, Legal); 951 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 952 953 // FIXME: Do we need to handle scalar-to-vector here? 954 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 955 956 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 957 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal); 958 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 959 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 960 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 961 962 // i8 and i16 vectors are custom , because the source register and source 963 // source memory operand types are not the same width. f32 vectors are 964 // custom since the immediate controlling the insert encodes additional 965 // information. 966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 970 971 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom); 972 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom); 973 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom); 974 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 975 976 // FIXME: these should be Legal but thats only for the case where 977 // the index is constant. For now custom expand to deal with that. 978 if (Subtarget->is64Bit()) { 979 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 980 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 981 } 982 } 983 984 if (Subtarget->hasSSE2()) { 985 setOperationAction(ISD::SRL, MVT::v8i16, Custom); 986 setOperationAction(ISD::SRL, MVT::v16i8, Custom); 987 988 setOperationAction(ISD::SHL, MVT::v8i16, Custom); 989 setOperationAction(ISD::SHL, MVT::v16i8, Custom); 990 991 setOperationAction(ISD::SRA, MVT::v8i16, Custom); 992 setOperationAction(ISD::SRA, MVT::v16i8, Custom); 993 994 if (Subtarget->hasAVX2()) { 995 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 996 setOperationAction(ISD::SRL, MVT::v4i32, Legal); 997 998 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 999 setOperationAction(ISD::SHL, MVT::v4i32, Legal); 1000 1001 setOperationAction(ISD::SRA, MVT::v4i32, Legal); 1002 } else { 1003 setOperationAction(ISD::SRL, MVT::v2i64, Custom); 1004 setOperationAction(ISD::SRL, MVT::v4i32, Custom); 1005 1006 setOperationAction(ISD::SHL, MVT::v2i64, Custom); 1007 setOperationAction(ISD::SHL, MVT::v4i32, Custom); 1008 1009 setOperationAction(ISD::SRA, MVT::v4i32, Custom); 1010 } 1011 } 1012 1013 if (Subtarget->hasSSE42()) 1014 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1015 1016 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) { 1017 addRegisterClass(MVT::v32i8, &X86::VR256RegClass); 1018 addRegisterClass(MVT::v16i16, &X86::VR256RegClass); 1019 addRegisterClass(MVT::v8i32, &X86::VR256RegClass); 1020 addRegisterClass(MVT::v8f32, &X86::VR256RegClass); 1021 addRegisterClass(MVT::v4i64, &X86::VR256RegClass); 1022 addRegisterClass(MVT::v4f64, &X86::VR256RegClass); 1023 1024 setOperationAction(ISD::LOAD, MVT::v8f32, Legal); 1025 setOperationAction(ISD::LOAD, MVT::v4f64, Legal); 1026 setOperationAction(ISD::LOAD, MVT::v4i64, Legal); 1027 1028 setOperationAction(ISD::FADD, MVT::v8f32, Legal); 1029 setOperationAction(ISD::FSUB, MVT::v8f32, Legal); 1030 setOperationAction(ISD::FMUL, MVT::v8f32, Legal); 1031 setOperationAction(ISD::FDIV, MVT::v8f32, Legal); 1032 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal); 1033 setOperationAction(ISD::FNEG, MVT::v8f32, Custom); 1034 1035 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1036 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1037 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1038 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1039 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1040 setOperationAction(ISD::FNEG, MVT::v4f64, Custom); 1041 1042 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal); 1043 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal); 1044 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal); 1045 1046 setOperationAction(ISD::SRL, MVT::v16i16, Custom); 1047 setOperationAction(ISD::SRL, MVT::v32i8, Custom); 1048 1049 setOperationAction(ISD::SHL, MVT::v16i16, Custom); 1050 setOperationAction(ISD::SHL, MVT::v32i8, Custom); 1051 1052 setOperationAction(ISD::SRA, MVT::v16i16, Custom); 1053 setOperationAction(ISD::SRA, MVT::v32i8, Custom); 1054 1055 setOperationAction(ISD::SETCC, MVT::v32i8, Custom); 1056 setOperationAction(ISD::SETCC, MVT::v16i16, Custom); 1057 setOperationAction(ISD::SETCC, MVT::v8i32, Custom); 1058 setOperationAction(ISD::SETCC, MVT::v4i64, Custom); 1059 1060 setOperationAction(ISD::SELECT, MVT::v4f64, Custom); 1061 setOperationAction(ISD::SELECT, MVT::v4i64, Custom); 1062 setOperationAction(ISD::SELECT, MVT::v8f32, Custom); 1063 1064 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1065 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal); 1066 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal); 1067 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal); 1068 1069 if (Subtarget->hasFMA()) { 1070 setOperationAction(ISD::FMA, MVT::v8f32, Custom); 1071 setOperationAction(ISD::FMA, MVT::v4f64, Custom); 1072 setOperationAction(ISD::FMA, MVT::v4f32, Custom); 1073 setOperationAction(ISD::FMA, MVT::v2f64, Custom); 1074 setOperationAction(ISD::FMA, MVT::f32, Custom); 1075 setOperationAction(ISD::FMA, MVT::f64, Custom); 1076 } 1077 1078 if (Subtarget->hasAVX2()) { 1079 setOperationAction(ISD::ADD, MVT::v4i64, Legal); 1080 setOperationAction(ISD::ADD, MVT::v8i32, Legal); 1081 setOperationAction(ISD::ADD, MVT::v16i16, Legal); 1082 setOperationAction(ISD::ADD, MVT::v32i8, Legal); 1083 1084 setOperationAction(ISD::SUB, MVT::v4i64, Legal); 1085 setOperationAction(ISD::SUB, MVT::v8i32, Legal); 1086 setOperationAction(ISD::SUB, MVT::v16i16, Legal); 1087 setOperationAction(ISD::SUB, MVT::v32i8, Legal); 1088 1089 setOperationAction(ISD::MUL, MVT::v4i64, Custom); 1090 setOperationAction(ISD::MUL, MVT::v8i32, Legal); 1091 setOperationAction(ISD::MUL, MVT::v16i16, Legal); 1092 // Don't lower v32i8 because there is no 128-bit byte mul 1093 1094 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal); 1095 1096 setOperationAction(ISD::SRL, MVT::v4i64, Legal); 1097 setOperationAction(ISD::SRL, MVT::v8i32, Legal); 1098 1099 setOperationAction(ISD::SHL, MVT::v4i64, Legal); 1100 setOperationAction(ISD::SHL, MVT::v8i32, Legal); 1101 1102 setOperationAction(ISD::SRA, MVT::v8i32, Legal); 1103 } else { 1104 setOperationAction(ISD::ADD, MVT::v4i64, Custom); 1105 setOperationAction(ISD::ADD, MVT::v8i32, Custom); 1106 setOperationAction(ISD::ADD, MVT::v16i16, Custom); 1107 setOperationAction(ISD::ADD, MVT::v32i8, Custom); 1108 1109 setOperationAction(ISD::SUB, MVT::v4i64, Custom); 1110 setOperationAction(ISD::SUB, MVT::v8i32, Custom); 1111 setOperationAction(ISD::SUB, MVT::v16i16, Custom); 1112 setOperationAction(ISD::SUB, MVT::v32i8, Custom); 1113 1114 setOperationAction(ISD::MUL, MVT::v4i64, Custom); 1115 setOperationAction(ISD::MUL, MVT::v8i32, Custom); 1116 setOperationAction(ISD::MUL, MVT::v16i16, Custom); 1117 // Don't lower v32i8 because there is no 128-bit byte mul 1118 1119 setOperationAction(ISD::SRL, MVT::v4i64, Custom); 1120 setOperationAction(ISD::SRL, MVT::v8i32, Custom); 1121 1122 setOperationAction(ISD::SHL, MVT::v4i64, Custom); 1123 setOperationAction(ISD::SHL, MVT::v8i32, Custom); 1124 1125 setOperationAction(ISD::SRA, MVT::v8i32, Custom); 1126 } 1127 1128 // Custom lower several nodes for 256-bit types. 1129 for (int i = MVT::FIRST_VECTOR_VALUETYPE; 1130 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) { 1131 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 1132 EVT VT = SVT; 1133 1134 // Extract subvector is special because the value type 1135 // (result) is 128-bit but the source is 256-bit wide. 1136 if (VT.is128BitVector()) 1137 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom); 1138 1139 // Do not attempt to custom lower other non-256-bit vectors 1140 if (!VT.is256BitVector()) 1141 continue; 1142 1143 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom); 1144 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom); 1145 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom); 1146 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom); 1147 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom); 1148 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom); 1149 setOperationAction(ISD::CONCAT_VECTORS, SVT, Custom); 1150 } 1151 1152 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64. 1153 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) { 1154 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 1155 EVT VT = SVT; 1156 1157 // Do not attempt to promote non-256-bit vectors 1158 if (!VT.is256BitVector()) 1159 continue; 1160 1161 setOperationAction(ISD::AND, SVT, Promote); 1162 AddPromotedToType (ISD::AND, SVT, MVT::v4i64); 1163 setOperationAction(ISD::OR, SVT, Promote); 1164 AddPromotedToType (ISD::OR, SVT, MVT::v4i64); 1165 setOperationAction(ISD::XOR, SVT, Promote); 1166 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64); 1167 setOperationAction(ISD::LOAD, SVT, Promote); 1168 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64); 1169 setOperationAction(ISD::SELECT, SVT, Promote); 1170 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64); 1171 } 1172 } 1173 1174 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion 1175 // of this type with custom code. 1176 for (int VT = MVT::FIRST_VECTOR_VALUETYPE; 1177 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) { 1178 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, 1179 Custom); 1180 } 1181 1182 // We want to custom lower some of our intrinsics. 1183 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1184 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 1185 1186 1187 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't 1188 // handle type legalization for these operations here. 1189 // 1190 // FIXME: We really should do custom legalization for addition and 1191 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better 1192 // than generic legalization for 64-bit multiplication-with-overflow, though. 1193 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) { 1194 // Add/Sub/Mul with overflow operations are custom lowered. 1195 MVT VT = IntVTs[i]; 1196 setOperationAction(ISD::SADDO, VT, Custom); 1197 setOperationAction(ISD::UADDO, VT, Custom); 1198 setOperationAction(ISD::SSUBO, VT, Custom); 1199 setOperationAction(ISD::USUBO, VT, Custom); 1200 setOperationAction(ISD::SMULO, VT, Custom); 1201 setOperationAction(ISD::UMULO, VT, Custom); 1202 } 1203 1204 // There are no 8-bit 3-address imul/mul instructions 1205 setOperationAction(ISD::SMULO, MVT::i8, Expand); 1206 setOperationAction(ISD::UMULO, MVT::i8, Expand); 1207 1208 if (!Subtarget->is64Bit()) { 1209 // These libcalls are not available in 32-bit. 1210 setLibcallName(RTLIB::SHL_I128, 0); 1211 setLibcallName(RTLIB::SRL_I128, 0); 1212 setLibcallName(RTLIB::SRA_I128, 0); 1213 } 1214 1215 // We have target-specific dag combine patterns for the following nodes: 1216 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1217 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 1218 setTargetDAGCombine(ISD::VSELECT); 1219 setTargetDAGCombine(ISD::SELECT); 1220 setTargetDAGCombine(ISD::SHL); 1221 setTargetDAGCombine(ISD::SRA); 1222 setTargetDAGCombine(ISD::SRL); 1223 setTargetDAGCombine(ISD::OR); 1224 setTargetDAGCombine(ISD::AND); 1225 setTargetDAGCombine(ISD::ADD); 1226 setTargetDAGCombine(ISD::FADD); 1227 setTargetDAGCombine(ISD::FSUB); 1228 setTargetDAGCombine(ISD::FMA); 1229 setTargetDAGCombine(ISD::SUB); 1230 setTargetDAGCombine(ISD::LOAD); 1231 setTargetDAGCombine(ISD::STORE); 1232 setTargetDAGCombine(ISD::ZERO_EXTEND); 1233 setTargetDAGCombine(ISD::ANY_EXTEND); 1234 setTargetDAGCombine(ISD::SIGN_EXTEND); 1235 setTargetDAGCombine(ISD::TRUNCATE); 1236 setTargetDAGCombine(ISD::UINT_TO_FP); 1237 setTargetDAGCombine(ISD::SINT_TO_FP); 1238 setTargetDAGCombine(ISD::SETCC); 1239 setTargetDAGCombine(ISD::FP_TO_SINT); 1240 if (Subtarget->is64Bit()) 1241 setTargetDAGCombine(ISD::MUL); 1242 setTargetDAGCombine(ISD::XOR); 1243 1244 computeRegisterProperties(); 1245 1246 // On Darwin, -Os means optimize for size without hurting performance, 1247 // do not reduce the limit. 1248 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores 1249 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8; 1250 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores 1251 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1252 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores 1253 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1254 setPrefLoopAlignment(4); // 2^4 bytes. 1255 benefitFromCodePlacementOpt = true; 1256 1257 // Predictable cmov don't hurt on atom because it's in-order. 1258 predictableSelectIsExpensive = !Subtarget->isAtom(); 1259 1260 setPrefFunctionAlignment(4); // 2^4 bytes. 1261} 1262 1263 1264EVT X86TargetLowering::getSetCCResultType(EVT VT) const { 1265 if (!VT.isVector()) return MVT::i8; 1266 return VT.changeVectorElementTypeToInteger(); 1267} 1268 1269 1270/// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1271/// the desired ByVal argument alignment. 1272static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) { 1273 if (MaxAlign == 16) 1274 return; 1275 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1276 if (VTy->getBitWidth() == 128) 1277 MaxAlign = 16; 1278 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1279 unsigned EltAlign = 0; 1280 getMaxByValAlign(ATy->getElementType(), EltAlign); 1281 if (EltAlign > MaxAlign) 1282 MaxAlign = EltAlign; 1283 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1284 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1285 unsigned EltAlign = 0; 1286 getMaxByValAlign(STy->getElementType(i), EltAlign); 1287 if (EltAlign > MaxAlign) 1288 MaxAlign = EltAlign; 1289 if (MaxAlign == 16) 1290 break; 1291 } 1292 } 1293} 1294 1295/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1296/// function arguments in the caller parameter area. For X86, aggregates 1297/// that contain SSE vectors are placed at 16-byte boundaries while the rest 1298/// are at 4-byte boundaries. 1299unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const { 1300 if (Subtarget->is64Bit()) { 1301 // Max of 8 and alignment of type. 1302 unsigned TyAlign = TD->getABITypeAlignment(Ty); 1303 if (TyAlign > 8) 1304 return TyAlign; 1305 return 8; 1306 } 1307 1308 unsigned Align = 4; 1309 if (Subtarget->hasSSE1()) 1310 getMaxByValAlign(Ty, Align); 1311 return Align; 1312} 1313 1314/// getOptimalMemOpType - Returns the target specific optimal type for load 1315/// and store operations as a result of memset, memcpy, and memmove 1316/// lowering. If DstAlign is zero that means it's safe to destination 1317/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 1318/// means there isn't a need to check it against alignment requirement, 1319/// probably because the source does not need to be loaded. If 1320/// 'IsZeroVal' is true, that means it's safe to return a 1321/// non-scalar-integer type, e.g. empty string source, constant, or loaded 1322/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is 1323/// constant so it does not need to be loaded. 1324/// It returns EVT::Other if the type should be determined using generic 1325/// target-independent logic. 1326EVT 1327X86TargetLowering::getOptimalMemOpType(uint64_t Size, 1328 unsigned DstAlign, unsigned SrcAlign, 1329 bool IsZeroVal, 1330 bool MemcpyStrSrc, 1331 MachineFunction &MF) const { 1332 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like 1333 // linux. This is because the stack realignment code can't handle certain 1334 // cases like PR2962. This should be removed when PR2962 is fixed. 1335 const Function *F = MF.getFunction(); 1336 if (IsZeroVal && 1337 !F->hasFnAttr(Attribute::NoImplicitFloat)) { 1338 if (Size >= 16 && 1339 (Subtarget->isUnalignedMemAccessFast() || 1340 ((DstAlign == 0 || DstAlign >= 16) && 1341 (SrcAlign == 0 || SrcAlign >= 16))) && 1342 Subtarget->getStackAlignment() >= 16) { 1343 if (Subtarget->getStackAlignment() >= 32) { 1344 if (Subtarget->hasAVX2()) 1345 return MVT::v8i32; 1346 if (Subtarget->hasAVX()) 1347 return MVT::v8f32; 1348 } 1349 if (Subtarget->hasSSE2()) 1350 return MVT::v4i32; 1351 if (Subtarget->hasSSE1()) 1352 return MVT::v4f32; 1353 } else if (!MemcpyStrSrc && Size >= 8 && 1354 !Subtarget->is64Bit() && 1355 Subtarget->getStackAlignment() >= 8 && 1356 Subtarget->hasSSE2()) { 1357 // Do not use f64 to lower memcpy if source is string constant. It's 1358 // better to use i32 to avoid the loads. 1359 return MVT::f64; 1360 } 1361 } 1362 if (Subtarget->is64Bit() && Size >= 8) 1363 return MVT::i64; 1364 return MVT::i32; 1365} 1366 1367/// getJumpTableEncoding - Return the entry encoding for a jump table in the 1368/// current function. The returned value is a member of the 1369/// MachineJumpTableInfo::JTEntryKind enum. 1370unsigned X86TargetLowering::getJumpTableEncoding() const { 1371 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF 1372 // symbol. 1373 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1374 Subtarget->isPICStyleGOT()) 1375 return MachineJumpTableInfo::EK_Custom32; 1376 1377 // Otherwise, use the normal jump table encoding heuristics. 1378 return TargetLowering::getJumpTableEncoding(); 1379} 1380 1381const MCExpr * 1382X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, 1383 const MachineBasicBlock *MBB, 1384 unsigned uid,MCContext &Ctx) const{ 1385 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1386 Subtarget->isPICStyleGOT()); 1387 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF 1388 // entries. 1389 return MCSymbolRefExpr::Create(MBB->getSymbol(), 1390 MCSymbolRefExpr::VK_GOTOFF, Ctx); 1391} 1392 1393/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC 1394/// jumptable. 1395SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table, 1396 SelectionDAG &DAG) const { 1397 if (!Subtarget->is64Bit()) 1398 // This doesn't have DebugLoc associated with it, but is not really the 1399 // same as a Register. 1400 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy()); 1401 return Table; 1402} 1403 1404/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the 1405/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an 1406/// MCExpr. 1407const MCExpr *X86TargetLowering:: 1408getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, 1409 MCContext &Ctx) const { 1410 // X86-64 uses RIP relative addressing based on the jump table label. 1411 if (Subtarget->isPICStyleRIPRel()) 1412 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 1413 1414 // Otherwise, the reference is relative to the PIC base. 1415 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx); 1416} 1417 1418// FIXME: Why this routine is here? Move to RegInfo! 1419std::pair<const TargetRegisterClass*, uint8_t> 1420X86TargetLowering::findRepresentativeClass(EVT VT) const{ 1421 const TargetRegisterClass *RRC = 0; 1422 uint8_t Cost = 1; 1423 switch (VT.getSimpleVT().SimpleTy) { 1424 default: 1425 return TargetLowering::findRepresentativeClass(VT); 1426 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64: 1427 RRC = Subtarget->is64Bit() ? 1428 (const TargetRegisterClass*)&X86::GR64RegClass : 1429 (const TargetRegisterClass*)&X86::GR32RegClass; 1430 break; 1431 case MVT::x86mmx: 1432 RRC = &X86::VR64RegClass; 1433 break; 1434 case MVT::f32: case MVT::f64: 1435 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1436 case MVT::v4f32: case MVT::v2f64: 1437 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32: 1438 case MVT::v4f64: 1439 RRC = &X86::VR128RegClass; 1440 break; 1441 } 1442 return std::make_pair(RRC, Cost); 1443} 1444 1445bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace, 1446 unsigned &Offset) const { 1447 if (!Subtarget->isTargetLinux()) 1448 return false; 1449 1450 if (Subtarget->is64Bit()) { 1451 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs: 1452 Offset = 0x28; 1453 if (getTargetMachine().getCodeModel() == CodeModel::Kernel) 1454 AddressSpace = 256; 1455 else 1456 AddressSpace = 257; 1457 } else { 1458 // %gs:0x14 on i386 1459 Offset = 0x14; 1460 AddressSpace = 256; 1461 } 1462 return true; 1463} 1464 1465 1466//===----------------------------------------------------------------------===// 1467// Return Value Calling Convention Implementation 1468//===----------------------------------------------------------------------===// 1469 1470#include "X86GenCallingConv.inc" 1471 1472bool 1473X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, 1474 MachineFunction &MF, bool isVarArg, 1475 const SmallVectorImpl<ISD::OutputArg> &Outs, 1476 LLVMContext &Context) const { 1477 SmallVector<CCValAssign, 16> RVLocs; 1478 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1479 RVLocs, Context); 1480 return CCInfo.CheckReturn(Outs, RetCC_X86); 1481} 1482 1483SDValue 1484X86TargetLowering::LowerReturn(SDValue Chain, 1485 CallingConv::ID CallConv, bool isVarArg, 1486 const SmallVectorImpl<ISD::OutputArg> &Outs, 1487 const SmallVectorImpl<SDValue> &OutVals, 1488 DebugLoc dl, SelectionDAG &DAG) const { 1489 MachineFunction &MF = DAG.getMachineFunction(); 1490 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1491 1492 SmallVector<CCValAssign, 16> RVLocs; 1493 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1494 RVLocs, *DAG.getContext()); 1495 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 1496 1497 // Add the regs to the liveout set for the function. 1498 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1499 for (unsigned i = 0; i != RVLocs.size(); ++i) 1500 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg())) 1501 MRI.addLiveOut(RVLocs[i].getLocReg()); 1502 1503 SDValue Flag; 1504 1505 SmallVector<SDValue, 6> RetOps; 1506 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1507 // Operand #1 = Bytes To Pop 1508 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), 1509 MVT::i16)); 1510 1511 // Copy the result values into the output registers. 1512 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1513 CCValAssign &VA = RVLocs[i]; 1514 assert(VA.isRegLoc() && "Can only return in registers!"); 1515 SDValue ValToCopy = OutVals[i]; 1516 EVT ValVT = ValToCopy.getValueType(); 1517 1518 // Promote values to the appropriate types 1519 if (VA.getLocInfo() == CCValAssign::SExt) 1520 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy); 1521 else if (VA.getLocInfo() == CCValAssign::ZExt) 1522 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy); 1523 else if (VA.getLocInfo() == CCValAssign::AExt) 1524 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy); 1525 else if (VA.getLocInfo() == CCValAssign::BCvt) 1526 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy); 1527 1528 // If this is x86-64, and we disabled SSE, we can't return FP values, 1529 // or SSE or MMX vectors. 1530 if ((ValVT == MVT::f32 || ValVT == MVT::f64 || 1531 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) && 1532 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) { 1533 report_fatal_error("SSE register return with SSE disabled"); 1534 } 1535 // Likewise we can't return F64 values with SSE1 only. gcc does so, but 1536 // llvm-gcc has never done it right and no one has noticed, so this 1537 // should be OK for now. 1538 if (ValVT == MVT::f64 && 1539 (Subtarget->is64Bit() && !Subtarget->hasSSE2())) 1540 report_fatal_error("SSE2 register return with SSE2 disabled"); 1541 1542 // Returns in ST0/ST1 are handled specially: these are pushed as operands to 1543 // the RET instruction and handled by the FP Stackifier. 1544 if (VA.getLocReg() == X86::ST0 || 1545 VA.getLocReg() == X86::ST1) { 1546 // If this is a copy from an xmm register to ST(0), use an FPExtend to 1547 // change the value to the FP stack register class. 1548 if (isScalarFPTypeInSSEReg(VA.getValVT())) 1549 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy); 1550 RetOps.push_back(ValToCopy); 1551 // Don't emit a copytoreg. 1552 continue; 1553 } 1554 1555 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64 1556 // which is returned in RAX / RDX. 1557 if (Subtarget->is64Bit()) { 1558 if (ValVT == MVT::x86mmx) { 1559 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) { 1560 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy); 1561 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 1562 ValToCopy); 1563 // If we don't have SSE2 available, convert to v4f32 so the generated 1564 // register is legal. 1565 if (!Subtarget->hasSSE2()) 1566 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy); 1567 } 1568 } 1569 } 1570 1571 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag); 1572 Flag = Chain.getValue(1); 1573 } 1574 1575 // The x86-64 ABI for returning structs by value requires that we copy 1576 // the sret argument into %rax for the return. We saved the argument into 1577 // a virtual register in the entry block, so now we copy the value out 1578 // and into %rax. 1579 if (Subtarget->is64Bit() && 1580 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) { 1581 MachineFunction &MF = DAG.getMachineFunction(); 1582 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1583 unsigned Reg = FuncInfo->getSRetReturnReg(); 1584 assert(Reg && 1585 "SRetReturnReg should have been set in LowerFormalArguments()."); 1586 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy()); 1587 1588 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag); 1589 Flag = Chain.getValue(1); 1590 1591 // RAX now acts like a return value. 1592 MRI.addLiveOut(X86::RAX); 1593 } 1594 1595 RetOps[0] = Chain; // Update chain. 1596 1597 // Add the flag if we have it. 1598 if (Flag.getNode()) 1599 RetOps.push_back(Flag); 1600 1601 return DAG.getNode(X86ISD::RET_FLAG, dl, 1602 MVT::Other, &RetOps[0], RetOps.size()); 1603} 1604 1605bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 1606 if (N->getNumValues() != 1) 1607 return false; 1608 if (!N->hasNUsesOfValue(1, 0)) 1609 return false; 1610 1611 SDValue TCChain = Chain; 1612 SDNode *Copy = *N->use_begin(); 1613 if (Copy->getOpcode() == ISD::CopyToReg) { 1614 // If the copy has a glue operand, we conservatively assume it isn't safe to 1615 // perform a tail call. 1616 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 1617 return false; 1618 TCChain = Copy->getOperand(0); 1619 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 1620 return false; 1621 1622 bool HasRet = false; 1623 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 1624 UI != UE; ++UI) { 1625 if (UI->getOpcode() != X86ISD::RET_FLAG) 1626 return false; 1627 HasRet = true; 1628 } 1629 1630 if (!HasRet) 1631 return false; 1632 1633 Chain = TCChain; 1634 return true; 1635} 1636 1637EVT 1638X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT, 1639 ISD::NodeType ExtendKind) const { 1640 MVT ReturnMVT; 1641 // TODO: Is this also valid on 32-bit? 1642 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND) 1643 ReturnMVT = MVT::i8; 1644 else 1645 ReturnMVT = MVT::i32; 1646 1647 EVT MinVT = getRegisterType(Context, ReturnMVT); 1648 return VT.bitsLT(MinVT) ? MinVT : VT; 1649} 1650 1651/// LowerCallResult - Lower the result values of a call into the 1652/// appropriate copies out of appropriate physical registers. 1653/// 1654SDValue 1655X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1656 CallingConv::ID CallConv, bool isVarArg, 1657 const SmallVectorImpl<ISD::InputArg> &Ins, 1658 DebugLoc dl, SelectionDAG &DAG, 1659 SmallVectorImpl<SDValue> &InVals) const { 1660 1661 // Assign locations to each value returned by this call. 1662 SmallVector<CCValAssign, 16> RVLocs; 1663 bool Is64Bit = Subtarget->is64Bit(); 1664 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 1665 getTargetMachine(), RVLocs, *DAG.getContext()); 1666 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 1667 1668 // Copy all of the result registers out of their specified physreg. 1669 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1670 CCValAssign &VA = RVLocs[i]; 1671 EVT CopyVT = VA.getValVT(); 1672 1673 // If this is x86-64, and we disabled SSE, we can't return FP values 1674 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 1675 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) { 1676 report_fatal_error("SSE register return with SSE disabled"); 1677 } 1678 1679 SDValue Val; 1680 1681 // If this is a call to a function that returns an fp value on the floating 1682 // point stack, we must guarantee the value is popped from the stack, so 1683 // a CopyFromReg is not good enough - the copy instruction may be eliminated 1684 // if the return value is not used. We use the FpPOP_RETVAL instruction 1685 // instead. 1686 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) { 1687 // If we prefer to use the value in xmm registers, copy it out as f80 and 1688 // use a truncate to move it from fp stack reg to xmm reg. 1689 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80; 1690 SDValue Ops[] = { Chain, InFlag }; 1691 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT, 1692 MVT::Other, MVT::Glue, Ops, 2), 1); 1693 Val = Chain.getValue(0); 1694 1695 // Round the f80 to the right size, which also moves it to the appropriate 1696 // xmm register. 1697 if (CopyVT != VA.getValVT()) 1698 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val, 1699 // This truncation won't change the value. 1700 DAG.getIntPtrConstant(1)); 1701 } else { 1702 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1703 CopyVT, InFlag).getValue(1); 1704 Val = Chain.getValue(0); 1705 } 1706 InFlag = Chain.getValue(2); 1707 InVals.push_back(Val); 1708 } 1709 1710 return Chain; 1711} 1712 1713 1714//===----------------------------------------------------------------------===// 1715// C & StdCall & Fast Calling Convention implementation 1716//===----------------------------------------------------------------------===// 1717// StdCall calling convention seems to be standard for many Windows' API 1718// routines and around. It differs from C calling convention just a little: 1719// callee should clean up the stack, not caller. Symbols should be also 1720// decorated in some fancy way :) It doesn't support any vector arguments. 1721// For info on fast calling convention see Fast Calling Convention (tail call) 1722// implementation LowerX86_32FastCCCallTo. 1723 1724/// CallIsStructReturn - Determines whether a call uses struct return 1725/// semantics. 1726enum StructReturnType { 1727 NotStructReturn, 1728 RegStructReturn, 1729 StackStructReturn 1730}; 1731static StructReturnType 1732callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) { 1733 if (Outs.empty()) 1734 return NotStructReturn; 1735 1736 const ISD::ArgFlagsTy &Flags = Outs[0].Flags; 1737 if (!Flags.isSRet()) 1738 return NotStructReturn; 1739 if (Flags.isInReg()) 1740 return RegStructReturn; 1741 return StackStructReturn; 1742} 1743 1744/// ArgsAreStructReturn - Determines whether a function uses struct 1745/// return semantics. 1746static StructReturnType 1747argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) { 1748 if (Ins.empty()) 1749 return NotStructReturn; 1750 1751 const ISD::ArgFlagsTy &Flags = Ins[0].Flags; 1752 if (!Flags.isSRet()) 1753 return NotStructReturn; 1754 if (Flags.isInReg()) 1755 return RegStructReturn; 1756 return StackStructReturn; 1757} 1758 1759/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 1760/// by "Src" to address "Dst" with size and alignment information specified by 1761/// the specific parameter attribute. The copy will be passed as a byval 1762/// function parameter. 1763static SDValue 1764CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 1765 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 1766 DebugLoc dl) { 1767 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 1768 1769 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 1770 /*isVolatile*/false, /*AlwaysInline=*/true, 1771 MachinePointerInfo(), MachinePointerInfo()); 1772} 1773 1774/// IsTailCallConvention - Return true if the calling convention is one that 1775/// supports tail call optimization. 1776static bool IsTailCallConvention(CallingConv::ID CC) { 1777 return (CC == CallingConv::Fast || CC == CallingConv::GHC); 1778} 1779 1780bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 1781 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls) 1782 return false; 1783 1784 CallSite CS(CI); 1785 CallingConv::ID CalleeCC = CS.getCallingConv(); 1786 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C) 1787 return false; 1788 1789 return true; 1790} 1791 1792/// FuncIsMadeTailCallSafe - Return true if the function is being made into 1793/// a tailcall target by changing its ABI. 1794static bool FuncIsMadeTailCallSafe(CallingConv::ID CC, 1795 bool GuaranteedTailCallOpt) { 1796 return GuaranteedTailCallOpt && IsTailCallConvention(CC); 1797} 1798 1799SDValue 1800X86TargetLowering::LowerMemArgument(SDValue Chain, 1801 CallingConv::ID CallConv, 1802 const SmallVectorImpl<ISD::InputArg> &Ins, 1803 DebugLoc dl, SelectionDAG &DAG, 1804 const CCValAssign &VA, 1805 MachineFrameInfo *MFI, 1806 unsigned i) const { 1807 // Create the nodes corresponding to a load from this parameter slot. 1808 ISD::ArgFlagsTy Flags = Ins[i].Flags; 1809 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv, 1810 getTargetMachine().Options.GuaranteedTailCallOpt); 1811 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal(); 1812 EVT ValVT; 1813 1814 // If value is passed by pointer we have address passed instead of the value 1815 // itself. 1816 if (VA.getLocInfo() == CCValAssign::Indirect) 1817 ValVT = VA.getLocVT(); 1818 else 1819 ValVT = VA.getValVT(); 1820 1821 // FIXME: For now, all byval parameter objects are marked mutable. This can be 1822 // changed with more analysis. 1823 // In case of tail call optimization mark all arguments mutable. Since they 1824 // could be overwritten by lowering of arguments in case of a tail call. 1825 if (Flags.isByVal()) { 1826 unsigned Bytes = Flags.getByValSize(); 1827 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects. 1828 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable); 1829 return DAG.getFrameIndex(FI, getPointerTy()); 1830 } else { 1831 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8, 1832 VA.getLocMemOffset(), isImmutable); 1833 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 1834 return DAG.getLoad(ValVT, dl, Chain, FIN, 1835 MachinePointerInfo::getFixedStack(FI), 1836 false, false, false, 0); 1837 } 1838} 1839 1840SDValue 1841X86TargetLowering::LowerFormalArguments(SDValue Chain, 1842 CallingConv::ID CallConv, 1843 bool isVarArg, 1844 const SmallVectorImpl<ISD::InputArg> &Ins, 1845 DebugLoc dl, 1846 SelectionDAG &DAG, 1847 SmallVectorImpl<SDValue> &InVals) 1848 const { 1849 MachineFunction &MF = DAG.getMachineFunction(); 1850 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1851 1852 const Function* Fn = MF.getFunction(); 1853 if (Fn->hasExternalLinkage() && 1854 Subtarget->isTargetCygMing() && 1855 Fn->getName() == "main") 1856 FuncInfo->setForceFramePointer(true); 1857 1858 MachineFrameInfo *MFI = MF.getFrameInfo(); 1859 bool Is64Bit = Subtarget->is64Bit(); 1860 bool IsWindows = Subtarget->isTargetWindows(); 1861 bool IsWin64 = Subtarget->isTargetWin64(); 1862 1863 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 1864 "Var args not supported with calling convention fastcc or ghc"); 1865 1866 // Assign locations to all of the incoming arguments. 1867 SmallVector<CCValAssign, 16> ArgLocs; 1868 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1869 ArgLocs, *DAG.getContext()); 1870 1871 // Allocate shadow area for Win64 1872 if (IsWin64) { 1873 CCInfo.AllocateStack(32, 8); 1874 } 1875 1876 CCInfo.AnalyzeFormalArguments(Ins, CC_X86); 1877 1878 unsigned LastVal = ~0U; 1879 SDValue ArgValue; 1880 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 1881 CCValAssign &VA = ArgLocs[i]; 1882 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later 1883 // places. 1884 assert(VA.getValNo() != LastVal && 1885 "Don't support value assigned to multiple locs yet"); 1886 (void)LastVal; 1887 LastVal = VA.getValNo(); 1888 1889 if (VA.isRegLoc()) { 1890 EVT RegVT = VA.getLocVT(); 1891 const TargetRegisterClass *RC; 1892 if (RegVT == MVT::i32) 1893 RC = &X86::GR32RegClass; 1894 else if (Is64Bit && RegVT == MVT::i64) 1895 RC = &X86::GR64RegClass; 1896 else if (RegVT == MVT::f32) 1897 RC = &X86::FR32RegClass; 1898 else if (RegVT == MVT::f64) 1899 RC = &X86::FR64RegClass; 1900 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256) 1901 RC = &X86::VR256RegClass; 1902 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128) 1903 RC = &X86::VR128RegClass; 1904 else if (RegVT == MVT::x86mmx) 1905 RC = &X86::VR64RegClass; 1906 else 1907 llvm_unreachable("Unknown argument type!"); 1908 1909 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 1910 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 1911 1912 // If this is an 8 or 16-bit value, it is really passed promoted to 32 1913 // bits. Insert an assert[sz]ext to capture this, then truncate to the 1914 // right size. 1915 if (VA.getLocInfo() == CCValAssign::SExt) 1916 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 1917 DAG.getValueType(VA.getValVT())); 1918 else if (VA.getLocInfo() == CCValAssign::ZExt) 1919 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 1920 DAG.getValueType(VA.getValVT())); 1921 else if (VA.getLocInfo() == CCValAssign::BCvt) 1922 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 1923 1924 if (VA.isExtInLoc()) { 1925 // Handle MMX values passed in XMM regs. 1926 if (RegVT.isVector()) { 1927 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), 1928 ArgValue); 1929 } else 1930 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 1931 } 1932 } else { 1933 assert(VA.isMemLoc()); 1934 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i); 1935 } 1936 1937 // If value is passed via pointer - do a load. 1938 if (VA.getLocInfo() == CCValAssign::Indirect) 1939 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, 1940 MachinePointerInfo(), false, false, false, 0); 1941 1942 InVals.push_back(ArgValue); 1943 } 1944 1945 // The x86-64 ABI for returning structs by value requires that we copy 1946 // the sret argument into %rax for the return. Save the argument into 1947 // a virtual register so that we can access it from the return points. 1948 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) { 1949 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1950 unsigned Reg = FuncInfo->getSRetReturnReg(); 1951 if (!Reg) { 1952 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64)); 1953 FuncInfo->setSRetReturnReg(Reg); 1954 } 1955 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]); 1956 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain); 1957 } 1958 1959 unsigned StackSize = CCInfo.getNextStackOffset(); 1960 // Align stack specially for tail calls. 1961 if (FuncIsMadeTailCallSafe(CallConv, 1962 MF.getTarget().Options.GuaranteedTailCallOpt)) 1963 StackSize = GetAlignedArgumentStackSize(StackSize, DAG); 1964 1965 // If the function takes variable number of arguments, make a frame index for 1966 // the start of the first vararg value... for expansion of llvm.va_start. 1967 if (isVarArg) { 1968 if (Is64Bit || (CallConv != CallingConv::X86_FastCall && 1969 CallConv != CallingConv::X86_ThisCall)) { 1970 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true)); 1971 } 1972 if (Is64Bit) { 1973 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0; 1974 1975 // FIXME: We should really autogenerate these arrays 1976 static const uint16_t GPR64ArgRegsWin64[] = { 1977 X86::RCX, X86::RDX, X86::R8, X86::R9 1978 }; 1979 static const uint16_t GPR64ArgRegs64Bit[] = { 1980 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9 1981 }; 1982 static const uint16_t XMMArgRegs64Bit[] = { 1983 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 1984 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 1985 }; 1986 const uint16_t *GPR64ArgRegs; 1987 unsigned NumXMMRegs = 0; 1988 1989 if (IsWin64) { 1990 // The XMM registers which might contain var arg parameters are shadowed 1991 // in their paired GPR. So we only need to save the GPR to their home 1992 // slots. 1993 TotalNumIntRegs = 4; 1994 GPR64ArgRegs = GPR64ArgRegsWin64; 1995 } else { 1996 TotalNumIntRegs = 6; TotalNumXMMRegs = 8; 1997 GPR64ArgRegs = GPR64ArgRegs64Bit; 1998 1999 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, 2000 TotalNumXMMRegs); 2001 } 2002 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 2003 TotalNumIntRegs); 2004 2005 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat); 2006 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) && 2007 "SSE register cannot be used when SSE is disabled!"); 2008 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat && 2009 NoImplicitFloatOps) && 2010 "SSE register cannot be used when SSE is disabled!"); 2011 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps || 2012 !Subtarget->hasSSE1()) 2013 // Kernel mode asks for SSE to be disabled, so don't push them 2014 // on the stack. 2015 TotalNumXMMRegs = 0; 2016 2017 if (IsWin64) { 2018 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering(); 2019 // Get to the caller-allocated home save location. Add 8 to account 2020 // for the return address. 2021 int HomeOffset = TFI.getOffsetOfLocalArea() + 8; 2022 FuncInfo->setRegSaveFrameIndex( 2023 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false)); 2024 // Fixup to set vararg frame on shadow area (4 x i64). 2025 if (NumIntRegs < 4) 2026 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex()); 2027 } else { 2028 // For X86-64, if there are vararg parameters that are passed via 2029 // registers, then we must store them to their spots on the stack so 2030 // they may be loaded by deferencing the result of va_next. 2031 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8); 2032 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16); 2033 FuncInfo->setRegSaveFrameIndex( 2034 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16, 2035 false)); 2036 } 2037 2038 // Store the integer parameter registers. 2039 SmallVector<SDValue, 8> MemOps; 2040 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 2041 getPointerTy()); 2042 unsigned Offset = FuncInfo->getVarArgsGPOffset(); 2043 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) { 2044 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN, 2045 DAG.getIntPtrConstant(Offset)); 2046 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs], 2047 &X86::GR64RegClass); 2048 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 2049 SDValue Store = 2050 DAG.getStore(Val.getValue(1), dl, Val, FIN, 2051 MachinePointerInfo::getFixedStack( 2052 FuncInfo->getRegSaveFrameIndex(), Offset), 2053 false, false, 0); 2054 MemOps.push_back(Store); 2055 Offset += 8; 2056 } 2057 2058 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) { 2059 // Now store the XMM (fp + vector) parameter registers. 2060 SmallVector<SDValue, 11> SaveXMMOps; 2061 SaveXMMOps.push_back(Chain); 2062 2063 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass); 2064 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8); 2065 SaveXMMOps.push_back(ALVal); 2066 2067 SaveXMMOps.push_back(DAG.getIntPtrConstant( 2068 FuncInfo->getRegSaveFrameIndex())); 2069 SaveXMMOps.push_back(DAG.getIntPtrConstant( 2070 FuncInfo->getVarArgsFPOffset())); 2071 2072 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) { 2073 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs], 2074 &X86::VR128RegClass); 2075 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32); 2076 SaveXMMOps.push_back(Val); 2077 } 2078 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl, 2079 MVT::Other, 2080 &SaveXMMOps[0], SaveXMMOps.size())); 2081 } 2082 2083 if (!MemOps.empty()) 2084 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2085 &MemOps[0], MemOps.size()); 2086 } 2087 } 2088 2089 // Some CCs need callee pop. 2090 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, 2091 MF.getTarget().Options.GuaranteedTailCallOpt)) { 2092 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything. 2093 } else { 2094 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing. 2095 // If this is an sret function, the return should pop the hidden pointer. 2096 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows && 2097 argsAreStructReturn(Ins) == StackStructReturn) 2098 FuncInfo->setBytesToPopOnReturn(4); 2099 } 2100 2101 if (!Is64Bit) { 2102 // RegSaveFrameIndex is X86-64 only. 2103 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA); 2104 if (CallConv == CallingConv::X86_FastCall || 2105 CallConv == CallingConv::X86_ThisCall) 2106 // fastcc functions can't have varargs. 2107 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA); 2108 } 2109 2110 FuncInfo->setArgumentStackSize(StackSize); 2111 2112 return Chain; 2113} 2114 2115SDValue 2116X86TargetLowering::LowerMemOpCallTo(SDValue Chain, 2117 SDValue StackPtr, SDValue Arg, 2118 DebugLoc dl, SelectionDAG &DAG, 2119 const CCValAssign &VA, 2120 ISD::ArgFlagsTy Flags) const { 2121 unsigned LocMemOffset = VA.getLocMemOffset(); 2122 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 2123 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 2124 if (Flags.isByVal()) 2125 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl); 2126 2127 return DAG.getStore(Chain, dl, Arg, PtrOff, 2128 MachinePointerInfo::getStack(LocMemOffset), 2129 false, false, 0); 2130} 2131 2132/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call 2133/// optimization is performed and it is required. 2134SDValue 2135X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 2136 SDValue &OutRetAddr, SDValue Chain, 2137 bool IsTailCall, bool Is64Bit, 2138 int FPDiff, DebugLoc dl) const { 2139 // Adjust the Return address stack slot. 2140 EVT VT = getPointerTy(); 2141 OutRetAddr = getReturnAddressFrameIndex(DAG); 2142 2143 // Load the "old" Return address. 2144 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(), 2145 false, false, false, 0); 2146 return SDValue(OutRetAddr.getNode(), 1); 2147} 2148 2149/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call 2150/// optimization is performed and it is required (FPDiff!=0). 2151static SDValue 2152EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 2153 SDValue Chain, SDValue RetAddrFrIdx, 2154 bool Is64Bit, int FPDiff, DebugLoc dl) { 2155 // Store the return address to the appropriate stack slot. 2156 if (!FPDiff) return Chain; 2157 // Calculate the new stack slot for the return address. 2158 int SlotSize = Is64Bit ? 8 : 4; 2159 int NewReturnAddrFI = 2160 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false); 2161 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2162 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT); 2163 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx, 2164 MachinePointerInfo::getFixedStack(NewReturnAddrFI), 2165 false, false, 0); 2166 return Chain; 2167} 2168 2169SDValue 2170X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2171 SmallVectorImpl<SDValue> &InVals) const { 2172 SelectionDAG &DAG = CLI.DAG; 2173 DebugLoc &dl = CLI.DL; 2174 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2175 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2176 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2177 SDValue Chain = CLI.Chain; 2178 SDValue Callee = CLI.Callee; 2179 CallingConv::ID CallConv = CLI.CallConv; 2180 bool &isTailCall = CLI.IsTailCall; 2181 bool isVarArg = CLI.IsVarArg; 2182 2183 MachineFunction &MF = DAG.getMachineFunction(); 2184 bool Is64Bit = Subtarget->is64Bit(); 2185 bool IsWin64 = Subtarget->isTargetWin64(); 2186 bool IsWindows = Subtarget->isTargetWindows(); 2187 StructReturnType SR = callIsStructReturn(Outs); 2188 bool IsSibcall = false; 2189 2190 if (MF.getTarget().Options.DisableTailCalls) 2191 isTailCall = false; 2192 2193 if (isTailCall) { 2194 // Check if it's really possible to do a tail call. 2195 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 2196 isVarArg, SR != NotStructReturn, 2197 MF.getFunction()->hasStructRetAttr(), 2198 Outs, OutVals, Ins, DAG); 2199 2200 // Sibcalls are automatically detected tailcalls which do not require 2201 // ABI changes. 2202 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall) 2203 IsSibcall = true; 2204 2205 if (isTailCall) 2206 ++NumTailCalls; 2207 } 2208 2209 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 2210 "Var args not supported with calling convention fastcc or ghc"); 2211 2212 // Analyze operands of the call, assigning locations to each operand. 2213 SmallVector<CCValAssign, 16> ArgLocs; 2214 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 2215 ArgLocs, *DAG.getContext()); 2216 2217 // Allocate shadow area for Win64 2218 if (IsWin64) { 2219 CCInfo.AllocateStack(32, 8); 2220 } 2221 2222 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2223 2224 // Get a count of how many bytes are to be pushed on the stack. 2225 unsigned NumBytes = CCInfo.getNextStackOffset(); 2226 if (IsSibcall) 2227 // This is a sibcall. The memory operands are available in caller's 2228 // own caller's stack. 2229 NumBytes = 0; 2230 else if (getTargetMachine().Options.GuaranteedTailCallOpt && 2231 IsTailCallConvention(CallConv)) 2232 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG); 2233 2234 int FPDiff = 0; 2235 if (isTailCall && !IsSibcall) { 2236 // Lower arguments at fp - stackoffset + fpdiff. 2237 unsigned NumBytesCallerPushed = 2238 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn(); 2239 FPDiff = NumBytesCallerPushed - NumBytes; 2240 2241 // Set the delta of movement of the returnaddr stackslot. 2242 // But only set if delta is greater than previous delta. 2243 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta())) 2244 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff); 2245 } 2246 2247 if (!IsSibcall) 2248 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true)); 2249 2250 SDValue RetAddrFrIdx; 2251 // Load return address for tail calls. 2252 if (isTailCall && FPDiff) 2253 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, 2254 Is64Bit, FPDiff, dl); 2255 2256 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2257 SmallVector<SDValue, 8> MemOpChains; 2258 SDValue StackPtr; 2259 2260 // Walk the register/memloc assignments, inserting copies/loads. In the case 2261 // of tail call optimization arguments are handle later. 2262 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2263 CCValAssign &VA = ArgLocs[i]; 2264 EVT RegVT = VA.getLocVT(); 2265 SDValue Arg = OutVals[i]; 2266 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2267 bool isByVal = Flags.isByVal(); 2268 2269 // Promote the value if needed. 2270 switch (VA.getLocInfo()) { 2271 default: llvm_unreachable("Unknown loc info!"); 2272 case CCValAssign::Full: break; 2273 case CCValAssign::SExt: 2274 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg); 2275 break; 2276 case CCValAssign::ZExt: 2277 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg); 2278 break; 2279 case CCValAssign::AExt: 2280 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) { 2281 // Special case: passing MMX values in XMM registers. 2282 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 2283 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg); 2284 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg); 2285 } else 2286 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg); 2287 break; 2288 case CCValAssign::BCvt: 2289 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg); 2290 break; 2291 case CCValAssign::Indirect: { 2292 // Store the argument. 2293 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT()); 2294 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 2295 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot, 2296 MachinePointerInfo::getFixedStack(FI), 2297 false, false, 0); 2298 Arg = SpillSlot; 2299 break; 2300 } 2301 } 2302 2303 if (VA.isRegLoc()) { 2304 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2305 if (isVarArg && IsWin64) { 2306 // Win64 ABI requires argument XMM reg to be copied to the corresponding 2307 // shadow reg if callee is a varargs function. 2308 unsigned ShadowReg = 0; 2309 switch (VA.getLocReg()) { 2310 case X86::XMM0: ShadowReg = X86::RCX; break; 2311 case X86::XMM1: ShadowReg = X86::RDX; break; 2312 case X86::XMM2: ShadowReg = X86::R8; break; 2313 case X86::XMM3: ShadowReg = X86::R9; break; 2314 } 2315 if (ShadowReg) 2316 RegsToPass.push_back(std::make_pair(ShadowReg, Arg)); 2317 } 2318 } else if (!IsSibcall && (!isTailCall || isByVal)) { 2319 assert(VA.isMemLoc()); 2320 if (StackPtr.getNode() == 0) 2321 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy()); 2322 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2323 dl, DAG, VA, Flags)); 2324 } 2325 } 2326 2327 if (!MemOpChains.empty()) 2328 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2329 &MemOpChains[0], MemOpChains.size()); 2330 2331 if (Subtarget->isPICStyleGOT()) { 2332 // ELF / PIC requires GOT in the EBX register before function calls via PLT 2333 // GOT pointer. 2334 if (!isTailCall) { 2335 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX), 2336 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy()))); 2337 } else { 2338 // If we are tail calling and generating PIC/GOT style code load the 2339 // address of the callee into ECX. The value in ecx is used as target of 2340 // the tail jump. This is done to circumvent the ebx/callee-saved problem 2341 // for tail calls on PIC/GOT architectures. Normally we would just put the 2342 // address of GOT into ebx and then call target@PLT. But for tail calls 2343 // ebx would be restored (since ebx is callee saved) before jumping to the 2344 // target@PLT. 2345 2346 // Note: The actual moving to ECX is done further down. 2347 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 2348 if (G && !G->getGlobal()->hasHiddenVisibility() && 2349 !G->getGlobal()->hasProtectedVisibility()) 2350 Callee = LowerGlobalAddress(Callee, DAG); 2351 else if (isa<ExternalSymbolSDNode>(Callee)) 2352 Callee = LowerExternalSymbol(Callee, DAG); 2353 } 2354 } 2355 2356 if (Is64Bit && isVarArg && !IsWin64) { 2357 // From AMD64 ABI document: 2358 // For calls that may call functions that use varargs or stdargs 2359 // (prototype-less calls or calls to functions containing ellipsis (...) in 2360 // the declaration) %al is used as hidden argument to specify the number 2361 // of SSE registers used. The contents of %al do not need to match exactly 2362 // the number of registers, but must be an ubound on the number of SSE 2363 // registers used and is in the range 0 - 8 inclusive. 2364 2365 // Count the number of XMM registers allocated. 2366 static const uint16_t XMMArgRegs[] = { 2367 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2368 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2369 }; 2370 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8); 2371 assert((Subtarget->hasSSE1() || !NumXMMRegs) 2372 && "SSE registers cannot be used when SSE is disabled"); 2373 2374 RegsToPass.push_back(std::make_pair(unsigned(X86::AL), 2375 DAG.getConstant(NumXMMRegs, MVT::i8))); 2376 } 2377 2378 // For tail calls lower the arguments to the 'real' stack slot. 2379 if (isTailCall) { 2380 // Force all the incoming stack arguments to be loaded from the stack 2381 // before any new outgoing arguments are stored to the stack, because the 2382 // outgoing stack slots may alias the incoming argument stack slots, and 2383 // the alias isn't otherwise explicit. This is slightly more conservative 2384 // than necessary, because it means that each store effectively depends 2385 // on every argument instead of just those arguments it would clobber. 2386 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain); 2387 2388 SmallVector<SDValue, 8> MemOpChains2; 2389 SDValue FIN; 2390 int FI = 0; 2391 if (getTargetMachine().Options.GuaranteedTailCallOpt) { 2392 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2393 CCValAssign &VA = ArgLocs[i]; 2394 if (VA.isRegLoc()) 2395 continue; 2396 assert(VA.isMemLoc()); 2397 SDValue Arg = OutVals[i]; 2398 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2399 // Create frame index. 2400 int32_t Offset = VA.getLocMemOffset()+FPDiff; 2401 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8; 2402 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 2403 FIN = DAG.getFrameIndex(FI, getPointerTy()); 2404 2405 if (Flags.isByVal()) { 2406 // Copy relative to framepointer. 2407 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset()); 2408 if (StackPtr.getNode() == 0) 2409 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, 2410 getPointerTy()); 2411 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source); 2412 2413 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, 2414 ArgChain, 2415 Flags, DAG, dl)); 2416 } else { 2417 // Store relative to framepointer. 2418 MemOpChains2.push_back( 2419 DAG.getStore(ArgChain, dl, Arg, FIN, 2420 MachinePointerInfo::getFixedStack(FI), 2421 false, false, 0)); 2422 } 2423 } 2424 } 2425 2426 if (!MemOpChains2.empty()) 2427 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2428 &MemOpChains2[0], MemOpChains2.size()); 2429 2430 // Store the return address to the appropriate stack slot. 2431 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit, 2432 FPDiff, dl); 2433 } 2434 2435 // Build a sequence of copy-to-reg nodes chained together with token chain 2436 // and flag operands which copy the outgoing args into registers. 2437 SDValue InFlag; 2438 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2439 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2440 RegsToPass[i].second, InFlag); 2441 InFlag = Chain.getValue(1); 2442 } 2443 2444 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 2445 assert(Is64Bit && "Large code model is only legal in 64-bit mode."); 2446 // In the 64-bit large code model, we have to make all calls 2447 // through a register, since the call instruction's 32-bit 2448 // pc-relative offset may not be large enough to hold the whole 2449 // address. 2450 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2451 // If the callee is a GlobalAddress node (quite common, every direct call 2452 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack 2453 // it. 2454 2455 // We should use extra load for direct calls to dllimported functions in 2456 // non-JIT mode. 2457 const GlobalValue *GV = G->getGlobal(); 2458 if (!GV->hasDLLImportLinkage()) { 2459 unsigned char OpFlags = 0; 2460 bool ExtraLoad = false; 2461 unsigned WrapperKind = ISD::DELETED_NODE; 2462 2463 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to 2464 // external symbols most go through the PLT in PIC mode. If the symbol 2465 // has hidden or protected visibility, or if it is static or local, then 2466 // we don't need to use the PLT - we can directly call it. 2467 if (Subtarget->isTargetELF() && 2468 getTargetMachine().getRelocationModel() == Reloc::PIC_ && 2469 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) { 2470 OpFlags = X86II::MO_PLT; 2471 } else if (Subtarget->isPICStyleStubAny() && 2472 (GV->isDeclaration() || GV->isWeakForLinker()) && 2473 (!Subtarget->getTargetTriple().isMacOSX() || 2474 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2475 // PC-relative references to external symbols should go through $stub, 2476 // unless we're building with the leopard linker or later, which 2477 // automatically synthesizes these stubs. 2478 OpFlags = X86II::MO_DARWIN_STUB; 2479 } else if (Subtarget->isPICStyleRIPRel() && 2480 isa<Function>(GV) && 2481 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) { 2482 // If the function is marked as non-lazy, generate an indirect call 2483 // which loads from the GOT directly. This avoids runtime overhead 2484 // at the cost of eager binding (and one extra byte of encoding). 2485 OpFlags = X86II::MO_GOTPCREL; 2486 WrapperKind = X86ISD::WrapperRIP; 2487 ExtraLoad = true; 2488 } 2489 2490 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 2491 G->getOffset(), OpFlags); 2492 2493 // Add a wrapper if needed. 2494 if (WrapperKind != ISD::DELETED_NODE) 2495 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee); 2496 // Add extra indirection if needed. 2497 if (ExtraLoad) 2498 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee, 2499 MachinePointerInfo::getGOT(), 2500 false, false, false, 0); 2501 } 2502 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2503 unsigned char OpFlags = 0; 2504 2505 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to 2506 // external symbols should go through the PLT. 2507 if (Subtarget->isTargetELF() && 2508 getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2509 OpFlags = X86II::MO_PLT; 2510 } else if (Subtarget->isPICStyleStubAny() && 2511 (!Subtarget->getTargetTriple().isMacOSX() || 2512 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2513 // PC-relative references to external symbols should go through $stub, 2514 // unless we're building with the leopard linker or later, which 2515 // automatically synthesizes these stubs. 2516 OpFlags = X86II::MO_DARWIN_STUB; 2517 } 2518 2519 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(), 2520 OpFlags); 2521 } 2522 2523 // Returns a chain & a flag for retval copy to use. 2524 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2525 SmallVector<SDValue, 8> Ops; 2526 2527 if (!IsSibcall && isTailCall) { 2528 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 2529 DAG.getIntPtrConstant(0, true), InFlag); 2530 InFlag = Chain.getValue(1); 2531 } 2532 2533 Ops.push_back(Chain); 2534 Ops.push_back(Callee); 2535 2536 if (isTailCall) 2537 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32)); 2538 2539 // Add argument registers to the end of the list so that they are known live 2540 // into the call. 2541 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2542 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2543 RegsToPass[i].second.getValueType())); 2544 2545 // Add a register mask operand representing the call-preserved registers. 2546 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo(); 2547 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv); 2548 assert(Mask && "Missing call preserved mask for calling convention"); 2549 Ops.push_back(DAG.getRegisterMask(Mask)); 2550 2551 if (InFlag.getNode()) 2552 Ops.push_back(InFlag); 2553 2554 if (isTailCall) { 2555 // We used to do: 2556 //// If this is the first return lowered for this function, add the regs 2557 //// to the liveout set for the function. 2558 // This isn't right, although it's probably harmless on x86; liveouts 2559 // should be computed from returns not tail calls. Consider a void 2560 // function making a tail call to a function returning int. 2561 return DAG.getNode(X86ISD::TC_RETURN, dl, 2562 NodeTys, &Ops[0], Ops.size()); 2563 } 2564 2565 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size()); 2566 InFlag = Chain.getValue(1); 2567 2568 // Create the CALLSEQ_END node. 2569 unsigned NumBytesForCalleeToPush; 2570 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, 2571 getTargetMachine().Options.GuaranteedTailCallOpt)) 2572 NumBytesForCalleeToPush = NumBytes; // Callee pops everything 2573 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows && 2574 SR == StackStructReturn) 2575 // If this is a call to a struct-return function, the callee 2576 // pops the hidden struct pointer, so we have to push it back. 2577 // This is common for Darwin/X86, Linux & Mingw32 targets. 2578 // For MSVC Win32 targets, the caller pops the hidden struct pointer. 2579 NumBytesForCalleeToPush = 4; 2580 else 2581 NumBytesForCalleeToPush = 0; // Callee pops nothing. 2582 2583 // Returns a flag for retval copy to use. 2584 if (!IsSibcall) { 2585 Chain = DAG.getCALLSEQ_END(Chain, 2586 DAG.getIntPtrConstant(NumBytes, true), 2587 DAG.getIntPtrConstant(NumBytesForCalleeToPush, 2588 true), 2589 InFlag); 2590 InFlag = Chain.getValue(1); 2591 } 2592 2593 // Handle result values, copying them out of physregs into vregs that we 2594 // return. 2595 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 2596 Ins, dl, DAG, InVals); 2597} 2598 2599 2600//===----------------------------------------------------------------------===// 2601// Fast Calling Convention (tail call) implementation 2602//===----------------------------------------------------------------------===// 2603 2604// Like std call, callee cleans arguments, convention except that ECX is 2605// reserved for storing the tail called function address. Only 2 registers are 2606// free for argument passing (inreg). Tail call optimization is performed 2607// provided: 2608// * tailcallopt is enabled 2609// * caller/callee are fastcc 2610// On X86_64 architecture with GOT-style position independent code only local 2611// (within module) calls are supported at the moment. 2612// To keep the stack aligned according to platform abi the function 2613// GetAlignedArgumentStackSize ensures that argument delta is always multiples 2614// of stack alignment. (Dynamic linkers need this - darwin's dyld for example) 2615// If a tail called function callee has more arguments than the caller the 2616// caller needs to make sure that there is room to move the RETADDR to. This is 2617// achieved by reserving an area the size of the argument delta right after the 2618// original REtADDR, but before the saved framepointer or the spilled registers 2619// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4) 2620// stack layout: 2621// arg1 2622// arg2 2623// RETADDR 2624// [ new RETADDR 2625// move area ] 2626// (possible EBP) 2627// ESI 2628// EDI 2629// local1 .. 2630 2631/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned 2632/// for a 16 byte align requirement. 2633unsigned 2634X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 2635 SelectionDAG& DAG) const { 2636 MachineFunction &MF = DAG.getMachineFunction(); 2637 const TargetMachine &TM = MF.getTarget(); 2638 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 2639 unsigned StackAlignment = TFI.getStackAlignment(); 2640 uint64_t AlignMask = StackAlignment - 1; 2641 int64_t Offset = StackSize; 2642 uint64_t SlotSize = TD->getPointerSize(); 2643 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) { 2644 // Number smaller than 12 so just add the difference. 2645 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask)); 2646 } else { 2647 // Mask out lower bits, add stackalignment once plus the 12 bytes. 2648 Offset = ((~AlignMask) & Offset) + StackAlignment + 2649 (StackAlignment-SlotSize); 2650 } 2651 return Offset; 2652} 2653 2654/// MatchingStackOffset - Return true if the given stack call argument is 2655/// already available in the same position (relatively) of the caller's 2656/// incoming argument stack. 2657static 2658bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2659 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2660 const X86InstrInfo *TII) { 2661 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2662 int FI = INT_MAX; 2663 if (Arg.getOpcode() == ISD::CopyFromReg) { 2664 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2665 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2666 return false; 2667 MachineInstr *Def = MRI->getVRegDef(VR); 2668 if (!Def) 2669 return false; 2670 if (!Flags.isByVal()) { 2671 if (!TII->isLoadFromStackSlot(Def, FI)) 2672 return false; 2673 } else { 2674 unsigned Opcode = Def->getOpcode(); 2675 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) && 2676 Def->getOperand(1).isFI()) { 2677 FI = Def->getOperand(1).getIndex(); 2678 Bytes = Flags.getByValSize(); 2679 } else 2680 return false; 2681 } 2682 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2683 if (Flags.isByVal()) 2684 // ByVal argument is passed in as a pointer but it's now being 2685 // dereferenced. e.g. 2686 // define @foo(%struct.X* %A) { 2687 // tail call @bar(%struct.X* byval %A) 2688 // } 2689 return false; 2690 SDValue Ptr = Ld->getBasePtr(); 2691 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2692 if (!FINode) 2693 return false; 2694 FI = FINode->getIndex(); 2695 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) { 2696 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg); 2697 FI = FINode->getIndex(); 2698 Bytes = Flags.getByValSize(); 2699 } else 2700 return false; 2701 2702 assert(FI != INT_MAX); 2703 if (!MFI->isFixedObjectIndex(FI)) 2704 return false; 2705 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2706} 2707 2708/// IsEligibleForTailCallOptimization - Check whether the call is eligible 2709/// for tail call optimization. Targets which want to do tail call 2710/// optimization should implement this function. 2711bool 2712X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2713 CallingConv::ID CalleeCC, 2714 bool isVarArg, 2715 bool isCalleeStructRet, 2716 bool isCallerStructRet, 2717 const SmallVectorImpl<ISD::OutputArg> &Outs, 2718 const SmallVectorImpl<SDValue> &OutVals, 2719 const SmallVectorImpl<ISD::InputArg> &Ins, 2720 SelectionDAG& DAG) const { 2721 if (!IsTailCallConvention(CalleeCC) && 2722 CalleeCC != CallingConv::C) 2723 return false; 2724 2725 // If -tailcallopt is specified, make fastcc functions tail-callable. 2726 const MachineFunction &MF = DAG.getMachineFunction(); 2727 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2728 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2729 bool CCMatch = CallerCC == CalleeCC; 2730 2731 if (getTargetMachine().Options.GuaranteedTailCallOpt) { 2732 if (IsTailCallConvention(CalleeCC) && CCMatch) 2733 return true; 2734 return false; 2735 } 2736 2737 // Look for obvious safe cases to perform tail call optimization that do not 2738 // require ABI changes. This is what gcc calls sibcall. 2739 2740 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to 2741 // emit a special epilogue. 2742 if (RegInfo->needsStackRealignment(MF)) 2743 return false; 2744 2745 // Also avoid sibcall optimization if either caller or callee uses struct 2746 // return semantics. 2747 if (isCalleeStructRet || isCallerStructRet) 2748 return false; 2749 2750 // An stdcall caller is expected to clean up its arguments; the callee 2751 // isn't going to do that. 2752 if (!CCMatch && CallerCC==CallingConv::X86_StdCall) 2753 return false; 2754 2755 // Do not sibcall optimize vararg calls unless all arguments are passed via 2756 // registers. 2757 if (isVarArg && !Outs.empty()) { 2758 2759 // Optimizing for varargs on Win64 is unlikely to be safe without 2760 // additional testing. 2761 if (Subtarget->isTargetWin64()) 2762 return false; 2763 2764 SmallVector<CCValAssign, 16> ArgLocs; 2765 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2766 getTargetMachine(), ArgLocs, *DAG.getContext()); 2767 2768 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2769 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) 2770 if (!ArgLocs[i].isRegLoc()) 2771 return false; 2772 } 2773 2774 // If the call result is in ST0 / ST1, it needs to be popped off the x87 2775 // stack. Therefore, if it's not used by the call it is not safe to optimize 2776 // this into a sibcall. 2777 bool Unused = false; 2778 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 2779 if (!Ins[i].Used) { 2780 Unused = true; 2781 break; 2782 } 2783 } 2784 if (Unused) { 2785 SmallVector<CCValAssign, 16> RVLocs; 2786 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), 2787 getTargetMachine(), RVLocs, *DAG.getContext()); 2788 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 2789 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 2790 CCValAssign &VA = RVLocs[i]; 2791 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) 2792 return false; 2793 } 2794 } 2795 2796 // If the calling conventions do not match, then we'd better make sure the 2797 // results are returned in the same way as what the caller expects. 2798 if (!CCMatch) { 2799 SmallVector<CCValAssign, 16> RVLocs1; 2800 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), 2801 getTargetMachine(), RVLocs1, *DAG.getContext()); 2802 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86); 2803 2804 SmallVector<CCValAssign, 16> RVLocs2; 2805 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), 2806 getTargetMachine(), RVLocs2, *DAG.getContext()); 2807 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86); 2808 2809 if (RVLocs1.size() != RVLocs2.size()) 2810 return false; 2811 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2812 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2813 return false; 2814 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2815 return false; 2816 if (RVLocs1[i].isRegLoc()) { 2817 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2818 return false; 2819 } else { 2820 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2821 return false; 2822 } 2823 } 2824 } 2825 2826 // If the callee takes no arguments then go on to check the results of the 2827 // call. 2828 if (!Outs.empty()) { 2829 // Check if stack adjustment is needed. For now, do not do this if any 2830 // argument is passed on the stack. 2831 SmallVector<CCValAssign, 16> ArgLocs; 2832 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2833 getTargetMachine(), ArgLocs, *DAG.getContext()); 2834 2835 // Allocate shadow area for Win64 2836 if (Subtarget->isTargetWin64()) { 2837 CCInfo.AllocateStack(32, 8); 2838 } 2839 2840 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2841 if (CCInfo.getNextStackOffset()) { 2842 MachineFunction &MF = DAG.getMachineFunction(); 2843 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) 2844 return false; 2845 2846 // Check if the arguments are already laid out in the right way as 2847 // the caller's fixed stack objects. 2848 MachineFrameInfo *MFI = MF.getFrameInfo(); 2849 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2850 const X86InstrInfo *TII = 2851 ((X86TargetMachine&)getTargetMachine()).getInstrInfo(); 2852 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2853 CCValAssign &VA = ArgLocs[i]; 2854 SDValue Arg = OutVals[i]; 2855 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2856 if (VA.getLocInfo() == CCValAssign::Indirect) 2857 return false; 2858 if (!VA.isRegLoc()) { 2859 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2860 MFI, MRI, TII)) 2861 return false; 2862 } 2863 } 2864 } 2865 2866 // If the tailcall address may be in a register, then make sure it's 2867 // possible to register allocate for it. In 32-bit, the call address can 2868 // only target EAX, EDX, or ECX since the tail call must be scheduled after 2869 // callee-saved registers are restored. These happen to be the same 2870 // registers used to pass 'inreg' arguments so watch out for those. 2871 if (!Subtarget->is64Bit() && 2872 !isa<GlobalAddressSDNode>(Callee) && 2873 !isa<ExternalSymbolSDNode>(Callee)) { 2874 unsigned NumInRegs = 0; 2875 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2876 CCValAssign &VA = ArgLocs[i]; 2877 if (!VA.isRegLoc()) 2878 continue; 2879 unsigned Reg = VA.getLocReg(); 2880 switch (Reg) { 2881 default: break; 2882 case X86::EAX: case X86::EDX: case X86::ECX: 2883 if (++NumInRegs == 3) 2884 return false; 2885 break; 2886 } 2887 } 2888 } 2889 } 2890 2891 return true; 2892} 2893 2894FastISel * 2895X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 2896 const TargetLibraryInfo *libInfo) const { 2897 return X86::createFastISel(funcInfo, libInfo); 2898} 2899 2900 2901//===----------------------------------------------------------------------===// 2902// Other Lowering Hooks 2903//===----------------------------------------------------------------------===// 2904 2905static bool MayFoldLoad(SDValue Op) { 2906 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode()); 2907} 2908 2909static bool MayFoldIntoStore(SDValue Op) { 2910 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin()); 2911} 2912 2913static bool isTargetShuffle(unsigned Opcode) { 2914 switch(Opcode) { 2915 default: return false; 2916 case X86ISD::PSHUFD: 2917 case X86ISD::PSHUFHW: 2918 case X86ISD::PSHUFLW: 2919 case X86ISD::SHUFP: 2920 case X86ISD::PALIGN: 2921 case X86ISD::MOVLHPS: 2922 case X86ISD::MOVLHPD: 2923 case X86ISD::MOVHLPS: 2924 case X86ISD::MOVLPS: 2925 case X86ISD::MOVLPD: 2926 case X86ISD::MOVSHDUP: 2927 case X86ISD::MOVSLDUP: 2928 case X86ISD::MOVDDUP: 2929 case X86ISD::MOVSS: 2930 case X86ISD::MOVSD: 2931 case X86ISD::UNPCKL: 2932 case X86ISD::UNPCKH: 2933 case X86ISD::VPERMILP: 2934 case X86ISD::VPERM2X128: 2935 case X86ISD::VPERMI: 2936 return true; 2937 } 2938} 2939 2940static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2941 SDValue V1, SelectionDAG &DAG) { 2942 switch(Opc) { 2943 default: llvm_unreachable("Unknown x86 shuffle node"); 2944 case X86ISD::MOVSHDUP: 2945 case X86ISD::MOVSLDUP: 2946 case X86ISD::MOVDDUP: 2947 return DAG.getNode(Opc, dl, VT, V1); 2948 } 2949} 2950 2951static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2952 SDValue V1, unsigned TargetMask, 2953 SelectionDAG &DAG) { 2954 switch(Opc) { 2955 default: llvm_unreachable("Unknown x86 shuffle node"); 2956 case X86ISD::PSHUFD: 2957 case X86ISD::PSHUFHW: 2958 case X86ISD::PSHUFLW: 2959 case X86ISD::VPERMILP: 2960 case X86ISD::VPERMI: 2961 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8)); 2962 } 2963} 2964 2965static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2966 SDValue V1, SDValue V2, unsigned TargetMask, 2967 SelectionDAG &DAG) { 2968 switch(Opc) { 2969 default: llvm_unreachable("Unknown x86 shuffle node"); 2970 case X86ISD::PALIGN: 2971 case X86ISD::SHUFP: 2972 case X86ISD::VPERM2X128: 2973 return DAG.getNode(Opc, dl, VT, V1, V2, 2974 DAG.getConstant(TargetMask, MVT::i8)); 2975 } 2976} 2977 2978static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2979 SDValue V1, SDValue V2, SelectionDAG &DAG) { 2980 switch(Opc) { 2981 default: llvm_unreachable("Unknown x86 shuffle node"); 2982 case X86ISD::MOVLHPS: 2983 case X86ISD::MOVLHPD: 2984 case X86ISD::MOVHLPS: 2985 case X86ISD::MOVLPS: 2986 case X86ISD::MOVLPD: 2987 case X86ISD::MOVSS: 2988 case X86ISD::MOVSD: 2989 case X86ISD::UNPCKL: 2990 case X86ISD::UNPCKH: 2991 return DAG.getNode(Opc, dl, VT, V1, V2); 2992 } 2993} 2994 2995SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const { 2996 MachineFunction &MF = DAG.getMachineFunction(); 2997 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 2998 int ReturnAddrIndex = FuncInfo->getRAIndex(); 2999 3000 if (ReturnAddrIndex == 0) { 3001 // Set up a frame object for the return address. 3002 uint64_t SlotSize = TD->getPointerSize(); 3003 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize, 3004 false); 3005 FuncInfo->setRAIndex(ReturnAddrIndex); 3006 } 3007 3008 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy()); 3009} 3010 3011 3012bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M, 3013 bool hasSymbolicDisplacement) { 3014 // Offset should fit into 32 bit immediate field. 3015 if (!isInt<32>(Offset)) 3016 return false; 3017 3018 // If we don't have a symbolic displacement - we don't have any extra 3019 // restrictions. 3020 if (!hasSymbolicDisplacement) 3021 return true; 3022 3023 // FIXME: Some tweaks might be needed for medium code model. 3024 if (M != CodeModel::Small && M != CodeModel::Kernel) 3025 return false; 3026 3027 // For small code model we assume that latest object is 16MB before end of 31 3028 // bits boundary. We may also accept pretty large negative constants knowing 3029 // that all objects are in the positive half of address space. 3030 if (M == CodeModel::Small && Offset < 16*1024*1024) 3031 return true; 3032 3033 // For kernel code model we know that all object resist in the negative half 3034 // of 32bits address space. We may not accept negative offsets, since they may 3035 // be just off and we may accept pretty large positive ones. 3036 if (M == CodeModel::Kernel && Offset > 0) 3037 return true; 3038 3039 return false; 3040} 3041 3042/// isCalleePop - Determines whether the callee is required to pop its 3043/// own arguments. Callee pop is necessary to support tail calls. 3044bool X86::isCalleePop(CallingConv::ID CallingConv, 3045 bool is64Bit, bool IsVarArg, bool TailCallOpt) { 3046 if (IsVarArg) 3047 return false; 3048 3049 switch (CallingConv) { 3050 default: 3051 return false; 3052 case CallingConv::X86_StdCall: 3053 return !is64Bit; 3054 case CallingConv::X86_FastCall: 3055 return !is64Bit; 3056 case CallingConv::X86_ThisCall: 3057 return !is64Bit; 3058 case CallingConv::Fast: 3059 return TailCallOpt; 3060 case CallingConv::GHC: 3061 return TailCallOpt; 3062 } 3063} 3064 3065/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86 3066/// specific condition code, returning the condition code and the LHS/RHS of the 3067/// comparison to make. 3068static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP, 3069 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) { 3070 if (!isFP) { 3071 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 3072 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) { 3073 // X > -1 -> X == 0, jump !sign. 3074 RHS = DAG.getConstant(0, RHS.getValueType()); 3075 return X86::COND_NS; 3076 } 3077 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) { 3078 // X < 0 -> X == 0, jump on sign. 3079 return X86::COND_S; 3080 } 3081 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) { 3082 // X < 1 -> X <= 0 3083 RHS = DAG.getConstant(0, RHS.getValueType()); 3084 return X86::COND_LE; 3085 } 3086 } 3087 3088 switch (SetCCOpcode) { 3089 default: llvm_unreachable("Invalid integer condition!"); 3090 case ISD::SETEQ: return X86::COND_E; 3091 case ISD::SETGT: return X86::COND_G; 3092 case ISD::SETGE: return X86::COND_GE; 3093 case ISD::SETLT: return X86::COND_L; 3094 case ISD::SETLE: return X86::COND_LE; 3095 case ISD::SETNE: return X86::COND_NE; 3096 case ISD::SETULT: return X86::COND_B; 3097 case ISD::SETUGT: return X86::COND_A; 3098 case ISD::SETULE: return X86::COND_BE; 3099 case ISD::SETUGE: return X86::COND_AE; 3100 } 3101 } 3102 3103 // First determine if it is required or is profitable to flip the operands. 3104 3105 // If LHS is a foldable load, but RHS is not, flip the condition. 3106 if (ISD::isNON_EXTLoad(LHS.getNode()) && 3107 !ISD::isNON_EXTLoad(RHS.getNode())) { 3108 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode); 3109 std::swap(LHS, RHS); 3110 } 3111 3112 switch (SetCCOpcode) { 3113 default: break; 3114 case ISD::SETOLT: 3115 case ISD::SETOLE: 3116 case ISD::SETUGT: 3117 case ISD::SETUGE: 3118 std::swap(LHS, RHS); 3119 break; 3120 } 3121 3122 // On a floating point condition, the flags are set as follows: 3123 // ZF PF CF op 3124 // 0 | 0 | 0 | X > Y 3125 // 0 | 0 | 1 | X < Y 3126 // 1 | 0 | 0 | X == Y 3127 // 1 | 1 | 1 | unordered 3128 switch (SetCCOpcode) { 3129 default: llvm_unreachable("Condcode should be pre-legalized away"); 3130 case ISD::SETUEQ: 3131 case ISD::SETEQ: return X86::COND_E; 3132 case ISD::SETOLT: // flipped 3133 case ISD::SETOGT: 3134 case ISD::SETGT: return X86::COND_A; 3135 case ISD::SETOLE: // flipped 3136 case ISD::SETOGE: 3137 case ISD::SETGE: return X86::COND_AE; 3138 case ISD::SETUGT: // flipped 3139 case ISD::SETULT: 3140 case ISD::SETLT: return X86::COND_B; 3141 case ISD::SETUGE: // flipped 3142 case ISD::SETULE: 3143 case ISD::SETLE: return X86::COND_BE; 3144 case ISD::SETONE: 3145 case ISD::SETNE: return X86::COND_NE; 3146 case ISD::SETUO: return X86::COND_P; 3147 case ISD::SETO: return X86::COND_NP; 3148 case ISD::SETOEQ: 3149 case ISD::SETUNE: return X86::COND_INVALID; 3150 } 3151} 3152 3153/// hasFPCMov - is there a floating point cmov for the specific X86 condition 3154/// code. Current x86 isa includes the following FP cmov instructions: 3155/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu. 3156static bool hasFPCMov(unsigned X86CC) { 3157 switch (X86CC) { 3158 default: 3159 return false; 3160 case X86::COND_B: 3161 case X86::COND_BE: 3162 case X86::COND_E: 3163 case X86::COND_P: 3164 case X86::COND_A: 3165 case X86::COND_AE: 3166 case X86::COND_NE: 3167 case X86::COND_NP: 3168 return true; 3169 } 3170} 3171 3172/// isFPImmLegal - Returns true if the target can instruction select the 3173/// specified FP immediate natively. If false, the legalizer will 3174/// materialize the FP immediate as a load from a constant pool. 3175bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 3176 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) { 3177 if (Imm.bitwiseIsEqual(LegalFPImmediates[i])) 3178 return true; 3179 } 3180 return false; 3181} 3182 3183/// isUndefOrInRange - Return true if Val is undef or if its value falls within 3184/// the specified range (L, H]. 3185static bool isUndefOrInRange(int Val, int Low, int Hi) { 3186 return (Val < 0) || (Val >= Low && Val < Hi); 3187} 3188 3189/// isUndefOrEqual - Val is either less than zero (undef) or equal to the 3190/// specified value. 3191static bool isUndefOrEqual(int Val, int CmpVal) { 3192 if (Val < 0 || Val == CmpVal) 3193 return true; 3194 return false; 3195} 3196 3197/// isSequentialOrUndefInRange - Return true if every element in Mask, beginning 3198/// from position Pos and ending in Pos+Size, falls within the specified 3199/// sequential range (L, L+Pos]. or is undef. 3200static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, 3201 unsigned Pos, unsigned Size, int Low) { 3202 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low) 3203 if (!isUndefOrEqual(Mask[i], Low)) 3204 return false; 3205 return true; 3206} 3207 3208/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that 3209/// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference 3210/// the second operand. 3211static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) { 3212 if (VT == MVT::v4f32 || VT == MVT::v4i32 ) 3213 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4); 3214 if (VT == MVT::v2f64 || VT == MVT::v2i64) 3215 return (Mask[0] < 2 && Mask[1] < 2); 3216 return false; 3217} 3218 3219/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that 3220/// is suitable for input to PSHUFHW. 3221static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) { 3222 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16)) 3223 return false; 3224 3225 // Lower quadword copied in order or undef. 3226 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0)) 3227 return false; 3228 3229 // Upper quadword shuffled. 3230 for (unsigned i = 4; i != 8; ++i) 3231 if (!isUndefOrInRange(Mask[i], 4, 8)) 3232 return false; 3233 3234 if (VT == MVT::v16i16) { 3235 // Lower quadword copied in order or undef. 3236 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8)) 3237 return false; 3238 3239 // Upper quadword shuffled. 3240 for (unsigned i = 12; i != 16; ++i) 3241 if (!isUndefOrInRange(Mask[i], 12, 16)) 3242 return false; 3243 } 3244 3245 return true; 3246} 3247 3248/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that 3249/// is suitable for input to PSHUFLW. 3250static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) { 3251 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16)) 3252 return false; 3253 3254 // Upper quadword copied in order. 3255 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4)) 3256 return false; 3257 3258 // Lower quadword shuffled. 3259 for (unsigned i = 0; i != 4; ++i) 3260 if (!isUndefOrInRange(Mask[i], 0, 4)) 3261 return false; 3262 3263 if (VT == MVT::v16i16) { 3264 // Upper quadword copied in order. 3265 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12)) 3266 return false; 3267 3268 // Lower quadword shuffled. 3269 for (unsigned i = 8; i != 12; ++i) 3270 if (!isUndefOrInRange(Mask[i], 8, 12)) 3271 return false; 3272 } 3273 3274 return true; 3275} 3276 3277/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that 3278/// is suitable for input to PALIGNR. 3279static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT, 3280 const X86Subtarget *Subtarget) { 3281 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) || 3282 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())) 3283 return false; 3284 3285 unsigned NumElts = VT.getVectorNumElements(); 3286 unsigned NumLanes = VT.getSizeInBits()/128; 3287 unsigned NumLaneElts = NumElts/NumLanes; 3288 3289 // Do not handle 64-bit element shuffles with palignr. 3290 if (NumLaneElts == 2) 3291 return false; 3292 3293 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) { 3294 unsigned i; 3295 for (i = 0; i != NumLaneElts; ++i) { 3296 if (Mask[i+l] >= 0) 3297 break; 3298 } 3299 3300 // Lane is all undef, go to next lane 3301 if (i == NumLaneElts) 3302 continue; 3303 3304 int Start = Mask[i+l]; 3305 3306 // Make sure its in this lane in one of the sources 3307 if (!isUndefOrInRange(Start, l, l+NumLaneElts) && 3308 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts)) 3309 return false; 3310 3311 // If not lane 0, then we must match lane 0 3312 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l)) 3313 return false; 3314 3315 // Correct second source to be contiguous with first source 3316 if (Start >= (int)NumElts) 3317 Start -= NumElts - NumLaneElts; 3318 3319 // Make sure we're shifting in the right direction. 3320 if (Start <= (int)(i+l)) 3321 return false; 3322 3323 Start -= i; 3324 3325 // Check the rest of the elements to see if they are consecutive. 3326 for (++i; i != NumLaneElts; ++i) { 3327 int Idx = Mask[i+l]; 3328 3329 // Make sure its in this lane 3330 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) && 3331 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts)) 3332 return false; 3333 3334 // If not lane 0, then we must match lane 0 3335 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l)) 3336 return false; 3337 3338 if (Idx >= (int)NumElts) 3339 Idx -= NumElts - NumLaneElts; 3340 3341 if (!isUndefOrEqual(Idx, Start+i)) 3342 return false; 3343 3344 } 3345 } 3346 3347 return true; 3348} 3349 3350/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming 3351/// the two vector operands have swapped position. 3352static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, 3353 unsigned NumElems) { 3354 for (unsigned i = 0; i != NumElems; ++i) { 3355 int idx = Mask[i]; 3356 if (idx < 0) 3357 continue; 3358 else if (idx < (int)NumElems) 3359 Mask[i] = idx + NumElems; 3360 else 3361 Mask[i] = idx - NumElems; 3362 } 3363} 3364 3365/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand 3366/// specifies a shuffle of elements that is suitable for input to 128/256-bit 3367/// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be 3368/// reverse of what x86 shuffles want. 3369static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX, 3370 bool Commuted = false) { 3371 if (!HasAVX && VT.getSizeInBits() == 256) 3372 return false; 3373 3374 unsigned NumElems = VT.getVectorNumElements(); 3375 unsigned NumLanes = VT.getSizeInBits()/128; 3376 unsigned NumLaneElems = NumElems/NumLanes; 3377 3378 if (NumLaneElems != 2 && NumLaneElems != 4) 3379 return false; 3380 3381 // VSHUFPSY divides the resulting vector into 4 chunks. 3382 // The sources are also splitted into 4 chunks, and each destination 3383 // chunk must come from a different source chunk. 3384 // 3385 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0 3386 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9 3387 // 3388 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4, 3389 // Y3..Y0, Y3..Y0, X3..X0, X3..X0 3390 // 3391 // VSHUFPDY divides the resulting vector into 4 chunks. 3392 // The sources are also splitted into 4 chunks, and each destination 3393 // chunk must come from a different source chunk. 3394 // 3395 // SRC1 => X3 X2 X1 X0 3396 // SRC2 => Y3 Y2 Y1 Y0 3397 // 3398 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0 3399 // 3400 unsigned HalfLaneElems = NumLaneElems/2; 3401 for (unsigned l = 0; l != NumElems; l += NumLaneElems) { 3402 for (unsigned i = 0; i != NumLaneElems; ++i) { 3403 int Idx = Mask[i+l]; 3404 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0); 3405 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems)) 3406 return false; 3407 // For VSHUFPSY, the mask of the second half must be the same as the 3408 // first but with the appropriate offsets. This works in the same way as 3409 // VPERMILPS works with masks. 3410 if (NumElems != 8 || l == 0 || Mask[i] < 0) 3411 continue; 3412 if (!isUndefOrEqual(Idx, Mask[i]+l)) 3413 return false; 3414 } 3415 } 3416 3417 return true; 3418} 3419 3420/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand 3421/// specifies a shuffle of elements that is suitable for input to MOVHLPS. 3422static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) { 3423 unsigned NumElems = VT.getVectorNumElements(); 3424 3425 if (VT.getSizeInBits() != 128) 3426 return false; 3427 3428 if (NumElems != 4) 3429 return false; 3430 3431 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3 3432 return isUndefOrEqual(Mask[0], 6) && 3433 isUndefOrEqual(Mask[1], 7) && 3434 isUndefOrEqual(Mask[2], 2) && 3435 isUndefOrEqual(Mask[3], 3); 3436} 3437 3438/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form 3439/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef, 3440/// <2, 3, 2, 3> 3441static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) { 3442 unsigned NumElems = VT.getVectorNumElements(); 3443 3444 if (VT.getSizeInBits() != 128) 3445 return false; 3446 3447 if (NumElems != 4) 3448 return false; 3449 3450 return isUndefOrEqual(Mask[0], 2) && 3451 isUndefOrEqual(Mask[1], 3) && 3452 isUndefOrEqual(Mask[2], 2) && 3453 isUndefOrEqual(Mask[3], 3); 3454} 3455 3456/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand 3457/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}. 3458static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) { 3459 if (VT.getSizeInBits() != 128) 3460 return false; 3461 3462 unsigned NumElems = VT.getVectorNumElements(); 3463 3464 if (NumElems != 2 && NumElems != 4) 3465 return false; 3466 3467 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3468 if (!isUndefOrEqual(Mask[i], i + NumElems)) 3469 return false; 3470 3471 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i) 3472 if (!isUndefOrEqual(Mask[i], i)) 3473 return false; 3474 3475 return true; 3476} 3477 3478/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand 3479/// specifies a shuffle of elements that is suitable for input to MOVLHPS. 3480static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) { 3481 unsigned NumElems = VT.getVectorNumElements(); 3482 3483 if ((NumElems != 2 && NumElems != 4) 3484 || VT.getSizeInBits() > 128) 3485 return false; 3486 3487 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3488 if (!isUndefOrEqual(Mask[i], i)) 3489 return false; 3490 3491 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3492 if (!isUndefOrEqual(Mask[i + e], i + NumElems)) 3493 return false; 3494 3495 return true; 3496} 3497 3498// 3499// Some special combinations that can be optimized. 3500// 3501static 3502SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp, 3503 SelectionDAG &DAG) { 3504 EVT VT = SVOp->getValueType(0); 3505 DebugLoc dl = SVOp->getDebugLoc(); 3506 3507 if (VT != MVT::v8i32 && VT != MVT::v8f32) 3508 return SDValue(); 3509 3510 ArrayRef<int> Mask = SVOp->getMask(); 3511 3512 // These are the special masks that may be optimized. 3513 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14}; 3514 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15}; 3515 bool MatchEvenMask = true; 3516 bool MatchOddMask = true; 3517 for (int i=0; i<8; ++i) { 3518 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i])) 3519 MatchEvenMask = false; 3520 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i])) 3521 MatchOddMask = false; 3522 } 3523 static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1}; 3524 static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1}; 3525 3526 const int *CompactionMask; 3527 if (MatchEvenMask) 3528 CompactionMask = CompactionMaskEven; 3529 else if (MatchOddMask) 3530 CompactionMask = CompactionMaskOdd; 3531 else 3532 return SDValue(); 3533 3534 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT); 3535 3536 SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0), 3537 UndefNode, CompactionMask); 3538 SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1), 3539 UndefNode, CompactionMask); 3540 static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13}; 3541 return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask); 3542} 3543 3544/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand 3545/// specifies a shuffle of elements that is suitable for input to UNPCKL. 3546static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT, 3547 bool HasAVX2, bool V2IsSplat = false) { 3548 unsigned NumElts = VT.getVectorNumElements(); 3549 3550 assert((VT.is128BitVector() || VT.is256BitVector()) && 3551 "Unsupported vector type for unpckh"); 3552 3553 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 && 3554 (!HasAVX2 || (NumElts != 16 && NumElts != 32))) 3555 return false; 3556 3557 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3558 // independently on 128-bit lanes. 3559 unsigned NumLanes = VT.getSizeInBits()/128; 3560 unsigned NumLaneElts = NumElts/NumLanes; 3561 3562 for (unsigned l = 0; l != NumLanes; ++l) { 3563 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts; 3564 i != (l+1)*NumLaneElts; 3565 i += 2, ++j) { 3566 int BitI = Mask[i]; 3567 int BitI1 = Mask[i+1]; 3568 if (!isUndefOrEqual(BitI, j)) 3569 return false; 3570 if (V2IsSplat) { 3571 if (!isUndefOrEqual(BitI1, NumElts)) 3572 return false; 3573 } else { 3574 if (!isUndefOrEqual(BitI1, j + NumElts)) 3575 return false; 3576 } 3577 } 3578 } 3579 3580 return true; 3581} 3582 3583/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand 3584/// specifies a shuffle of elements that is suitable for input to UNPCKH. 3585static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT, 3586 bool HasAVX2, bool V2IsSplat = false) { 3587 unsigned NumElts = VT.getVectorNumElements(); 3588 3589 assert((VT.is128BitVector() || VT.is256BitVector()) && 3590 "Unsupported vector type for unpckh"); 3591 3592 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 && 3593 (!HasAVX2 || (NumElts != 16 && NumElts != 32))) 3594 return false; 3595 3596 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3597 // independently on 128-bit lanes. 3598 unsigned NumLanes = VT.getSizeInBits()/128; 3599 unsigned NumLaneElts = NumElts/NumLanes; 3600 3601 for (unsigned l = 0; l != NumLanes; ++l) { 3602 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2; 3603 i != (l+1)*NumLaneElts; i += 2, ++j) { 3604 int BitI = Mask[i]; 3605 int BitI1 = Mask[i+1]; 3606 if (!isUndefOrEqual(BitI, j)) 3607 return false; 3608 if (V2IsSplat) { 3609 if (isUndefOrEqual(BitI1, NumElts)) 3610 return false; 3611 } else { 3612 if (!isUndefOrEqual(BitI1, j+NumElts)) 3613 return false; 3614 } 3615 } 3616 } 3617 return true; 3618} 3619 3620/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form 3621/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef, 3622/// <0, 0, 1, 1> 3623static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, 3624 bool HasAVX2) { 3625 unsigned NumElts = VT.getVectorNumElements(); 3626 3627 assert((VT.is128BitVector() || VT.is256BitVector()) && 3628 "Unsupported vector type for unpckh"); 3629 3630 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 && 3631 (!HasAVX2 || (NumElts != 16 && NumElts != 32))) 3632 return false; 3633 3634 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern 3635 // FIXME: Need a better way to get rid of this, there's no latency difference 3636 // between UNPCKLPD and MOVDDUP, the later should always be checked first and 3637 // the former later. We should also remove the "_undef" special mask. 3638 if (NumElts == 4 && VT.getSizeInBits() == 256) 3639 return false; 3640 3641 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3642 // independently on 128-bit lanes. 3643 unsigned NumLanes = VT.getSizeInBits()/128; 3644 unsigned NumLaneElts = NumElts/NumLanes; 3645 3646 for (unsigned l = 0; l != NumLanes; ++l) { 3647 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts; 3648 i != (l+1)*NumLaneElts; 3649 i += 2, ++j) { 3650 int BitI = Mask[i]; 3651 int BitI1 = Mask[i+1]; 3652 3653 if (!isUndefOrEqual(BitI, j)) 3654 return false; 3655 if (!isUndefOrEqual(BitI1, j)) 3656 return false; 3657 } 3658 } 3659 3660 return true; 3661} 3662 3663/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form 3664/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef, 3665/// <2, 2, 3, 3> 3666static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) { 3667 unsigned NumElts = VT.getVectorNumElements(); 3668 3669 assert((VT.is128BitVector() || VT.is256BitVector()) && 3670 "Unsupported vector type for unpckh"); 3671 3672 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 && 3673 (!HasAVX2 || (NumElts != 16 && NumElts != 32))) 3674 return false; 3675 3676 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3677 // independently on 128-bit lanes. 3678 unsigned NumLanes = VT.getSizeInBits()/128; 3679 unsigned NumLaneElts = NumElts/NumLanes; 3680 3681 for (unsigned l = 0; l != NumLanes; ++l) { 3682 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2; 3683 i != (l+1)*NumLaneElts; i += 2, ++j) { 3684 int BitI = Mask[i]; 3685 int BitI1 = Mask[i+1]; 3686 if (!isUndefOrEqual(BitI, j)) 3687 return false; 3688 if (!isUndefOrEqual(BitI1, j)) 3689 return false; 3690 } 3691 } 3692 return true; 3693} 3694 3695/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand 3696/// specifies a shuffle of elements that is suitable for input to MOVSS, 3697/// MOVSD, and MOVD, i.e. setting the lowest element. 3698static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) { 3699 if (VT.getVectorElementType().getSizeInBits() < 32) 3700 return false; 3701 if (VT.getSizeInBits() == 256) 3702 return false; 3703 3704 unsigned NumElts = VT.getVectorNumElements(); 3705 3706 if (!isUndefOrEqual(Mask[0], NumElts)) 3707 return false; 3708 3709 for (unsigned i = 1; i != NumElts; ++i) 3710 if (!isUndefOrEqual(Mask[i], i)) 3711 return false; 3712 3713 return true; 3714} 3715 3716/// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered 3717/// as permutations between 128-bit chunks or halves. As an example: this 3718/// shuffle bellow: 3719/// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15> 3720/// The first half comes from the second half of V1 and the second half from the 3721/// the second half of V2. 3722static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) { 3723 if (!HasAVX || VT.getSizeInBits() != 256) 3724 return false; 3725 3726 // The shuffle result is divided into half A and half B. In total the two 3727 // sources have 4 halves, namely: C, D, E, F. The final values of A and 3728 // B must come from C, D, E or F. 3729 unsigned HalfSize = VT.getVectorNumElements()/2; 3730 bool MatchA = false, MatchB = false; 3731 3732 // Check if A comes from one of C, D, E, F. 3733 for (unsigned Half = 0; Half != 4; ++Half) { 3734 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) { 3735 MatchA = true; 3736 break; 3737 } 3738 } 3739 3740 // Check if B comes from one of C, D, E, F. 3741 for (unsigned Half = 0; Half != 4; ++Half) { 3742 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) { 3743 MatchB = true; 3744 break; 3745 } 3746 } 3747 3748 return MatchA && MatchB; 3749} 3750 3751/// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle 3752/// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions. 3753static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) { 3754 EVT VT = SVOp->getValueType(0); 3755 3756 unsigned HalfSize = VT.getVectorNumElements()/2; 3757 3758 unsigned FstHalf = 0, SndHalf = 0; 3759 for (unsigned i = 0; i < HalfSize; ++i) { 3760 if (SVOp->getMaskElt(i) > 0) { 3761 FstHalf = SVOp->getMaskElt(i)/HalfSize; 3762 break; 3763 } 3764 } 3765 for (unsigned i = HalfSize; i < HalfSize*2; ++i) { 3766 if (SVOp->getMaskElt(i) > 0) { 3767 SndHalf = SVOp->getMaskElt(i)/HalfSize; 3768 break; 3769 } 3770 } 3771 3772 return (FstHalf | (SndHalf << 4)); 3773} 3774 3775/// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand 3776/// specifies a shuffle of elements that is suitable for input to VPERMILPD*. 3777/// Note that VPERMIL mask matching is different depending whether theunderlying 3778/// type is 32 or 64. In the VPERMILPS the high half of the mask should point 3779/// to the same elements of the low, but to the higher half of the source. 3780/// In VPERMILPD the two lanes could be shuffled independently of each other 3781/// with the same restriction that lanes can't be crossed. Also handles PSHUFDY. 3782static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) { 3783 if (!HasAVX) 3784 return false; 3785 3786 unsigned NumElts = VT.getVectorNumElements(); 3787 // Only match 256-bit with 32/64-bit types 3788 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8)) 3789 return false; 3790 3791 unsigned NumLanes = VT.getSizeInBits()/128; 3792 unsigned LaneSize = NumElts/NumLanes; 3793 for (unsigned l = 0; l != NumElts; l += LaneSize) { 3794 for (unsigned i = 0; i != LaneSize; ++i) { 3795 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize)) 3796 return false; 3797 if (NumElts != 8 || l == 0) 3798 continue; 3799 // VPERMILPS handling 3800 if (Mask[i] < 0) 3801 continue; 3802 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l)) 3803 return false; 3804 } 3805 } 3806 3807 return true; 3808} 3809 3810/// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse 3811/// of what x86 movss want. X86 movs requires the lowest element to be lowest 3812/// element of vector 2 and the other elements to come from vector 1 in order. 3813static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT, 3814 bool V2IsSplat = false, bool V2IsUndef = false) { 3815 unsigned NumOps = VT.getVectorNumElements(); 3816 if (VT.getSizeInBits() == 256) 3817 return false; 3818 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16) 3819 return false; 3820 3821 if (!isUndefOrEqual(Mask[0], 0)) 3822 return false; 3823 3824 for (unsigned i = 1; i != NumOps; ++i) 3825 if (!(isUndefOrEqual(Mask[i], i+NumOps) || 3826 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) || 3827 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps)))) 3828 return false; 3829 3830 return true; 3831} 3832 3833/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3834/// specifies a shuffle of elements that is suitable for input to MOVSHDUP. 3835/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7> 3836static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT, 3837 const X86Subtarget *Subtarget) { 3838 if (!Subtarget->hasSSE3()) 3839 return false; 3840 3841 unsigned NumElems = VT.getVectorNumElements(); 3842 3843 if ((VT.getSizeInBits() == 128 && NumElems != 4) || 3844 (VT.getSizeInBits() == 256 && NumElems != 8)) 3845 return false; 3846 3847 // "i+1" is the value the indexed mask element must have 3848 for (unsigned i = 0; i != NumElems; i += 2) 3849 if (!isUndefOrEqual(Mask[i], i+1) || 3850 !isUndefOrEqual(Mask[i+1], i+1)) 3851 return false; 3852 3853 return true; 3854} 3855 3856/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3857/// specifies a shuffle of elements that is suitable for input to MOVSLDUP. 3858/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6> 3859static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT, 3860 const X86Subtarget *Subtarget) { 3861 if (!Subtarget->hasSSE3()) 3862 return false; 3863 3864 unsigned NumElems = VT.getVectorNumElements(); 3865 3866 if ((VT.getSizeInBits() == 128 && NumElems != 4) || 3867 (VT.getSizeInBits() == 256 && NumElems != 8)) 3868 return false; 3869 3870 // "i" is the value the indexed mask element must have 3871 for (unsigned i = 0; i != NumElems; i += 2) 3872 if (!isUndefOrEqual(Mask[i], i) || 3873 !isUndefOrEqual(Mask[i+1], i)) 3874 return false; 3875 3876 return true; 3877} 3878 3879/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand 3880/// specifies a shuffle of elements that is suitable for input to 256-bit 3881/// version of MOVDDUP. 3882static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) { 3883 unsigned NumElts = VT.getVectorNumElements(); 3884 3885 if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4) 3886 return false; 3887 3888 for (unsigned i = 0; i != NumElts/2; ++i) 3889 if (!isUndefOrEqual(Mask[i], 0)) 3890 return false; 3891 for (unsigned i = NumElts/2; i != NumElts; ++i) 3892 if (!isUndefOrEqual(Mask[i], NumElts/2)) 3893 return false; 3894 return true; 3895} 3896 3897/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3898/// specifies a shuffle of elements that is suitable for input to 128-bit 3899/// version of MOVDDUP. 3900static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) { 3901 if (VT.getSizeInBits() != 128) 3902 return false; 3903 3904 unsigned e = VT.getVectorNumElements() / 2; 3905 for (unsigned i = 0; i != e; ++i) 3906 if (!isUndefOrEqual(Mask[i], i)) 3907 return false; 3908 for (unsigned i = 0; i != e; ++i) 3909 if (!isUndefOrEqual(Mask[e+i], i)) 3910 return false; 3911 return true; 3912} 3913 3914/// isVEXTRACTF128Index - Return true if the specified 3915/// EXTRACT_SUBVECTOR operand specifies a vector extract that is 3916/// suitable for input to VEXTRACTF128. 3917bool X86::isVEXTRACTF128Index(SDNode *N) { 3918 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 3919 return false; 3920 3921 // The index should be aligned on a 128-bit boundary. 3922 uint64_t Index = 3923 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 3924 3925 unsigned VL = N->getValueType(0).getVectorNumElements(); 3926 unsigned VBits = N->getValueType(0).getSizeInBits(); 3927 unsigned ElSize = VBits / VL; 3928 bool Result = (Index * ElSize) % 128 == 0; 3929 3930 return Result; 3931} 3932 3933/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR 3934/// operand specifies a subvector insert that is suitable for input to 3935/// VINSERTF128. 3936bool X86::isVINSERTF128Index(SDNode *N) { 3937 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 3938 return false; 3939 3940 // The index should be aligned on a 128-bit boundary. 3941 uint64_t Index = 3942 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 3943 3944 unsigned VL = N->getValueType(0).getVectorNumElements(); 3945 unsigned VBits = N->getValueType(0).getSizeInBits(); 3946 unsigned ElSize = VBits / VL; 3947 bool Result = (Index * ElSize) % 128 == 0; 3948 3949 return Result; 3950} 3951 3952/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle 3953/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions. 3954/// Handles 128-bit and 256-bit. 3955static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) { 3956 EVT VT = N->getValueType(0); 3957 3958 assert((VT.is128BitVector() || VT.is256BitVector()) && 3959 "Unsupported vector type for PSHUF/SHUFP"); 3960 3961 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate 3962 // independently on 128-bit lanes. 3963 unsigned NumElts = VT.getVectorNumElements(); 3964 unsigned NumLanes = VT.getSizeInBits()/128; 3965 unsigned NumLaneElts = NumElts/NumLanes; 3966 3967 assert((NumLaneElts == 2 || NumLaneElts == 4) && 3968 "Only supports 2 or 4 elements per lane"); 3969 3970 unsigned Shift = (NumLaneElts == 4) ? 1 : 0; 3971 unsigned Mask = 0; 3972 for (unsigned i = 0; i != NumElts; ++i) { 3973 int Elt = N->getMaskElt(i); 3974 if (Elt < 0) continue; 3975 Elt &= NumLaneElts - 1; 3976 unsigned ShAmt = (i << Shift) % 8; 3977 Mask |= Elt << ShAmt; 3978 } 3979 3980 return Mask; 3981} 3982 3983/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle 3984/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction. 3985static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) { 3986 EVT VT = N->getValueType(0); 3987 3988 assert((VT == MVT::v8i16 || VT == MVT::v16i16) && 3989 "Unsupported vector type for PSHUFHW"); 3990 3991 unsigned NumElts = VT.getVectorNumElements(); 3992 3993 unsigned Mask = 0; 3994 for (unsigned l = 0; l != NumElts; l += 8) { 3995 // 8 nodes per lane, but we only care about the last 4. 3996 for (unsigned i = 0; i < 4; ++i) { 3997 int Elt = N->getMaskElt(l+i+4); 3998 if (Elt < 0) continue; 3999 Elt &= 0x3; // only 2-bits. 4000 Mask |= Elt << (i * 2); 4001 } 4002 } 4003 4004 return Mask; 4005} 4006 4007/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle 4008/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction. 4009static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) { 4010 EVT VT = N->getValueType(0); 4011 4012 assert((VT == MVT::v8i16 || VT == MVT::v16i16) && 4013 "Unsupported vector type for PSHUFHW"); 4014 4015 unsigned NumElts = VT.getVectorNumElements(); 4016 4017 unsigned Mask = 0; 4018 for (unsigned l = 0; l != NumElts; l += 8) { 4019 // 8 nodes per lane, but we only care about the first 4. 4020 for (unsigned i = 0; i < 4; ++i) { 4021 int Elt = N->getMaskElt(l+i); 4022 if (Elt < 0) continue; 4023 Elt &= 0x3; // only 2-bits 4024 Mask |= Elt << (i * 2); 4025 } 4026 } 4027 4028 return Mask; 4029} 4030 4031/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle 4032/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction. 4033static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) { 4034 EVT VT = SVOp->getValueType(0); 4035 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3; 4036 4037 unsigned NumElts = VT.getVectorNumElements(); 4038 unsigned NumLanes = VT.getSizeInBits()/128; 4039 unsigned NumLaneElts = NumElts/NumLanes; 4040 4041 int Val = 0; 4042 unsigned i; 4043 for (i = 0; i != NumElts; ++i) { 4044 Val = SVOp->getMaskElt(i); 4045 if (Val >= 0) 4046 break; 4047 } 4048 if (Val >= (int)NumElts) 4049 Val -= NumElts - NumLaneElts; 4050 4051 assert(Val - i > 0 && "PALIGNR imm should be positive"); 4052 return (Val - i) * EltSize; 4053} 4054 4055/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate 4056/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128 4057/// instructions. 4058unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) { 4059 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 4060 llvm_unreachable("Illegal extract subvector for VEXTRACTF128"); 4061 4062 uint64_t Index = 4063 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 4064 4065 EVT VecVT = N->getOperand(0).getValueType(); 4066 EVT ElVT = VecVT.getVectorElementType(); 4067 4068 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 4069 return Index / NumElemsPerChunk; 4070} 4071 4072/// getInsertVINSERTF128Immediate - Return the appropriate immediate 4073/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128 4074/// instructions. 4075unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) { 4076 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 4077 llvm_unreachable("Illegal insert subvector for VINSERTF128"); 4078 4079 uint64_t Index = 4080 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 4081 4082 EVT VecVT = N->getValueType(0); 4083 EVT ElVT = VecVT.getVectorElementType(); 4084 4085 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 4086 return Index / NumElemsPerChunk; 4087} 4088 4089/// getShuffleCLImmediate - Return the appropriate immediate to shuffle 4090/// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions. 4091/// Handles 256-bit. 4092static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) { 4093 EVT VT = N->getValueType(0); 4094 4095 unsigned NumElts = VT.getVectorNumElements(); 4096 4097 assert((VT.is256BitVector() && NumElts == 4) && 4098 "Unsupported vector type for VPERMQ/VPERMPD"); 4099 4100 unsigned Mask = 0; 4101 for (unsigned i = 0; i != NumElts; ++i) { 4102 int Elt = N->getMaskElt(i); 4103 if (Elt < 0) 4104 continue; 4105 Mask |= Elt << (i*2); 4106 } 4107 4108 return Mask; 4109} 4110/// isZeroNode - Returns true if Elt is a constant zero or a floating point 4111/// constant +0.0. 4112bool X86::isZeroNode(SDValue Elt) { 4113 return ((isa<ConstantSDNode>(Elt) && 4114 cast<ConstantSDNode>(Elt)->isNullValue()) || 4115 (isa<ConstantFPSDNode>(Elt) && 4116 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero())); 4117} 4118 4119/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in 4120/// their permute mask. 4121static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp, 4122 SelectionDAG &DAG) { 4123 EVT VT = SVOp->getValueType(0); 4124 unsigned NumElems = VT.getVectorNumElements(); 4125 SmallVector<int, 8> MaskVec; 4126 4127 for (unsigned i = 0; i != NumElems; ++i) { 4128 int Idx = SVOp->getMaskElt(i); 4129 if (Idx >= 0) { 4130 if (Idx < (int)NumElems) 4131 Idx += NumElems; 4132 else 4133 Idx -= NumElems; 4134 } 4135 MaskVec.push_back(Idx); 4136 } 4137 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1), 4138 SVOp->getOperand(0), &MaskVec[0]); 4139} 4140 4141/// ShouldXformToMOVHLPS - Return true if the node should be transformed to 4142/// match movhlps. The lower half elements should come from upper half of 4143/// V1 (and in order), and the upper half elements should come from the upper 4144/// half of V2 (and in order). 4145static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) { 4146 if (VT.getSizeInBits() != 128) 4147 return false; 4148 if (VT.getVectorNumElements() != 4) 4149 return false; 4150 for (unsigned i = 0, e = 2; i != e; ++i) 4151 if (!isUndefOrEqual(Mask[i], i+2)) 4152 return false; 4153 for (unsigned i = 2; i != 4; ++i) 4154 if (!isUndefOrEqual(Mask[i], i+4)) 4155 return false; 4156 return true; 4157} 4158 4159/// isScalarLoadToVector - Returns true if the node is a scalar load that 4160/// is promoted to a vector. It also returns the LoadSDNode by reference if 4161/// required. 4162static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) { 4163 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR) 4164 return false; 4165 N = N->getOperand(0).getNode(); 4166 if (!ISD::isNON_EXTLoad(N)) 4167 return false; 4168 if (LD) 4169 *LD = cast<LoadSDNode>(N); 4170 return true; 4171} 4172 4173// Test whether the given value is a vector value which will be legalized 4174// into a load. 4175static bool WillBeConstantPoolLoad(SDNode *N) { 4176 if (N->getOpcode() != ISD::BUILD_VECTOR) 4177 return false; 4178 4179 // Check for any non-constant elements. 4180 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 4181 switch (N->getOperand(i).getNode()->getOpcode()) { 4182 case ISD::UNDEF: 4183 case ISD::ConstantFP: 4184 case ISD::Constant: 4185 break; 4186 default: 4187 return false; 4188 } 4189 4190 // Vectors of all-zeros and all-ones are materialized with special 4191 // instructions rather than being loaded. 4192 return !ISD::isBuildVectorAllZeros(N) && 4193 !ISD::isBuildVectorAllOnes(N); 4194} 4195 4196/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to 4197/// match movlp{s|d}. The lower half elements should come from lower half of 4198/// V1 (and in order), and the upper half elements should come from the upper 4199/// half of V2 (and in order). And since V1 will become the source of the 4200/// MOVLP, it must be either a vector load or a scalar load to vector. 4201static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, 4202 ArrayRef<int> Mask, EVT VT) { 4203 if (VT.getSizeInBits() != 128) 4204 return false; 4205 4206 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1)) 4207 return false; 4208 // Is V2 is a vector load, don't do this transformation. We will try to use 4209 // load folding shufps op. 4210 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2)) 4211 return false; 4212 4213 unsigned NumElems = VT.getVectorNumElements(); 4214 4215 if (NumElems != 2 && NumElems != 4) 4216 return false; 4217 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 4218 if (!isUndefOrEqual(Mask[i], i)) 4219 return false; 4220 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i) 4221 if (!isUndefOrEqual(Mask[i], i+NumElems)) 4222 return false; 4223 return true; 4224} 4225 4226/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are 4227/// all the same. 4228static bool isSplatVector(SDNode *N) { 4229 if (N->getOpcode() != ISD::BUILD_VECTOR) 4230 return false; 4231 4232 SDValue SplatValue = N->getOperand(0); 4233 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i) 4234 if (N->getOperand(i) != SplatValue) 4235 return false; 4236 return true; 4237} 4238 4239/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved 4240/// to an zero vector. 4241/// FIXME: move to dag combiner / method on ShuffleVectorSDNode 4242static bool isZeroShuffle(ShuffleVectorSDNode *N) { 4243 SDValue V1 = N->getOperand(0); 4244 SDValue V2 = N->getOperand(1); 4245 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 4246 for (unsigned i = 0; i != NumElems; ++i) { 4247 int Idx = N->getMaskElt(i); 4248 if (Idx >= (int)NumElems) { 4249 unsigned Opc = V2.getOpcode(); 4250 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode())) 4251 continue; 4252 if (Opc != ISD::BUILD_VECTOR || 4253 !X86::isZeroNode(V2.getOperand(Idx-NumElems))) 4254 return false; 4255 } else if (Idx >= 0) { 4256 unsigned Opc = V1.getOpcode(); 4257 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode())) 4258 continue; 4259 if (Opc != ISD::BUILD_VECTOR || 4260 !X86::isZeroNode(V1.getOperand(Idx))) 4261 return false; 4262 } 4263 } 4264 return true; 4265} 4266 4267/// getZeroVector - Returns a vector of specified type with all zero elements. 4268/// 4269static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget, 4270 SelectionDAG &DAG, DebugLoc dl) { 4271 assert(VT.isVector() && "Expected a vector type"); 4272 unsigned Size = VT.getSizeInBits(); 4273 4274 // Always build SSE zero vectors as <4 x i32> bitcasted 4275 // to their dest type. This ensures they get CSE'd. 4276 SDValue Vec; 4277 if (Size == 128) { // SSE 4278 if (Subtarget->hasSSE2()) { // SSE2 4279 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 4280 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4281 } else { // SSE1 4282 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4283 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst); 4284 } 4285 } else if (Size == 256) { // AVX 4286 if (Subtarget->hasAVX2()) { // AVX2 4287 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 4288 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4289 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8); 4290 } else { 4291 // 256-bit logic and arithmetic instructions in AVX are all 4292 // floating-point, no support for integer ops. Emit fp zeroed vectors. 4293 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4294 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4295 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8); 4296 } 4297 } else 4298 llvm_unreachable("Unexpected vector type"); 4299 4300 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4301} 4302 4303/// getOnesVector - Returns a vector of specified type with all bits set. 4304/// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with 4305/// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately. 4306/// Then bitcast to their original type, ensuring they get CSE'd. 4307static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG, 4308 DebugLoc dl) { 4309 assert(VT.isVector() && "Expected a vector type"); 4310 unsigned Size = VT.getSizeInBits(); 4311 4312 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32); 4313 SDValue Vec; 4314 if (Size == 256) { 4315 if (HasAVX2) { // AVX2 4316 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4317 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8); 4318 } else { // AVX 4319 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4320 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl); 4321 } 4322 } else if (Size == 128) { 4323 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4324 } else 4325 llvm_unreachable("Unexpected vector type"); 4326 4327 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4328} 4329 4330/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements 4331/// that point to V2 points to its first element. 4332static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) { 4333 for (unsigned i = 0; i != NumElems; ++i) { 4334 if (Mask[i] > (int)NumElems) { 4335 Mask[i] = NumElems; 4336 } 4337 } 4338} 4339 4340/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd 4341/// operation of specified width. 4342static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4343 SDValue V2) { 4344 unsigned NumElems = VT.getVectorNumElements(); 4345 SmallVector<int, 8> Mask; 4346 Mask.push_back(NumElems); 4347 for (unsigned i = 1; i != NumElems; ++i) 4348 Mask.push_back(i); 4349 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4350} 4351 4352/// getUnpackl - Returns a vector_shuffle node for an unpackl operation. 4353static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4354 SDValue V2) { 4355 unsigned NumElems = VT.getVectorNumElements(); 4356 SmallVector<int, 8> Mask; 4357 for (unsigned i = 0, e = NumElems/2; i != e; ++i) { 4358 Mask.push_back(i); 4359 Mask.push_back(i + NumElems); 4360 } 4361 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4362} 4363 4364/// getUnpackh - Returns a vector_shuffle node for an unpackh operation. 4365static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4366 SDValue V2) { 4367 unsigned NumElems = VT.getVectorNumElements(); 4368 SmallVector<int, 8> Mask; 4369 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) { 4370 Mask.push_back(i + Half); 4371 Mask.push_back(i + NumElems + Half); 4372 } 4373 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4374} 4375 4376// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by 4377// a generic shuffle instruction because the target has no such instructions. 4378// Generate shuffles which repeat i16 and i8 several times until they can be 4379// represented by v4f32 and then be manipulated by target suported shuffles. 4380static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) { 4381 EVT VT = V.getValueType(); 4382 int NumElems = VT.getVectorNumElements(); 4383 DebugLoc dl = V.getDebugLoc(); 4384 4385 while (NumElems > 4) { 4386 if (EltNo < NumElems/2) { 4387 V = getUnpackl(DAG, dl, VT, V, V); 4388 } else { 4389 V = getUnpackh(DAG, dl, VT, V, V); 4390 EltNo -= NumElems/2; 4391 } 4392 NumElems >>= 1; 4393 } 4394 return V; 4395} 4396 4397/// getLegalSplat - Generate a legal splat with supported x86 shuffles 4398static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) { 4399 EVT VT = V.getValueType(); 4400 DebugLoc dl = V.getDebugLoc(); 4401 unsigned Size = VT.getSizeInBits(); 4402 4403 if (Size == 128) { 4404 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V); 4405 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo }; 4406 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32), 4407 &SplatMask[0]); 4408 } else if (Size == 256) { 4409 // To use VPERMILPS to splat scalars, the second half of indicies must 4410 // refer to the higher part, which is a duplication of the lower one, 4411 // because VPERMILPS can only handle in-lane permutations. 4412 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo, 4413 EltNo+4, EltNo+4, EltNo+4, EltNo+4 }; 4414 4415 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V); 4416 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32), 4417 &SplatMask[0]); 4418 } else 4419 llvm_unreachable("Vector size not supported"); 4420 4421 return DAG.getNode(ISD::BITCAST, dl, VT, V); 4422} 4423 4424/// PromoteSplat - Splat is promoted to target supported vector shuffles. 4425static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) { 4426 EVT SrcVT = SV->getValueType(0); 4427 SDValue V1 = SV->getOperand(0); 4428 DebugLoc dl = SV->getDebugLoc(); 4429 4430 int EltNo = SV->getSplatIndex(); 4431 int NumElems = SrcVT.getVectorNumElements(); 4432 unsigned Size = SrcVT.getSizeInBits(); 4433 4434 assert(((Size == 128 && NumElems > 4) || Size == 256) && 4435 "Unknown how to promote splat for type"); 4436 4437 // Extract the 128-bit part containing the splat element and update 4438 // the splat element index when it refers to the higher register. 4439 if (Size == 256) { 4440 V1 = Extract128BitVector(V1, EltNo, DAG, dl); 4441 if (EltNo >= NumElems/2) 4442 EltNo -= NumElems/2; 4443 } 4444 4445 // All i16 and i8 vector types can't be used directly by a generic shuffle 4446 // instruction because the target has no such instruction. Generate shuffles 4447 // which repeat i16 and i8 several times until they fit in i32, and then can 4448 // be manipulated by target suported shuffles. 4449 EVT EltVT = SrcVT.getVectorElementType(); 4450 if (EltVT == MVT::i8 || EltVT == MVT::i16) 4451 V1 = PromoteSplati8i16(V1, DAG, EltNo); 4452 4453 // Recreate the 256-bit vector and place the same 128-bit vector 4454 // into the low and high part. This is necessary because we want 4455 // to use VPERM* to shuffle the vectors 4456 if (Size == 256) { 4457 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1); 4458 } 4459 4460 return getLegalSplat(DAG, V1, EltNo); 4461} 4462 4463/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified 4464/// vector of zero or undef vector. This produces a shuffle where the low 4465/// element of V2 is swizzled into the zero/undef vector, landing at element 4466/// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3). 4467static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx, 4468 bool IsZero, 4469 const X86Subtarget *Subtarget, 4470 SelectionDAG &DAG) { 4471 EVT VT = V2.getValueType(); 4472 SDValue V1 = IsZero 4473 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT); 4474 unsigned NumElems = VT.getVectorNumElements(); 4475 SmallVector<int, 16> MaskVec; 4476 for (unsigned i = 0; i != NumElems; ++i) 4477 // If this is the insertion idx, put the low elt of V2 here. 4478 MaskVec.push_back(i == Idx ? NumElems : i); 4479 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]); 4480} 4481 4482/// getTargetShuffleMask - Calculates the shuffle mask corresponding to the 4483/// target specific opcode. Returns true if the Mask could be calculated. 4484/// Sets IsUnary to true if only uses one source. 4485static bool getTargetShuffleMask(SDNode *N, MVT VT, 4486 SmallVectorImpl<int> &Mask, bool &IsUnary) { 4487 unsigned NumElems = VT.getVectorNumElements(); 4488 SDValue ImmN; 4489 4490 IsUnary = false; 4491 switch(N->getOpcode()) { 4492 case X86ISD::SHUFP: 4493 ImmN = N->getOperand(N->getNumOperands()-1); 4494 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4495 break; 4496 case X86ISD::UNPCKH: 4497 DecodeUNPCKHMask(VT, Mask); 4498 break; 4499 case X86ISD::UNPCKL: 4500 DecodeUNPCKLMask(VT, Mask); 4501 break; 4502 case X86ISD::MOVHLPS: 4503 DecodeMOVHLPSMask(NumElems, Mask); 4504 break; 4505 case X86ISD::MOVLHPS: 4506 DecodeMOVLHPSMask(NumElems, Mask); 4507 break; 4508 case X86ISD::PSHUFD: 4509 case X86ISD::VPERMILP: 4510 ImmN = N->getOperand(N->getNumOperands()-1); 4511 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4512 IsUnary = true; 4513 break; 4514 case X86ISD::PSHUFHW: 4515 ImmN = N->getOperand(N->getNumOperands()-1); 4516 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4517 IsUnary = true; 4518 break; 4519 case X86ISD::PSHUFLW: 4520 ImmN = N->getOperand(N->getNumOperands()-1); 4521 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4522 IsUnary = true; 4523 break; 4524 case X86ISD::VPERMI: 4525 ImmN = N->getOperand(N->getNumOperands()-1); 4526 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4527 IsUnary = true; 4528 break; 4529 case X86ISD::MOVSS: 4530 case X86ISD::MOVSD: { 4531 // The index 0 always comes from the first element of the second source, 4532 // this is why MOVSS and MOVSD are used in the first place. The other 4533 // elements come from the other positions of the first source vector 4534 Mask.push_back(NumElems); 4535 for (unsigned i = 1; i != NumElems; ++i) { 4536 Mask.push_back(i); 4537 } 4538 break; 4539 } 4540 case X86ISD::VPERM2X128: 4541 ImmN = N->getOperand(N->getNumOperands()-1); 4542 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4543 if (Mask.empty()) return false; 4544 break; 4545 case X86ISD::MOVDDUP: 4546 case X86ISD::MOVLHPD: 4547 case X86ISD::MOVLPD: 4548 case X86ISD::MOVLPS: 4549 case X86ISD::MOVSHDUP: 4550 case X86ISD::MOVSLDUP: 4551 case X86ISD::PALIGN: 4552 // Not yet implemented 4553 return false; 4554 default: llvm_unreachable("unknown target shuffle node"); 4555 } 4556 4557 return true; 4558} 4559 4560/// getShuffleScalarElt - Returns the scalar element that will make up the ith 4561/// element of the result of the vector shuffle. 4562static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG, 4563 unsigned Depth) { 4564 if (Depth == 6) 4565 return SDValue(); // Limit search depth. 4566 4567 SDValue V = SDValue(N, 0); 4568 EVT VT = V.getValueType(); 4569 unsigned Opcode = V.getOpcode(); 4570 4571 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars. 4572 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) { 4573 int Elt = SV->getMaskElt(Index); 4574 4575 if (Elt < 0) 4576 return DAG.getUNDEF(VT.getVectorElementType()); 4577 4578 unsigned NumElems = VT.getVectorNumElements(); 4579 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0) 4580 : SV->getOperand(1); 4581 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1); 4582 } 4583 4584 // Recurse into target specific vector shuffles to find scalars. 4585 if (isTargetShuffle(Opcode)) { 4586 MVT ShufVT = V.getValueType().getSimpleVT(); 4587 unsigned NumElems = ShufVT.getVectorNumElements(); 4588 SmallVector<int, 16> ShuffleMask; 4589 SDValue ImmN; 4590 bool IsUnary; 4591 4592 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary)) 4593 return SDValue(); 4594 4595 int Elt = ShuffleMask[Index]; 4596 if (Elt < 0) 4597 return DAG.getUNDEF(ShufVT.getVectorElementType()); 4598 4599 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0) 4600 : N->getOperand(1); 4601 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, 4602 Depth+1); 4603 } 4604 4605 // Actual nodes that may contain scalar elements 4606 if (Opcode == ISD::BITCAST) { 4607 V = V.getOperand(0); 4608 EVT SrcVT = V.getValueType(); 4609 unsigned NumElems = VT.getVectorNumElements(); 4610 4611 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems) 4612 return SDValue(); 4613 } 4614 4615 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 4616 return (Index == 0) ? V.getOperand(0) 4617 : DAG.getUNDEF(VT.getVectorElementType()); 4618 4619 if (V.getOpcode() == ISD::BUILD_VECTOR) 4620 return V.getOperand(Index); 4621 4622 return SDValue(); 4623} 4624 4625/// getNumOfConsecutiveZeros - Return the number of elements of a vector 4626/// shuffle operation which come from a consecutively from a zero. The 4627/// search can start in two different directions, from left or right. 4628static 4629unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems, 4630 bool ZerosFromLeft, SelectionDAG &DAG) { 4631 unsigned i; 4632 for (i = 0; i != NumElems; ++i) { 4633 unsigned Index = ZerosFromLeft ? i : NumElems-i-1; 4634 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0); 4635 if (!(Elt.getNode() && 4636 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt)))) 4637 break; 4638 } 4639 4640 return i; 4641} 4642 4643/// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE) 4644/// correspond consecutively to elements from one of the vector operands, 4645/// starting from its index OpIdx. Also tell OpNum which source vector operand. 4646static 4647bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, 4648 unsigned MaskI, unsigned MaskE, unsigned OpIdx, 4649 unsigned NumElems, unsigned &OpNum) { 4650 bool SeenV1 = false; 4651 bool SeenV2 = false; 4652 4653 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) { 4654 int Idx = SVOp->getMaskElt(i); 4655 // Ignore undef indicies 4656 if (Idx < 0) 4657 continue; 4658 4659 if (Idx < (int)NumElems) 4660 SeenV1 = true; 4661 else 4662 SeenV2 = true; 4663 4664 // Only accept consecutive elements from the same vector 4665 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2)) 4666 return false; 4667 } 4668 4669 OpNum = SeenV1 ? 0 : 1; 4670 return true; 4671} 4672 4673/// isVectorShiftRight - Returns true if the shuffle can be implemented as a 4674/// logical left shift of a vector. 4675static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4676 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4677 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4678 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4679 false /* check zeros from right */, DAG); 4680 unsigned OpSrc; 4681 4682 if (!NumZeros) 4683 return false; 4684 4685 // Considering the elements in the mask that are not consecutive zeros, 4686 // check if they consecutively come from only one of the source vectors. 4687 // 4688 // V1 = {X, A, B, C} 0 4689 // \ \ \ / 4690 // vector_shuffle V1, V2 <1, 2, 3, X> 4691 // 4692 if (!isShuffleMaskConsecutive(SVOp, 4693 0, // Mask Start Index 4694 NumElems-NumZeros, // Mask End Index(exclusive) 4695 NumZeros, // Where to start looking in the src vector 4696 NumElems, // Number of elements in vector 4697 OpSrc)) // Which source operand ? 4698 return false; 4699 4700 isLeft = false; 4701 ShAmt = NumZeros; 4702 ShVal = SVOp->getOperand(OpSrc); 4703 return true; 4704} 4705 4706/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a 4707/// logical left shift of a vector. 4708static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4709 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4710 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4711 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4712 true /* check zeros from left */, DAG); 4713 unsigned OpSrc; 4714 4715 if (!NumZeros) 4716 return false; 4717 4718 // Considering the elements in the mask that are not consecutive zeros, 4719 // check if they consecutively come from only one of the source vectors. 4720 // 4721 // 0 { A, B, X, X } = V2 4722 // / \ / / 4723 // vector_shuffle V1, V2 <X, X, 4, 5> 4724 // 4725 if (!isShuffleMaskConsecutive(SVOp, 4726 NumZeros, // Mask Start Index 4727 NumElems, // Mask End Index(exclusive) 4728 0, // Where to start looking in the src vector 4729 NumElems, // Number of elements in vector 4730 OpSrc)) // Which source operand ? 4731 return false; 4732 4733 isLeft = true; 4734 ShAmt = NumZeros; 4735 ShVal = SVOp->getOperand(OpSrc); 4736 return true; 4737} 4738 4739/// isVectorShift - Returns true if the shuffle can be implemented as a 4740/// logical left or right shift of a vector. 4741static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4742 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4743 // Although the logic below support any bitwidth size, there are no 4744 // shift instructions which handle more than 128-bit vectors. 4745 if (SVOp->getValueType(0).getSizeInBits() > 128) 4746 return false; 4747 4748 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) || 4749 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt)) 4750 return true; 4751 4752 return false; 4753} 4754 4755/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8. 4756/// 4757static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros, 4758 unsigned NumNonZero, unsigned NumZero, 4759 SelectionDAG &DAG, 4760 const X86Subtarget* Subtarget, 4761 const TargetLowering &TLI) { 4762 if (NumNonZero > 8) 4763 return SDValue(); 4764 4765 DebugLoc dl = Op.getDebugLoc(); 4766 SDValue V(0, 0); 4767 bool First = true; 4768 for (unsigned i = 0; i < 16; ++i) { 4769 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0; 4770 if (ThisIsNonZero && First) { 4771 if (NumZero) 4772 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl); 4773 else 4774 V = DAG.getUNDEF(MVT::v8i16); 4775 First = false; 4776 } 4777 4778 if ((i & 1) != 0) { 4779 SDValue ThisElt(0, 0), LastElt(0, 0); 4780 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0; 4781 if (LastIsNonZero) { 4782 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl, 4783 MVT::i16, Op.getOperand(i-1)); 4784 } 4785 if (ThisIsNonZero) { 4786 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i)); 4787 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16, 4788 ThisElt, DAG.getConstant(8, MVT::i8)); 4789 if (LastIsNonZero) 4790 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt); 4791 } else 4792 ThisElt = LastElt; 4793 4794 if (ThisElt.getNode()) 4795 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt, 4796 DAG.getIntPtrConstant(i/2)); 4797 } 4798 } 4799 4800 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V); 4801} 4802 4803/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16. 4804/// 4805static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros, 4806 unsigned NumNonZero, unsigned NumZero, 4807 SelectionDAG &DAG, 4808 const X86Subtarget* Subtarget, 4809 const TargetLowering &TLI) { 4810 if (NumNonZero > 4) 4811 return SDValue(); 4812 4813 DebugLoc dl = Op.getDebugLoc(); 4814 SDValue V(0, 0); 4815 bool First = true; 4816 for (unsigned i = 0; i < 8; ++i) { 4817 bool isNonZero = (NonZeros & (1 << i)) != 0; 4818 if (isNonZero) { 4819 if (First) { 4820 if (NumZero) 4821 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl); 4822 else 4823 V = DAG.getUNDEF(MVT::v8i16); 4824 First = false; 4825 } 4826 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, 4827 MVT::v8i16, V, Op.getOperand(i), 4828 DAG.getIntPtrConstant(i)); 4829 } 4830 } 4831 4832 return V; 4833} 4834 4835/// getVShift - Return a vector logical shift node. 4836/// 4837static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, 4838 unsigned NumBits, SelectionDAG &DAG, 4839 const TargetLowering &TLI, DebugLoc dl) { 4840 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift"); 4841 EVT ShVT = MVT::v2i64; 4842 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ; 4843 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp); 4844 return DAG.getNode(ISD::BITCAST, dl, VT, 4845 DAG.getNode(Opc, dl, ShVT, SrcOp, 4846 DAG.getConstant(NumBits, 4847 TLI.getShiftAmountTy(SrcOp.getValueType())))); 4848} 4849 4850SDValue 4851X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl, 4852 SelectionDAG &DAG) const { 4853 4854 // Check if the scalar load can be widened into a vector load. And if 4855 // the address is "base + cst" see if the cst can be "absorbed" into 4856 // the shuffle mask. 4857 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) { 4858 SDValue Ptr = LD->getBasePtr(); 4859 if (!ISD::isNormalLoad(LD) || LD->isVolatile()) 4860 return SDValue(); 4861 EVT PVT = LD->getValueType(0); 4862 if (PVT != MVT::i32 && PVT != MVT::f32) 4863 return SDValue(); 4864 4865 int FI = -1; 4866 int64_t Offset = 0; 4867 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) { 4868 FI = FINode->getIndex(); 4869 Offset = 0; 4870 } else if (DAG.isBaseWithConstantOffset(Ptr) && 4871 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 4872 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 4873 Offset = Ptr.getConstantOperandVal(1); 4874 Ptr = Ptr.getOperand(0); 4875 } else { 4876 return SDValue(); 4877 } 4878 4879 // FIXME: 256-bit vector instructions don't require a strict alignment, 4880 // improve this code to support it better. 4881 unsigned RequiredAlign = VT.getSizeInBits()/8; 4882 SDValue Chain = LD->getChain(); 4883 // Make sure the stack object alignment is at least 16 or 32. 4884 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4885 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) { 4886 if (MFI->isFixedObjectIndex(FI)) { 4887 // Can't change the alignment. FIXME: It's possible to compute 4888 // the exact stack offset and reference FI + adjust offset instead. 4889 // If someone *really* cares about this. That's the way to implement it. 4890 return SDValue(); 4891 } else { 4892 MFI->setObjectAlignment(FI, RequiredAlign); 4893 } 4894 } 4895 4896 // (Offset % 16 or 32) must be multiple of 4. Then address is then 4897 // Ptr + (Offset & ~15). 4898 if (Offset < 0) 4899 return SDValue(); 4900 if ((Offset % RequiredAlign) & 3) 4901 return SDValue(); 4902 int64_t StartOffset = Offset & ~(RequiredAlign-1); 4903 if (StartOffset) 4904 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(), 4905 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType())); 4906 4907 int EltNo = (Offset - StartOffset) >> 2; 4908 unsigned NumElems = VT.getVectorNumElements(); 4909 4910 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems); 4911 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr, 4912 LD->getPointerInfo().getWithOffset(StartOffset), 4913 false, false, false, 0); 4914 4915 SmallVector<int, 8> Mask; 4916 for (unsigned i = 0; i != NumElems; ++i) 4917 Mask.push_back(EltNo); 4918 4919 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]); 4920 } 4921 4922 return SDValue(); 4923} 4924 4925/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 4926/// vector of type 'VT', see if the elements can be replaced by a single large 4927/// load which has the same value as a build_vector whose operands are 'elts'. 4928/// 4929/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a 4930/// 4931/// FIXME: we'd also like to handle the case where the last elements are zero 4932/// rather than undef via VZEXT_LOAD, but we do not detect that case today. 4933/// There's even a handy isZeroNode for that purpose. 4934static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts, 4935 DebugLoc &DL, SelectionDAG &DAG) { 4936 EVT EltVT = VT.getVectorElementType(); 4937 unsigned NumElems = Elts.size(); 4938 4939 LoadSDNode *LDBase = NULL; 4940 unsigned LastLoadedElt = -1U; 4941 4942 // For each element in the initializer, see if we've found a load or an undef. 4943 // If we don't find an initial load element, or later load elements are 4944 // non-consecutive, bail out. 4945 for (unsigned i = 0; i < NumElems; ++i) { 4946 SDValue Elt = Elts[i]; 4947 4948 if (!Elt.getNode() || 4949 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode()))) 4950 return SDValue(); 4951 if (!LDBase) { 4952 if (Elt.getNode()->getOpcode() == ISD::UNDEF) 4953 return SDValue(); 4954 LDBase = cast<LoadSDNode>(Elt.getNode()); 4955 LastLoadedElt = i; 4956 continue; 4957 } 4958 if (Elt.getOpcode() == ISD::UNDEF) 4959 continue; 4960 4961 LoadSDNode *LD = cast<LoadSDNode>(Elt); 4962 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i)) 4963 return SDValue(); 4964 LastLoadedElt = i; 4965 } 4966 4967 // If we have found an entire vector of loads and undefs, then return a large 4968 // load of the entire vector width starting at the base pointer. If we found 4969 // consecutive loads for the low half, generate a vzext_load node. 4970 if (LastLoadedElt == NumElems - 1) { 4971 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16) 4972 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 4973 LDBase->getPointerInfo(), 4974 LDBase->isVolatile(), LDBase->isNonTemporal(), 4975 LDBase->isInvariant(), 0); 4976 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 4977 LDBase->getPointerInfo(), 4978 LDBase->isVolatile(), LDBase->isNonTemporal(), 4979 LDBase->isInvariant(), LDBase->getAlignment()); 4980 } 4981 if (NumElems == 4 && LastLoadedElt == 1 && 4982 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) { 4983 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other); 4984 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() }; 4985 SDValue ResNode = 4986 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64, 4987 LDBase->getPointerInfo(), 4988 LDBase->getAlignment(), 4989 false/*isVolatile*/, true/*ReadMem*/, 4990 false/*WriteMem*/); 4991 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode); 4992 } 4993 return SDValue(); 4994} 4995 4996/// LowerVectorBroadcast - Attempt to use the vbroadcast instruction 4997/// to generate a splat value for the following cases: 4998/// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant. 4999/// 2. A splat shuffle which uses a scalar_to_vector node which comes from 5000/// a scalar load, or a constant. 5001/// The VBROADCAST node is returned when a pattern is found, 5002/// or SDValue() otherwise. 5003SDValue 5004X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const { 5005 if (!Subtarget->hasAVX()) 5006 return SDValue(); 5007 5008 EVT VT = Op.getValueType(); 5009 DebugLoc dl = Op.getDebugLoc(); 5010 5011 assert((VT.is128BitVector() || VT.is256BitVector()) && 5012 "Unsupported vector type for broadcast."); 5013 5014 SDValue Ld; 5015 bool ConstSplatVal; 5016 5017 switch (Op.getOpcode()) { 5018 default: 5019 // Unknown pattern found. 5020 return SDValue(); 5021 5022 case ISD::BUILD_VECTOR: { 5023 // The BUILD_VECTOR node must be a splat. 5024 if (!isSplatVector(Op.getNode())) 5025 return SDValue(); 5026 5027 Ld = Op.getOperand(0); 5028 ConstSplatVal = (Ld.getOpcode() == ISD::Constant || 5029 Ld.getOpcode() == ISD::ConstantFP); 5030 5031 // The suspected load node has several users. Make sure that all 5032 // of its users are from the BUILD_VECTOR node. 5033 // Constants may have multiple users. 5034 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0)) 5035 return SDValue(); 5036 break; 5037 } 5038 5039 case ISD::VECTOR_SHUFFLE: { 5040 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5041 5042 // Shuffles must have a splat mask where the first element is 5043 // broadcasted. 5044 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0) 5045 return SDValue(); 5046 5047 SDValue Sc = Op.getOperand(0); 5048 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR && 5049 Sc.getOpcode() != ISD::BUILD_VECTOR) { 5050 5051 if (!Subtarget->hasAVX2()) 5052 return SDValue(); 5053 5054 // Use the register form of the broadcast instruction available on AVX2. 5055 if (VT.is256BitVector()) 5056 Sc = Extract128BitVector(Sc, 0, DAG, dl); 5057 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc); 5058 } 5059 5060 Ld = Sc.getOperand(0); 5061 ConstSplatVal = (Ld.getOpcode() == ISD::Constant || 5062 Ld.getOpcode() == ISD::ConstantFP); 5063 5064 // The scalar_to_vector node and the suspected 5065 // load node must have exactly one user. 5066 // Constants may have multiple users. 5067 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse())) 5068 return SDValue(); 5069 break; 5070 } 5071 } 5072 5073 bool Is256 = VT.getSizeInBits() == 256; 5074 5075 // Handle the broadcasting a single constant scalar from the constant pool 5076 // into a vector. On Sandybridge it is still better to load a constant vector 5077 // from the constant pool and not to broadcast it from a scalar. 5078 if (ConstSplatVal && Subtarget->hasAVX2()) { 5079 EVT CVT = Ld.getValueType(); 5080 assert(!CVT.isVector() && "Must not broadcast a vector type"); 5081 unsigned ScalarSize = CVT.getSizeInBits(); 5082 5083 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) { 5084 const Constant *C = 0; 5085 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld)) 5086 C = CI->getConstantIntValue(); 5087 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld)) 5088 C = CF->getConstantFPValue(); 5089 5090 assert(C && "Invalid constant type"); 5091 5092 SDValue CP = DAG.getConstantPool(C, getPointerTy()); 5093 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment(); 5094 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP, 5095 MachinePointerInfo::getConstantPool(), 5096 false, false, false, Alignment); 5097 5098 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5099 } 5100 } 5101 5102 bool IsLoad = ISD::isNormalLoad(Ld.getNode()); 5103 unsigned ScalarSize = Ld.getValueType().getSizeInBits(); 5104 5105 // Handle AVX2 in-register broadcasts. 5106 if (!IsLoad && Subtarget->hasAVX2() && 5107 (ScalarSize == 32 || (Is256 && ScalarSize == 64))) 5108 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5109 5110 // The scalar source must be a normal load. 5111 if (!IsLoad) 5112 return SDValue(); 5113 5114 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) 5115 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5116 5117 // The integer check is needed for the 64-bit into 128-bit so it doesn't match 5118 // double since there is no vbroadcastsd xmm 5119 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) { 5120 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64) 5121 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5122 } 5123 5124 // Unsupported broadcast. 5125 return SDValue(); 5126} 5127 5128SDValue 5129X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const { 5130 DebugLoc dl = Op.getDebugLoc(); 5131 5132 EVT VT = Op.getValueType(); 5133 EVT ExtVT = VT.getVectorElementType(); 5134 unsigned NumElems = Op.getNumOperands(); 5135 5136 // Vectors containing all zeros can be matched by pxor and xorps later 5137 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 5138 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd 5139 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts. 5140 if (VT == MVT::v4i32 || VT == MVT::v8i32) 5141 return Op; 5142 5143 return getZeroVector(VT, Subtarget, DAG, dl); 5144 } 5145 5146 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width 5147 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use 5148 // vpcmpeqd on 256-bit vectors. 5149 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 5150 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2())) 5151 return Op; 5152 5153 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl); 5154 } 5155 5156 SDValue Broadcast = LowerVectorBroadcast(Op, DAG); 5157 if (Broadcast.getNode()) 5158 return Broadcast; 5159 5160 unsigned EVTBits = ExtVT.getSizeInBits(); 5161 5162 unsigned NumZero = 0; 5163 unsigned NumNonZero = 0; 5164 unsigned NonZeros = 0; 5165 bool IsAllConstants = true; 5166 SmallSet<SDValue, 8> Values; 5167 for (unsigned i = 0; i < NumElems; ++i) { 5168 SDValue Elt = Op.getOperand(i); 5169 if (Elt.getOpcode() == ISD::UNDEF) 5170 continue; 5171 Values.insert(Elt); 5172 if (Elt.getOpcode() != ISD::Constant && 5173 Elt.getOpcode() != ISD::ConstantFP) 5174 IsAllConstants = false; 5175 if (X86::isZeroNode(Elt)) 5176 NumZero++; 5177 else { 5178 NonZeros |= (1 << i); 5179 NumNonZero++; 5180 } 5181 } 5182 5183 // All undef vector. Return an UNDEF. All zero vectors were handled above. 5184 if (NumNonZero == 0) 5185 return DAG.getUNDEF(VT); 5186 5187 // Special case for single non-zero, non-undef, element. 5188 if (NumNonZero == 1) { 5189 unsigned Idx = CountTrailingZeros_32(NonZeros); 5190 SDValue Item = Op.getOperand(Idx); 5191 5192 // If this is an insertion of an i64 value on x86-32, and if the top bits of 5193 // the value are obviously zero, truncate the value to i32 and do the 5194 // insertion that way. Only do this if the value is non-constant or if the 5195 // value is a constant being inserted into element 0. It is cheaper to do 5196 // a constant pool load than it is to do a movd + shuffle. 5197 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() && 5198 (!IsAllConstants || Idx == 0)) { 5199 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) { 5200 // Handle SSE only. 5201 assert(VT == MVT::v2i64 && "Expected an SSE value type!"); 5202 EVT VecVT = MVT::v4i32; 5203 unsigned VecElts = 4; 5204 5205 // Truncate the value (which may itself be a constant) to i32, and 5206 // convert it to a vector with movd (S2V+shuffle to zero extend). 5207 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item); 5208 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item); 5209 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG); 5210 5211 // Now we have our 32-bit value zero extended in the low element of 5212 // a vector. If Idx != 0, swizzle it into place. 5213 if (Idx != 0) { 5214 SmallVector<int, 4> Mask; 5215 Mask.push_back(Idx); 5216 for (unsigned i = 1; i != VecElts; ++i) 5217 Mask.push_back(i); 5218 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT), 5219 &Mask[0]); 5220 } 5221 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 5222 } 5223 } 5224 5225 // If we have a constant or non-constant insertion into the low element of 5226 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into 5227 // the rest of the elements. This will be matched as movd/movq/movss/movsd 5228 // depending on what the source datatype is. 5229 if (Idx == 0) { 5230 if (NumZero == 0) 5231 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5232 5233 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 || 5234 (ExtVT == MVT::i64 && Subtarget->is64Bit())) { 5235 if (VT.getSizeInBits() == 256) { 5236 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl); 5237 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec, 5238 Item, DAG.getIntPtrConstant(0)); 5239 } 5240 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!"); 5241 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5242 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector. 5243 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG); 5244 } 5245 5246 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) { 5247 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item); 5248 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item); 5249 if (VT.getSizeInBits() == 256) { 5250 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl); 5251 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl); 5252 } else { 5253 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!"); 5254 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG); 5255 } 5256 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 5257 } 5258 } 5259 5260 // Is it a vector logical left shift? 5261 if (NumElems == 2 && Idx == 1 && 5262 X86::isZeroNode(Op.getOperand(0)) && 5263 !X86::isZeroNode(Op.getOperand(1))) { 5264 unsigned NumBits = VT.getSizeInBits(); 5265 return getVShift(true, VT, 5266 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 5267 VT, Op.getOperand(1)), 5268 NumBits/2, DAG, *this, dl); 5269 } 5270 5271 if (IsAllConstants) // Otherwise, it's better to do a constpool load. 5272 return SDValue(); 5273 5274 // Otherwise, if this is a vector with i32 or f32 elements, and the element 5275 // is a non-constant being inserted into an element other than the low one, 5276 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka 5277 // movd/movss) to move this into the low element, then shuffle it into 5278 // place. 5279 if (EVTBits == 32) { 5280 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5281 5282 // Turn it into a shuffle of zero and zero-extended scalar to vector. 5283 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG); 5284 SmallVector<int, 8> MaskVec; 5285 for (unsigned i = 0; i != NumElems; ++i) 5286 MaskVec.push_back(i == Idx ? 0 : 1); 5287 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]); 5288 } 5289 } 5290 5291 // Splat is obviously ok. Let legalizer expand it to a shuffle. 5292 if (Values.size() == 1) { 5293 if (EVTBits == 32) { 5294 // Instead of a shuffle like this: 5295 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0> 5296 // Check if it's possible to issue this instead. 5297 // shuffle (vload ptr)), undef, <1, 1, 1, 1> 5298 unsigned Idx = CountTrailingZeros_32(NonZeros); 5299 SDValue Item = Op.getOperand(Idx); 5300 if (Op.getNode()->isOnlyUserOf(Item.getNode())) 5301 return LowerAsSplatVectorLoad(Item, VT, dl, DAG); 5302 } 5303 return SDValue(); 5304 } 5305 5306 // A vector full of immediates; various special cases are already 5307 // handled, so this is best done with a single constant-pool load. 5308 if (IsAllConstants) 5309 return SDValue(); 5310 5311 // For AVX-length vectors, build the individual 128-bit pieces and use 5312 // shuffles to put them in place. 5313 if (VT.getSizeInBits() == 256) { 5314 SmallVector<SDValue, 32> V; 5315 for (unsigned i = 0; i != NumElems; ++i) 5316 V.push_back(Op.getOperand(i)); 5317 5318 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2); 5319 5320 // Build both the lower and upper subvector. 5321 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2); 5322 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2], 5323 NumElems/2); 5324 5325 // Recreate the wider vector with the lower and upper part. 5326 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl); 5327 } 5328 5329 // Let legalizer expand 2-wide build_vectors. 5330 if (EVTBits == 64) { 5331 if (NumNonZero == 1) { 5332 // One half is zero or undef. 5333 unsigned Idx = CountTrailingZeros_32(NonZeros); 5334 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, 5335 Op.getOperand(Idx)); 5336 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG); 5337 } 5338 return SDValue(); 5339 } 5340 5341 // If element VT is < 32 bits, convert it to inserts into a zero vector. 5342 if (EVTBits == 8 && NumElems == 16) { 5343 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG, 5344 Subtarget, *this); 5345 if (V.getNode()) return V; 5346 } 5347 5348 if (EVTBits == 16 && NumElems == 8) { 5349 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG, 5350 Subtarget, *this); 5351 if (V.getNode()) return V; 5352 } 5353 5354 // If element VT is == 32 bits, turn it into a number of shuffles. 5355 SmallVector<SDValue, 8> V(NumElems); 5356 if (NumElems == 4 && NumZero > 0) { 5357 for (unsigned i = 0; i < 4; ++i) { 5358 bool isZero = !(NonZeros & (1 << i)); 5359 if (isZero) 5360 V[i] = getZeroVector(VT, Subtarget, DAG, dl); 5361 else 5362 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 5363 } 5364 5365 for (unsigned i = 0; i < 2; ++i) { 5366 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) { 5367 default: break; 5368 case 0: 5369 V[i] = V[i*2]; // Must be a zero vector. 5370 break; 5371 case 1: 5372 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]); 5373 break; 5374 case 2: 5375 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]); 5376 break; 5377 case 3: 5378 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]); 5379 break; 5380 } 5381 } 5382 5383 bool Reverse1 = (NonZeros & 0x3) == 2; 5384 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2; 5385 int MaskVec[] = { 5386 Reverse1 ? 1 : 0, 5387 Reverse1 ? 0 : 1, 5388 static_cast<int>(Reverse2 ? NumElems+1 : NumElems), 5389 static_cast<int>(Reverse2 ? NumElems : NumElems+1) 5390 }; 5391 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]); 5392 } 5393 5394 if (Values.size() > 1 && VT.getSizeInBits() == 128) { 5395 // Check for a build vector of consecutive loads. 5396 for (unsigned i = 0; i < NumElems; ++i) 5397 V[i] = Op.getOperand(i); 5398 5399 // Check for elements which are consecutive loads. 5400 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG); 5401 if (LD.getNode()) 5402 return LD; 5403 5404 // For SSE 4.1, use insertps to put the high elements into the low element. 5405 if (getSubtarget()->hasSSE41()) { 5406 SDValue Result; 5407 if (Op.getOperand(0).getOpcode() != ISD::UNDEF) 5408 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0)); 5409 else 5410 Result = DAG.getUNDEF(VT); 5411 5412 for (unsigned i = 1; i < NumElems; ++i) { 5413 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue; 5414 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result, 5415 Op.getOperand(i), DAG.getIntPtrConstant(i)); 5416 } 5417 return Result; 5418 } 5419 5420 // Otherwise, expand into a number of unpckl*, start by extending each of 5421 // our (non-undef) elements to the full vector width with the element in the 5422 // bottom slot of the vector (which generates no code for SSE). 5423 for (unsigned i = 0; i < NumElems; ++i) { 5424 if (Op.getOperand(i).getOpcode() != ISD::UNDEF) 5425 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 5426 else 5427 V[i] = DAG.getUNDEF(VT); 5428 } 5429 5430 // Next, we iteratively mix elements, e.g. for v4f32: 5431 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0> 5432 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1> 5433 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0> 5434 unsigned EltStride = NumElems >> 1; 5435 while (EltStride != 0) { 5436 for (unsigned i = 0; i < EltStride; ++i) { 5437 // If V[i+EltStride] is undef and this is the first round of mixing, 5438 // then it is safe to just drop this shuffle: V[i] is already in the 5439 // right place, the one element (since it's the first round) being 5440 // inserted as undef can be dropped. This isn't safe for successive 5441 // rounds because they will permute elements within both vectors. 5442 if (V[i+EltStride].getOpcode() == ISD::UNDEF && 5443 EltStride == NumElems/2) 5444 continue; 5445 5446 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]); 5447 } 5448 EltStride >>= 1; 5449 } 5450 return V[0]; 5451 } 5452 return SDValue(); 5453} 5454 5455// LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place 5456// them in a MMX register. This is better than doing a stack convert. 5457static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5458 DebugLoc dl = Op.getDebugLoc(); 5459 EVT ResVT = Op.getValueType(); 5460 5461 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 || 5462 ResVT == MVT::v8i16 || ResVT == MVT::v16i8); 5463 int Mask[2]; 5464 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0)); 5465 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 5466 InVec = Op.getOperand(1); 5467 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5468 unsigned NumElts = ResVT.getVectorNumElements(); 5469 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 5470 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp, 5471 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1)); 5472 } else { 5473 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec); 5474 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 5475 Mask[0] = 0; Mask[1] = 2; 5476 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask); 5477 } 5478 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 5479} 5480 5481// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction 5482// to create 256-bit vectors from two other 128-bit ones. 5483static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5484 DebugLoc dl = Op.getDebugLoc(); 5485 EVT ResVT = Op.getValueType(); 5486 5487 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide"); 5488 5489 SDValue V1 = Op.getOperand(0); 5490 SDValue V2 = Op.getOperand(1); 5491 unsigned NumElems = ResVT.getVectorNumElements(); 5492 5493 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl); 5494} 5495 5496SDValue 5497X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const { 5498 EVT ResVT = Op.getValueType(); 5499 5500 assert(Op.getNumOperands() == 2); 5501 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) && 5502 "Unsupported CONCAT_VECTORS for value type"); 5503 5504 // We support concatenate two MMX registers and place them in a MMX register. 5505 // This is better than doing a stack convert. 5506 if (ResVT.is128BitVector()) 5507 return LowerMMXCONCAT_VECTORS(Op, DAG); 5508 5509 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors 5510 // from two other 128-bit ones. 5511 return LowerAVXCONCAT_VECTORS(Op, DAG); 5512} 5513 5514// Try to lower a shuffle node into a simple blend instruction. 5515static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp, 5516 const X86Subtarget *Subtarget, 5517 SelectionDAG &DAG) { 5518 SDValue V1 = SVOp->getOperand(0); 5519 SDValue V2 = SVOp->getOperand(1); 5520 DebugLoc dl = SVOp->getDebugLoc(); 5521 MVT VT = SVOp->getValueType(0).getSimpleVT(); 5522 unsigned NumElems = VT.getVectorNumElements(); 5523 5524 if (!Subtarget->hasSSE41()) 5525 return SDValue(); 5526 5527 unsigned ISDNo = 0; 5528 MVT OpTy; 5529 5530 switch (VT.SimpleTy) { 5531 default: return SDValue(); 5532 case MVT::v8i16: 5533 ISDNo = X86ISD::BLENDPW; 5534 OpTy = MVT::v8i16; 5535 break; 5536 case MVT::v4i32: 5537 case MVT::v4f32: 5538 ISDNo = X86ISD::BLENDPS; 5539 OpTy = MVT::v4f32; 5540 break; 5541 case MVT::v2i64: 5542 case MVT::v2f64: 5543 ISDNo = X86ISD::BLENDPD; 5544 OpTy = MVT::v2f64; 5545 break; 5546 case MVT::v8i32: 5547 case MVT::v8f32: 5548 if (!Subtarget->hasAVX()) 5549 return SDValue(); 5550 ISDNo = X86ISD::BLENDPS; 5551 OpTy = MVT::v8f32; 5552 break; 5553 case MVT::v4i64: 5554 case MVT::v4f64: 5555 if (!Subtarget->hasAVX()) 5556 return SDValue(); 5557 ISDNo = X86ISD::BLENDPD; 5558 OpTy = MVT::v4f64; 5559 break; 5560 } 5561 assert(ISDNo && "Invalid Op Number"); 5562 5563 unsigned MaskVals = 0; 5564 5565 for (unsigned i = 0; i != NumElems; ++i) { 5566 int EltIdx = SVOp->getMaskElt(i); 5567 if (EltIdx == (int)i || EltIdx < 0) 5568 MaskVals |= (1<<i); 5569 else if (EltIdx == (int)(i + NumElems)) 5570 continue; // Bit is set to zero; 5571 else 5572 return SDValue(); 5573 } 5574 5575 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1); 5576 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2); 5577 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2, 5578 DAG.getConstant(MaskVals, MVT::i32)); 5579 return DAG.getNode(ISD::BITCAST, dl, VT, Ret); 5580} 5581 5582// v8i16 shuffles - Prefer shuffles in the following order: 5583// 1. [all] pshuflw, pshufhw, optional move 5584// 2. [ssse3] 1 x pshufb 5585// 3. [ssse3] 2 x pshufb + 1 x por 5586// 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw) 5587SDValue 5588X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op, 5589 SelectionDAG &DAG) const { 5590 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5591 SDValue V1 = SVOp->getOperand(0); 5592 SDValue V2 = SVOp->getOperand(1); 5593 DebugLoc dl = SVOp->getDebugLoc(); 5594 SmallVector<int, 8> MaskVals; 5595 5596 // Determine if more than 1 of the words in each of the low and high quadwords 5597 // of the result come from the same quadword of one of the two inputs. Undef 5598 // mask values count as coming from any quadword, for better codegen. 5599 unsigned LoQuad[] = { 0, 0, 0, 0 }; 5600 unsigned HiQuad[] = { 0, 0, 0, 0 }; 5601 std::bitset<4> InputQuads; 5602 for (unsigned i = 0; i < 8; ++i) { 5603 unsigned *Quad = i < 4 ? LoQuad : HiQuad; 5604 int EltIdx = SVOp->getMaskElt(i); 5605 MaskVals.push_back(EltIdx); 5606 if (EltIdx < 0) { 5607 ++Quad[0]; 5608 ++Quad[1]; 5609 ++Quad[2]; 5610 ++Quad[3]; 5611 continue; 5612 } 5613 ++Quad[EltIdx / 4]; 5614 InputQuads.set(EltIdx / 4); 5615 } 5616 5617 int BestLoQuad = -1; 5618 unsigned MaxQuad = 1; 5619 for (unsigned i = 0; i < 4; ++i) { 5620 if (LoQuad[i] > MaxQuad) { 5621 BestLoQuad = i; 5622 MaxQuad = LoQuad[i]; 5623 } 5624 } 5625 5626 int BestHiQuad = -1; 5627 MaxQuad = 1; 5628 for (unsigned i = 0; i < 4; ++i) { 5629 if (HiQuad[i] > MaxQuad) { 5630 BestHiQuad = i; 5631 MaxQuad = HiQuad[i]; 5632 } 5633 } 5634 5635 // For SSSE3, If all 8 words of the result come from only 1 quadword of each 5636 // of the two input vectors, shuffle them into one input vector so only a 5637 // single pshufb instruction is necessary. If There are more than 2 input 5638 // quads, disable the next transformation since it does not help SSSE3. 5639 bool V1Used = InputQuads[0] || InputQuads[1]; 5640 bool V2Used = InputQuads[2] || InputQuads[3]; 5641 if (Subtarget->hasSSSE3()) { 5642 if (InputQuads.count() == 2 && V1Used && V2Used) { 5643 BestLoQuad = InputQuads[0] ? 0 : 1; 5644 BestHiQuad = InputQuads[2] ? 2 : 3; 5645 } 5646 if (InputQuads.count() > 2) { 5647 BestLoQuad = -1; 5648 BestHiQuad = -1; 5649 } 5650 } 5651 5652 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update 5653 // the shuffle mask. If a quad is scored as -1, that means that it contains 5654 // words from all 4 input quadwords. 5655 SDValue NewV; 5656 if (BestLoQuad >= 0 || BestHiQuad >= 0) { 5657 int MaskV[] = { 5658 BestLoQuad < 0 ? 0 : BestLoQuad, 5659 BestHiQuad < 0 ? 1 : BestHiQuad 5660 }; 5661 NewV = DAG.getVectorShuffle(MVT::v2i64, dl, 5662 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1), 5663 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]); 5664 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV); 5665 5666 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the 5667 // source words for the shuffle, to aid later transformations. 5668 bool AllWordsInNewV = true; 5669 bool InOrder[2] = { true, true }; 5670 for (unsigned i = 0; i != 8; ++i) { 5671 int idx = MaskVals[i]; 5672 if (idx != (int)i) 5673 InOrder[i/4] = false; 5674 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad) 5675 continue; 5676 AllWordsInNewV = false; 5677 break; 5678 } 5679 5680 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV; 5681 if (AllWordsInNewV) { 5682 for (int i = 0; i != 8; ++i) { 5683 int idx = MaskVals[i]; 5684 if (idx < 0) 5685 continue; 5686 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4; 5687 if ((idx != i) && idx < 4) 5688 pshufhw = false; 5689 if ((idx != i) && idx > 3) 5690 pshuflw = false; 5691 } 5692 V1 = NewV; 5693 V2Used = false; 5694 BestLoQuad = 0; 5695 BestHiQuad = 1; 5696 } 5697 5698 // If we've eliminated the use of V2, and the new mask is a pshuflw or 5699 // pshufhw, that's as cheap as it gets. Return the new shuffle. 5700 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) { 5701 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW; 5702 unsigned TargetMask = 0; 5703 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, 5704 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]); 5705 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode()); 5706 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp): 5707 getShufflePSHUFLWImmediate(SVOp); 5708 V1 = NewV.getOperand(0); 5709 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG); 5710 } 5711 } 5712 5713 // If we have SSSE3, and all words of the result are from 1 input vector, 5714 // case 2 is generated, otherwise case 3 is generated. If no SSSE3 5715 // is present, fall back to case 4. 5716 if (Subtarget->hasSSSE3()) { 5717 SmallVector<SDValue,16> pshufbMask; 5718 5719 // If we have elements from both input vectors, set the high bit of the 5720 // shuffle mask element to zero out elements that come from V2 in the V1 5721 // mask, and elements that come from V1 in the V2 mask, so that the two 5722 // results can be OR'd together. 5723 bool TwoInputs = V1Used && V2Used; 5724 for (unsigned i = 0; i != 8; ++i) { 5725 int EltIdx = MaskVals[i] * 2; 5726 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx; 5727 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1; 5728 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8)); 5729 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8)); 5730 } 5731 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1); 5732 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 5733 DAG.getNode(ISD::BUILD_VECTOR, dl, 5734 MVT::v16i8, &pshufbMask[0], 16)); 5735 if (!TwoInputs) 5736 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5737 5738 // Calculate the shuffle mask for the second input, shuffle it, and 5739 // OR it with the first shuffled input. 5740 pshufbMask.clear(); 5741 for (unsigned i = 0; i != 8; ++i) { 5742 int EltIdx = MaskVals[i] * 2; 5743 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16; 5744 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15; 5745 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8)); 5746 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8)); 5747 } 5748 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2); 5749 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 5750 DAG.getNode(ISD::BUILD_VECTOR, dl, 5751 MVT::v16i8, &pshufbMask[0], 16)); 5752 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 5753 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5754 } 5755 5756 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order, 5757 // and update MaskVals with new element order. 5758 std::bitset<8> InOrder; 5759 if (BestLoQuad >= 0) { 5760 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 }; 5761 for (int i = 0; i != 4; ++i) { 5762 int idx = MaskVals[i]; 5763 if (idx < 0) { 5764 InOrder.set(i); 5765 } else if ((idx / 4) == BestLoQuad) { 5766 MaskV[i] = idx & 3; 5767 InOrder.set(i); 5768 } 5769 } 5770 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 5771 &MaskV[0]); 5772 5773 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) { 5774 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode()); 5775 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16, 5776 NewV.getOperand(0), 5777 getShufflePSHUFLWImmediate(SVOp), DAG); 5778 } 5779 } 5780 5781 // If BestHi >= 0, generate a pshufhw to put the high elements in order, 5782 // and update MaskVals with the new element order. 5783 if (BestHiQuad >= 0) { 5784 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 }; 5785 for (unsigned i = 4; i != 8; ++i) { 5786 int idx = MaskVals[i]; 5787 if (idx < 0) { 5788 InOrder.set(i); 5789 } else if ((idx / 4) == BestHiQuad) { 5790 MaskV[i] = (idx & 3) + 4; 5791 InOrder.set(i); 5792 } 5793 } 5794 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 5795 &MaskV[0]); 5796 5797 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) { 5798 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode()); 5799 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16, 5800 NewV.getOperand(0), 5801 getShufflePSHUFHWImmediate(SVOp), DAG); 5802 } 5803 } 5804 5805 // In case BestHi & BestLo were both -1, which means each quadword has a word 5806 // from each of the four input quadwords, calculate the InOrder bitvector now 5807 // before falling through to the insert/extract cleanup. 5808 if (BestLoQuad == -1 && BestHiQuad == -1) { 5809 NewV = V1; 5810 for (int i = 0; i != 8; ++i) 5811 if (MaskVals[i] < 0 || MaskVals[i] == i) 5812 InOrder.set(i); 5813 } 5814 5815 // The other elements are put in the right place using pextrw and pinsrw. 5816 for (unsigned i = 0; i != 8; ++i) { 5817 if (InOrder[i]) 5818 continue; 5819 int EltIdx = MaskVals[i]; 5820 if (EltIdx < 0) 5821 continue; 5822 SDValue ExtOp = (EltIdx < 8) ? 5823 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1, 5824 DAG.getIntPtrConstant(EltIdx)) : 5825 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2, 5826 DAG.getIntPtrConstant(EltIdx - 8)); 5827 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp, 5828 DAG.getIntPtrConstant(i)); 5829 } 5830 return NewV; 5831} 5832 5833// v16i8 shuffles - Prefer shuffles in the following order: 5834// 1. [ssse3] 1 x pshufb 5835// 2. [ssse3] 2 x pshufb + 1 x por 5836// 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw 5837static 5838SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp, 5839 SelectionDAG &DAG, 5840 const X86TargetLowering &TLI) { 5841 SDValue V1 = SVOp->getOperand(0); 5842 SDValue V2 = SVOp->getOperand(1); 5843 DebugLoc dl = SVOp->getDebugLoc(); 5844 ArrayRef<int> MaskVals = SVOp->getMask(); 5845 5846 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 5847 5848 // If we have SSSE3, case 1 is generated when all result bytes come from 5849 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is 5850 // present, fall back to case 3. 5851 5852 // If SSSE3, use 1 pshufb instruction per vector with elements in the result. 5853 if (TLI.getSubtarget()->hasSSSE3()) { 5854 SmallVector<SDValue,16> pshufbMask; 5855 5856 // If all result elements are from one input vector, then only translate 5857 // undef mask values to 0x80 (zero out result) in the pshufb mask. 5858 // 5859 // Otherwise, we have elements from both input vectors, and must zero out 5860 // elements that come from V2 in the first mask, and V1 in the second mask 5861 // so that we can OR them together. 5862 for (unsigned i = 0; i != 16; ++i) { 5863 int EltIdx = MaskVals[i]; 5864 if (EltIdx < 0 || EltIdx >= 16) 5865 EltIdx = 0x80; 5866 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 5867 } 5868 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 5869 DAG.getNode(ISD::BUILD_VECTOR, dl, 5870 MVT::v16i8, &pshufbMask[0], 16)); 5871 if (V2IsUndef) 5872 return V1; 5873 5874 // Calculate the shuffle mask for the second input, shuffle it, and 5875 // OR it with the first shuffled input. 5876 pshufbMask.clear(); 5877 for (unsigned i = 0; i != 16; ++i) { 5878 int EltIdx = MaskVals[i]; 5879 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16; 5880 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 5881 } 5882 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 5883 DAG.getNode(ISD::BUILD_VECTOR, dl, 5884 MVT::v16i8, &pshufbMask[0], 16)); 5885 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 5886 } 5887 5888 // No SSSE3 - Calculate in place words and then fix all out of place words 5889 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from 5890 // the 16 different words that comprise the two doublequadword input vectors. 5891 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5892 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 5893 SDValue NewV = V1; 5894 for (int i = 0; i != 8; ++i) { 5895 int Elt0 = MaskVals[i*2]; 5896 int Elt1 = MaskVals[i*2+1]; 5897 5898 // This word of the result is all undef, skip it. 5899 if (Elt0 < 0 && Elt1 < 0) 5900 continue; 5901 5902 // This word of the result is already in the correct place, skip it. 5903 if ((Elt0 == i*2) && (Elt1 == i*2+1)) 5904 continue; 5905 5906 SDValue Elt0Src = Elt0 < 16 ? V1 : V2; 5907 SDValue Elt1Src = Elt1 < 16 ? V1 : V2; 5908 SDValue InsElt; 5909 5910 // If Elt0 and Elt1 are defined, are consecutive, and can be load 5911 // using a single extract together, load it and store it. 5912 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) { 5913 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5914 DAG.getIntPtrConstant(Elt1 / 2)); 5915 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5916 DAG.getIntPtrConstant(i)); 5917 continue; 5918 } 5919 5920 // If Elt1 is defined, extract it from the appropriate source. If the 5921 // source byte is not also odd, shift the extracted word left 8 bits 5922 // otherwise clear the bottom 8 bits if we need to do an or. 5923 if (Elt1 >= 0) { 5924 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5925 DAG.getIntPtrConstant(Elt1 / 2)); 5926 if ((Elt1 & 1) == 0) 5927 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt, 5928 DAG.getConstant(8, 5929 TLI.getShiftAmountTy(InsElt.getValueType()))); 5930 else if (Elt0 >= 0) 5931 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt, 5932 DAG.getConstant(0xFF00, MVT::i16)); 5933 } 5934 // If Elt0 is defined, extract it from the appropriate source. If the 5935 // source byte is not also even, shift the extracted word right 8 bits. If 5936 // Elt1 was also defined, OR the extracted values together before 5937 // inserting them in the result. 5938 if (Elt0 >= 0) { 5939 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, 5940 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2)); 5941 if ((Elt0 & 1) != 0) 5942 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0, 5943 DAG.getConstant(8, 5944 TLI.getShiftAmountTy(InsElt0.getValueType()))); 5945 else if (Elt1 >= 0) 5946 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0, 5947 DAG.getConstant(0x00FF, MVT::i16)); 5948 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0) 5949 : InsElt0; 5950 } 5951 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5952 DAG.getIntPtrConstant(i)); 5953 } 5954 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV); 5955} 5956 5957/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide 5958/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be 5959/// done when every pair / quad of shuffle mask elements point to elements in 5960/// the right sequence. e.g. 5961/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15> 5962static 5963SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp, 5964 SelectionDAG &DAG, DebugLoc dl) { 5965 MVT VT = SVOp->getValueType(0).getSimpleVT(); 5966 unsigned NumElems = VT.getVectorNumElements(); 5967 MVT NewVT; 5968 unsigned Scale; 5969 switch (VT.SimpleTy) { 5970 default: llvm_unreachable("Unexpected!"); 5971 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break; 5972 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break; 5973 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break; 5974 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break; 5975 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break; 5976 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break; 5977 } 5978 5979 SmallVector<int, 8> MaskVec; 5980 for (unsigned i = 0; i != NumElems; i += Scale) { 5981 int StartIdx = -1; 5982 for (unsigned j = 0; j != Scale; ++j) { 5983 int EltIdx = SVOp->getMaskElt(i+j); 5984 if (EltIdx < 0) 5985 continue; 5986 if (StartIdx < 0) 5987 StartIdx = (EltIdx / Scale); 5988 if (EltIdx != (int)(StartIdx*Scale + j)) 5989 return SDValue(); 5990 } 5991 MaskVec.push_back(StartIdx); 5992 } 5993 5994 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0)); 5995 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1)); 5996 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]); 5997} 5998 5999/// getVZextMovL - Return a zero-extending vector move low node. 6000/// 6001static SDValue getVZextMovL(EVT VT, EVT OpVT, 6002 SDValue SrcOp, SelectionDAG &DAG, 6003 const X86Subtarget *Subtarget, DebugLoc dl) { 6004 if (VT == MVT::v2f64 || VT == MVT::v4f32) { 6005 LoadSDNode *LD = NULL; 6006 if (!isScalarLoadToVector(SrcOp.getNode(), &LD)) 6007 LD = dyn_cast<LoadSDNode>(SrcOp); 6008 if (!LD) { 6009 // movssrr and movsdrr do not clear top bits. Try to use movd, movq 6010 // instead. 6011 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32; 6012 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) && 6013 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR && 6014 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST && 6015 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) { 6016 // PR2108 6017 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32; 6018 return DAG.getNode(ISD::BITCAST, dl, VT, 6019 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 6020 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 6021 OpVT, 6022 SrcOp.getOperand(0) 6023 .getOperand(0)))); 6024 } 6025 } 6026 } 6027 6028 return DAG.getNode(ISD::BITCAST, dl, VT, 6029 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 6030 DAG.getNode(ISD::BITCAST, dl, 6031 OpVT, SrcOp))); 6032} 6033 6034/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles 6035/// which could not be matched by any known target speficic shuffle 6036static SDValue 6037LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 6038 6039 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG); 6040 if (NewOp.getNode()) 6041 return NewOp; 6042 6043 EVT VT = SVOp->getValueType(0); 6044 6045 unsigned NumElems = VT.getVectorNumElements(); 6046 unsigned NumLaneElems = NumElems / 2; 6047 6048 DebugLoc dl = SVOp->getDebugLoc(); 6049 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 6050 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems); 6051 SDValue Output[2]; 6052 6053 SmallVector<int, 16> Mask; 6054 for (unsigned l = 0; l < 2; ++l) { 6055 // Build a shuffle mask for the output, discovering on the fly which 6056 // input vectors to use as shuffle operands (recorded in InputUsed). 6057 // If building a suitable shuffle vector proves too hard, then bail 6058 // out with UseBuildVector set. 6059 bool UseBuildVector = false; 6060 int InputUsed[2] = { -1, -1 }; // Not yet discovered. 6061 unsigned LaneStart = l * NumLaneElems; 6062 for (unsigned i = 0; i != NumLaneElems; ++i) { 6063 // The mask element. This indexes into the input. 6064 int Idx = SVOp->getMaskElt(i+LaneStart); 6065 if (Idx < 0) { 6066 // the mask element does not index into any input vector. 6067 Mask.push_back(-1); 6068 continue; 6069 } 6070 6071 // The input vector this mask element indexes into. 6072 int Input = Idx / NumLaneElems; 6073 6074 // Turn the index into an offset from the start of the input vector. 6075 Idx -= Input * NumLaneElems; 6076 6077 // Find or create a shuffle vector operand to hold this input. 6078 unsigned OpNo; 6079 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) { 6080 if (InputUsed[OpNo] == Input) 6081 // This input vector is already an operand. 6082 break; 6083 if (InputUsed[OpNo] < 0) { 6084 // Create a new operand for this input vector. 6085 InputUsed[OpNo] = Input; 6086 break; 6087 } 6088 } 6089 6090 if (OpNo >= array_lengthof(InputUsed)) { 6091 // More than two input vectors used! Give up on trying to create a 6092 // shuffle vector. Insert all elements into a BUILD_VECTOR instead. 6093 UseBuildVector = true; 6094 break; 6095 } 6096 6097 // Add the mask index for the new shuffle vector. 6098 Mask.push_back(Idx + OpNo * NumLaneElems); 6099 } 6100 6101 if (UseBuildVector) { 6102 SmallVector<SDValue, 16> SVOps; 6103 for (unsigned i = 0; i != NumLaneElems; ++i) { 6104 // The mask element. This indexes into the input. 6105 int Idx = SVOp->getMaskElt(i+LaneStart); 6106 if (Idx < 0) { 6107 SVOps.push_back(DAG.getUNDEF(EltVT)); 6108 continue; 6109 } 6110 6111 // The input vector this mask element indexes into. 6112 int Input = Idx / NumElems; 6113 6114 // Turn the index into an offset from the start of the input vector. 6115 Idx -= Input * NumElems; 6116 6117 // Extract the vector element by hand. 6118 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6119 SVOp->getOperand(Input), 6120 DAG.getIntPtrConstant(Idx))); 6121 } 6122 6123 // Construct the output using a BUILD_VECTOR. 6124 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0], 6125 SVOps.size()); 6126 } else if (InputUsed[0] < 0) { 6127 // No input vectors were used! The result is undefined. 6128 Output[l] = DAG.getUNDEF(NVT); 6129 } else { 6130 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2), 6131 (InputUsed[0] % 2) * NumLaneElems, 6132 DAG, dl); 6133 // If only one input was used, use an undefined vector for the other. 6134 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) : 6135 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2), 6136 (InputUsed[1] % 2) * NumLaneElems, DAG, dl); 6137 // At least one input vector was used. Create a new shuffle vector. 6138 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]); 6139 } 6140 6141 Mask.clear(); 6142 } 6143 6144 // Concatenate the result back 6145 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]); 6146} 6147 6148/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with 6149/// 4 elements, and match them with several different shuffle types. 6150static SDValue 6151LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 6152 SDValue V1 = SVOp->getOperand(0); 6153 SDValue V2 = SVOp->getOperand(1); 6154 DebugLoc dl = SVOp->getDebugLoc(); 6155 EVT VT = SVOp->getValueType(0); 6156 6157 assert(VT.getSizeInBits() == 128 && "Unsupported vector size"); 6158 6159 std::pair<int, int> Locs[4]; 6160 int Mask1[] = { -1, -1, -1, -1 }; 6161 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end()); 6162 6163 unsigned NumHi = 0; 6164 unsigned NumLo = 0; 6165 for (unsigned i = 0; i != 4; ++i) { 6166 int Idx = PermMask[i]; 6167 if (Idx < 0) { 6168 Locs[i] = std::make_pair(-1, -1); 6169 } else { 6170 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!"); 6171 if (Idx < 4) { 6172 Locs[i] = std::make_pair(0, NumLo); 6173 Mask1[NumLo] = Idx; 6174 NumLo++; 6175 } else { 6176 Locs[i] = std::make_pair(1, NumHi); 6177 if (2+NumHi < 4) 6178 Mask1[2+NumHi] = Idx; 6179 NumHi++; 6180 } 6181 } 6182 } 6183 6184 if (NumLo <= 2 && NumHi <= 2) { 6185 // If no more than two elements come from either vector. This can be 6186 // implemented with two shuffles. First shuffle gather the elements. 6187 // The second shuffle, which takes the first shuffle as both of its 6188 // vector operands, put the elements into the right order. 6189 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6190 6191 int Mask2[] = { -1, -1, -1, -1 }; 6192 6193 for (unsigned i = 0; i != 4; ++i) 6194 if (Locs[i].first != -1) { 6195 unsigned Idx = (i < 2) ? 0 : 4; 6196 Idx += Locs[i].first * 2 + Locs[i].second; 6197 Mask2[i] = Idx; 6198 } 6199 6200 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]); 6201 } 6202 6203 if (NumLo == 3 || NumHi == 3) { 6204 // Otherwise, we must have three elements from one vector, call it X, and 6205 // one element from the other, call it Y. First, use a shufps to build an 6206 // intermediate vector with the one element from Y and the element from X 6207 // that will be in the same half in the final destination (the indexes don't 6208 // matter). Then, use a shufps to build the final vector, taking the half 6209 // containing the element from Y from the intermediate, and the other half 6210 // from X. 6211 if (NumHi == 3) { 6212 // Normalize it so the 3 elements come from V1. 6213 CommuteVectorShuffleMask(PermMask, 4); 6214 std::swap(V1, V2); 6215 } 6216 6217 // Find the element from V2. 6218 unsigned HiIndex; 6219 for (HiIndex = 0; HiIndex < 3; ++HiIndex) { 6220 int Val = PermMask[HiIndex]; 6221 if (Val < 0) 6222 continue; 6223 if (Val >= 4) 6224 break; 6225 } 6226 6227 Mask1[0] = PermMask[HiIndex]; 6228 Mask1[1] = -1; 6229 Mask1[2] = PermMask[HiIndex^1]; 6230 Mask1[3] = -1; 6231 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6232 6233 if (HiIndex >= 2) { 6234 Mask1[0] = PermMask[0]; 6235 Mask1[1] = PermMask[1]; 6236 Mask1[2] = HiIndex & 1 ? 6 : 4; 6237 Mask1[3] = HiIndex & 1 ? 4 : 6; 6238 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6239 } 6240 6241 Mask1[0] = HiIndex & 1 ? 2 : 0; 6242 Mask1[1] = HiIndex & 1 ? 0 : 2; 6243 Mask1[2] = PermMask[2]; 6244 Mask1[3] = PermMask[3]; 6245 if (Mask1[2] >= 0) 6246 Mask1[2] += 4; 6247 if (Mask1[3] >= 0) 6248 Mask1[3] += 4; 6249 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]); 6250 } 6251 6252 // Break it into (shuffle shuffle_hi, shuffle_lo). 6253 int LoMask[] = { -1, -1, -1, -1 }; 6254 int HiMask[] = { -1, -1, -1, -1 }; 6255 6256 int *MaskPtr = LoMask; 6257 unsigned MaskIdx = 0; 6258 unsigned LoIdx = 0; 6259 unsigned HiIdx = 2; 6260 for (unsigned i = 0; i != 4; ++i) { 6261 if (i == 2) { 6262 MaskPtr = HiMask; 6263 MaskIdx = 1; 6264 LoIdx = 0; 6265 HiIdx = 2; 6266 } 6267 int Idx = PermMask[i]; 6268 if (Idx < 0) { 6269 Locs[i] = std::make_pair(-1, -1); 6270 } else if (Idx < 4) { 6271 Locs[i] = std::make_pair(MaskIdx, LoIdx); 6272 MaskPtr[LoIdx] = Idx; 6273 LoIdx++; 6274 } else { 6275 Locs[i] = std::make_pair(MaskIdx, HiIdx); 6276 MaskPtr[HiIdx] = Idx; 6277 HiIdx++; 6278 } 6279 } 6280 6281 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]); 6282 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]); 6283 int MaskOps[] = { -1, -1, -1, -1 }; 6284 for (unsigned i = 0; i != 4; ++i) 6285 if (Locs[i].first != -1) 6286 MaskOps[i] = Locs[i].first * 4 + Locs[i].second; 6287 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]); 6288} 6289 6290static bool MayFoldVectorLoad(SDValue V) { 6291 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 6292 V = V.getOperand(0); 6293 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 6294 V = V.getOperand(0); 6295 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR && 6296 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF) 6297 // BUILD_VECTOR (load), undef 6298 V = V.getOperand(0); 6299 if (MayFoldLoad(V)) 6300 return true; 6301 return false; 6302} 6303 6304// FIXME: the version above should always be used. Since there's 6305// a bug where several vector shuffles can't be folded because the 6306// DAG is not updated during lowering and a node claims to have two 6307// uses while it only has one, use this version, and let isel match 6308// another instruction if the load really happens to have more than 6309// one use. Remove this version after this bug get fixed. 6310// rdar://8434668, PR8156 6311static bool RelaxedMayFoldVectorLoad(SDValue V) { 6312 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 6313 V = V.getOperand(0); 6314 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 6315 V = V.getOperand(0); 6316 if (ISD::isNormalLoad(V.getNode())) 6317 return true; 6318 return false; 6319} 6320 6321static 6322SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) { 6323 EVT VT = Op.getValueType(); 6324 6325 // Canonizalize to v2f64. 6326 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 6327 return DAG.getNode(ISD::BITCAST, dl, VT, 6328 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64, 6329 V1, DAG)); 6330} 6331 6332static 6333SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, 6334 bool HasSSE2) { 6335 SDValue V1 = Op.getOperand(0); 6336 SDValue V2 = Op.getOperand(1); 6337 EVT VT = Op.getValueType(); 6338 6339 assert(VT != MVT::v2i64 && "unsupported shuffle type"); 6340 6341 if (HasSSE2 && VT == MVT::v2f64) 6342 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG); 6343 6344 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1) 6345 return DAG.getNode(ISD::BITCAST, dl, VT, 6346 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32, 6347 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1), 6348 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG)); 6349} 6350 6351static 6352SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) { 6353 SDValue V1 = Op.getOperand(0); 6354 SDValue V2 = Op.getOperand(1); 6355 EVT VT = Op.getValueType(); 6356 6357 assert((VT == MVT::v4i32 || VT == MVT::v4f32) && 6358 "unsupported shuffle type"); 6359 6360 if (V2.getOpcode() == ISD::UNDEF) 6361 V2 = V1; 6362 6363 // v4i32 or v4f32 6364 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG); 6365} 6366 6367static 6368SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) { 6369 SDValue V1 = Op.getOperand(0); 6370 SDValue V2 = Op.getOperand(1); 6371 EVT VT = Op.getValueType(); 6372 unsigned NumElems = VT.getVectorNumElements(); 6373 6374 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second 6375 // operand of these instructions is only memory, so check if there's a 6376 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the 6377 // same masks. 6378 bool CanFoldLoad = false; 6379 6380 // Trivial case, when V2 comes from a load. 6381 if (MayFoldVectorLoad(V2)) 6382 CanFoldLoad = true; 6383 6384 // When V1 is a load, it can be folded later into a store in isel, example: 6385 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1) 6386 // turns into: 6387 // (MOVLPSmr addr:$src1, VR128:$src2) 6388 // So, recognize this potential and also use MOVLPS or MOVLPD 6389 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op)) 6390 CanFoldLoad = true; 6391 6392 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6393 if (CanFoldLoad) { 6394 if (HasSSE2 && NumElems == 2) 6395 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG); 6396 6397 if (NumElems == 4) 6398 // If we don't care about the second element, proceed to use movss. 6399 if (SVOp->getMaskElt(1) != -1) 6400 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG); 6401 } 6402 6403 // movl and movlp will both match v2i64, but v2i64 is never matched by 6404 // movl earlier because we make it strict to avoid messing with the movlp load 6405 // folding logic (see the code above getMOVLP call). Match it here then, 6406 // this is horrible, but will stay like this until we move all shuffle 6407 // matching to x86 specific nodes. Note that for the 1st condition all 6408 // types are matched with movsd. 6409 if (HasSSE2) { 6410 // FIXME: isMOVLMask should be checked and matched before getMOVLP, 6411 // as to remove this logic from here, as much as possible 6412 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT)) 6413 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 6414 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 6415 } 6416 6417 assert(VT != MVT::v4i32 && "unsupported shuffle type"); 6418 6419 // Invert the operand order and use SHUFPS to match it. 6420 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1, 6421 getShuffleSHUFImmediate(SVOp), DAG); 6422} 6423 6424SDValue 6425X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const { 6426 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6427 EVT VT = Op.getValueType(); 6428 DebugLoc dl = Op.getDebugLoc(); 6429 SDValue V1 = Op.getOperand(0); 6430 SDValue V2 = Op.getOperand(1); 6431 6432 if (isZeroShuffle(SVOp)) 6433 return getZeroVector(VT, Subtarget, DAG, dl); 6434 6435 // Handle splat operations 6436 if (SVOp->isSplat()) { 6437 unsigned NumElem = VT.getVectorNumElements(); 6438 int Size = VT.getSizeInBits(); 6439 6440 // Use vbroadcast whenever the splat comes from a foldable load 6441 SDValue Broadcast = LowerVectorBroadcast(Op, DAG); 6442 if (Broadcast.getNode()) 6443 return Broadcast; 6444 6445 // Handle splats by matching through known shuffle masks 6446 if ((Size == 128 && NumElem <= 4) || 6447 (Size == 256 && NumElem < 8)) 6448 return SDValue(); 6449 6450 // All remaning splats are promoted to target supported vector shuffles. 6451 return PromoteSplat(SVOp, DAG); 6452 } 6453 6454 // If the shuffle can be profitably rewritten as a narrower shuffle, then 6455 // do it! 6456 if (VT == MVT::v8i16 || VT == MVT::v16i8 || 6457 VT == MVT::v16i16 || VT == MVT::v32i8) { 6458 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6459 if (NewOp.getNode()) 6460 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp); 6461 } else if ((VT == MVT::v4i32 || 6462 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) { 6463 // FIXME: Figure out a cleaner way to do this. 6464 // Try to make use of movq to zero out the top part. 6465 if (ISD::isBuildVectorAllZeros(V2.getNode())) { 6466 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6467 if (NewOp.getNode()) { 6468 EVT NewVT = NewOp.getValueType(); 6469 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), 6470 NewVT, true, false)) 6471 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), 6472 DAG, Subtarget, dl); 6473 } 6474 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) { 6475 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6476 if (NewOp.getNode()) { 6477 EVT NewVT = NewOp.getValueType(); 6478 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT)) 6479 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), 6480 DAG, Subtarget, dl); 6481 } 6482 } 6483 } 6484 return SDValue(); 6485} 6486 6487SDValue 6488X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const { 6489 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6490 SDValue V1 = Op.getOperand(0); 6491 SDValue V2 = Op.getOperand(1); 6492 EVT VT = Op.getValueType(); 6493 DebugLoc dl = Op.getDebugLoc(); 6494 unsigned NumElems = VT.getVectorNumElements(); 6495 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF; 6496 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 6497 bool V1IsSplat = false; 6498 bool V2IsSplat = false; 6499 bool HasSSE2 = Subtarget->hasSSE2(); 6500 bool HasAVX = Subtarget->hasAVX(); 6501 bool HasAVX2 = Subtarget->hasAVX2(); 6502 MachineFunction &MF = DAG.getMachineFunction(); 6503 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize); 6504 6505 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles"); 6506 6507 if (V1IsUndef && V2IsUndef) 6508 return DAG.getUNDEF(VT); 6509 6510 assert(!V1IsUndef && "Op 1 of shuffle should not be undef"); 6511 6512 // Vector shuffle lowering takes 3 steps: 6513 // 6514 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable 6515 // narrowing and commutation of operands should be handled. 6516 // 2) Matching of shuffles with known shuffle masks to x86 target specific 6517 // shuffle nodes. 6518 // 3) Rewriting of unmatched masks into new generic shuffle operations, 6519 // so the shuffle can be broken into other shuffles and the legalizer can 6520 // try the lowering again. 6521 // 6522 // The general idea is that no vector_shuffle operation should be left to 6523 // be matched during isel, all of them must be converted to a target specific 6524 // node here. 6525 6526 // Normalize the input vectors. Here splats, zeroed vectors, profitable 6527 // narrowing and commutation of operands should be handled. The actual code 6528 // doesn't include all of those, work in progress... 6529 SDValue NewOp = NormalizeVectorShuffle(Op, DAG); 6530 if (NewOp.getNode()) 6531 return NewOp; 6532 6533 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end()); 6534 6535 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and 6536 // unpckh_undef). Only use pshufd if speed is more important than size. 6537 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2)) 6538 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG); 6539 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2)) 6540 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG); 6541 6542 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() && 6543 V2IsUndef && RelaxedMayFoldVectorLoad(V1)) 6544 return getMOVDDup(Op, dl, V1, DAG); 6545 6546 if (isMOVHLPS_v_undef_Mask(M, VT)) 6547 return getMOVHighToLow(Op, dl, DAG); 6548 6549 // Use to match splats 6550 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef && 6551 (VT == MVT::v2f64 || VT == MVT::v2i64)) 6552 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG); 6553 6554 if (isPSHUFDMask(M, VT)) { 6555 // The actual implementation will match the mask in the if above and then 6556 // during isel it can match several different instructions, not only pshufd 6557 // as its name says, sad but true, emulate the behavior for now... 6558 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64))) 6559 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG); 6560 6561 unsigned TargetMask = getShuffleSHUFImmediate(SVOp); 6562 6563 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64)) 6564 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG); 6565 6566 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32)) 6567 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG); 6568 6569 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1, 6570 TargetMask, DAG); 6571 } 6572 6573 // Check if this can be converted into a logical shift. 6574 bool isLeft = false; 6575 unsigned ShAmt = 0; 6576 SDValue ShVal; 6577 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt); 6578 if (isShift && ShVal.hasOneUse()) { 6579 // If the shifted value has multiple uses, it may be cheaper to use 6580 // v_set0 + movlhps or movhlps, etc. 6581 EVT EltVT = VT.getVectorElementType(); 6582 ShAmt *= EltVT.getSizeInBits(); 6583 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 6584 } 6585 6586 if (isMOVLMask(M, VT)) { 6587 if (ISD::isBuildVectorAllZeros(V1.getNode())) 6588 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl); 6589 if (!isMOVLPMask(M, VT)) { 6590 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64)) 6591 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 6592 6593 if (VT == MVT::v4i32 || VT == MVT::v4f32) 6594 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 6595 } 6596 } 6597 6598 // FIXME: fold these into legal mask. 6599 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2)) 6600 return getMOVLowToHigh(Op, dl, DAG, HasSSE2); 6601 6602 if (isMOVHLPSMask(M, VT)) 6603 return getMOVHighToLow(Op, dl, DAG); 6604 6605 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget)) 6606 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG); 6607 6608 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget)) 6609 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG); 6610 6611 if (isMOVLPMask(M, VT)) 6612 return getMOVLP(Op, dl, DAG, HasSSE2); 6613 6614 if (ShouldXformToMOVHLPS(M, VT) || 6615 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT)) 6616 return CommuteVectorShuffle(SVOp, DAG); 6617 6618 if (isShift) { 6619 // No better options. Use a vshldq / vsrldq. 6620 EVT EltVT = VT.getVectorElementType(); 6621 ShAmt *= EltVT.getSizeInBits(); 6622 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 6623 } 6624 6625 bool Commuted = false; 6626 // FIXME: This should also accept a bitcast of a splat? Be careful, not 6627 // 1,1,1,1 -> v8i16 though. 6628 V1IsSplat = isSplatVector(V1.getNode()); 6629 V2IsSplat = isSplatVector(V2.getNode()); 6630 6631 // Canonicalize the splat or undef, if present, to be on the RHS. 6632 if (!V2IsUndef && V1IsSplat && !V2IsSplat) { 6633 CommuteVectorShuffleMask(M, NumElems); 6634 std::swap(V1, V2); 6635 std::swap(V1IsSplat, V2IsSplat); 6636 Commuted = true; 6637 } 6638 6639 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) { 6640 // Shuffling low element of v1 into undef, just return v1. 6641 if (V2IsUndef) 6642 return V1; 6643 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which 6644 // the instruction selector will not match, so get a canonical MOVL with 6645 // swapped operands to undo the commute. 6646 return getMOVL(DAG, dl, VT, V2, V1); 6647 } 6648 6649 if (isUNPCKLMask(M, VT, HasAVX2)) 6650 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG); 6651 6652 if (isUNPCKHMask(M, VT, HasAVX2)) 6653 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG); 6654 6655 if (V2IsSplat) { 6656 // Normalize mask so all entries that point to V2 points to its first 6657 // element then try to match unpck{h|l} again. If match, return a 6658 // new vector_shuffle with the corrected mask.p 6659 SmallVector<int, 8> NewMask(M.begin(), M.end()); 6660 NormalizeMask(NewMask, NumElems); 6661 if (isUNPCKLMask(NewMask, VT, HasAVX2, true)) 6662 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG); 6663 if (isUNPCKHMask(NewMask, VT, HasAVX2, true)) 6664 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG); 6665 } 6666 6667 if (Commuted) { 6668 // Commute is back and try unpck* again. 6669 // FIXME: this seems wrong. 6670 CommuteVectorShuffleMask(M, NumElems); 6671 std::swap(V1, V2); 6672 std::swap(V1IsSplat, V2IsSplat); 6673 Commuted = false; 6674 6675 if (isUNPCKLMask(M, VT, HasAVX2)) 6676 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG); 6677 6678 if (isUNPCKHMask(M, VT, HasAVX2)) 6679 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG); 6680 } 6681 6682 // Normalize the node to match x86 shuffle ops if needed 6683 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true))) 6684 return CommuteVectorShuffle(SVOp, DAG); 6685 6686 // The checks below are all present in isShuffleMaskLegal, but they are 6687 // inlined here right now to enable us to directly emit target specific 6688 // nodes, and remove one by one until they don't return Op anymore. 6689 6690 if (isPALIGNRMask(M, VT, Subtarget)) 6691 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2, 6692 getShufflePALIGNRImmediate(SVOp), 6693 DAG); 6694 6695 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) && 6696 SVOp->getSplatIndex() == 0 && V2IsUndef) { 6697 if (VT == MVT::v2f64 || VT == MVT::v2i64) 6698 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG); 6699 } 6700 6701 if (isPSHUFHWMask(M, VT, HasAVX2)) 6702 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1, 6703 getShufflePSHUFHWImmediate(SVOp), 6704 DAG); 6705 6706 if (isPSHUFLWMask(M, VT, HasAVX2)) 6707 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1, 6708 getShufflePSHUFLWImmediate(SVOp), 6709 DAG); 6710 6711 if (isSHUFPMask(M, VT, HasAVX)) 6712 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2, 6713 getShuffleSHUFImmediate(SVOp), DAG); 6714 6715 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2)) 6716 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG); 6717 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2)) 6718 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG); 6719 6720 //===--------------------------------------------------------------------===// 6721 // Generate target specific nodes for 128 or 256-bit shuffles only 6722 // supported in the AVX instruction set. 6723 // 6724 6725 // Handle VMOVDDUPY permutations 6726 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX)) 6727 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG); 6728 6729 // Handle VPERMILPS/D* permutations 6730 if (isVPERMILPMask(M, VT, HasAVX)) { 6731 if (HasAVX2 && VT == MVT::v8i32) 6732 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, 6733 getShuffleSHUFImmediate(SVOp), DAG); 6734 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, 6735 getShuffleSHUFImmediate(SVOp), DAG); 6736 } 6737 6738 // Handle VPERM2F128/VPERM2I128 permutations 6739 if (isVPERM2X128Mask(M, VT, HasAVX)) 6740 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1, 6741 V2, getShuffleVPERM2X128Immediate(SVOp), DAG); 6742 6743 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG); 6744 if (BlendOp.getNode()) 6745 return BlendOp; 6746 6747 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) { 6748 SmallVector<SDValue, 8> permclMask; 6749 for (unsigned i = 0; i != 8; ++i) { 6750 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32)); 6751 } 6752 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, 6753 &permclMask[0], 8); 6754 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32 6755 return DAG.getNode(X86ISD::VPERMV, dl, VT, 6756 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1); 6757 } 6758 6759 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64)) 6760 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, 6761 getShuffleCLImmediate(SVOp), DAG); 6762 6763 6764 //===--------------------------------------------------------------------===// 6765 // Since no target specific shuffle was selected for this generic one, 6766 // lower it into other known shuffles. FIXME: this isn't true yet, but 6767 // this is the plan. 6768 // 6769 6770 // Handle v8i16 specifically since SSE can do byte extraction and insertion. 6771 if (VT == MVT::v8i16) { 6772 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG); 6773 if (NewOp.getNode()) 6774 return NewOp; 6775 } 6776 6777 if (VT == MVT::v16i8) { 6778 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this); 6779 if (NewOp.getNode()) 6780 return NewOp; 6781 } 6782 6783 // Handle all 128-bit wide vectors with 4 elements, and match them with 6784 // several different shuffle types. 6785 if (NumElems == 4 && VT.getSizeInBits() == 128) 6786 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG); 6787 6788 // Handle general 256-bit shuffles 6789 if (VT.is256BitVector()) 6790 return LowerVECTOR_SHUFFLE_256(SVOp, DAG); 6791 6792 return SDValue(); 6793} 6794 6795SDValue 6796X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, 6797 SelectionDAG &DAG) const { 6798 EVT VT = Op.getValueType(); 6799 DebugLoc dl = Op.getDebugLoc(); 6800 6801 if (Op.getOperand(0).getValueType().getSizeInBits() != 128) 6802 return SDValue(); 6803 6804 if (VT.getSizeInBits() == 8) { 6805 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, 6806 Op.getOperand(0), Op.getOperand(1)); 6807 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 6808 DAG.getValueType(VT)); 6809 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6810 } 6811 6812 if (VT.getSizeInBits() == 16) { 6813 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6814 // If Idx is 0, it's cheaper to do a move instead of a pextrw. 6815 if (Idx == 0) 6816 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 6817 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 6818 DAG.getNode(ISD::BITCAST, dl, 6819 MVT::v4i32, 6820 Op.getOperand(0)), 6821 Op.getOperand(1))); 6822 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, 6823 Op.getOperand(0), Op.getOperand(1)); 6824 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 6825 DAG.getValueType(VT)); 6826 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6827 } 6828 6829 if (VT == MVT::f32) { 6830 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy 6831 // the result back to FR32 register. It's only worth matching if the 6832 // result has a single use which is a store or a bitcast to i32. And in 6833 // the case of a store, it's not worth it if the index is a constant 0, 6834 // because a MOVSSmr can be used instead, which is smaller and faster. 6835 if (!Op.hasOneUse()) 6836 return SDValue(); 6837 SDNode *User = *Op.getNode()->use_begin(); 6838 if ((User->getOpcode() != ISD::STORE || 6839 (isa<ConstantSDNode>(Op.getOperand(1)) && 6840 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) && 6841 (User->getOpcode() != ISD::BITCAST || 6842 User->getValueType(0) != MVT::i32)) 6843 return SDValue(); 6844 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 6845 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, 6846 Op.getOperand(0)), 6847 Op.getOperand(1)); 6848 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract); 6849 } 6850 6851 if (VT == MVT::i32 || VT == MVT::i64) { 6852 // ExtractPS/pextrq works with constant index. 6853 if (isa<ConstantSDNode>(Op.getOperand(1))) 6854 return Op; 6855 } 6856 return SDValue(); 6857} 6858 6859 6860SDValue 6861X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 6862 SelectionDAG &DAG) const { 6863 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6864 return SDValue(); 6865 6866 SDValue Vec = Op.getOperand(0); 6867 EVT VecVT = Vec.getValueType(); 6868 6869 // If this is a 256-bit vector result, first extract the 128-bit vector and 6870 // then extract the element from the 128-bit vector. 6871 if (VecVT.getSizeInBits() == 256) { 6872 DebugLoc dl = Op.getNode()->getDebugLoc(); 6873 unsigned NumElems = VecVT.getVectorNumElements(); 6874 SDValue Idx = Op.getOperand(1); 6875 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 6876 6877 // Get the 128-bit vector. 6878 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl); 6879 6880 if (IdxVal >= NumElems/2) 6881 IdxVal -= NumElems/2; 6882 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec, 6883 DAG.getConstant(IdxVal, MVT::i32)); 6884 } 6885 6886 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length"); 6887 6888 if (Subtarget->hasSSE41()) { 6889 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG); 6890 if (Res.getNode()) 6891 return Res; 6892 } 6893 6894 EVT VT = Op.getValueType(); 6895 DebugLoc dl = Op.getDebugLoc(); 6896 // TODO: handle v16i8. 6897 if (VT.getSizeInBits() == 16) { 6898 SDValue Vec = Op.getOperand(0); 6899 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6900 if (Idx == 0) 6901 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 6902 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 6903 DAG.getNode(ISD::BITCAST, dl, 6904 MVT::v4i32, Vec), 6905 Op.getOperand(1))); 6906 // Transform it so it match pextrw which produces a 32-bit result. 6907 EVT EltVT = MVT::i32; 6908 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT, 6909 Op.getOperand(0), Op.getOperand(1)); 6910 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract, 6911 DAG.getValueType(VT)); 6912 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6913 } 6914 6915 if (VT.getSizeInBits() == 32) { 6916 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6917 if (Idx == 0) 6918 return Op; 6919 6920 // SHUFPS the element to the lowest double word, then movss. 6921 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 }; 6922 EVT VVT = Op.getOperand(0).getValueType(); 6923 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 6924 DAG.getUNDEF(VVT), Mask); 6925 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 6926 DAG.getIntPtrConstant(0)); 6927 } 6928 6929 if (VT.getSizeInBits() == 64) { 6930 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b 6931 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught 6932 // to match extract_elt for f64. 6933 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6934 if (Idx == 0) 6935 return Op; 6936 6937 // UNPCKHPD the element to the lowest double word, then movsd. 6938 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored 6939 // to a f64mem, the whole operation is folded into a single MOVHPDmr. 6940 int Mask[2] = { 1, -1 }; 6941 EVT VVT = Op.getOperand(0).getValueType(); 6942 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 6943 DAG.getUNDEF(VVT), Mask); 6944 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 6945 DAG.getIntPtrConstant(0)); 6946 } 6947 6948 return SDValue(); 6949} 6950 6951SDValue 6952X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, 6953 SelectionDAG &DAG) const { 6954 EVT VT = Op.getValueType(); 6955 EVT EltVT = VT.getVectorElementType(); 6956 DebugLoc dl = Op.getDebugLoc(); 6957 6958 SDValue N0 = Op.getOperand(0); 6959 SDValue N1 = Op.getOperand(1); 6960 SDValue N2 = Op.getOperand(2); 6961 6962 if (VT.getSizeInBits() == 256) 6963 return SDValue(); 6964 6965 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) && 6966 isa<ConstantSDNode>(N2)) { 6967 unsigned Opc; 6968 if (VT == MVT::v8i16) 6969 Opc = X86ISD::PINSRW; 6970 else if (VT == MVT::v16i8) 6971 Opc = X86ISD::PINSRB; 6972 else 6973 Opc = X86ISD::PINSRB; 6974 6975 // Transform it so it match pinsr{b,w} which expects a GR32 as its second 6976 // argument. 6977 if (N1.getValueType() != MVT::i32) 6978 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 6979 if (N2.getValueType() != MVT::i32) 6980 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 6981 return DAG.getNode(Opc, dl, VT, N0, N1, N2); 6982 } 6983 6984 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) { 6985 // Bits [7:6] of the constant are the source select. This will always be 6986 // zero here. The DAG Combiner may combine an extract_elt index into these 6987 // bits. For example (insert (extract, 3), 2) could be matched by putting 6988 // the '3' into bits [7:6] of X86ISD::INSERTPS. 6989 // Bits [5:4] of the constant are the destination select. This is the 6990 // value of the incoming immediate. 6991 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may 6992 // combine either bitwise AND or insert of float 0.0 to set these bits. 6993 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4); 6994 // Create this as a scalar to vector.. 6995 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1); 6996 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2); 6997 } 6998 6999 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) { 7000 // PINSR* works with constant index. 7001 return Op; 7002 } 7003 return SDValue(); 7004} 7005 7006SDValue 7007X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { 7008 EVT VT = Op.getValueType(); 7009 EVT EltVT = VT.getVectorElementType(); 7010 7011 DebugLoc dl = Op.getDebugLoc(); 7012 SDValue N0 = Op.getOperand(0); 7013 SDValue N1 = Op.getOperand(1); 7014 SDValue N2 = Op.getOperand(2); 7015 7016 // If this is a 256-bit vector result, first extract the 128-bit vector, 7017 // insert the element into the extracted half and then place it back. 7018 if (VT.getSizeInBits() == 256) { 7019 if (!isa<ConstantSDNode>(N2)) 7020 return SDValue(); 7021 7022 // Get the desired 128-bit vector half. 7023 unsigned NumElems = VT.getVectorNumElements(); 7024 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue(); 7025 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl); 7026 7027 // Insert the element into the desired half. 7028 bool Upper = IdxVal >= NumElems/2; 7029 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1, 7030 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32)); 7031 7032 // Insert the changed part back to the 256-bit vector 7033 return Insert128BitVector(N0, V, IdxVal, DAG, dl); 7034 } 7035 7036 if (Subtarget->hasSSE41()) 7037 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG); 7038 7039 if (EltVT == MVT::i8) 7040 return SDValue(); 7041 7042 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) { 7043 // Transform it so it match pinsrw which expects a 16-bit value in a GR32 7044 // as its second argument. 7045 if (N1.getValueType() != MVT::i32) 7046 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 7047 if (N2.getValueType() != MVT::i32) 7048 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 7049 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2); 7050 } 7051 return SDValue(); 7052} 7053 7054SDValue 7055X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const { 7056 LLVMContext *Context = DAG.getContext(); 7057 DebugLoc dl = Op.getDebugLoc(); 7058 EVT OpVT = Op.getValueType(); 7059 7060 // If this is a 256-bit vector result, first insert into a 128-bit 7061 // vector and then insert into the 256-bit vector. 7062 if (OpVT.getSizeInBits() > 128) { 7063 // Insert into a 128-bit vector. 7064 EVT VT128 = EVT::getVectorVT(*Context, 7065 OpVT.getVectorElementType(), 7066 OpVT.getVectorNumElements() / 2); 7067 7068 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0)); 7069 7070 // Insert the 128-bit vector. 7071 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl); 7072 } 7073 7074 if (OpVT == MVT::v1i64 && 7075 Op.getOperand(0).getValueType() == MVT::i64) 7076 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0)); 7077 7078 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0)); 7079 assert(OpVT.getSizeInBits() == 128 && "Expected an SSE type!"); 7080 return DAG.getNode(ISD::BITCAST, dl, OpVT, 7081 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt)); 7082} 7083 7084// Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in 7085// a simple subregister reference or explicit instructions to grab 7086// upper bits of a vector. 7087SDValue 7088X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 7089 if (Subtarget->hasAVX()) { 7090 DebugLoc dl = Op.getNode()->getDebugLoc(); 7091 SDValue Vec = Op.getNode()->getOperand(0); 7092 SDValue Idx = Op.getNode()->getOperand(1); 7093 7094 if (Op.getNode()->getValueType(0).getSizeInBits() == 128 && 7095 Vec.getNode()->getValueType(0).getSizeInBits() == 256 && 7096 isa<ConstantSDNode>(Idx)) { 7097 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 7098 return Extract128BitVector(Vec, IdxVal, DAG, dl); 7099 } 7100 } 7101 return SDValue(); 7102} 7103 7104// Lower a node with an INSERT_SUBVECTOR opcode. This may result in a 7105// simple superregister reference or explicit instructions to insert 7106// the upper bits of a vector. 7107SDValue 7108X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 7109 if (Subtarget->hasAVX()) { 7110 DebugLoc dl = Op.getNode()->getDebugLoc(); 7111 SDValue Vec = Op.getNode()->getOperand(0); 7112 SDValue SubVec = Op.getNode()->getOperand(1); 7113 SDValue Idx = Op.getNode()->getOperand(2); 7114 7115 if (Op.getNode()->getValueType(0).getSizeInBits() == 256 && 7116 SubVec.getNode()->getValueType(0).getSizeInBits() == 128 && 7117 isa<ConstantSDNode>(Idx)) { 7118 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 7119 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl); 7120 } 7121 } 7122 return SDValue(); 7123} 7124 7125// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 7126// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is 7127// one of the above mentioned nodes. It has to be wrapped because otherwise 7128// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 7129// be used to form addressing mode. These wrapped nodes will be selected 7130// into MOV32ri. 7131SDValue 7132X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const { 7133 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 7134 7135 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7136 // global base reg. 7137 unsigned char OpFlag = 0; 7138 unsigned WrapperKind = X86ISD::Wrapper; 7139 CodeModel::Model M = getTargetMachine().getCodeModel(); 7140 7141 if (Subtarget->isPICStyleRIPRel() && 7142 (M == CodeModel::Small || M == CodeModel::Kernel)) 7143 WrapperKind = X86ISD::WrapperRIP; 7144 else if (Subtarget->isPICStyleGOT()) 7145 OpFlag = X86II::MO_GOTOFF; 7146 else if (Subtarget->isPICStyleStubPIC()) 7147 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7148 7149 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(), 7150 CP->getAlignment(), 7151 CP->getOffset(), OpFlag); 7152 DebugLoc DL = CP->getDebugLoc(); 7153 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7154 // With PIC, the address is actually $g + Offset. 7155 if (OpFlag) { 7156 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7157 DAG.getNode(X86ISD::GlobalBaseReg, 7158 DebugLoc(), getPointerTy()), 7159 Result); 7160 } 7161 7162 return Result; 7163} 7164 7165SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 7166 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 7167 7168 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7169 // global base reg. 7170 unsigned char OpFlag = 0; 7171 unsigned WrapperKind = X86ISD::Wrapper; 7172 CodeModel::Model M = getTargetMachine().getCodeModel(); 7173 7174 if (Subtarget->isPICStyleRIPRel() && 7175 (M == CodeModel::Small || M == CodeModel::Kernel)) 7176 WrapperKind = X86ISD::WrapperRIP; 7177 else if (Subtarget->isPICStyleGOT()) 7178 OpFlag = X86II::MO_GOTOFF; 7179 else if (Subtarget->isPICStyleStubPIC()) 7180 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7181 7182 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(), 7183 OpFlag); 7184 DebugLoc DL = JT->getDebugLoc(); 7185 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7186 7187 // With PIC, the address is actually $g + Offset. 7188 if (OpFlag) 7189 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7190 DAG.getNode(X86ISD::GlobalBaseReg, 7191 DebugLoc(), getPointerTy()), 7192 Result); 7193 7194 return Result; 7195} 7196 7197SDValue 7198X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const { 7199 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 7200 7201 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7202 // global base reg. 7203 unsigned char OpFlag = 0; 7204 unsigned WrapperKind = X86ISD::Wrapper; 7205 CodeModel::Model M = getTargetMachine().getCodeModel(); 7206 7207 if (Subtarget->isPICStyleRIPRel() && 7208 (M == CodeModel::Small || M == CodeModel::Kernel)) { 7209 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF()) 7210 OpFlag = X86II::MO_GOTPCREL; 7211 WrapperKind = X86ISD::WrapperRIP; 7212 } else if (Subtarget->isPICStyleGOT()) { 7213 OpFlag = X86II::MO_GOT; 7214 } else if (Subtarget->isPICStyleStubPIC()) { 7215 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE; 7216 } else if (Subtarget->isPICStyleStubNoDynamic()) { 7217 OpFlag = X86II::MO_DARWIN_NONLAZY; 7218 } 7219 7220 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag); 7221 7222 DebugLoc DL = Op.getDebugLoc(); 7223 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7224 7225 7226 // With PIC, the address is actually $g + Offset. 7227 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 7228 !Subtarget->is64Bit()) { 7229 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7230 DAG.getNode(X86ISD::GlobalBaseReg, 7231 DebugLoc(), getPointerTy()), 7232 Result); 7233 } 7234 7235 // For symbols that require a load from a stub to get the address, emit the 7236 // load. 7237 if (isGlobalStubReference(OpFlag)) 7238 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result, 7239 MachinePointerInfo::getGOT(), false, false, false, 0); 7240 7241 return Result; 7242} 7243 7244SDValue 7245X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const { 7246 // Create the TargetBlockAddressAddress node. 7247 unsigned char OpFlags = 7248 Subtarget->ClassifyBlockAddressReference(); 7249 CodeModel::Model M = getTargetMachine().getCodeModel(); 7250 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 7251 DebugLoc dl = Op.getDebugLoc(); 7252 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), 7253 /*isTarget=*/true, OpFlags); 7254 7255 if (Subtarget->isPICStyleRIPRel() && 7256 (M == CodeModel::Small || M == CodeModel::Kernel)) 7257 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7258 else 7259 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7260 7261 // With PIC, the address is actually $g + Offset. 7262 if (isGlobalRelativeToPICBase(OpFlags)) { 7263 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7264 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7265 Result); 7266 } 7267 7268 return Result; 7269} 7270 7271SDValue 7272X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl, 7273 int64_t Offset, 7274 SelectionDAG &DAG) const { 7275 // Create the TargetGlobalAddress node, folding in the constant 7276 // offset if it is legal. 7277 unsigned char OpFlags = 7278 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 7279 CodeModel::Model M = getTargetMachine().getCodeModel(); 7280 SDValue Result; 7281 if (OpFlags == X86II::MO_NO_FLAG && 7282 X86::isOffsetSuitableForCodeModel(Offset, M)) { 7283 // A direct static reference to a global. 7284 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset); 7285 Offset = 0; 7286 } else { 7287 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags); 7288 } 7289 7290 if (Subtarget->isPICStyleRIPRel() && 7291 (M == CodeModel::Small || M == CodeModel::Kernel)) 7292 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7293 else 7294 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7295 7296 // With PIC, the address is actually $g + Offset. 7297 if (isGlobalRelativeToPICBase(OpFlags)) { 7298 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7299 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7300 Result); 7301 } 7302 7303 // For globals that require a load from a stub to get the address, emit the 7304 // load. 7305 if (isGlobalStubReference(OpFlags)) 7306 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result, 7307 MachinePointerInfo::getGOT(), false, false, false, 0); 7308 7309 // If there was a non-zero offset that we didn't fold, create an explicit 7310 // addition for it. 7311 if (Offset != 0) 7312 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result, 7313 DAG.getConstant(Offset, getPointerTy())); 7314 7315 return Result; 7316} 7317 7318SDValue 7319X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const { 7320 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 7321 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset(); 7322 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG); 7323} 7324 7325static SDValue 7326GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA, 7327 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg, 7328 unsigned char OperandFlags, bool LocalDynamic = false) { 7329 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 7330 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7331 DebugLoc dl = GA->getDebugLoc(); 7332 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7333 GA->getValueType(0), 7334 GA->getOffset(), 7335 OperandFlags); 7336 7337 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR 7338 : X86ISD::TLSADDR; 7339 7340 if (InFlag) { 7341 SDValue Ops[] = { Chain, TGA, *InFlag }; 7342 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3); 7343 } else { 7344 SDValue Ops[] = { Chain, TGA }; 7345 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2); 7346 } 7347 7348 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 7349 MFI->setAdjustsStack(true); 7350 7351 SDValue Flag = Chain.getValue(1); 7352 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag); 7353} 7354 7355// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit 7356static SDValue 7357LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7358 const EVT PtrVT) { 7359 SDValue InFlag; 7360 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better 7361 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 7362 DAG.getNode(X86ISD::GlobalBaseReg, 7363 DebugLoc(), PtrVT), InFlag); 7364 InFlag = Chain.getValue(1); 7365 7366 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD); 7367} 7368 7369// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit 7370static SDValue 7371LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7372 const EVT PtrVT) { 7373 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, 7374 X86::RAX, X86II::MO_TLSGD); 7375} 7376 7377static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA, 7378 SelectionDAG &DAG, 7379 const EVT PtrVT, 7380 bool is64Bit) { 7381 DebugLoc dl = GA->getDebugLoc(); 7382 7383 // Get the start address of the TLS block for this module. 7384 X86MachineFunctionInfo* MFI = DAG.getMachineFunction() 7385 .getInfo<X86MachineFunctionInfo>(); 7386 MFI->incNumLocalDynamicTLSAccesses(); 7387 7388 SDValue Base; 7389 if (is64Bit) { 7390 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX, 7391 X86II::MO_TLSLD, /*LocalDynamic=*/true); 7392 } else { 7393 SDValue InFlag; 7394 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 7395 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag); 7396 InFlag = Chain.getValue(1); 7397 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, 7398 X86II::MO_TLSLDM, /*LocalDynamic=*/true); 7399 } 7400 7401 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations 7402 // of Base. 7403 7404 // Build x@dtpoff. 7405 unsigned char OperandFlags = X86II::MO_DTPOFF; 7406 unsigned WrapperKind = X86ISD::Wrapper; 7407 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7408 GA->getValueType(0), 7409 GA->getOffset(), OperandFlags); 7410 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 7411 7412 // Add x@dtpoff with the base. 7413 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base); 7414} 7415 7416// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model. 7417static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7418 const EVT PtrVT, TLSModel::Model model, 7419 bool is64Bit, bool isPIC) { 7420 DebugLoc dl = GA->getDebugLoc(); 7421 7422 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit). 7423 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(), 7424 is64Bit ? 257 : 256)); 7425 7426 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 7427 DAG.getIntPtrConstant(0), 7428 MachinePointerInfo(Ptr), 7429 false, false, false, 0); 7430 7431 unsigned char OperandFlags = 0; 7432 // Most TLS accesses are not RIP relative, even on x86-64. One exception is 7433 // initialexec. 7434 unsigned WrapperKind = X86ISD::Wrapper; 7435 if (model == TLSModel::LocalExec) { 7436 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF; 7437 } else if (model == TLSModel::InitialExec) { 7438 if (is64Bit) { 7439 OperandFlags = X86II::MO_GOTTPOFF; 7440 WrapperKind = X86ISD::WrapperRIP; 7441 } else { 7442 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF; 7443 } 7444 } else { 7445 llvm_unreachable("Unexpected model"); 7446 } 7447 7448 // emit "addl x@ntpoff,%eax" (local exec) 7449 // or "addl x@indntpoff,%eax" (initial exec) 7450 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic) 7451 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7452 GA->getValueType(0), 7453 GA->getOffset(), OperandFlags); 7454 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 7455 7456 if (model == TLSModel::InitialExec) { 7457 if (isPIC && !is64Bit) { 7458 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, 7459 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), 7460 Offset); 7461 } 7462 7463 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset, 7464 MachinePointerInfo::getGOT(), false, false, false, 7465 0); 7466 } 7467 7468 // The address of the thread local variable is the add of the thread 7469 // pointer with the offset of the variable. 7470 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 7471} 7472 7473SDValue 7474X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 7475 7476 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 7477 const GlobalValue *GV = GA->getGlobal(); 7478 7479 if (Subtarget->isTargetELF()) { 7480 TLSModel::Model model = getTargetMachine().getTLSModel(GV); 7481 7482 switch (model) { 7483 case TLSModel::GeneralDynamic: 7484 if (Subtarget->is64Bit()) 7485 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy()); 7486 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy()); 7487 case TLSModel::LocalDynamic: 7488 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(), 7489 Subtarget->is64Bit()); 7490 case TLSModel::InitialExec: 7491 case TLSModel::LocalExec: 7492 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, 7493 Subtarget->is64Bit(), 7494 getTargetMachine().getRelocationModel() == Reloc::PIC_); 7495 } 7496 llvm_unreachable("Unknown TLS model."); 7497 } 7498 7499 if (Subtarget->isTargetDarwin()) { 7500 // Darwin only has one model of TLS. Lower to that. 7501 unsigned char OpFlag = 0; 7502 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ? 7503 X86ISD::WrapperRIP : X86ISD::Wrapper; 7504 7505 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7506 // global base reg. 7507 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) && 7508 !Subtarget->is64Bit(); 7509 if (PIC32) 7510 OpFlag = X86II::MO_TLVP_PIC_BASE; 7511 else 7512 OpFlag = X86II::MO_TLVP; 7513 DebugLoc DL = Op.getDebugLoc(); 7514 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL, 7515 GA->getValueType(0), 7516 GA->getOffset(), OpFlag); 7517 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7518 7519 // With PIC32, the address is actually $g + Offset. 7520 if (PIC32) 7521 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7522 DAG.getNode(X86ISD::GlobalBaseReg, 7523 DebugLoc(), getPointerTy()), 7524 Offset); 7525 7526 // Lowering the machine isd will make sure everything is in the right 7527 // location. 7528 SDValue Chain = DAG.getEntryNode(); 7529 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7530 SDValue Args[] = { Chain, Offset }; 7531 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2); 7532 7533 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls. 7534 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 7535 MFI->setAdjustsStack(true); 7536 7537 // And our return value (tls address) is in the standard call return value 7538 // location. 7539 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 7540 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(), 7541 Chain.getValue(1)); 7542 } 7543 7544 if (Subtarget->isTargetWindows()) { 7545 // Just use the implicit TLS architecture 7546 // Need to generate someting similar to: 7547 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage 7548 // ; from TEB 7549 // mov ecx, dword [rel _tls_index]: Load index (from C runtime) 7550 // mov rcx, qword [rdx+rcx*8] 7551 // mov eax, .tls$:tlsvar 7552 // [rax+rcx] contains the address 7553 // Windows 64bit: gs:0x58 7554 // Windows 32bit: fs:__tls_array 7555 7556 // If GV is an alias then use the aliasee for determining 7557 // thread-localness. 7558 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 7559 GV = GA->resolveAliasedGlobal(false); 7560 DebugLoc dl = GA->getDebugLoc(); 7561 SDValue Chain = DAG.getEntryNode(); 7562 7563 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or 7564 // %gs:0x58 (64-bit). 7565 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit() 7566 ? Type::getInt8PtrTy(*DAG.getContext(), 7567 256) 7568 : Type::getInt32PtrTy(*DAG.getContext(), 7569 257)); 7570 7571 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, 7572 Subtarget->is64Bit() 7573 ? DAG.getIntPtrConstant(0x58) 7574 : DAG.getExternalSymbol("_tls_array", 7575 getPointerTy()), 7576 MachinePointerInfo(Ptr), 7577 false, false, false, 0); 7578 7579 // Load the _tls_index variable 7580 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy()); 7581 if (Subtarget->is64Bit()) 7582 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, 7583 IDX, MachinePointerInfo(), MVT::i32, 7584 false, false, 0); 7585 else 7586 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(), 7587 false, false, false, 0); 7588 7589 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), 7590 getPointerTy()); 7591 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale); 7592 7593 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX); 7594 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(), 7595 false, false, false, 0); 7596 7597 // Get the offset of start of .tls section 7598 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7599 GA->getValueType(0), 7600 GA->getOffset(), X86II::MO_SECREL); 7601 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA); 7602 7603 // The address of the thread local variable is the add of the thread 7604 // pointer with the offset of the variable. 7605 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset); 7606 } 7607 7608 llvm_unreachable("TLS not implemented for this target."); 7609} 7610 7611 7612/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values 7613/// and take a 2 x i32 value to shift plus a shift amount. 7614SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{ 7615 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 7616 EVT VT = Op.getValueType(); 7617 unsigned VTBits = VT.getSizeInBits(); 7618 DebugLoc dl = Op.getDebugLoc(); 7619 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS; 7620 SDValue ShOpLo = Op.getOperand(0); 7621 SDValue ShOpHi = Op.getOperand(1); 7622 SDValue ShAmt = Op.getOperand(2); 7623 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7624 DAG.getConstant(VTBits - 1, MVT::i8)) 7625 : DAG.getConstant(0, VT); 7626 7627 SDValue Tmp2, Tmp3; 7628 if (Op.getOpcode() == ISD::SHL_PARTS) { 7629 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt); 7630 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 7631 } else { 7632 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt); 7633 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt); 7634 } 7635 7636 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt, 7637 DAG.getConstant(VTBits, MVT::i8)); 7638 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 7639 AndNode, DAG.getConstant(0, MVT::i8)); 7640 7641 SDValue Hi, Lo; 7642 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8); 7643 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond }; 7644 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond }; 7645 7646 if (Op.getOpcode() == ISD::SHL_PARTS) { 7647 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 7648 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 7649 } else { 7650 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 7651 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 7652 } 7653 7654 SDValue Ops[2] = { Lo, Hi }; 7655 return DAG.getMergeValues(Ops, 2, dl); 7656} 7657 7658SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, 7659 SelectionDAG &DAG) const { 7660 EVT SrcVT = Op.getOperand(0).getValueType(); 7661 7662 if (SrcVT.isVector()) 7663 return SDValue(); 7664 7665 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 && 7666 "Unknown SINT_TO_FP to lower!"); 7667 7668 // These are really Legal; return the operand so the caller accepts it as 7669 // Legal. 7670 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType())) 7671 return Op; 7672 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) && 7673 Subtarget->is64Bit()) { 7674 return Op; 7675 } 7676 7677 DebugLoc dl = Op.getDebugLoc(); 7678 unsigned Size = SrcVT.getSizeInBits()/8; 7679 MachineFunction &MF = DAG.getMachineFunction(); 7680 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false); 7681 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7682 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 7683 StackSlot, 7684 MachinePointerInfo::getFixedStack(SSFI), 7685 false, false, 0); 7686 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG); 7687} 7688 7689SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain, 7690 SDValue StackSlot, 7691 SelectionDAG &DAG) const { 7692 // Build the FILD 7693 DebugLoc DL = Op.getDebugLoc(); 7694 SDVTList Tys; 7695 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType()); 7696 if (useSSE) 7697 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue); 7698 else 7699 Tys = DAG.getVTList(Op.getValueType(), MVT::Other); 7700 7701 unsigned ByteSize = SrcVT.getSizeInBits()/8; 7702 7703 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot); 7704 MachineMemOperand *MMO; 7705 if (FI) { 7706 int SSFI = FI->getIndex(); 7707 MMO = 7708 DAG.getMachineFunction() 7709 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7710 MachineMemOperand::MOLoad, ByteSize, ByteSize); 7711 } else { 7712 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand(); 7713 StackSlot = StackSlot.getOperand(1); 7714 } 7715 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) }; 7716 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG : 7717 X86ISD::FILD, DL, 7718 Tys, Ops, array_lengthof(Ops), 7719 SrcVT, MMO); 7720 7721 if (useSSE) { 7722 Chain = Result.getValue(1); 7723 SDValue InFlag = Result.getValue(2); 7724 7725 // FIXME: Currently the FST is flagged to the FILD_FLAG. This 7726 // shouldn't be necessary except that RFP cannot be live across 7727 // multiple blocks. When stackifier is fixed, they can be uncoupled. 7728 MachineFunction &MF = DAG.getMachineFunction(); 7729 unsigned SSFISize = Op.getValueType().getSizeInBits()/8; 7730 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false); 7731 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7732 Tys = DAG.getVTList(MVT::Other); 7733 SDValue Ops[] = { 7734 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag 7735 }; 7736 MachineMemOperand *MMO = 7737 DAG.getMachineFunction() 7738 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7739 MachineMemOperand::MOStore, SSFISize, SSFISize); 7740 7741 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, 7742 Ops, array_lengthof(Ops), 7743 Op.getValueType(), MMO); 7744 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot, 7745 MachinePointerInfo::getFixedStack(SSFI), 7746 false, false, false, 0); 7747 } 7748 7749 return Result; 7750} 7751 7752// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion. 7753SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, 7754 SelectionDAG &DAG) const { 7755 // This algorithm is not obvious. Here it is what we're trying to output: 7756 /* 7757 movq %rax, %xmm0 7758 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U } 7759 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 } 7760 #ifdef __SSE3__ 7761 haddpd %xmm0, %xmm0 7762 #else 7763 pshufd $0x4e, %xmm0, %xmm1 7764 addpd %xmm1, %xmm0 7765 #endif 7766 */ 7767 7768 DebugLoc dl = Op.getDebugLoc(); 7769 LLVMContext *Context = DAG.getContext(); 7770 7771 // Build some magic constants. 7772 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 }; 7773 Constant *C0 = ConstantDataVector::get(*Context, CV0); 7774 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16); 7775 7776 SmallVector<Constant*,2> CV1; 7777 CV1.push_back( 7778 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL)))); 7779 CV1.push_back( 7780 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL)))); 7781 Constant *C1 = ConstantVector::get(CV1); 7782 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16); 7783 7784 // Load the 64-bit value into an XMM register. 7785 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 7786 Op.getOperand(0)); 7787 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0, 7788 MachinePointerInfo::getConstantPool(), 7789 false, false, false, 16); 7790 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, 7791 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1), 7792 CLod0); 7793 7794 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1, 7795 MachinePointerInfo::getConstantPool(), 7796 false, false, false, 16); 7797 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1); 7798 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1); 7799 SDValue Result; 7800 7801 if (Subtarget->hasSSE3()) { 7802 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'. 7803 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub); 7804 } else { 7805 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub); 7806 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32, 7807 S2F, 0x4E, DAG); 7808 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, 7809 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle), 7810 Sub); 7811 } 7812 7813 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result, 7814 DAG.getIntPtrConstant(0)); 7815} 7816 7817// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion. 7818SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, 7819 SelectionDAG &DAG) const { 7820 DebugLoc dl = Op.getDebugLoc(); 7821 // FP constant to bias correct the final result. 7822 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), 7823 MVT::f64); 7824 7825 // Load the 32-bit value into an XMM register. 7826 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 7827 Op.getOperand(0)); 7828 7829 // Zero out the upper parts of the register. 7830 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG); 7831 7832 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 7833 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load), 7834 DAG.getIntPtrConstant(0)); 7835 7836 // Or the load with the bias. 7837 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, 7838 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 7839 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 7840 MVT::v2f64, Load)), 7841 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 7842 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 7843 MVT::v2f64, Bias))); 7844 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 7845 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or), 7846 DAG.getIntPtrConstant(0)); 7847 7848 // Subtract the bias. 7849 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias); 7850 7851 // Handle final rounding. 7852 EVT DestVT = Op.getValueType(); 7853 7854 if (DestVT.bitsLT(MVT::f64)) 7855 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub, 7856 DAG.getIntPtrConstant(0)); 7857 if (DestVT.bitsGT(MVT::f64)) 7858 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub); 7859 7860 // Handle final rounding. 7861 return Sub; 7862} 7863 7864SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, 7865 SelectionDAG &DAG) const { 7866 SDValue N0 = Op.getOperand(0); 7867 DebugLoc dl = Op.getDebugLoc(); 7868 7869 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't 7870 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform 7871 // the optimization here. 7872 if (DAG.SignBitIsZero(N0)) 7873 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0); 7874 7875 EVT SrcVT = N0.getValueType(); 7876 EVT DstVT = Op.getValueType(); 7877 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64) 7878 return LowerUINT_TO_FP_i64(Op, DAG); 7879 if (SrcVT == MVT::i32 && X86ScalarSSEf64) 7880 return LowerUINT_TO_FP_i32(Op, DAG); 7881 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32) 7882 return SDValue(); 7883 7884 // Make a 64-bit buffer, and use it to build an FILD. 7885 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64); 7886 if (SrcVT == MVT::i32) { 7887 SDValue WordOff = DAG.getConstant(4, getPointerTy()); 7888 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, 7889 getPointerTy(), StackSlot, WordOff); 7890 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 7891 StackSlot, MachinePointerInfo(), 7892 false, false, 0); 7893 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32), 7894 OffsetSlot, MachinePointerInfo(), 7895 false, false, 0); 7896 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG); 7897 return Fild; 7898 } 7899 7900 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP"); 7901 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 7902 StackSlot, MachinePointerInfo(), 7903 false, false, 0); 7904 // For i64 source, we need to add the appropriate power of 2 if the input 7905 // was negative. This is the same as the optimization in 7906 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here, 7907 // we must be careful to do the computation in x87 extended precision, not 7908 // in SSE. (The generic code can't know it's OK to do this, or how to.) 7909 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex(); 7910 MachineMemOperand *MMO = 7911 DAG.getMachineFunction() 7912 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7913 MachineMemOperand::MOLoad, 8, 8); 7914 7915 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other); 7916 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) }; 7917 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3, 7918 MVT::i64, MMO); 7919 7920 APInt FF(32, 0x5F800000ULL); 7921 7922 // Check whether the sign bit is set. 7923 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), 7924 Op.getOperand(0), DAG.getConstant(0, MVT::i64), 7925 ISD::SETLT); 7926 7927 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits. 7928 SDValue FudgePtr = DAG.getConstantPool( 7929 ConstantInt::get(*DAG.getContext(), FF.zext(64)), 7930 getPointerTy()); 7931 7932 // Get a pointer to FF if the sign bit was set, or to 0 otherwise. 7933 SDValue Zero = DAG.getIntPtrConstant(0); 7934 SDValue Four = DAG.getIntPtrConstant(4); 7935 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet, 7936 Zero, Four); 7937 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset); 7938 7939 // Load the value out, extending it from f32 to f80. 7940 // FIXME: Avoid the extend by constructing the right constant pool? 7941 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), 7942 FudgePtr, MachinePointerInfo::getConstantPool(), 7943 MVT::f32, false, false, 4); 7944 // Extend everything to 80 bits to force it to be done on x87. 7945 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge); 7946 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0)); 7947} 7948 7949std::pair<SDValue,SDValue> X86TargetLowering:: 7950FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const { 7951 DebugLoc DL = Op.getDebugLoc(); 7952 7953 EVT DstTy = Op.getValueType(); 7954 7955 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) { 7956 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT"); 7957 DstTy = MVT::i64; 7958 } 7959 7960 assert(DstTy.getSimpleVT() <= MVT::i64 && 7961 DstTy.getSimpleVT() >= MVT::i16 && 7962 "Unknown FP_TO_INT to lower!"); 7963 7964 // These are really Legal. 7965 if (DstTy == MVT::i32 && 7966 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 7967 return std::make_pair(SDValue(), SDValue()); 7968 if (Subtarget->is64Bit() && 7969 DstTy == MVT::i64 && 7970 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 7971 return std::make_pair(SDValue(), SDValue()); 7972 7973 // We lower FP->int64 either into FISTP64 followed by a load from a temporary 7974 // stack slot, or into the FTOL runtime function. 7975 MachineFunction &MF = DAG.getMachineFunction(); 7976 unsigned MemSize = DstTy.getSizeInBits()/8; 7977 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 7978 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7979 7980 unsigned Opc; 7981 if (!IsSigned && isIntegerTypeFTOL(DstTy)) 7982 Opc = X86ISD::WIN_FTOL; 7983 else 7984 switch (DstTy.getSimpleVT().SimpleTy) { 7985 default: llvm_unreachable("Invalid FP_TO_SINT to lower!"); 7986 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break; 7987 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break; 7988 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break; 7989 } 7990 7991 SDValue Chain = DAG.getEntryNode(); 7992 SDValue Value = Op.getOperand(0); 7993 EVT TheVT = Op.getOperand(0).getValueType(); 7994 // FIXME This causes a redundant load/store if the SSE-class value is already 7995 // in memory, such as if it is on the callstack. 7996 if (isScalarFPTypeInSSEReg(TheVT)) { 7997 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!"); 7998 Chain = DAG.getStore(Chain, DL, Value, StackSlot, 7999 MachinePointerInfo::getFixedStack(SSFI), 8000 false, false, 0); 8001 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other); 8002 SDValue Ops[] = { 8003 Chain, StackSlot, DAG.getValueType(TheVT) 8004 }; 8005 8006 MachineMemOperand *MMO = 8007 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8008 MachineMemOperand::MOLoad, MemSize, MemSize); 8009 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3, 8010 DstTy, MMO); 8011 Chain = Value.getValue(1); 8012 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 8013 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8014 } 8015 8016 MachineMemOperand *MMO = 8017 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8018 MachineMemOperand::MOStore, MemSize, MemSize); 8019 8020 if (Opc != X86ISD::WIN_FTOL) { 8021 // Build the FP_TO_INT*_IN_MEM 8022 SDValue Ops[] = { Chain, Value, StackSlot }; 8023 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other), 8024 Ops, 3, DstTy, MMO); 8025 return std::make_pair(FIST, StackSlot); 8026 } else { 8027 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL, 8028 DAG.getVTList(MVT::Other, MVT::Glue), 8029 Chain, Value); 8030 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX, 8031 MVT::i32, ftol.getValue(1)); 8032 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX, 8033 MVT::i32, eax.getValue(2)); 8034 SDValue Ops[] = { eax, edx }; 8035 SDValue pair = IsReplace 8036 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2) 8037 : DAG.getMergeValues(Ops, 2, DL); 8038 return std::make_pair(pair, SDValue()); 8039 } 8040} 8041 8042SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, 8043 SelectionDAG &DAG) const { 8044 if (Op.getValueType().isVector()) 8045 return SDValue(); 8046 8047 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, 8048 /*IsSigned=*/ true, /*IsReplace=*/ false); 8049 SDValue FIST = Vals.first, StackSlot = Vals.second; 8050 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal. 8051 if (FIST.getNode() == 0) return Op; 8052 8053 if (StackSlot.getNode()) 8054 // Load the result. 8055 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 8056 FIST, StackSlot, MachinePointerInfo(), 8057 false, false, false, 0); 8058 8059 // The node is the result. 8060 return FIST; 8061} 8062 8063SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, 8064 SelectionDAG &DAG) const { 8065 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, 8066 /*IsSigned=*/ false, /*IsReplace=*/ false); 8067 SDValue FIST = Vals.first, StackSlot = Vals.second; 8068 assert(FIST.getNode() && "Unexpected failure"); 8069 8070 if (StackSlot.getNode()) 8071 // Load the result. 8072 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 8073 FIST, StackSlot, MachinePointerInfo(), 8074 false, false, false, 0); 8075 8076 // The node is the result. 8077 return FIST; 8078} 8079 8080SDValue X86TargetLowering::LowerFABS(SDValue Op, 8081 SelectionDAG &DAG) const { 8082 LLVMContext *Context = DAG.getContext(); 8083 DebugLoc dl = Op.getDebugLoc(); 8084 EVT VT = Op.getValueType(); 8085 EVT EltVT = VT; 8086 if (VT.isVector()) 8087 EltVT = VT.getVectorElementType(); 8088 Constant *C; 8089 if (EltVT == MVT::f64) { 8090 C = ConstantVector::getSplat(2, 8091 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))))); 8092 } else { 8093 C = ConstantVector::getSplat(4, 8094 ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))))); 8095 } 8096 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8097 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8098 MachinePointerInfo::getConstantPool(), 8099 false, false, false, 16); 8100 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask); 8101} 8102 8103SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const { 8104 LLVMContext *Context = DAG.getContext(); 8105 DebugLoc dl = Op.getDebugLoc(); 8106 EVT VT = Op.getValueType(); 8107 EVT EltVT = VT; 8108 unsigned NumElts = VT == MVT::f64 ? 2 : 4; 8109 if (VT.isVector()) { 8110 EltVT = VT.getVectorElementType(); 8111 NumElts = VT.getVectorNumElements(); 8112 } 8113 Constant *C; 8114 if (EltVT == MVT::f64) 8115 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))); 8116 else 8117 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))); 8118 C = ConstantVector::getSplat(NumElts, C); 8119 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8120 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8121 MachinePointerInfo::getConstantPool(), 8122 false, false, false, 16); 8123 if (VT.isVector()) { 8124 MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64; 8125 return DAG.getNode(ISD::BITCAST, dl, VT, 8126 DAG.getNode(ISD::XOR, dl, XORVT, 8127 DAG.getNode(ISD::BITCAST, dl, XORVT, 8128 Op.getOperand(0)), 8129 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask))); 8130 } 8131 8132 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask); 8133} 8134 8135SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 8136 LLVMContext *Context = DAG.getContext(); 8137 SDValue Op0 = Op.getOperand(0); 8138 SDValue Op1 = Op.getOperand(1); 8139 DebugLoc dl = Op.getDebugLoc(); 8140 EVT VT = Op.getValueType(); 8141 EVT SrcVT = Op1.getValueType(); 8142 8143 // If second operand is smaller, extend it first. 8144 if (SrcVT.bitsLT(VT)) { 8145 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1); 8146 SrcVT = VT; 8147 } 8148 // And if it is bigger, shrink it first. 8149 if (SrcVT.bitsGT(VT)) { 8150 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1)); 8151 SrcVT = VT; 8152 } 8153 8154 // At this point the operands and the result should have the same 8155 // type, and that won't be f80 since that is not custom lowered. 8156 8157 // First get the sign bit of second operand. 8158 SmallVector<Constant*,4> CV; 8159 if (SrcVT == MVT::f64) { 8160 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)))); 8161 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 8162 } else { 8163 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)))); 8164 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8165 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8166 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8167 } 8168 Constant *C = ConstantVector::get(CV); 8169 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8170 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx, 8171 MachinePointerInfo::getConstantPool(), 8172 false, false, false, 16); 8173 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1); 8174 8175 // Shift sign bit right or left if the two operands have different types. 8176 if (SrcVT.bitsGT(VT)) { 8177 // Op0 is MVT::f32, Op1 is MVT::f64. 8178 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit); 8179 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit, 8180 DAG.getConstant(32, MVT::i32)); 8181 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit); 8182 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit, 8183 DAG.getIntPtrConstant(0)); 8184 } 8185 8186 // Clear first operand sign bit. 8187 CV.clear(); 8188 if (VT == MVT::f64) { 8189 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))))); 8190 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 8191 } else { 8192 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))))); 8193 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8194 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8195 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8196 } 8197 C = ConstantVector::get(CV); 8198 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8199 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8200 MachinePointerInfo::getConstantPool(), 8201 false, false, false, 16); 8202 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2); 8203 8204 // Or the value with the sign bit. 8205 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit); 8206} 8207 8208SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const { 8209 SDValue N0 = Op.getOperand(0); 8210 DebugLoc dl = Op.getDebugLoc(); 8211 EVT VT = Op.getValueType(); 8212 8213 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1). 8214 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0, 8215 DAG.getConstant(1, VT)); 8216 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT)); 8217} 8218 8219/// Emit nodes that will be selected as "test Op0,Op0", or something 8220/// equivalent. 8221SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, 8222 SelectionDAG &DAG) const { 8223 DebugLoc dl = Op.getDebugLoc(); 8224 8225 // CF and OF aren't always set the way we want. Determine which 8226 // of these we need. 8227 bool NeedCF = false; 8228 bool NeedOF = false; 8229 switch (X86CC) { 8230 default: break; 8231 case X86::COND_A: case X86::COND_AE: 8232 case X86::COND_B: case X86::COND_BE: 8233 NeedCF = true; 8234 break; 8235 case X86::COND_G: case X86::COND_GE: 8236 case X86::COND_L: case X86::COND_LE: 8237 case X86::COND_O: case X86::COND_NO: 8238 NeedOF = true; 8239 break; 8240 } 8241 8242 // See if we can use the EFLAGS value from the operand instead of 8243 // doing a separate TEST. TEST always sets OF and CF to 0, so unless 8244 // we prove that the arithmetic won't overflow, we can't use OF or CF. 8245 if (Op.getResNo() != 0 || NeedOF || NeedCF) 8246 // Emit a CMP with 0, which is the TEST pattern. 8247 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 8248 DAG.getConstant(0, Op.getValueType())); 8249 8250 unsigned Opcode = 0; 8251 unsigned NumOperands = 0; 8252 switch (Op.getNode()->getOpcode()) { 8253 case ISD::ADD: 8254 // Due to an isel shortcoming, be conservative if this add is likely to be 8255 // selected as part of a load-modify-store instruction. When the root node 8256 // in a match is a store, isel doesn't know how to remap non-chain non-flag 8257 // uses of other nodes in the match, such as the ADD in this case. This 8258 // leads to the ADD being left around and reselected, with the result being 8259 // two adds in the output. Alas, even if none our users are stores, that 8260 // doesn't prove we're O.K. Ergo, if we have any parents that aren't 8261 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require 8262 // climbing the DAG back to the root, and it doesn't seem to be worth the 8263 // effort. 8264 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8265 UE = Op.getNode()->use_end(); UI != UE; ++UI) 8266 if (UI->getOpcode() != ISD::CopyToReg && 8267 UI->getOpcode() != ISD::SETCC && 8268 UI->getOpcode() != ISD::STORE) 8269 goto default_case; 8270 8271 if (ConstantSDNode *C = 8272 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) { 8273 // An add of one will be selected as an INC. 8274 if (C->getAPIntValue() == 1) { 8275 Opcode = X86ISD::INC; 8276 NumOperands = 1; 8277 break; 8278 } 8279 8280 // An add of negative one (subtract of one) will be selected as a DEC. 8281 if (C->getAPIntValue().isAllOnesValue()) { 8282 Opcode = X86ISD::DEC; 8283 NumOperands = 1; 8284 break; 8285 } 8286 } 8287 8288 // Otherwise use a regular EFLAGS-setting add. 8289 Opcode = X86ISD::ADD; 8290 NumOperands = 2; 8291 break; 8292 case ISD::AND: { 8293 // If the primary and result isn't used, don't bother using X86ISD::AND, 8294 // because a TEST instruction will be better. 8295 bool NonFlagUse = false; 8296 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8297 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 8298 SDNode *User = *UI; 8299 unsigned UOpNo = UI.getOperandNo(); 8300 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) { 8301 // Look pass truncate. 8302 UOpNo = User->use_begin().getOperandNo(); 8303 User = *User->use_begin(); 8304 } 8305 8306 if (User->getOpcode() != ISD::BRCOND && 8307 User->getOpcode() != ISD::SETCC && 8308 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) { 8309 NonFlagUse = true; 8310 break; 8311 } 8312 } 8313 8314 if (!NonFlagUse) 8315 break; 8316 } 8317 // FALL THROUGH 8318 case ISD::SUB: 8319 case ISD::OR: 8320 case ISD::XOR: 8321 // Due to the ISEL shortcoming noted above, be conservative if this op is 8322 // likely to be selected as part of a load-modify-store instruction. 8323 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8324 UE = Op.getNode()->use_end(); UI != UE; ++UI) 8325 if (UI->getOpcode() == ISD::STORE) 8326 goto default_case; 8327 8328 // Otherwise use a regular EFLAGS-setting instruction. 8329 switch (Op.getNode()->getOpcode()) { 8330 default: llvm_unreachable("unexpected operator!"); 8331 case ISD::SUB: 8332 Opcode = X86ISD::SUB; 8333 break; 8334 case ISD::OR: Opcode = X86ISD::OR; break; 8335 case ISD::XOR: Opcode = X86ISD::XOR; break; 8336 case ISD::AND: Opcode = X86ISD::AND; break; 8337 } 8338 8339 NumOperands = 2; 8340 break; 8341 case X86ISD::ADD: 8342 case X86ISD::SUB: 8343 case X86ISD::INC: 8344 case X86ISD::DEC: 8345 case X86ISD::OR: 8346 case X86ISD::XOR: 8347 case X86ISD::AND: 8348 return SDValue(Op.getNode(), 1); 8349 default: 8350 default_case: 8351 break; 8352 } 8353 8354 if (Opcode == 0) 8355 // Emit a CMP with 0, which is the TEST pattern. 8356 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 8357 DAG.getConstant(0, Op.getValueType())); 8358 8359 if (Opcode == X86ISD::CMP) { 8360 SDValue New = DAG.getNode(Opcode, dl, MVT::i32, Op.getOperand(0), 8361 Op.getOperand(1)); 8362 // We can't replace usage of SUB with CMP. 8363 // The SUB node will be removed later because there is no use of it. 8364 return SDValue(New.getNode(), 0); 8365 } 8366 8367 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 8368 SmallVector<SDValue, 4> Ops; 8369 for (unsigned i = 0; i != NumOperands; ++i) 8370 Ops.push_back(Op.getOperand(i)); 8371 8372 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands); 8373 DAG.ReplaceAllUsesWith(Op, New); 8374 return SDValue(New.getNode(), 1); 8375} 8376 8377/// Emit nodes that will be selected as "cmp Op0,Op1", or something 8378/// equivalent. 8379SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC, 8380 SelectionDAG &DAG) const { 8381 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) 8382 if (C->getAPIntValue() == 0) 8383 return EmitTest(Op0, X86CC, DAG); 8384 8385 DebugLoc dl = Op0.getDebugLoc(); 8386 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 || 8387 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) { 8388 // Use SUB instead of CMP to enable CSE between SUB and CMP. 8389 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32); 8390 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, 8391 Op0, Op1); 8392 return SDValue(Sub.getNode(), 1); 8393 } 8394 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1); 8395} 8396 8397/// Convert a comparison if required by the subtarget. 8398SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp, 8399 SelectionDAG &DAG) const { 8400 // If the subtarget does not support the FUCOMI instruction, floating-point 8401 // comparisons have to be converted. 8402 if (Subtarget->hasCMov() || 8403 Cmp.getOpcode() != X86ISD::CMP || 8404 !Cmp.getOperand(0).getValueType().isFloatingPoint() || 8405 !Cmp.getOperand(1).getValueType().isFloatingPoint()) 8406 return Cmp; 8407 8408 // The instruction selector will select an FUCOM instruction instead of 8409 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence 8410 // build an SDNode sequence that transfers the result from FPSW into EFLAGS: 8411 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8)))) 8412 DebugLoc dl = Cmp.getDebugLoc(); 8413 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp); 8414 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW); 8415 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW, 8416 DAG.getConstant(8, MVT::i8)); 8417 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl); 8418 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl); 8419} 8420 8421/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node 8422/// if it's possible. 8423SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC, 8424 DebugLoc dl, SelectionDAG &DAG) const { 8425 SDValue Op0 = And.getOperand(0); 8426 SDValue Op1 = And.getOperand(1); 8427 if (Op0.getOpcode() == ISD::TRUNCATE) 8428 Op0 = Op0.getOperand(0); 8429 if (Op1.getOpcode() == ISD::TRUNCATE) 8430 Op1 = Op1.getOperand(0); 8431 8432 SDValue LHS, RHS; 8433 if (Op1.getOpcode() == ISD::SHL) 8434 std::swap(Op0, Op1); 8435 if (Op0.getOpcode() == ISD::SHL) { 8436 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0))) 8437 if (And00C->getZExtValue() == 1) { 8438 // If we looked past a truncate, check that it's only truncating away 8439 // known zeros. 8440 unsigned BitWidth = Op0.getValueSizeInBits(); 8441 unsigned AndBitWidth = And.getValueSizeInBits(); 8442 if (BitWidth > AndBitWidth) { 8443 APInt Zeros, Ones; 8444 DAG.ComputeMaskedBits(Op0, Zeros, Ones); 8445 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth) 8446 return SDValue(); 8447 } 8448 LHS = Op1; 8449 RHS = Op0.getOperand(1); 8450 } 8451 } else if (Op1.getOpcode() == ISD::Constant) { 8452 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1); 8453 uint64_t AndRHSVal = AndRHS->getZExtValue(); 8454 SDValue AndLHS = Op0; 8455 8456 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) { 8457 LHS = AndLHS.getOperand(0); 8458 RHS = AndLHS.getOperand(1); 8459 } 8460 8461 // Use BT if the immediate can't be encoded in a TEST instruction. 8462 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) { 8463 LHS = AndLHS; 8464 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType()); 8465 } 8466 } 8467 8468 if (LHS.getNode()) { 8469 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT 8470 // instruction. Since the shift amount is in-range-or-undefined, we know 8471 // that doing a bittest on the i32 value is ok. We extend to i32 because 8472 // the encoding for the i16 version is larger than the i32 version. 8473 // Also promote i16 to i32 for performance / code size reason. 8474 if (LHS.getValueType() == MVT::i8 || 8475 LHS.getValueType() == MVT::i16) 8476 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 8477 8478 // If the operand types disagree, extend the shift amount to match. Since 8479 // BT ignores high bits (like shifts) we can use anyextend. 8480 if (LHS.getValueType() != RHS.getValueType()) 8481 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS); 8482 8483 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS); 8484 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B; 8485 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8486 DAG.getConstant(Cond, MVT::i8), BT); 8487 } 8488 8489 return SDValue(); 8490} 8491 8492SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 8493 8494 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG); 8495 8496 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer"); 8497 SDValue Op0 = Op.getOperand(0); 8498 SDValue Op1 = Op.getOperand(1); 8499 DebugLoc dl = Op.getDebugLoc(); 8500 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8501 8502 // Optimize to BT if possible. 8503 // Lower (X & (1 << N)) == 0 to BT(X, N). 8504 // Lower ((X >>u N) & 1) != 0 to BT(X, N). 8505 // Lower ((X >>s N) & 1) != 0 to BT(X, N). 8506 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && 8507 Op1.getOpcode() == ISD::Constant && 8508 cast<ConstantSDNode>(Op1)->isNullValue() && 8509 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 8510 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG); 8511 if (NewSetCC.getNode()) 8512 return NewSetCC; 8513 } 8514 8515 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of 8516 // these. 8517 if (Op1.getOpcode() == ISD::Constant && 8518 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 || 8519 cast<ConstantSDNode>(Op1)->isNullValue()) && 8520 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 8521 8522 // If the input is a setcc, then reuse the input setcc or use a new one with 8523 // the inverted condition. 8524 if (Op0.getOpcode() == X86ISD::SETCC) { 8525 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0); 8526 bool Invert = (CC == ISD::SETNE) ^ 8527 cast<ConstantSDNode>(Op1)->isNullValue(); 8528 if (!Invert) return Op0; 8529 8530 CCode = X86::GetOppositeBranchCondition(CCode); 8531 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8532 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1)); 8533 } 8534 } 8535 8536 bool isFP = Op1.getValueType().isFloatingPoint(); 8537 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG); 8538 if (X86CC == X86::COND_INVALID) 8539 return SDValue(); 8540 8541 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG); 8542 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG); 8543 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8544 DAG.getConstant(X86CC, MVT::i8), EFLAGS); 8545} 8546 8547// Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128 8548// ones, and then concatenate the result back. 8549static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) { 8550 EVT VT = Op.getValueType(); 8551 8552 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC && 8553 "Unsupported value type for operation"); 8554 8555 unsigned NumElems = VT.getVectorNumElements(); 8556 DebugLoc dl = Op.getDebugLoc(); 8557 SDValue CC = Op.getOperand(2); 8558 8559 // Extract the LHS vectors 8560 SDValue LHS = Op.getOperand(0); 8561 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl); 8562 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl); 8563 8564 // Extract the RHS vectors 8565 SDValue RHS = Op.getOperand(1); 8566 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl); 8567 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl); 8568 8569 // Issue the operation on the smaller types and concatenate the result back 8570 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 8571 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 8572 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 8573 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC), 8574 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC)); 8575} 8576 8577 8578SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const { 8579 SDValue Cond; 8580 SDValue Op0 = Op.getOperand(0); 8581 SDValue Op1 = Op.getOperand(1); 8582 SDValue CC = Op.getOperand(2); 8583 EVT VT = Op.getValueType(); 8584 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 8585 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint(); 8586 DebugLoc dl = Op.getDebugLoc(); 8587 8588 if (isFP) { 8589 unsigned SSECC = 8; 8590 EVT EltVT = Op0.getValueType().getVectorElementType(); 8591 assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT; 8592 8593 bool Swap = false; 8594 8595 // SSE Condition code mapping: 8596 // 0 - EQ 8597 // 1 - LT 8598 // 2 - LE 8599 // 3 - UNORD 8600 // 4 - NEQ 8601 // 5 - NLT 8602 // 6 - NLE 8603 // 7 - ORD 8604 switch (SetCCOpcode) { 8605 default: break; 8606 case ISD::SETOEQ: 8607 case ISD::SETEQ: SSECC = 0; break; 8608 case ISD::SETOGT: 8609 case ISD::SETGT: Swap = true; // Fallthrough 8610 case ISD::SETLT: 8611 case ISD::SETOLT: SSECC = 1; break; 8612 case ISD::SETOGE: 8613 case ISD::SETGE: Swap = true; // Fallthrough 8614 case ISD::SETLE: 8615 case ISD::SETOLE: SSECC = 2; break; 8616 case ISD::SETUO: SSECC = 3; break; 8617 case ISD::SETUNE: 8618 case ISD::SETNE: SSECC = 4; break; 8619 case ISD::SETULE: Swap = true; 8620 case ISD::SETUGE: SSECC = 5; break; 8621 case ISD::SETULT: Swap = true; 8622 case ISD::SETUGT: SSECC = 6; break; 8623 case ISD::SETO: SSECC = 7; break; 8624 } 8625 if (Swap) 8626 std::swap(Op0, Op1); 8627 8628 // In the two special cases we can't handle, emit two comparisons. 8629 if (SSECC == 8) { 8630 if (SetCCOpcode == ISD::SETUEQ) { 8631 SDValue UNORD, EQ; 8632 UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 8633 DAG.getConstant(3, MVT::i8)); 8634 EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 8635 DAG.getConstant(0, MVT::i8)); 8636 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ); 8637 } 8638 if (SetCCOpcode == ISD::SETONE) { 8639 SDValue ORD, NEQ; 8640 ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 8641 DAG.getConstant(7, MVT::i8)); 8642 NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 8643 DAG.getConstant(4, MVT::i8)); 8644 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ); 8645 } 8646 llvm_unreachable("Illegal FP comparison"); 8647 } 8648 // Handle all other FP comparisons here. 8649 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 8650 DAG.getConstant(SSECC, MVT::i8)); 8651 } 8652 8653 // Break 256-bit integer vector compare into smaller ones. 8654 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()) 8655 return Lower256IntVSETCC(Op, DAG); 8656 8657 // We are handling one of the integer comparisons here. Since SSE only has 8658 // GT and EQ comparisons for integer, swapping operands and multiple 8659 // operations may be required for some comparisons. 8660 unsigned Opc = 0; 8661 bool Swap = false, Invert = false, FlipSigns = false; 8662 8663 switch (SetCCOpcode) { 8664 default: break; 8665 case ISD::SETNE: Invert = true; 8666 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break; 8667 case ISD::SETLT: Swap = true; 8668 case ISD::SETGT: Opc = X86ISD::PCMPGT; break; 8669 case ISD::SETGE: Swap = true; 8670 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break; 8671 case ISD::SETULT: Swap = true; 8672 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break; 8673 case ISD::SETUGE: Swap = true; 8674 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break; 8675 } 8676 if (Swap) 8677 std::swap(Op0, Op1); 8678 8679 // Check that the operation in question is available (most are plain SSE2, 8680 // but PCMPGTQ and PCMPEQQ have different requirements). 8681 if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42()) 8682 return SDValue(); 8683 if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41()) 8684 return SDValue(); 8685 8686 // Since SSE has no unsigned integer comparisons, we need to flip the sign 8687 // bits of the inputs before performing those operations. 8688 if (FlipSigns) { 8689 EVT EltVT = VT.getVectorElementType(); 8690 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), 8691 EltVT); 8692 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit); 8693 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0], 8694 SignBits.size()); 8695 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec); 8696 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec); 8697 } 8698 8699 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 8700 8701 // If the logical-not of the result is required, perform that now. 8702 if (Invert) 8703 Result = DAG.getNOT(dl, Result, VT); 8704 8705 return Result; 8706} 8707 8708// isX86LogicalCmp - Return true if opcode is a X86 logical comparison. 8709static bool isX86LogicalCmp(SDValue Op) { 8710 unsigned Opc = Op.getNode()->getOpcode(); 8711 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI || 8712 Opc == X86ISD::SAHF) 8713 return true; 8714 if (Op.getResNo() == 1 && 8715 (Opc == X86ISD::ADD || 8716 Opc == X86ISD::SUB || 8717 Opc == X86ISD::ADC || 8718 Opc == X86ISD::SBB || 8719 Opc == X86ISD::SMUL || 8720 Opc == X86ISD::UMUL || 8721 Opc == X86ISD::INC || 8722 Opc == X86ISD::DEC || 8723 Opc == X86ISD::OR || 8724 Opc == X86ISD::XOR || 8725 Opc == X86ISD::AND)) 8726 return true; 8727 8728 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL) 8729 return true; 8730 8731 return false; 8732} 8733 8734static bool isZero(SDValue V) { 8735 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 8736 return C && C->isNullValue(); 8737} 8738 8739static bool isAllOnes(SDValue V) { 8740 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 8741 return C && C->isAllOnesValue(); 8742} 8743 8744static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) { 8745 if (V.getOpcode() != ISD::TRUNCATE) 8746 return false; 8747 8748 SDValue VOp0 = V.getOperand(0); 8749 unsigned InBits = VOp0.getValueSizeInBits(); 8750 unsigned Bits = V.getValueSizeInBits(); 8751 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits)); 8752} 8753 8754SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8755 bool addTest = true; 8756 SDValue Cond = Op.getOperand(0); 8757 SDValue Op1 = Op.getOperand(1); 8758 SDValue Op2 = Op.getOperand(2); 8759 DebugLoc DL = Op.getDebugLoc(); 8760 SDValue CC; 8761 8762 if (Cond.getOpcode() == ISD::SETCC) { 8763 SDValue NewCond = LowerSETCC(Cond, DAG); 8764 if (NewCond.getNode()) 8765 Cond = NewCond; 8766 } 8767 8768 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y 8769 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y 8770 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y 8771 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y 8772 if (Cond.getOpcode() == X86ISD::SETCC && 8773 Cond.getOperand(1).getOpcode() == X86ISD::CMP && 8774 isZero(Cond.getOperand(1).getOperand(1))) { 8775 SDValue Cmp = Cond.getOperand(1); 8776 8777 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue(); 8778 8779 if ((isAllOnes(Op1) || isAllOnes(Op2)) && 8780 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) { 8781 SDValue Y = isAllOnes(Op2) ? Op1 : Op2; 8782 8783 SDValue CmpOp0 = Cmp.getOperand(0); 8784 // Apply further optimizations for special cases 8785 // (select (x != 0), -1, 0) -> neg & sbb 8786 // (select (x == 0), 0, -1) -> neg & sbb 8787 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y)) 8788 if (YC->isNullValue() && 8789 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) { 8790 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32); 8791 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs, 8792 DAG.getConstant(0, CmpOp0.getValueType()), 8793 CmpOp0); 8794 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 8795 DAG.getConstant(X86::COND_B, MVT::i8), 8796 SDValue(Neg.getNode(), 1)); 8797 return Res; 8798 } 8799 8800 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, 8801 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType())); 8802 Cmp = ConvertCmpIfNecessary(Cmp, DAG); 8803 8804 SDValue Res = // Res = 0 or -1. 8805 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 8806 DAG.getConstant(X86::COND_B, MVT::i8), Cmp); 8807 8808 if (isAllOnes(Op1) != (CondCode == X86::COND_E)) 8809 Res = DAG.getNOT(DL, Res, Res.getValueType()); 8810 8811 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2); 8812 if (N2C == 0 || !N2C->isNullValue()) 8813 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y); 8814 return Res; 8815 } 8816 } 8817 8818 // Look past (and (setcc_carry (cmp ...)), 1). 8819 if (Cond.getOpcode() == ISD::AND && 8820 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 8821 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 8822 if (C && C->getAPIntValue() == 1) 8823 Cond = Cond.getOperand(0); 8824 } 8825 8826 // If condition flag is set by a X86ISD::CMP, then use it as the condition 8827 // setting operand in place of the X86ISD::SETCC. 8828 unsigned CondOpcode = Cond.getOpcode(); 8829 if (CondOpcode == X86ISD::SETCC || 8830 CondOpcode == X86ISD::SETCC_CARRY) { 8831 CC = Cond.getOperand(0); 8832 8833 SDValue Cmp = Cond.getOperand(1); 8834 unsigned Opc = Cmp.getOpcode(); 8835 EVT VT = Op.getValueType(); 8836 8837 bool IllegalFPCMov = false; 8838 if (VT.isFloatingPoint() && !VT.isVector() && 8839 !isScalarFPTypeInSSEReg(VT)) // FPStack? 8840 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue()); 8841 8842 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) || 8843 Opc == X86ISD::BT) { // FIXME 8844 Cond = Cmp; 8845 addTest = false; 8846 } 8847 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO || 8848 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO || 8849 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) && 8850 Cond.getOperand(0).getValueType() != MVT::i8)) { 8851 SDValue LHS = Cond.getOperand(0); 8852 SDValue RHS = Cond.getOperand(1); 8853 unsigned X86Opcode; 8854 unsigned X86Cond; 8855 SDVTList VTs; 8856 switch (CondOpcode) { 8857 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break; 8858 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break; 8859 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break; 8860 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break; 8861 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break; 8862 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break; 8863 default: llvm_unreachable("unexpected overflowing operator"); 8864 } 8865 if (CondOpcode == ISD::UMULO) 8866 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(), 8867 MVT::i32); 8868 else 8869 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 8870 8871 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS); 8872 8873 if (CondOpcode == ISD::UMULO) 8874 Cond = X86Op.getValue(2); 8875 else 8876 Cond = X86Op.getValue(1); 8877 8878 CC = DAG.getConstant(X86Cond, MVT::i8); 8879 addTest = false; 8880 } 8881 8882 if (addTest) { 8883 // Look pass the truncate if the high bits are known zero. 8884 if (isTruncWithZeroHighBitsInput(Cond, DAG)) 8885 Cond = Cond.getOperand(0); 8886 8887 // We know the result of AND is compared against zero. Try to match 8888 // it to BT. 8889 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 8890 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG); 8891 if (NewSetCC.getNode()) { 8892 CC = NewSetCC.getOperand(0); 8893 Cond = NewSetCC.getOperand(1); 8894 addTest = false; 8895 } 8896 } 8897 } 8898 8899 if (addTest) { 8900 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 8901 Cond = EmitTest(Cond, X86::COND_NE, DAG); 8902 } 8903 8904 // a < b ? -1 : 0 -> RES = ~setcc_carry 8905 // a < b ? 0 : -1 -> RES = setcc_carry 8906 // a >= b ? -1 : 0 -> RES = setcc_carry 8907 // a >= b ? 0 : -1 -> RES = ~setcc_carry 8908 if (Cond.getOpcode() == X86ISD::SUB) { 8909 Cond = ConvertCmpIfNecessary(Cond, DAG); 8910 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue(); 8911 8912 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) && 8913 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) { 8914 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 8915 DAG.getConstant(X86::COND_B, MVT::i8), Cond); 8916 if (isAllOnes(Op1) != (CondCode == X86::COND_B)) 8917 return DAG.getNOT(DL, Res, Res.getValueType()); 8918 return Res; 8919 } 8920 } 8921 8922 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if 8923 // condition is true. 8924 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 8925 SDValue Ops[] = { Op2, Op1, CC, Cond }; 8926 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops)); 8927} 8928 8929// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or 8930// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart 8931// from the AND / OR. 8932static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) { 8933 Opc = Op.getOpcode(); 8934 if (Opc != ISD::OR && Opc != ISD::AND) 8935 return false; 8936 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC && 8937 Op.getOperand(0).hasOneUse() && 8938 Op.getOperand(1).getOpcode() == X86ISD::SETCC && 8939 Op.getOperand(1).hasOneUse()); 8940} 8941 8942// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and 8943// 1 and that the SETCC node has a single use. 8944static bool isXor1OfSetCC(SDValue Op) { 8945 if (Op.getOpcode() != ISD::XOR) 8946 return false; 8947 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8948 if (N1C && N1C->getAPIntValue() == 1) { 8949 return Op.getOperand(0).getOpcode() == X86ISD::SETCC && 8950 Op.getOperand(0).hasOneUse(); 8951 } 8952 return false; 8953} 8954 8955SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 8956 bool addTest = true; 8957 SDValue Chain = Op.getOperand(0); 8958 SDValue Cond = Op.getOperand(1); 8959 SDValue Dest = Op.getOperand(2); 8960 DebugLoc dl = Op.getDebugLoc(); 8961 SDValue CC; 8962 bool Inverted = false; 8963 8964 if (Cond.getOpcode() == ISD::SETCC) { 8965 // Check for setcc([su]{add,sub,mul}o == 0). 8966 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ && 8967 isa<ConstantSDNode>(Cond.getOperand(1)) && 8968 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() && 8969 Cond.getOperand(0).getResNo() == 1 && 8970 (Cond.getOperand(0).getOpcode() == ISD::SADDO || 8971 Cond.getOperand(0).getOpcode() == ISD::UADDO || 8972 Cond.getOperand(0).getOpcode() == ISD::SSUBO || 8973 Cond.getOperand(0).getOpcode() == ISD::USUBO || 8974 Cond.getOperand(0).getOpcode() == ISD::SMULO || 8975 Cond.getOperand(0).getOpcode() == ISD::UMULO)) { 8976 Inverted = true; 8977 Cond = Cond.getOperand(0); 8978 } else { 8979 SDValue NewCond = LowerSETCC(Cond, DAG); 8980 if (NewCond.getNode()) 8981 Cond = NewCond; 8982 } 8983 } 8984#if 0 8985 // FIXME: LowerXALUO doesn't handle these!! 8986 else if (Cond.getOpcode() == X86ISD::ADD || 8987 Cond.getOpcode() == X86ISD::SUB || 8988 Cond.getOpcode() == X86ISD::SMUL || 8989 Cond.getOpcode() == X86ISD::UMUL) 8990 Cond = LowerXALUO(Cond, DAG); 8991#endif 8992 8993 // Look pass (and (setcc_carry (cmp ...)), 1). 8994 if (Cond.getOpcode() == ISD::AND && 8995 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 8996 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 8997 if (C && C->getAPIntValue() == 1) 8998 Cond = Cond.getOperand(0); 8999 } 9000 9001 // If condition flag is set by a X86ISD::CMP, then use it as the condition 9002 // setting operand in place of the X86ISD::SETCC. 9003 unsigned CondOpcode = Cond.getOpcode(); 9004 if (CondOpcode == X86ISD::SETCC || 9005 CondOpcode == X86ISD::SETCC_CARRY) { 9006 CC = Cond.getOperand(0); 9007 9008 SDValue Cmp = Cond.getOperand(1); 9009 unsigned Opc = Cmp.getOpcode(); 9010 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp?? 9011 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) { 9012 Cond = Cmp; 9013 addTest = false; 9014 } else { 9015 switch (cast<ConstantSDNode>(CC)->getZExtValue()) { 9016 default: break; 9017 case X86::COND_O: 9018 case X86::COND_B: 9019 // These can only come from an arithmetic instruction with overflow, 9020 // e.g. SADDO, UADDO. 9021 Cond = Cond.getNode()->getOperand(1); 9022 addTest = false; 9023 break; 9024 } 9025 } 9026 } 9027 CondOpcode = Cond.getOpcode(); 9028 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO || 9029 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO || 9030 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) && 9031 Cond.getOperand(0).getValueType() != MVT::i8)) { 9032 SDValue LHS = Cond.getOperand(0); 9033 SDValue RHS = Cond.getOperand(1); 9034 unsigned X86Opcode; 9035 unsigned X86Cond; 9036 SDVTList VTs; 9037 switch (CondOpcode) { 9038 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break; 9039 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break; 9040 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break; 9041 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break; 9042 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break; 9043 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break; 9044 default: llvm_unreachable("unexpected overflowing operator"); 9045 } 9046 if (Inverted) 9047 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond); 9048 if (CondOpcode == ISD::UMULO) 9049 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(), 9050 MVT::i32); 9051 else 9052 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 9053 9054 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS); 9055 9056 if (CondOpcode == ISD::UMULO) 9057 Cond = X86Op.getValue(2); 9058 else 9059 Cond = X86Op.getValue(1); 9060 9061 CC = DAG.getConstant(X86Cond, MVT::i8); 9062 addTest = false; 9063 } else { 9064 unsigned CondOpc; 9065 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) { 9066 SDValue Cmp = Cond.getOperand(0).getOperand(1); 9067 if (CondOpc == ISD::OR) { 9068 // Also, recognize the pattern generated by an FCMP_UNE. We can emit 9069 // two branches instead of an explicit OR instruction with a 9070 // separate test. 9071 if (Cmp == Cond.getOperand(1).getOperand(1) && 9072 isX86LogicalCmp(Cmp)) { 9073 CC = Cond.getOperand(0).getOperand(0); 9074 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9075 Chain, Dest, CC, Cmp); 9076 CC = Cond.getOperand(1).getOperand(0); 9077 Cond = Cmp; 9078 addTest = false; 9079 } 9080 } else { // ISD::AND 9081 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit 9082 // two branches instead of an explicit AND instruction with a 9083 // separate test. However, we only do this if this block doesn't 9084 // have a fall-through edge, because this requires an explicit 9085 // jmp when the condition is false. 9086 if (Cmp == Cond.getOperand(1).getOperand(1) && 9087 isX86LogicalCmp(Cmp) && 9088 Op.getNode()->hasOneUse()) { 9089 X86::CondCode CCode = 9090 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 9091 CCode = X86::GetOppositeBranchCondition(CCode); 9092 CC = DAG.getConstant(CCode, MVT::i8); 9093 SDNode *User = *Op.getNode()->use_begin(); 9094 // Look for an unconditional branch following this conditional branch. 9095 // We need this because we need to reverse the successors in order 9096 // to implement FCMP_OEQ. 9097 if (User->getOpcode() == ISD::BR) { 9098 SDValue FalseBB = User->getOperand(1); 9099 SDNode *NewBR = 9100 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 9101 assert(NewBR == User); 9102 (void)NewBR; 9103 Dest = FalseBB; 9104 9105 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9106 Chain, Dest, CC, Cmp); 9107 X86::CondCode CCode = 9108 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0); 9109 CCode = X86::GetOppositeBranchCondition(CCode); 9110 CC = DAG.getConstant(CCode, MVT::i8); 9111 Cond = Cmp; 9112 addTest = false; 9113 } 9114 } 9115 } 9116 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) { 9117 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition. 9118 // It should be transformed during dag combiner except when the condition 9119 // is set by a arithmetics with overflow node. 9120 X86::CondCode CCode = 9121 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 9122 CCode = X86::GetOppositeBranchCondition(CCode); 9123 CC = DAG.getConstant(CCode, MVT::i8); 9124 Cond = Cond.getOperand(0).getOperand(1); 9125 addTest = false; 9126 } else if (Cond.getOpcode() == ISD::SETCC && 9127 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) { 9128 // For FCMP_OEQ, we can emit 9129 // two branches instead of an explicit AND instruction with a 9130 // separate test. However, we only do this if this block doesn't 9131 // have a fall-through edge, because this requires an explicit 9132 // jmp when the condition is false. 9133 if (Op.getNode()->hasOneUse()) { 9134 SDNode *User = *Op.getNode()->use_begin(); 9135 // Look for an unconditional branch following this conditional branch. 9136 // We need this because we need to reverse the successors in order 9137 // to implement FCMP_OEQ. 9138 if (User->getOpcode() == ISD::BR) { 9139 SDValue FalseBB = User->getOperand(1); 9140 SDNode *NewBR = 9141 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 9142 assert(NewBR == User); 9143 (void)NewBR; 9144 Dest = FalseBB; 9145 9146 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 9147 Cond.getOperand(0), Cond.getOperand(1)); 9148 Cmp = ConvertCmpIfNecessary(Cmp, DAG); 9149 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9150 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9151 Chain, Dest, CC, Cmp); 9152 CC = DAG.getConstant(X86::COND_P, MVT::i8); 9153 Cond = Cmp; 9154 addTest = false; 9155 } 9156 } 9157 } else if (Cond.getOpcode() == ISD::SETCC && 9158 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) { 9159 // For FCMP_UNE, we can emit 9160 // two branches instead of an explicit AND instruction with a 9161 // separate test. However, we only do this if this block doesn't 9162 // have a fall-through edge, because this requires an explicit 9163 // jmp when the condition is false. 9164 if (Op.getNode()->hasOneUse()) { 9165 SDNode *User = *Op.getNode()->use_begin(); 9166 // Look for an unconditional branch following this conditional branch. 9167 // We need this because we need to reverse the successors in order 9168 // to implement FCMP_UNE. 9169 if (User->getOpcode() == ISD::BR) { 9170 SDValue FalseBB = User->getOperand(1); 9171 SDNode *NewBR = 9172 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 9173 assert(NewBR == User); 9174 (void)NewBR; 9175 9176 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 9177 Cond.getOperand(0), Cond.getOperand(1)); 9178 Cmp = ConvertCmpIfNecessary(Cmp, DAG); 9179 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9180 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9181 Chain, Dest, CC, Cmp); 9182 CC = DAG.getConstant(X86::COND_NP, MVT::i8); 9183 Cond = Cmp; 9184 addTest = false; 9185 Dest = FalseBB; 9186 } 9187 } 9188 } 9189 } 9190 9191 if (addTest) { 9192 // Look pass the truncate if the high bits are known zero. 9193 if (isTruncWithZeroHighBitsInput(Cond, DAG)) 9194 Cond = Cond.getOperand(0); 9195 9196 // We know the result of AND is compared against zero. Try to match 9197 // it to BT. 9198 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 9199 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG); 9200 if (NewSetCC.getNode()) { 9201 CC = NewSetCC.getOperand(0); 9202 Cond = NewSetCC.getOperand(1); 9203 addTest = false; 9204 } 9205 } 9206 } 9207 9208 if (addTest) { 9209 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9210 Cond = EmitTest(Cond, X86::COND_NE, DAG); 9211 } 9212 Cond = ConvertCmpIfNecessary(Cond, DAG); 9213 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9214 Chain, Dest, CC, Cond); 9215} 9216 9217 9218// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets. 9219// Calls to _alloca is needed to probe the stack when allocating more than 4k 9220// bytes in one go. Touching the stack at 4K increments is necessary to ensure 9221// that the guard pages used by the OS virtual memory manager are allocated in 9222// correct sequence. 9223SDValue 9224X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 9225 SelectionDAG &DAG) const { 9226 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() || 9227 getTargetMachine().Options.EnableSegmentedStacks) && 9228 "This should be used only on Windows targets or when segmented stacks " 9229 "are being used"); 9230 assert(!Subtarget->isTargetEnvMacho() && "Not implemented"); 9231 DebugLoc dl = Op.getDebugLoc(); 9232 9233 // Get the inputs. 9234 SDValue Chain = Op.getOperand(0); 9235 SDValue Size = Op.getOperand(1); 9236 // FIXME: Ensure alignment here 9237 9238 bool Is64Bit = Subtarget->is64Bit(); 9239 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32; 9240 9241 if (getTargetMachine().Options.EnableSegmentedStacks) { 9242 MachineFunction &MF = DAG.getMachineFunction(); 9243 MachineRegisterInfo &MRI = MF.getRegInfo(); 9244 9245 if (Is64Bit) { 9246 // The 64 bit implementation of segmented stacks needs to clobber both r10 9247 // r11. This makes it impossible to use it along with nested parameters. 9248 const Function *F = MF.getFunction(); 9249 9250 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 9251 I != E; ++I) 9252 if (I->hasNestAttr()) 9253 report_fatal_error("Cannot use segmented stacks with functions that " 9254 "have nested arguments."); 9255 } 9256 9257 const TargetRegisterClass *AddrRegClass = 9258 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32); 9259 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass); 9260 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size); 9261 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain, 9262 DAG.getRegister(Vreg, SPTy)); 9263 SDValue Ops1[2] = { Value, Chain }; 9264 return DAG.getMergeValues(Ops1, 2, dl); 9265 } else { 9266 SDValue Flag; 9267 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX); 9268 9269 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag); 9270 Flag = Chain.getValue(1); 9271 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9272 9273 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag); 9274 Flag = Chain.getValue(1); 9275 9276 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1); 9277 9278 SDValue Ops1[2] = { Chain.getValue(0), Chain }; 9279 return DAG.getMergeValues(Ops1, 2, dl); 9280 } 9281} 9282 9283SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 9284 MachineFunction &MF = DAG.getMachineFunction(); 9285 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 9286 9287 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 9288 DebugLoc DL = Op.getDebugLoc(); 9289 9290 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) { 9291 // vastart just stores the address of the VarArgsFrameIndex slot into the 9292 // memory location argument. 9293 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 9294 getPointerTy()); 9295 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 9296 MachinePointerInfo(SV), false, false, 0); 9297 } 9298 9299 // __va_list_tag: 9300 // gp_offset (0 - 6 * 8) 9301 // fp_offset (48 - 48 + 8 * 16) 9302 // overflow_arg_area (point to parameters coming in memory). 9303 // reg_save_area 9304 SmallVector<SDValue, 8> MemOps; 9305 SDValue FIN = Op.getOperand(1); 9306 // Store gp_offset 9307 SDValue Store = DAG.getStore(Op.getOperand(0), DL, 9308 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), 9309 MVT::i32), 9310 FIN, MachinePointerInfo(SV), false, false, 0); 9311 MemOps.push_back(Store); 9312 9313 // Store fp_offset 9314 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 9315 FIN, DAG.getIntPtrConstant(4)); 9316 Store = DAG.getStore(Op.getOperand(0), DL, 9317 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), 9318 MVT::i32), 9319 FIN, MachinePointerInfo(SV, 4), false, false, 0); 9320 MemOps.push_back(Store); 9321 9322 // Store ptr to overflow_arg_area 9323 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 9324 FIN, DAG.getIntPtrConstant(4)); 9325 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 9326 getPointerTy()); 9327 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, 9328 MachinePointerInfo(SV, 8), 9329 false, false, 0); 9330 MemOps.push_back(Store); 9331 9332 // Store ptr to reg_save_area. 9333 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 9334 FIN, DAG.getIntPtrConstant(8)); 9335 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 9336 getPointerTy()); 9337 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, 9338 MachinePointerInfo(SV, 16), false, false, 0); 9339 MemOps.push_back(Store); 9340 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 9341 &MemOps[0], MemOps.size()); 9342} 9343 9344SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 9345 assert(Subtarget->is64Bit() && 9346 "LowerVAARG only handles 64-bit va_arg!"); 9347 assert((Subtarget->isTargetLinux() || 9348 Subtarget->isTargetDarwin()) && 9349 "Unhandled target in LowerVAARG"); 9350 assert(Op.getNode()->getNumOperands() == 4); 9351 SDValue Chain = Op.getOperand(0); 9352 SDValue SrcPtr = Op.getOperand(1); 9353 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 9354 unsigned Align = Op.getConstantOperandVal(3); 9355 DebugLoc dl = Op.getDebugLoc(); 9356 9357 EVT ArgVT = Op.getNode()->getValueType(0); 9358 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 9359 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy); 9360 uint8_t ArgMode; 9361 9362 // Decide which area this value should be read from. 9363 // TODO: Implement the AMD64 ABI in its entirety. This simple 9364 // selection mechanism works only for the basic types. 9365 if (ArgVT == MVT::f80) { 9366 llvm_unreachable("va_arg for f80 not yet implemented"); 9367 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) { 9368 ArgMode = 2; // Argument passed in XMM register. Use fp_offset. 9369 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) { 9370 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset. 9371 } else { 9372 llvm_unreachable("Unhandled argument type in LowerVAARG"); 9373 } 9374 9375 if (ArgMode == 2) { 9376 // Sanity Check: Make sure using fp_offset makes sense. 9377 assert(!getTargetMachine().Options.UseSoftFloat && 9378 !(DAG.getMachineFunction() 9379 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) && 9380 Subtarget->hasSSE1()); 9381 } 9382 9383 // Insert VAARG_64 node into the DAG 9384 // VAARG_64 returns two values: Variable Argument Address, Chain 9385 SmallVector<SDValue, 11> InstOps; 9386 InstOps.push_back(Chain); 9387 InstOps.push_back(SrcPtr); 9388 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32)); 9389 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8)); 9390 InstOps.push_back(DAG.getConstant(Align, MVT::i32)); 9391 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other); 9392 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl, 9393 VTs, &InstOps[0], InstOps.size(), 9394 MVT::i64, 9395 MachinePointerInfo(SV), 9396 /*Align=*/0, 9397 /*Volatile=*/false, 9398 /*ReadMem=*/true, 9399 /*WriteMem=*/true); 9400 Chain = VAARG.getValue(1); 9401 9402 // Load the next argument and return it 9403 return DAG.getLoad(ArgVT, dl, 9404 Chain, 9405 VAARG, 9406 MachinePointerInfo(), 9407 false, false, false, 0); 9408} 9409 9410SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 9411 // X86-64 va_list is a struct { i32, i32, i8*, i8* }. 9412 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!"); 9413 SDValue Chain = Op.getOperand(0); 9414 SDValue DstPtr = Op.getOperand(1); 9415 SDValue SrcPtr = Op.getOperand(2); 9416 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 9417 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 9418 DebugLoc DL = Op.getDebugLoc(); 9419 9420 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, 9421 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false, 9422 false, 9423 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV)); 9424} 9425 9426// getTargetVShiftNOde - Handle vector element shifts where the shift amount 9427// may or may not be a constant. Takes immediate version of shift as input. 9428static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT, 9429 SDValue SrcOp, SDValue ShAmt, 9430 SelectionDAG &DAG) { 9431 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32"); 9432 9433 if (isa<ConstantSDNode>(ShAmt)) { 9434 // Constant may be a TargetConstant. Use a regular constant. 9435 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 9436 switch (Opc) { 9437 default: llvm_unreachable("Unknown target vector shift node"); 9438 case X86ISD::VSHLI: 9439 case X86ISD::VSRLI: 9440 case X86ISD::VSRAI: 9441 return DAG.getNode(Opc, dl, VT, SrcOp, 9442 DAG.getConstant(ShiftAmt, MVT::i32)); 9443 } 9444 } 9445 9446 // Change opcode to non-immediate version 9447 switch (Opc) { 9448 default: llvm_unreachable("Unknown target vector shift node"); 9449 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break; 9450 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break; 9451 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break; 9452 } 9453 9454 // Need to build a vector containing shift amount 9455 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0 9456 SDValue ShOps[4]; 9457 ShOps[0] = ShAmt; 9458 ShOps[1] = DAG.getConstant(0, MVT::i32); 9459 ShOps[2] = DAG.getUNDEF(MVT::i32); 9460 ShOps[3] = DAG.getUNDEF(MVT::i32); 9461 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4); 9462 9463 // The return type has to be a 128-bit type with the same element 9464 // type as the input type. 9465 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 9466 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits()); 9467 9468 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt); 9469 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt); 9470} 9471 9472SDValue 9473X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const { 9474 DebugLoc dl = Op.getDebugLoc(); 9475 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9476 switch (IntNo) { 9477 default: return SDValue(); // Don't custom lower most intrinsics. 9478 // Comparison intrinsics. 9479 case Intrinsic::x86_sse_comieq_ss: 9480 case Intrinsic::x86_sse_comilt_ss: 9481 case Intrinsic::x86_sse_comile_ss: 9482 case Intrinsic::x86_sse_comigt_ss: 9483 case Intrinsic::x86_sse_comige_ss: 9484 case Intrinsic::x86_sse_comineq_ss: 9485 case Intrinsic::x86_sse_ucomieq_ss: 9486 case Intrinsic::x86_sse_ucomilt_ss: 9487 case Intrinsic::x86_sse_ucomile_ss: 9488 case Intrinsic::x86_sse_ucomigt_ss: 9489 case Intrinsic::x86_sse_ucomige_ss: 9490 case Intrinsic::x86_sse_ucomineq_ss: 9491 case Intrinsic::x86_sse2_comieq_sd: 9492 case Intrinsic::x86_sse2_comilt_sd: 9493 case Intrinsic::x86_sse2_comile_sd: 9494 case Intrinsic::x86_sse2_comigt_sd: 9495 case Intrinsic::x86_sse2_comige_sd: 9496 case Intrinsic::x86_sse2_comineq_sd: 9497 case Intrinsic::x86_sse2_ucomieq_sd: 9498 case Intrinsic::x86_sse2_ucomilt_sd: 9499 case Intrinsic::x86_sse2_ucomile_sd: 9500 case Intrinsic::x86_sse2_ucomigt_sd: 9501 case Intrinsic::x86_sse2_ucomige_sd: 9502 case Intrinsic::x86_sse2_ucomineq_sd: { 9503 unsigned Opc = 0; 9504 ISD::CondCode CC = ISD::SETCC_INVALID; 9505 switch (IntNo) { 9506 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 9507 case Intrinsic::x86_sse_comieq_ss: 9508 case Intrinsic::x86_sse2_comieq_sd: 9509 Opc = X86ISD::COMI; 9510 CC = ISD::SETEQ; 9511 break; 9512 case Intrinsic::x86_sse_comilt_ss: 9513 case Intrinsic::x86_sse2_comilt_sd: 9514 Opc = X86ISD::COMI; 9515 CC = ISD::SETLT; 9516 break; 9517 case Intrinsic::x86_sse_comile_ss: 9518 case Intrinsic::x86_sse2_comile_sd: 9519 Opc = X86ISD::COMI; 9520 CC = ISD::SETLE; 9521 break; 9522 case Intrinsic::x86_sse_comigt_ss: 9523 case Intrinsic::x86_sse2_comigt_sd: 9524 Opc = X86ISD::COMI; 9525 CC = ISD::SETGT; 9526 break; 9527 case Intrinsic::x86_sse_comige_ss: 9528 case Intrinsic::x86_sse2_comige_sd: 9529 Opc = X86ISD::COMI; 9530 CC = ISD::SETGE; 9531 break; 9532 case Intrinsic::x86_sse_comineq_ss: 9533 case Intrinsic::x86_sse2_comineq_sd: 9534 Opc = X86ISD::COMI; 9535 CC = ISD::SETNE; 9536 break; 9537 case Intrinsic::x86_sse_ucomieq_ss: 9538 case Intrinsic::x86_sse2_ucomieq_sd: 9539 Opc = X86ISD::UCOMI; 9540 CC = ISD::SETEQ; 9541 break; 9542 case Intrinsic::x86_sse_ucomilt_ss: 9543 case Intrinsic::x86_sse2_ucomilt_sd: 9544 Opc = X86ISD::UCOMI; 9545 CC = ISD::SETLT; 9546 break; 9547 case Intrinsic::x86_sse_ucomile_ss: 9548 case Intrinsic::x86_sse2_ucomile_sd: 9549 Opc = X86ISD::UCOMI; 9550 CC = ISD::SETLE; 9551 break; 9552 case Intrinsic::x86_sse_ucomigt_ss: 9553 case Intrinsic::x86_sse2_ucomigt_sd: 9554 Opc = X86ISD::UCOMI; 9555 CC = ISD::SETGT; 9556 break; 9557 case Intrinsic::x86_sse_ucomige_ss: 9558 case Intrinsic::x86_sse2_ucomige_sd: 9559 Opc = X86ISD::UCOMI; 9560 CC = ISD::SETGE; 9561 break; 9562 case Intrinsic::x86_sse_ucomineq_ss: 9563 case Intrinsic::x86_sse2_ucomineq_sd: 9564 Opc = X86ISD::UCOMI; 9565 CC = ISD::SETNE; 9566 break; 9567 } 9568 9569 SDValue LHS = Op.getOperand(1); 9570 SDValue RHS = Op.getOperand(2); 9571 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG); 9572 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!"); 9573 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS); 9574 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9575 DAG.getConstant(X86CC, MVT::i8), Cond); 9576 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 9577 } 9578 // Arithmetic intrinsics. 9579 case Intrinsic::x86_sse2_pmulu_dq: 9580 case Intrinsic::x86_avx2_pmulu_dq: 9581 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(), 9582 Op.getOperand(1), Op.getOperand(2)); 9583 case Intrinsic::x86_sse3_hadd_ps: 9584 case Intrinsic::x86_sse3_hadd_pd: 9585 case Intrinsic::x86_avx_hadd_ps_256: 9586 case Intrinsic::x86_avx_hadd_pd_256: 9587 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(), 9588 Op.getOperand(1), Op.getOperand(2)); 9589 case Intrinsic::x86_sse3_hsub_ps: 9590 case Intrinsic::x86_sse3_hsub_pd: 9591 case Intrinsic::x86_avx_hsub_ps_256: 9592 case Intrinsic::x86_avx_hsub_pd_256: 9593 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(), 9594 Op.getOperand(1), Op.getOperand(2)); 9595 case Intrinsic::x86_ssse3_phadd_w_128: 9596 case Intrinsic::x86_ssse3_phadd_d_128: 9597 case Intrinsic::x86_avx2_phadd_w: 9598 case Intrinsic::x86_avx2_phadd_d: 9599 return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(), 9600 Op.getOperand(1), Op.getOperand(2)); 9601 case Intrinsic::x86_ssse3_phsub_w_128: 9602 case Intrinsic::x86_ssse3_phsub_d_128: 9603 case Intrinsic::x86_avx2_phsub_w: 9604 case Intrinsic::x86_avx2_phsub_d: 9605 return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(), 9606 Op.getOperand(1), Op.getOperand(2)); 9607 case Intrinsic::x86_avx2_psllv_d: 9608 case Intrinsic::x86_avx2_psllv_q: 9609 case Intrinsic::x86_avx2_psllv_d_256: 9610 case Intrinsic::x86_avx2_psllv_q_256: 9611 return DAG.getNode(ISD::SHL, dl, Op.getValueType(), 9612 Op.getOperand(1), Op.getOperand(2)); 9613 case Intrinsic::x86_avx2_psrlv_d: 9614 case Intrinsic::x86_avx2_psrlv_q: 9615 case Intrinsic::x86_avx2_psrlv_d_256: 9616 case Intrinsic::x86_avx2_psrlv_q_256: 9617 return DAG.getNode(ISD::SRL, dl, Op.getValueType(), 9618 Op.getOperand(1), Op.getOperand(2)); 9619 case Intrinsic::x86_avx2_psrav_d: 9620 case Intrinsic::x86_avx2_psrav_d_256: 9621 return DAG.getNode(ISD::SRA, dl, Op.getValueType(), 9622 Op.getOperand(1), Op.getOperand(2)); 9623 case Intrinsic::x86_ssse3_pshuf_b_128: 9624 case Intrinsic::x86_avx2_pshuf_b: 9625 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(), 9626 Op.getOperand(1), Op.getOperand(2)); 9627 case Intrinsic::x86_ssse3_psign_b_128: 9628 case Intrinsic::x86_ssse3_psign_w_128: 9629 case Intrinsic::x86_ssse3_psign_d_128: 9630 case Intrinsic::x86_avx2_psign_b: 9631 case Intrinsic::x86_avx2_psign_w: 9632 case Intrinsic::x86_avx2_psign_d: 9633 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(), 9634 Op.getOperand(1), Op.getOperand(2)); 9635 case Intrinsic::x86_sse41_insertps: 9636 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(), 9637 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 9638 case Intrinsic::x86_avx_vperm2f128_ps_256: 9639 case Intrinsic::x86_avx_vperm2f128_pd_256: 9640 case Intrinsic::x86_avx_vperm2f128_si_256: 9641 case Intrinsic::x86_avx2_vperm2i128: 9642 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(), 9643 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 9644 case Intrinsic::x86_avx2_permd: 9645 case Intrinsic::x86_avx2_permps: 9646 // Operands intentionally swapped. Mask is last operand to intrinsic, 9647 // but second operand for node/intruction. 9648 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(), 9649 Op.getOperand(2), Op.getOperand(1)); 9650 9651 // ptest and testp intrinsics. The intrinsic these come from are designed to 9652 // return an integer value, not just an instruction so lower it to the ptest 9653 // or testp pattern and a setcc for the result. 9654 case Intrinsic::x86_sse41_ptestz: 9655 case Intrinsic::x86_sse41_ptestc: 9656 case Intrinsic::x86_sse41_ptestnzc: 9657 case Intrinsic::x86_avx_ptestz_256: 9658 case Intrinsic::x86_avx_ptestc_256: 9659 case Intrinsic::x86_avx_ptestnzc_256: 9660 case Intrinsic::x86_avx_vtestz_ps: 9661 case Intrinsic::x86_avx_vtestc_ps: 9662 case Intrinsic::x86_avx_vtestnzc_ps: 9663 case Intrinsic::x86_avx_vtestz_pd: 9664 case Intrinsic::x86_avx_vtestc_pd: 9665 case Intrinsic::x86_avx_vtestnzc_pd: 9666 case Intrinsic::x86_avx_vtestz_ps_256: 9667 case Intrinsic::x86_avx_vtestc_ps_256: 9668 case Intrinsic::x86_avx_vtestnzc_ps_256: 9669 case Intrinsic::x86_avx_vtestz_pd_256: 9670 case Intrinsic::x86_avx_vtestc_pd_256: 9671 case Intrinsic::x86_avx_vtestnzc_pd_256: { 9672 bool IsTestPacked = false; 9673 unsigned X86CC = 0; 9674 switch (IntNo) { 9675 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering."); 9676 case Intrinsic::x86_avx_vtestz_ps: 9677 case Intrinsic::x86_avx_vtestz_pd: 9678 case Intrinsic::x86_avx_vtestz_ps_256: 9679 case Intrinsic::x86_avx_vtestz_pd_256: 9680 IsTestPacked = true; // Fallthrough 9681 case Intrinsic::x86_sse41_ptestz: 9682 case Intrinsic::x86_avx_ptestz_256: 9683 // ZF = 1 9684 X86CC = X86::COND_E; 9685 break; 9686 case Intrinsic::x86_avx_vtestc_ps: 9687 case Intrinsic::x86_avx_vtestc_pd: 9688 case Intrinsic::x86_avx_vtestc_ps_256: 9689 case Intrinsic::x86_avx_vtestc_pd_256: 9690 IsTestPacked = true; // Fallthrough 9691 case Intrinsic::x86_sse41_ptestc: 9692 case Intrinsic::x86_avx_ptestc_256: 9693 // CF = 1 9694 X86CC = X86::COND_B; 9695 break; 9696 case Intrinsic::x86_avx_vtestnzc_ps: 9697 case Intrinsic::x86_avx_vtestnzc_pd: 9698 case Intrinsic::x86_avx_vtestnzc_ps_256: 9699 case Intrinsic::x86_avx_vtestnzc_pd_256: 9700 IsTestPacked = true; // Fallthrough 9701 case Intrinsic::x86_sse41_ptestnzc: 9702 case Intrinsic::x86_avx_ptestnzc_256: 9703 // ZF and CF = 0 9704 X86CC = X86::COND_A; 9705 break; 9706 } 9707 9708 SDValue LHS = Op.getOperand(1); 9709 SDValue RHS = Op.getOperand(2); 9710 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST; 9711 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS); 9712 SDValue CC = DAG.getConstant(X86CC, MVT::i8); 9713 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test); 9714 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 9715 } 9716 9717 // SSE/AVX shift intrinsics 9718 case Intrinsic::x86_sse2_psll_w: 9719 case Intrinsic::x86_sse2_psll_d: 9720 case Intrinsic::x86_sse2_psll_q: 9721 case Intrinsic::x86_avx2_psll_w: 9722 case Intrinsic::x86_avx2_psll_d: 9723 case Intrinsic::x86_avx2_psll_q: 9724 return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(), 9725 Op.getOperand(1), Op.getOperand(2)); 9726 case Intrinsic::x86_sse2_psrl_w: 9727 case Intrinsic::x86_sse2_psrl_d: 9728 case Intrinsic::x86_sse2_psrl_q: 9729 case Intrinsic::x86_avx2_psrl_w: 9730 case Intrinsic::x86_avx2_psrl_d: 9731 case Intrinsic::x86_avx2_psrl_q: 9732 return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(), 9733 Op.getOperand(1), Op.getOperand(2)); 9734 case Intrinsic::x86_sse2_psra_w: 9735 case Intrinsic::x86_sse2_psra_d: 9736 case Intrinsic::x86_avx2_psra_w: 9737 case Intrinsic::x86_avx2_psra_d: 9738 return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(), 9739 Op.getOperand(1), Op.getOperand(2)); 9740 case Intrinsic::x86_sse2_pslli_w: 9741 case Intrinsic::x86_sse2_pslli_d: 9742 case Intrinsic::x86_sse2_pslli_q: 9743 case Intrinsic::x86_avx2_pslli_w: 9744 case Intrinsic::x86_avx2_pslli_d: 9745 case Intrinsic::x86_avx2_pslli_q: 9746 return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(), 9747 Op.getOperand(1), Op.getOperand(2), DAG); 9748 case Intrinsic::x86_sse2_psrli_w: 9749 case Intrinsic::x86_sse2_psrli_d: 9750 case Intrinsic::x86_sse2_psrli_q: 9751 case Intrinsic::x86_avx2_psrli_w: 9752 case Intrinsic::x86_avx2_psrli_d: 9753 case Intrinsic::x86_avx2_psrli_q: 9754 return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(), 9755 Op.getOperand(1), Op.getOperand(2), DAG); 9756 case Intrinsic::x86_sse2_psrai_w: 9757 case Intrinsic::x86_sse2_psrai_d: 9758 case Intrinsic::x86_avx2_psrai_w: 9759 case Intrinsic::x86_avx2_psrai_d: 9760 return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(), 9761 Op.getOperand(1), Op.getOperand(2), DAG); 9762 // Fix vector shift instructions where the last operand is a non-immediate 9763 // i32 value. 9764 case Intrinsic::x86_mmx_pslli_w: 9765 case Intrinsic::x86_mmx_pslli_d: 9766 case Intrinsic::x86_mmx_pslli_q: 9767 case Intrinsic::x86_mmx_psrli_w: 9768 case Intrinsic::x86_mmx_psrli_d: 9769 case Intrinsic::x86_mmx_psrli_q: 9770 case Intrinsic::x86_mmx_psrai_w: 9771 case Intrinsic::x86_mmx_psrai_d: { 9772 SDValue ShAmt = Op.getOperand(2); 9773 if (isa<ConstantSDNode>(ShAmt)) 9774 return SDValue(); 9775 9776 unsigned NewIntNo = 0; 9777 switch (IntNo) { 9778 case Intrinsic::x86_mmx_pslli_w: 9779 NewIntNo = Intrinsic::x86_mmx_psll_w; 9780 break; 9781 case Intrinsic::x86_mmx_pslli_d: 9782 NewIntNo = Intrinsic::x86_mmx_psll_d; 9783 break; 9784 case Intrinsic::x86_mmx_pslli_q: 9785 NewIntNo = Intrinsic::x86_mmx_psll_q; 9786 break; 9787 case Intrinsic::x86_mmx_psrli_w: 9788 NewIntNo = Intrinsic::x86_mmx_psrl_w; 9789 break; 9790 case Intrinsic::x86_mmx_psrli_d: 9791 NewIntNo = Intrinsic::x86_mmx_psrl_d; 9792 break; 9793 case Intrinsic::x86_mmx_psrli_q: 9794 NewIntNo = Intrinsic::x86_mmx_psrl_q; 9795 break; 9796 case Intrinsic::x86_mmx_psrai_w: 9797 NewIntNo = Intrinsic::x86_mmx_psra_w; 9798 break; 9799 case Intrinsic::x86_mmx_psrai_d: 9800 NewIntNo = Intrinsic::x86_mmx_psra_d; 9801 break; 9802 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 9803 } 9804 9805 // The vector shift intrinsics with scalars uses 32b shift amounts but 9806 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 9807 // to be zero. 9808 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt, 9809 DAG.getConstant(0, MVT::i32)); 9810// FIXME this must be lowered to get rid of the invalid type. 9811 9812 EVT VT = Op.getValueType(); 9813 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt); 9814 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9815 DAG.getConstant(NewIntNo, MVT::i32), 9816 Op.getOperand(1), ShAmt); 9817 } 9818 case Intrinsic::x86_sse42_pcmpistria128: 9819 case Intrinsic::x86_sse42_pcmpestria128: 9820 case Intrinsic::x86_sse42_pcmpistric128: 9821 case Intrinsic::x86_sse42_pcmpestric128: 9822 case Intrinsic::x86_sse42_pcmpistrio128: 9823 case Intrinsic::x86_sse42_pcmpestrio128: 9824 case Intrinsic::x86_sse42_pcmpistris128: 9825 case Intrinsic::x86_sse42_pcmpestris128: 9826 case Intrinsic::x86_sse42_pcmpistriz128: 9827 case Intrinsic::x86_sse42_pcmpestriz128: { 9828 unsigned Opcode; 9829 unsigned X86CC; 9830 switch (IntNo) { 9831 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 9832 case Intrinsic::x86_sse42_pcmpistria128: 9833 Opcode = X86ISD::PCMPISTRI; 9834 X86CC = X86::COND_A; 9835 break; 9836 case Intrinsic::x86_sse42_pcmpestria128: 9837 Opcode = X86ISD::PCMPESTRI; 9838 X86CC = X86::COND_A; 9839 break; 9840 case Intrinsic::x86_sse42_pcmpistric128: 9841 Opcode = X86ISD::PCMPISTRI; 9842 X86CC = X86::COND_B; 9843 break; 9844 case Intrinsic::x86_sse42_pcmpestric128: 9845 Opcode = X86ISD::PCMPESTRI; 9846 X86CC = X86::COND_B; 9847 break; 9848 case Intrinsic::x86_sse42_pcmpistrio128: 9849 Opcode = X86ISD::PCMPISTRI; 9850 X86CC = X86::COND_O; 9851 break; 9852 case Intrinsic::x86_sse42_pcmpestrio128: 9853 Opcode = X86ISD::PCMPESTRI; 9854 X86CC = X86::COND_O; 9855 break; 9856 case Intrinsic::x86_sse42_pcmpistris128: 9857 Opcode = X86ISD::PCMPISTRI; 9858 X86CC = X86::COND_S; 9859 break; 9860 case Intrinsic::x86_sse42_pcmpestris128: 9861 Opcode = X86ISD::PCMPESTRI; 9862 X86CC = X86::COND_S; 9863 break; 9864 case Intrinsic::x86_sse42_pcmpistriz128: 9865 Opcode = X86ISD::PCMPISTRI; 9866 X86CC = X86::COND_E; 9867 break; 9868 case Intrinsic::x86_sse42_pcmpestriz128: 9869 Opcode = X86ISD::PCMPESTRI; 9870 X86CC = X86::COND_E; 9871 break; 9872 } 9873 SmallVector<SDValue, 5> NewOps; 9874 NewOps.append(Op->op_begin()+1, Op->op_end()); 9875 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 9876 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size()); 9877 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9878 DAG.getConstant(X86CC, MVT::i8), 9879 SDValue(PCMP.getNode(), 1)); 9880 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 9881 } 9882 case Intrinsic::x86_sse42_pcmpistri128: 9883 case Intrinsic::x86_sse42_pcmpestri128: { 9884 unsigned Opcode; 9885 if (IntNo == Intrinsic::x86_sse42_pcmpistri128) 9886 Opcode = X86ISD::PCMPISTRI; 9887 else 9888 Opcode = X86ISD::PCMPESTRI; 9889 9890 SmallVector<SDValue, 5> NewOps; 9891 NewOps.append(Op->op_begin()+1, Op->op_end()); 9892 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 9893 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size()); 9894 } 9895 } 9896} 9897 9898SDValue 9899X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const { 9900 DebugLoc dl = Op.getDebugLoc(); 9901 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 9902 switch (IntNo) { 9903 default: return SDValue(); // Don't custom lower most intrinsics. 9904 9905 // RDRAND intrinsics. 9906 case Intrinsic::x86_rdrand_16: 9907 case Intrinsic::x86_rdrand_32: 9908 case Intrinsic::x86_rdrand_64: { 9909 // Emit the node with the right value type. 9910 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other); 9911 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0)); 9912 9913 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise 9914 // return the value from Rand, which is always 0, casted to i32. 9915 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)), 9916 DAG.getConstant(1, Op->getValueType(1)), 9917 DAG.getConstant(X86::COND_B, MVT::i32), 9918 SDValue(Result.getNode(), 1) }; 9919 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, 9920 DAG.getVTList(Op->getValueType(1), MVT::Glue), 9921 Ops, 4); 9922 9923 // Return { result, isValid, chain }. 9924 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid, 9925 SDValue(Result.getNode(), 2)); 9926 } 9927 } 9928} 9929 9930SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, 9931 SelectionDAG &DAG) const { 9932 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 9933 MFI->setReturnAddressIsTaken(true); 9934 9935 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9936 DebugLoc dl = Op.getDebugLoc(); 9937 9938 if (Depth > 0) { 9939 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 9940 SDValue Offset = 9941 DAG.getConstant(TD->getPointerSize(), 9942 Subtarget->is64Bit() ? MVT::i64 : MVT::i32); 9943 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 9944 DAG.getNode(ISD::ADD, dl, getPointerTy(), 9945 FrameAddr, Offset), 9946 MachinePointerInfo(), false, false, false, 0); 9947 } 9948 9949 // Just load the return address. 9950 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG); 9951 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 9952 RetAddrFI, MachinePointerInfo(), false, false, false, 0); 9953} 9954 9955SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 9956 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 9957 MFI->setFrameAddressIsTaken(true); 9958 9959 EVT VT = Op.getValueType(); 9960 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful 9961 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9962 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP; 9963 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 9964 while (Depth--) 9965 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 9966 MachinePointerInfo(), 9967 false, false, false, 0); 9968 return FrameAddr; 9969} 9970 9971SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op, 9972 SelectionDAG &DAG) const { 9973 return DAG.getIntPtrConstant(2*TD->getPointerSize()); 9974} 9975 9976SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const { 9977 SDValue Chain = Op.getOperand(0); 9978 SDValue Offset = Op.getOperand(1); 9979 SDValue Handler = Op.getOperand(2); 9980 DebugLoc dl = Op.getDebugLoc(); 9981 9982 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, 9983 Subtarget->is64Bit() ? X86::RBP : X86::EBP, 9984 getPointerTy()); 9985 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX); 9986 9987 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame, 9988 DAG.getIntPtrConstant(TD->getPointerSize())); 9989 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset); 9990 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(), 9991 false, false, 0); 9992 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr); 9993 9994 return DAG.getNode(X86ISD::EH_RETURN, dl, 9995 MVT::Other, 9996 Chain, DAG.getRegister(StoreAddrReg, getPointerTy())); 9997} 9998 9999SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 10000 SelectionDAG &DAG) const { 10001 return Op.getOperand(0); 10002} 10003 10004SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 10005 SelectionDAG &DAG) const { 10006 SDValue Root = Op.getOperand(0); 10007 SDValue Trmp = Op.getOperand(1); // trampoline 10008 SDValue FPtr = Op.getOperand(2); // nested function 10009 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 10010 DebugLoc dl = Op.getDebugLoc(); 10011 10012 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 10013 10014 if (Subtarget->is64Bit()) { 10015 SDValue OutChains[6]; 10016 10017 // Large code-model. 10018 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode. 10019 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode. 10020 10021 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10); 10022 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11); 10023 10024 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix 10025 10026 // Load the pointer to the nested function into R11. 10027 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11 10028 SDValue Addr = Trmp; 10029 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 10030 Addr, MachinePointerInfo(TrmpAddr), 10031 false, false, 0); 10032 10033 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 10034 DAG.getConstant(2, MVT::i64)); 10035 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, 10036 MachinePointerInfo(TrmpAddr, 2), 10037 false, false, 2); 10038 10039 // Load the 'nest' parameter value into R10. 10040 // R10 is specified in X86CallingConv.td 10041 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10 10042 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 10043 DAG.getConstant(10, MVT::i64)); 10044 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 10045 Addr, MachinePointerInfo(TrmpAddr, 10), 10046 false, false, 0); 10047 10048 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 10049 DAG.getConstant(12, MVT::i64)); 10050 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, 10051 MachinePointerInfo(TrmpAddr, 12), 10052 false, false, 2); 10053 10054 // Jump to the nested function. 10055 OpCode = (JMP64r << 8) | REX_WB; // jmpq *... 10056 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 10057 DAG.getConstant(20, MVT::i64)); 10058 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 10059 Addr, MachinePointerInfo(TrmpAddr, 20), 10060 false, false, 0); 10061 10062 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11 10063 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 10064 DAG.getConstant(22, MVT::i64)); 10065 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr, 10066 MachinePointerInfo(TrmpAddr, 22), 10067 false, false, 0); 10068 10069 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6); 10070 } else { 10071 const Function *Func = 10072 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue()); 10073 CallingConv::ID CC = Func->getCallingConv(); 10074 unsigned NestReg; 10075 10076 switch (CC) { 10077 default: 10078 llvm_unreachable("Unsupported calling convention"); 10079 case CallingConv::C: 10080 case CallingConv::X86_StdCall: { 10081 // Pass 'nest' parameter in ECX. 10082 // Must be kept in sync with X86CallingConv.td 10083 NestReg = X86::ECX; 10084 10085 // Check that ECX wasn't needed by an 'inreg' parameter. 10086 FunctionType *FTy = Func->getFunctionType(); 10087 const AttrListPtr &Attrs = Func->getAttributes(); 10088 10089 if (!Attrs.isEmpty() && !Func->isVarArg()) { 10090 unsigned InRegCount = 0; 10091 unsigned Idx = 1; 10092 10093 for (FunctionType::param_iterator I = FTy->param_begin(), 10094 E = FTy->param_end(); I != E; ++I, ++Idx) 10095 if (Attrs.paramHasAttr(Idx, Attribute::InReg)) 10096 // FIXME: should only count parameters that are lowered to integers. 10097 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32; 10098 10099 if (InRegCount > 2) { 10100 report_fatal_error("Nest register in use - reduce number of inreg" 10101 " parameters!"); 10102 } 10103 } 10104 break; 10105 } 10106 case CallingConv::X86_FastCall: 10107 case CallingConv::X86_ThisCall: 10108 case CallingConv::Fast: 10109 // Pass 'nest' parameter in EAX. 10110 // Must be kept in sync with X86CallingConv.td 10111 NestReg = X86::EAX; 10112 break; 10113 } 10114 10115 SDValue OutChains[4]; 10116 SDValue Addr, Disp; 10117 10118 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 10119 DAG.getConstant(10, MVT::i32)); 10120 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr); 10121 10122 // This is storing the opcode for MOV32ri. 10123 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte. 10124 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg); 10125 OutChains[0] = DAG.getStore(Root, dl, 10126 DAG.getConstant(MOV32ri|N86Reg, MVT::i8), 10127 Trmp, MachinePointerInfo(TrmpAddr), 10128 false, false, 0); 10129 10130 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 10131 DAG.getConstant(1, MVT::i32)); 10132 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, 10133 MachinePointerInfo(TrmpAddr, 1), 10134 false, false, 1); 10135 10136 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode. 10137 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 10138 DAG.getConstant(5, MVT::i32)); 10139 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr, 10140 MachinePointerInfo(TrmpAddr, 5), 10141 false, false, 1); 10142 10143 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 10144 DAG.getConstant(6, MVT::i32)); 10145 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, 10146 MachinePointerInfo(TrmpAddr, 6), 10147 false, false, 1); 10148 10149 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4); 10150 } 10151} 10152 10153SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 10154 SelectionDAG &DAG) const { 10155 /* 10156 The rounding mode is in bits 11:10 of FPSR, and has the following 10157 settings: 10158 00 Round to nearest 10159 01 Round to -inf 10160 10 Round to +inf 10161 11 Round to 0 10162 10163 FLT_ROUNDS, on the other hand, expects the following: 10164 -1 Undefined 10165 0 Round to 0 10166 1 Round to nearest 10167 2 Round to +inf 10168 3 Round to -inf 10169 10170 To perform the conversion, we do: 10171 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3) 10172 */ 10173 10174 MachineFunction &MF = DAG.getMachineFunction(); 10175 const TargetMachine &TM = MF.getTarget(); 10176 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 10177 unsigned StackAlignment = TFI.getStackAlignment(); 10178 EVT VT = Op.getValueType(); 10179 DebugLoc DL = Op.getDebugLoc(); 10180 10181 // Save FP Control Word to stack slot 10182 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false); 10183 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 10184 10185 10186 MachineMemOperand *MMO = 10187 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 10188 MachineMemOperand::MOStore, 2, 2); 10189 10190 SDValue Ops[] = { DAG.getEntryNode(), StackSlot }; 10191 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL, 10192 DAG.getVTList(MVT::Other), 10193 Ops, 2, MVT::i16, MMO); 10194 10195 // Load FP Control Word from stack slot 10196 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, 10197 MachinePointerInfo(), false, false, false, 0); 10198 10199 // Transform as necessary 10200 SDValue CWD1 = 10201 DAG.getNode(ISD::SRL, DL, MVT::i16, 10202 DAG.getNode(ISD::AND, DL, MVT::i16, 10203 CWD, DAG.getConstant(0x800, MVT::i16)), 10204 DAG.getConstant(11, MVT::i8)); 10205 SDValue CWD2 = 10206 DAG.getNode(ISD::SRL, DL, MVT::i16, 10207 DAG.getNode(ISD::AND, DL, MVT::i16, 10208 CWD, DAG.getConstant(0x400, MVT::i16)), 10209 DAG.getConstant(9, MVT::i8)); 10210 10211 SDValue RetVal = 10212 DAG.getNode(ISD::AND, DL, MVT::i16, 10213 DAG.getNode(ISD::ADD, DL, MVT::i16, 10214 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2), 10215 DAG.getConstant(1, MVT::i16)), 10216 DAG.getConstant(3, MVT::i16)); 10217 10218 10219 return DAG.getNode((VT.getSizeInBits() < 16 ? 10220 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal); 10221} 10222 10223SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const { 10224 EVT VT = Op.getValueType(); 10225 EVT OpVT = VT; 10226 unsigned NumBits = VT.getSizeInBits(); 10227 DebugLoc dl = Op.getDebugLoc(); 10228 10229 Op = Op.getOperand(0); 10230 if (VT == MVT::i8) { 10231 // Zero extend to i32 since there is not an i8 bsr. 10232 OpVT = MVT::i32; 10233 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 10234 } 10235 10236 // Issue a bsr (scan bits in reverse) which also sets EFLAGS. 10237 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 10238 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 10239 10240 // If src is zero (i.e. bsr sets ZF), returns NumBits. 10241 SDValue Ops[] = { 10242 Op, 10243 DAG.getConstant(NumBits+NumBits-1, OpVT), 10244 DAG.getConstant(X86::COND_E, MVT::i8), 10245 Op.getValue(1) 10246 }; 10247 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 10248 10249 // Finally xor with NumBits-1. 10250 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 10251 10252 if (VT == MVT::i8) 10253 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 10254 return Op; 10255} 10256 10257SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op, 10258 SelectionDAG &DAG) const { 10259 EVT VT = Op.getValueType(); 10260 EVT OpVT = VT; 10261 unsigned NumBits = VT.getSizeInBits(); 10262 DebugLoc dl = Op.getDebugLoc(); 10263 10264 Op = Op.getOperand(0); 10265 if (VT == MVT::i8) { 10266 // Zero extend to i32 since there is not an i8 bsr. 10267 OpVT = MVT::i32; 10268 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 10269 } 10270 10271 // Issue a bsr (scan bits in reverse). 10272 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 10273 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 10274 10275 // And xor with NumBits-1. 10276 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 10277 10278 if (VT == MVT::i8) 10279 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 10280 return Op; 10281} 10282 10283SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const { 10284 EVT VT = Op.getValueType(); 10285 unsigned NumBits = VT.getSizeInBits(); 10286 DebugLoc dl = Op.getDebugLoc(); 10287 Op = Op.getOperand(0); 10288 10289 // Issue a bsf (scan bits forward) which also sets EFLAGS. 10290 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 10291 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op); 10292 10293 // If src is zero (i.e. bsf sets ZF), returns NumBits. 10294 SDValue Ops[] = { 10295 Op, 10296 DAG.getConstant(NumBits, VT), 10297 DAG.getConstant(X86::COND_E, MVT::i8), 10298 Op.getValue(1) 10299 }; 10300 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops)); 10301} 10302 10303// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit 10304// ones, and then concatenate the result back. 10305static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) { 10306 EVT VT = Op.getValueType(); 10307 10308 assert(VT.getSizeInBits() == 256 && VT.isInteger() && 10309 "Unsupported value type for operation"); 10310 10311 unsigned NumElems = VT.getVectorNumElements(); 10312 DebugLoc dl = Op.getDebugLoc(); 10313 10314 // Extract the LHS vectors 10315 SDValue LHS = Op.getOperand(0); 10316 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl); 10317 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl); 10318 10319 // Extract the RHS vectors 10320 SDValue RHS = Op.getOperand(1); 10321 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl); 10322 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl); 10323 10324 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 10325 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 10326 10327 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 10328 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1), 10329 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2)); 10330} 10331 10332SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const { 10333 assert(Op.getValueType().getSizeInBits() == 256 && 10334 Op.getValueType().isInteger() && 10335 "Only handle AVX 256-bit vector integer operation"); 10336 return Lower256IntArith(Op, DAG); 10337} 10338 10339SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const { 10340 assert(Op.getValueType().getSizeInBits() == 256 && 10341 Op.getValueType().isInteger() && 10342 "Only handle AVX 256-bit vector integer operation"); 10343 return Lower256IntArith(Op, DAG); 10344} 10345 10346SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10347 EVT VT = Op.getValueType(); 10348 10349 // Decompose 256-bit ops into smaller 128-bit ops. 10350 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()) 10351 return Lower256IntArith(Op, DAG); 10352 10353 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && 10354 "Only know how to lower V2I64/V4I64 multiply"); 10355 10356 DebugLoc dl = Op.getDebugLoc(); 10357 10358 // Ahi = psrlqi(a, 32); 10359 // Bhi = psrlqi(b, 32); 10360 // 10361 // AloBlo = pmuludq(a, b); 10362 // AloBhi = pmuludq(a, Bhi); 10363 // AhiBlo = pmuludq(Ahi, b); 10364 10365 // AloBhi = psllqi(AloBhi, 32); 10366 // AhiBlo = psllqi(AhiBlo, 32); 10367 // return AloBlo + AloBhi + AhiBlo; 10368 10369 SDValue A = Op.getOperand(0); 10370 SDValue B = Op.getOperand(1); 10371 10372 SDValue ShAmt = DAG.getConstant(32, MVT::i32); 10373 10374 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt); 10375 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt); 10376 10377 // Bit cast to 32-bit vectors for MULUDQ 10378 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32; 10379 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A); 10380 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B); 10381 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi); 10382 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi); 10383 10384 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B); 10385 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi); 10386 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B); 10387 10388 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt); 10389 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt); 10390 10391 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi); 10392 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo); 10393} 10394 10395SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const { 10396 10397 EVT VT = Op.getValueType(); 10398 DebugLoc dl = Op.getDebugLoc(); 10399 SDValue R = Op.getOperand(0); 10400 SDValue Amt = Op.getOperand(1); 10401 LLVMContext *Context = DAG.getContext(); 10402 10403 if (!Subtarget->hasSSE2()) 10404 return SDValue(); 10405 10406 // Optimize shl/srl/sra with constant shift amount. 10407 if (isSplatVector(Amt.getNode())) { 10408 SDValue SclrAmt = Amt->getOperand(0); 10409 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) { 10410 uint64_t ShiftAmt = C->getZExtValue(); 10411 10412 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10413 (Subtarget->hasAVX2() && 10414 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) { 10415 if (Op.getOpcode() == ISD::SHL) 10416 return DAG.getNode(X86ISD::VSHLI, dl, VT, R, 10417 DAG.getConstant(ShiftAmt, MVT::i32)); 10418 if (Op.getOpcode() == ISD::SRL) 10419 return DAG.getNode(X86ISD::VSRLI, dl, VT, R, 10420 DAG.getConstant(ShiftAmt, MVT::i32)); 10421 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64) 10422 return DAG.getNode(X86ISD::VSRAI, dl, VT, R, 10423 DAG.getConstant(ShiftAmt, MVT::i32)); 10424 } 10425 10426 if (VT == MVT::v16i8) { 10427 if (Op.getOpcode() == ISD::SHL) { 10428 // Make a large shift. 10429 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R, 10430 DAG.getConstant(ShiftAmt, MVT::i32)); 10431 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL); 10432 // Zero out the rightmost bits. 10433 SmallVector<SDValue, 16> V(16, 10434 DAG.getConstant(uint8_t(-1U << ShiftAmt), 10435 MVT::i8)); 10436 return DAG.getNode(ISD::AND, dl, VT, SHL, 10437 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16)); 10438 } 10439 if (Op.getOpcode() == ISD::SRL) { 10440 // Make a large shift. 10441 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R, 10442 DAG.getConstant(ShiftAmt, MVT::i32)); 10443 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL); 10444 // Zero out the leftmost bits. 10445 SmallVector<SDValue, 16> V(16, 10446 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, 10447 MVT::i8)); 10448 return DAG.getNode(ISD::AND, dl, VT, SRL, 10449 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16)); 10450 } 10451 if (Op.getOpcode() == ISD::SRA) { 10452 if (ShiftAmt == 7) { 10453 // R s>> 7 === R s< 0 10454 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl); 10455 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R); 10456 } 10457 10458 // R s>> a === ((R u>> a) ^ m) - m 10459 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt); 10460 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt, 10461 MVT::i8)); 10462 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16); 10463 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask); 10464 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask); 10465 return Res; 10466 } 10467 llvm_unreachable("Unknown shift opcode."); 10468 } 10469 10470 if (Subtarget->hasAVX2() && VT == MVT::v32i8) { 10471 if (Op.getOpcode() == ISD::SHL) { 10472 // Make a large shift. 10473 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R, 10474 DAG.getConstant(ShiftAmt, MVT::i32)); 10475 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL); 10476 // Zero out the rightmost bits. 10477 SmallVector<SDValue, 32> V(32, 10478 DAG.getConstant(uint8_t(-1U << ShiftAmt), 10479 MVT::i8)); 10480 return DAG.getNode(ISD::AND, dl, VT, SHL, 10481 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32)); 10482 } 10483 if (Op.getOpcode() == ISD::SRL) { 10484 // Make a large shift. 10485 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R, 10486 DAG.getConstant(ShiftAmt, MVT::i32)); 10487 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL); 10488 // Zero out the leftmost bits. 10489 SmallVector<SDValue, 32> V(32, 10490 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, 10491 MVT::i8)); 10492 return DAG.getNode(ISD::AND, dl, VT, SRL, 10493 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32)); 10494 } 10495 if (Op.getOpcode() == ISD::SRA) { 10496 if (ShiftAmt == 7) { 10497 // R s>> 7 === R s< 0 10498 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl); 10499 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R); 10500 } 10501 10502 // R s>> a === ((R u>> a) ^ m) - m 10503 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt); 10504 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt, 10505 MVT::i8)); 10506 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32); 10507 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask); 10508 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask); 10509 return Res; 10510 } 10511 llvm_unreachable("Unknown shift opcode."); 10512 } 10513 } 10514 } 10515 10516 // Lower SHL with variable shift amount. 10517 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) { 10518 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1), 10519 DAG.getConstant(23, MVT::i32)); 10520 10521 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U}; 10522 Constant *C = ConstantDataVector::get(*Context, CV); 10523 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 10524 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 10525 MachinePointerInfo::getConstantPool(), 10526 false, false, false, 16); 10527 10528 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend); 10529 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op); 10530 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op); 10531 return DAG.getNode(ISD::MUL, dl, VT, Op, R); 10532 } 10533 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) { 10534 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq."); 10535 10536 // a = a << 5; 10537 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1), 10538 DAG.getConstant(5, MVT::i32)); 10539 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op); 10540 10541 // Turn 'a' into a mask suitable for VSELECT 10542 SDValue VSelM = DAG.getConstant(0x80, VT); 10543 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op); 10544 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM); 10545 10546 SDValue CM1 = DAG.getConstant(0x0f, VT); 10547 SDValue CM2 = DAG.getConstant(0x3f, VT); 10548 10549 // r = VSELECT(r, psllw(r & (char16)15, 4), a); 10550 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1); 10551 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 10552 DAG.getConstant(4, MVT::i32), DAG); 10553 M = DAG.getNode(ISD::BITCAST, dl, VT, M); 10554 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R); 10555 10556 // a += a 10557 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 10558 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op); 10559 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM); 10560 10561 // r = VSELECT(r, psllw(r & (char16)63, 2), a); 10562 M = DAG.getNode(ISD::AND, dl, VT, R, CM2); 10563 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 10564 DAG.getConstant(2, MVT::i32), DAG); 10565 M = DAG.getNode(ISD::BITCAST, dl, VT, M); 10566 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R); 10567 10568 // a += a 10569 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 10570 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op); 10571 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM); 10572 10573 // return VSELECT(r, r+r, a); 10574 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, 10575 DAG.getNode(ISD::ADD, dl, VT, R, R), R); 10576 return R; 10577 } 10578 10579 // Decompose 256-bit shifts into smaller 128-bit shifts. 10580 if (VT.getSizeInBits() == 256) { 10581 unsigned NumElems = VT.getVectorNumElements(); 10582 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 10583 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 10584 10585 // Extract the two vectors 10586 SDValue V1 = Extract128BitVector(R, 0, DAG, dl); 10587 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl); 10588 10589 // Recreate the shift amount vectors 10590 SDValue Amt1, Amt2; 10591 if (Amt.getOpcode() == ISD::BUILD_VECTOR) { 10592 // Constant shift amount 10593 SmallVector<SDValue, 4> Amt1Csts; 10594 SmallVector<SDValue, 4> Amt2Csts; 10595 for (unsigned i = 0; i != NumElems/2; ++i) 10596 Amt1Csts.push_back(Amt->getOperand(i)); 10597 for (unsigned i = NumElems/2; i != NumElems; ++i) 10598 Amt2Csts.push_back(Amt->getOperand(i)); 10599 10600 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 10601 &Amt1Csts[0], NumElems/2); 10602 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 10603 &Amt2Csts[0], NumElems/2); 10604 } else { 10605 // Variable shift amount 10606 Amt1 = Extract128BitVector(Amt, 0, DAG, dl); 10607 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl); 10608 } 10609 10610 // Issue new vector shifts for the smaller types 10611 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1); 10612 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2); 10613 10614 // Concatenate the result back 10615 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2); 10616 } 10617 10618 return SDValue(); 10619} 10620 10621SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 10622 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus 10623 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering 10624 // looks for this combo and may remove the "setcc" instruction if the "setcc" 10625 // has only one use. 10626 SDNode *N = Op.getNode(); 10627 SDValue LHS = N->getOperand(0); 10628 SDValue RHS = N->getOperand(1); 10629 unsigned BaseOp = 0; 10630 unsigned Cond = 0; 10631 DebugLoc DL = Op.getDebugLoc(); 10632 switch (Op.getOpcode()) { 10633 default: llvm_unreachable("Unknown ovf instruction!"); 10634 case ISD::SADDO: 10635 // A subtract of one will be selected as a INC. Note that INC doesn't 10636 // set CF, so we can't do this for UADDO. 10637 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 10638 if (C->isOne()) { 10639 BaseOp = X86ISD::INC; 10640 Cond = X86::COND_O; 10641 break; 10642 } 10643 BaseOp = X86ISD::ADD; 10644 Cond = X86::COND_O; 10645 break; 10646 case ISD::UADDO: 10647 BaseOp = X86ISD::ADD; 10648 Cond = X86::COND_B; 10649 break; 10650 case ISD::SSUBO: 10651 // A subtract of one will be selected as a DEC. Note that DEC doesn't 10652 // set CF, so we can't do this for USUBO. 10653 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 10654 if (C->isOne()) { 10655 BaseOp = X86ISD::DEC; 10656 Cond = X86::COND_O; 10657 break; 10658 } 10659 BaseOp = X86ISD::SUB; 10660 Cond = X86::COND_O; 10661 break; 10662 case ISD::USUBO: 10663 BaseOp = X86ISD::SUB; 10664 Cond = X86::COND_B; 10665 break; 10666 case ISD::SMULO: 10667 BaseOp = X86ISD::SMUL; 10668 Cond = X86::COND_O; 10669 break; 10670 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs 10671 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0), 10672 MVT::i32); 10673 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS); 10674 10675 SDValue SetCC = 10676 DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 10677 DAG.getConstant(X86::COND_O, MVT::i32), 10678 SDValue(Sum.getNode(), 2)); 10679 10680 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 10681 } 10682 } 10683 10684 // Also sets EFLAGS. 10685 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32); 10686 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS); 10687 10688 SDValue SetCC = 10689 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1), 10690 DAG.getConstant(Cond, MVT::i32), 10691 SDValue(Sum.getNode(), 1)); 10692 10693 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 10694} 10695 10696SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 10697 SelectionDAG &DAG) const { 10698 DebugLoc dl = Op.getDebugLoc(); 10699 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 10700 EVT VT = Op.getValueType(); 10701 10702 if (!Subtarget->hasSSE2() || !VT.isVector()) 10703 return SDValue(); 10704 10705 unsigned BitsDiff = VT.getScalarType().getSizeInBits() - 10706 ExtraVT.getScalarType().getSizeInBits(); 10707 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32); 10708 10709 switch (VT.getSimpleVT().SimpleTy) { 10710 default: return SDValue(); 10711 case MVT::v8i32: 10712 case MVT::v16i16: 10713 if (!Subtarget->hasAVX()) 10714 return SDValue(); 10715 if (!Subtarget->hasAVX2()) { 10716 // needs to be split 10717 unsigned NumElems = VT.getVectorNumElements(); 10718 10719 // Extract the LHS vectors 10720 SDValue LHS = Op.getOperand(0); 10721 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl); 10722 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl); 10723 10724 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 10725 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 10726 10727 EVT ExtraEltVT = ExtraVT.getVectorElementType(); 10728 unsigned ExtraNumElems = ExtraVT.getVectorNumElements(); 10729 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT, 10730 ExtraNumElems/2); 10731 SDValue Extra = DAG.getValueType(ExtraVT); 10732 10733 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra); 10734 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra); 10735 10736 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);; 10737 } 10738 // fall through 10739 case MVT::v4i32: 10740 case MVT::v8i16: { 10741 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, 10742 Op.getOperand(0), ShAmt, DAG); 10743 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG); 10744 } 10745 } 10746} 10747 10748 10749SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{ 10750 DebugLoc dl = Op.getDebugLoc(); 10751 10752 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2. 10753 // There isn't any reason to disable it if the target processor supports it. 10754 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) { 10755 SDValue Chain = Op.getOperand(0); 10756 SDValue Zero = DAG.getConstant(0, MVT::i32); 10757 SDValue Ops[] = { 10758 DAG.getRegister(X86::ESP, MVT::i32), // Base 10759 DAG.getTargetConstant(1, MVT::i8), // Scale 10760 DAG.getRegister(0, MVT::i32), // Index 10761 DAG.getTargetConstant(0, MVT::i32), // Disp 10762 DAG.getRegister(0, MVT::i32), // Segment. 10763 Zero, 10764 Chain 10765 }; 10766 SDNode *Res = 10767 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops, 10768 array_lengthof(Ops)); 10769 return SDValue(Res, 0); 10770 } 10771 10772 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 10773 if (!isDev) 10774 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 10775 10776 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 10777 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 10778 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 10779 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 10780 10781 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>; 10782 if (!Op1 && !Op2 && !Op3 && Op4) 10783 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0)); 10784 10785 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>; 10786 if (Op1 && !Op2 && !Op3 && !Op4) 10787 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0)); 10788 10789 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 10790 // (MFENCE)>; 10791 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 10792} 10793 10794SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op, 10795 SelectionDAG &DAG) const { 10796 DebugLoc dl = Op.getDebugLoc(); 10797 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>( 10798 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()); 10799 SynchronizationScope FenceScope = static_cast<SynchronizationScope>( 10800 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 10801 10802 // The only fence that needs an instruction is a sequentially-consistent 10803 // cross-thread fence. 10804 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) { 10805 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for 10806 // no-sse2). There isn't any reason to disable it if the target processor 10807 // supports it. 10808 if (Subtarget->hasSSE2() || Subtarget->is64Bit()) 10809 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 10810 10811 SDValue Chain = Op.getOperand(0); 10812 SDValue Zero = DAG.getConstant(0, MVT::i32); 10813 SDValue Ops[] = { 10814 DAG.getRegister(X86::ESP, MVT::i32), // Base 10815 DAG.getTargetConstant(1, MVT::i8), // Scale 10816 DAG.getRegister(0, MVT::i32), // Index 10817 DAG.getTargetConstant(0, MVT::i32), // Disp 10818 DAG.getRegister(0, MVT::i32), // Segment. 10819 Zero, 10820 Chain 10821 }; 10822 SDNode *Res = 10823 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops, 10824 array_lengthof(Ops)); 10825 return SDValue(Res, 0); 10826 } 10827 10828 // MEMBARRIER is a compiler barrier; it codegens to a no-op. 10829 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 10830} 10831 10832 10833SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 10834 EVT T = Op.getValueType(); 10835 DebugLoc DL = Op.getDebugLoc(); 10836 unsigned Reg = 0; 10837 unsigned size = 0; 10838 switch(T.getSimpleVT().SimpleTy) { 10839 default: llvm_unreachable("Invalid value type!"); 10840 case MVT::i8: Reg = X86::AL; size = 1; break; 10841 case MVT::i16: Reg = X86::AX; size = 2; break; 10842 case MVT::i32: Reg = X86::EAX; size = 4; break; 10843 case MVT::i64: 10844 assert(Subtarget->is64Bit() && "Node not type legal!"); 10845 Reg = X86::RAX; size = 8; 10846 break; 10847 } 10848 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg, 10849 Op.getOperand(2), SDValue()); 10850 SDValue Ops[] = { cpIn.getValue(0), 10851 Op.getOperand(1), 10852 Op.getOperand(3), 10853 DAG.getTargetConstant(size, MVT::i8), 10854 cpIn.getValue(1) }; 10855 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10856 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand(); 10857 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys, 10858 Ops, 5, T, MMO); 10859 SDValue cpOut = 10860 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1)); 10861 return cpOut; 10862} 10863 10864SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op, 10865 SelectionDAG &DAG) const { 10866 assert(Subtarget->is64Bit() && "Result not type legalized?"); 10867 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10868 SDValue TheChain = Op.getOperand(0); 10869 DebugLoc dl = Op.getDebugLoc(); 10870 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 10871 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1)); 10872 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64, 10873 rax.getValue(2)); 10874 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx, 10875 DAG.getConstant(32, MVT::i8)); 10876 SDValue Ops[] = { 10877 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp), 10878 rdx.getValue(1) 10879 }; 10880 return DAG.getMergeValues(Ops, 2, dl); 10881} 10882 10883SDValue X86TargetLowering::LowerBITCAST(SDValue Op, 10884 SelectionDAG &DAG) const { 10885 EVT SrcVT = Op.getOperand(0).getValueType(); 10886 EVT DstVT = Op.getValueType(); 10887 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() && 10888 Subtarget->hasMMX() && "Unexpected custom BITCAST"); 10889 assert((DstVT == MVT::i64 || 10890 (DstVT.isVector() && DstVT.getSizeInBits()==64)) && 10891 "Unexpected custom BITCAST"); 10892 // i64 <=> MMX conversions are Legal. 10893 if (SrcVT==MVT::i64 && DstVT.isVector()) 10894 return Op; 10895 if (DstVT==MVT::i64 && SrcVT.isVector()) 10896 return Op; 10897 // MMX <=> MMX conversions are Legal. 10898 if (SrcVT.isVector() && DstVT.isVector()) 10899 return Op; 10900 // All other conversions need to be expanded. 10901 return SDValue(); 10902} 10903 10904SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const { 10905 SDNode *Node = Op.getNode(); 10906 DebugLoc dl = Node->getDebugLoc(); 10907 EVT T = Node->getValueType(0); 10908 SDValue negOp = DAG.getNode(ISD::SUB, dl, T, 10909 DAG.getConstant(0, T), Node->getOperand(2)); 10910 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, 10911 cast<AtomicSDNode>(Node)->getMemoryVT(), 10912 Node->getOperand(0), 10913 Node->getOperand(1), negOp, 10914 cast<AtomicSDNode>(Node)->getSrcValue(), 10915 cast<AtomicSDNode>(Node)->getAlignment(), 10916 cast<AtomicSDNode>(Node)->getOrdering(), 10917 cast<AtomicSDNode>(Node)->getSynchScope()); 10918} 10919 10920static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) { 10921 SDNode *Node = Op.getNode(); 10922 DebugLoc dl = Node->getDebugLoc(); 10923 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 10924 10925 // Convert seq_cst store -> xchg 10926 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b) 10927 // FIXME: On 32-bit, store -> fist or movq would be more efficient 10928 // (The only way to get a 16-byte store is cmpxchg16b) 10929 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment. 10930 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent || 10931 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10932 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, 10933 cast<AtomicSDNode>(Node)->getMemoryVT(), 10934 Node->getOperand(0), 10935 Node->getOperand(1), Node->getOperand(2), 10936 cast<AtomicSDNode>(Node)->getMemOperand(), 10937 cast<AtomicSDNode>(Node)->getOrdering(), 10938 cast<AtomicSDNode>(Node)->getSynchScope()); 10939 return Swap.getValue(1); 10940 } 10941 // Other atomic stores have a simple pattern. 10942 return Op; 10943} 10944 10945static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 10946 EVT VT = Op.getNode()->getValueType(0); 10947 10948 // Let legalize expand this if it isn't a legal type yet. 10949 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10950 return SDValue(); 10951 10952 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 10953 10954 unsigned Opc; 10955 bool ExtraOp = false; 10956 switch (Op.getOpcode()) { 10957 default: llvm_unreachable("Invalid code"); 10958 case ISD::ADDC: Opc = X86ISD::ADD; break; 10959 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break; 10960 case ISD::SUBC: Opc = X86ISD::SUB; break; 10961 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break; 10962 } 10963 10964 if (!ExtraOp) 10965 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 10966 Op.getOperand(1)); 10967 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 10968 Op.getOperand(1), Op.getOperand(2)); 10969} 10970 10971/// LowerOperation - Provide custom lowering hooks for some operations. 10972/// 10973SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10974 switch (Op.getOpcode()) { 10975 default: llvm_unreachable("Should not custom lower this!"); 10976 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG); 10977 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG); 10978 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG); 10979 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG); 10980 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG); 10981 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG); 10982 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10983 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 10984 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10985 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10986 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10987 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG); 10988 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG); 10989 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10990 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10991 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10992 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10993 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG); 10994 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10995 case ISD::SHL_PARTS: 10996 case ISD::SRA_PARTS: 10997 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG); 10998 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG); 10999 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG); 11000 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG); 11001 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG); 11002 case ISD::FABS: return LowerFABS(Op, DAG); 11003 case ISD::FNEG: return LowerFNEG(Op, DAG); 11004 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 11005 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG); 11006 case ISD::SETCC: return LowerSETCC(Op, DAG); 11007 case ISD::SELECT: return LowerSELECT(Op, DAG); 11008 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 11009 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 11010 case ISD::VASTART: return LowerVASTART(Op, DAG); 11011 case ISD::VAARG: return LowerVAARG(Op, DAG); 11012 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 11013 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 11014 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 11015 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 11016 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 11017 case ISD::FRAME_TO_ARGS_OFFSET: 11018 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG); 11019 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 11020 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG); 11021 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 11022 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 11023 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 11024 case ISD::CTLZ: return LowerCTLZ(Op, DAG); 11025 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG); 11026 case ISD::CTTZ: return LowerCTTZ(Op, DAG); 11027 case ISD::MUL: return LowerMUL(Op, DAG); 11028 case ISD::SRA: 11029 case ISD::SRL: 11030 case ISD::SHL: return LowerShift(Op, DAG); 11031 case ISD::SADDO: 11032 case ISD::UADDO: 11033 case ISD::SSUBO: 11034 case ISD::USUBO: 11035 case ISD::SMULO: 11036 case ISD::UMULO: return LowerXALUO(Op, DAG); 11037 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG); 11038 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 11039 case ISD::ADDC: 11040 case ISD::ADDE: 11041 case ISD::SUBC: 11042 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 11043 case ISD::ADD: return LowerADD(Op, DAG); 11044 case ISD::SUB: return LowerSUB(Op, DAG); 11045 } 11046} 11047 11048static void ReplaceATOMIC_LOAD(SDNode *Node, 11049 SmallVectorImpl<SDValue> &Results, 11050 SelectionDAG &DAG) { 11051 DebugLoc dl = Node->getDebugLoc(); 11052 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 11053 11054 // Convert wide load -> cmpxchg8b/cmpxchg16b 11055 // FIXME: On 32-bit, load -> fild or movq would be more efficient 11056 // (The only way to get a 16-byte load is cmpxchg16b) 11057 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment. 11058 SDValue Zero = DAG.getConstant(0, VT); 11059 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT, 11060 Node->getOperand(0), 11061 Node->getOperand(1), Zero, Zero, 11062 cast<AtomicSDNode>(Node)->getMemOperand(), 11063 cast<AtomicSDNode>(Node)->getOrdering(), 11064 cast<AtomicSDNode>(Node)->getSynchScope()); 11065 Results.push_back(Swap.getValue(0)); 11066 Results.push_back(Swap.getValue(1)); 11067} 11068 11069void X86TargetLowering:: 11070ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results, 11071 SelectionDAG &DAG, unsigned NewOp) const { 11072 DebugLoc dl = Node->getDebugLoc(); 11073 assert (Node->getValueType(0) == MVT::i64 && 11074 "Only know how to expand i64 atomics"); 11075 11076 SDValue Chain = Node->getOperand(0); 11077 SDValue In1 = Node->getOperand(1); 11078 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 11079 Node->getOperand(2), DAG.getIntPtrConstant(0)); 11080 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 11081 Node->getOperand(2), DAG.getIntPtrConstant(1)); 11082 SDValue Ops[] = { Chain, In1, In2L, In2H }; 11083 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 11084 SDValue Result = 11085 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64, 11086 cast<MemSDNode>(Node)->getMemOperand()); 11087 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)}; 11088 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2)); 11089 Results.push_back(Result.getValue(2)); 11090} 11091 11092/// ReplaceNodeResults - Replace a node with an illegal result type 11093/// with a new node built out of custom code. 11094void X86TargetLowering::ReplaceNodeResults(SDNode *N, 11095 SmallVectorImpl<SDValue>&Results, 11096 SelectionDAG &DAG) const { 11097 DebugLoc dl = N->getDebugLoc(); 11098 switch (N->getOpcode()) { 11099 default: 11100 llvm_unreachable("Do not know how to custom type legalize this operation!"); 11101 case ISD::SIGN_EXTEND_INREG: 11102 case ISD::ADDC: 11103 case ISD::ADDE: 11104 case ISD::SUBC: 11105 case ISD::SUBE: 11106 // We don't want to expand or promote these. 11107 return; 11108 case ISD::FP_TO_SINT: 11109 case ISD::FP_TO_UINT: { 11110 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 11111 11112 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType())) 11113 return; 11114 11115 std::pair<SDValue,SDValue> Vals = 11116 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true); 11117 SDValue FIST = Vals.first, StackSlot = Vals.second; 11118 if (FIST.getNode() != 0) { 11119 EVT VT = N->getValueType(0); 11120 // Return a load from the stack slot. 11121 if (StackSlot.getNode() != 0) 11122 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, 11123 MachinePointerInfo(), 11124 false, false, false, 0)); 11125 else 11126 Results.push_back(FIST); 11127 } 11128 return; 11129 } 11130 case ISD::READCYCLECOUNTER: { 11131 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 11132 SDValue TheChain = N->getOperand(0); 11133 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 11134 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32, 11135 rd.getValue(1)); 11136 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32, 11137 eax.getValue(2)); 11138 // Use a buildpair to merge the two 32-bit values into a 64-bit one. 11139 SDValue Ops[] = { eax, edx }; 11140 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2)); 11141 Results.push_back(edx.getValue(1)); 11142 return; 11143 } 11144 case ISD::ATOMIC_CMP_SWAP: { 11145 EVT T = N->getValueType(0); 11146 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair"); 11147 bool Regs64bit = T == MVT::i128; 11148 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32; 11149 SDValue cpInL, cpInH; 11150 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 11151 DAG.getConstant(0, HalfT)); 11152 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 11153 DAG.getConstant(1, HalfT)); 11154 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, 11155 Regs64bit ? X86::RAX : X86::EAX, 11156 cpInL, SDValue()); 11157 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, 11158 Regs64bit ? X86::RDX : X86::EDX, 11159 cpInH, cpInL.getValue(1)); 11160 SDValue swapInL, swapInH; 11161 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 11162 DAG.getConstant(0, HalfT)); 11163 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 11164 DAG.getConstant(1, HalfT)); 11165 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, 11166 Regs64bit ? X86::RBX : X86::EBX, 11167 swapInL, cpInH.getValue(1)); 11168 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, 11169 Regs64bit ? X86::RCX : X86::ECX, 11170 swapInH, swapInL.getValue(1)); 11171 SDValue Ops[] = { swapInH.getValue(0), 11172 N->getOperand(1), 11173 swapInH.getValue(1) }; 11174 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 11175 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 11176 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG : 11177 X86ISD::LCMPXCHG8_DAG; 11178 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, 11179 Ops, 3, T, MMO); 11180 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, 11181 Regs64bit ? X86::RAX : X86::EAX, 11182 HalfT, Result.getValue(1)); 11183 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, 11184 Regs64bit ? X86::RDX : X86::EDX, 11185 HalfT, cpOutL.getValue(2)); 11186 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)}; 11187 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2)); 11188 Results.push_back(cpOutH.getValue(1)); 11189 return; 11190 } 11191 case ISD::ATOMIC_LOAD_ADD: 11192 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG); 11193 return; 11194 case ISD::ATOMIC_LOAD_AND: 11195 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG); 11196 return; 11197 case ISD::ATOMIC_LOAD_NAND: 11198 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG); 11199 return; 11200 case ISD::ATOMIC_LOAD_OR: 11201 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG); 11202 return; 11203 case ISD::ATOMIC_LOAD_SUB: 11204 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG); 11205 return; 11206 case ISD::ATOMIC_LOAD_XOR: 11207 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG); 11208 return; 11209 case ISD::ATOMIC_SWAP: 11210 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG); 11211 return; 11212 case ISD::ATOMIC_LOAD: 11213 ReplaceATOMIC_LOAD(N, Results, DAG); 11214 } 11215} 11216 11217const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const { 11218 switch (Opcode) { 11219 default: return NULL; 11220 case X86ISD::BSF: return "X86ISD::BSF"; 11221 case X86ISD::BSR: return "X86ISD::BSR"; 11222 case X86ISD::SHLD: return "X86ISD::SHLD"; 11223 case X86ISD::SHRD: return "X86ISD::SHRD"; 11224 case X86ISD::FAND: return "X86ISD::FAND"; 11225 case X86ISD::FOR: return "X86ISD::FOR"; 11226 case X86ISD::FXOR: return "X86ISD::FXOR"; 11227 case X86ISD::FSRL: return "X86ISD::FSRL"; 11228 case X86ISD::FILD: return "X86ISD::FILD"; 11229 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG"; 11230 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM"; 11231 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM"; 11232 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM"; 11233 case X86ISD::FLD: return "X86ISD::FLD"; 11234 case X86ISD::FST: return "X86ISD::FST"; 11235 case X86ISD::CALL: return "X86ISD::CALL"; 11236 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG"; 11237 case X86ISD::BT: return "X86ISD::BT"; 11238 case X86ISD::CMP: return "X86ISD::CMP"; 11239 case X86ISD::COMI: return "X86ISD::COMI"; 11240 case X86ISD::UCOMI: return "X86ISD::UCOMI"; 11241 case X86ISD::SETCC: return "X86ISD::SETCC"; 11242 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY"; 11243 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd"; 11244 case X86ISD::FSETCCss: return "X86ISD::FSETCCss"; 11245 case X86ISD::CMOV: return "X86ISD::CMOV"; 11246 case X86ISD::BRCOND: return "X86ISD::BRCOND"; 11247 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG"; 11248 case X86ISD::REP_STOS: return "X86ISD::REP_STOS"; 11249 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS"; 11250 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg"; 11251 case X86ISD::Wrapper: return "X86ISD::Wrapper"; 11252 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP"; 11253 case X86ISD::PEXTRB: return "X86ISD::PEXTRB"; 11254 case X86ISD::PEXTRW: return "X86ISD::PEXTRW"; 11255 case X86ISD::INSERTPS: return "X86ISD::INSERTPS"; 11256 case X86ISD::PINSRB: return "X86ISD::PINSRB"; 11257 case X86ISD::PINSRW: return "X86ISD::PINSRW"; 11258 case X86ISD::PSHUFB: return "X86ISD::PSHUFB"; 11259 case X86ISD::ANDNP: return "X86ISD::ANDNP"; 11260 case X86ISD::PSIGN: return "X86ISD::PSIGN"; 11261 case X86ISD::BLENDV: return "X86ISD::BLENDV"; 11262 case X86ISD::BLENDPW: return "X86ISD::BLENDPW"; 11263 case X86ISD::BLENDPS: return "X86ISD::BLENDPS"; 11264 case X86ISD::BLENDPD: return "X86ISD::BLENDPD"; 11265 case X86ISD::HADD: return "X86ISD::HADD"; 11266 case X86ISD::HSUB: return "X86ISD::HSUB"; 11267 case X86ISD::FHADD: return "X86ISD::FHADD"; 11268 case X86ISD::FHSUB: return "X86ISD::FHSUB"; 11269 case X86ISD::FMAX: return "X86ISD::FMAX"; 11270 case X86ISD::FMIN: return "X86ISD::FMIN"; 11271 case X86ISD::FRSQRT: return "X86ISD::FRSQRT"; 11272 case X86ISD::FRCP: return "X86ISD::FRCP"; 11273 case X86ISD::TLSADDR: return "X86ISD::TLSADDR"; 11274 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR"; 11275 case X86ISD::TLSCALL: return "X86ISD::TLSCALL"; 11276 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN"; 11277 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN"; 11278 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m"; 11279 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r"; 11280 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG"; 11281 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG"; 11282 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG"; 11283 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG"; 11284 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG"; 11285 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG"; 11286 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG"; 11287 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG"; 11288 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL"; 11289 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD"; 11290 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ"; 11291 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ"; 11292 case X86ISD::VSHL: return "X86ISD::VSHL"; 11293 case X86ISD::VSRL: return "X86ISD::VSRL"; 11294 case X86ISD::VSRA: return "X86ISD::VSRA"; 11295 case X86ISD::VSHLI: return "X86ISD::VSHLI"; 11296 case X86ISD::VSRLI: return "X86ISD::VSRLI"; 11297 case X86ISD::VSRAI: return "X86ISD::VSRAI"; 11298 case X86ISD::CMPP: return "X86ISD::CMPP"; 11299 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ"; 11300 case X86ISD::PCMPGT: return "X86ISD::PCMPGT"; 11301 case X86ISD::ADD: return "X86ISD::ADD"; 11302 case X86ISD::SUB: return "X86ISD::SUB"; 11303 case X86ISD::ADC: return "X86ISD::ADC"; 11304 case X86ISD::SBB: return "X86ISD::SBB"; 11305 case X86ISD::SMUL: return "X86ISD::SMUL"; 11306 case X86ISD::UMUL: return "X86ISD::UMUL"; 11307 case X86ISD::INC: return "X86ISD::INC"; 11308 case X86ISD::DEC: return "X86ISD::DEC"; 11309 case X86ISD::OR: return "X86ISD::OR"; 11310 case X86ISD::XOR: return "X86ISD::XOR"; 11311 case X86ISD::AND: return "X86ISD::AND"; 11312 case X86ISD::ANDN: return "X86ISD::ANDN"; 11313 case X86ISD::BLSI: return "X86ISD::BLSI"; 11314 case X86ISD::BLSMSK: return "X86ISD::BLSMSK"; 11315 case X86ISD::BLSR: return "X86ISD::BLSR"; 11316 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM"; 11317 case X86ISD::PTEST: return "X86ISD::PTEST"; 11318 case X86ISD::TESTP: return "X86ISD::TESTP"; 11319 case X86ISD::PALIGN: return "X86ISD::PALIGN"; 11320 case X86ISD::PSHUFD: return "X86ISD::PSHUFD"; 11321 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW"; 11322 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW"; 11323 case X86ISD::SHUFP: return "X86ISD::SHUFP"; 11324 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS"; 11325 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD"; 11326 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS"; 11327 case X86ISD::MOVLPS: return "X86ISD::MOVLPS"; 11328 case X86ISD::MOVLPD: return "X86ISD::MOVLPD"; 11329 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP"; 11330 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP"; 11331 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP"; 11332 case X86ISD::MOVSD: return "X86ISD::MOVSD"; 11333 case X86ISD::MOVSS: return "X86ISD::MOVSS"; 11334 case X86ISD::UNPCKL: return "X86ISD::UNPCKL"; 11335 case X86ISD::UNPCKH: return "X86ISD::UNPCKH"; 11336 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST"; 11337 case X86ISD::VPERMILP: return "X86ISD::VPERMILP"; 11338 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128"; 11339 case X86ISD::VPERMV: return "X86ISD::VPERMV"; 11340 case X86ISD::VPERMI: return "X86ISD::VPERMI"; 11341 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ"; 11342 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS"; 11343 case X86ISD::VAARG_64: return "X86ISD::VAARG_64"; 11344 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA"; 11345 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER"; 11346 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA"; 11347 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL"; 11348 case X86ISD::SAHF: return "X86ISD::SAHF"; 11349 case X86ISD::RDRAND: return "X86ISD::RDRAND"; 11350 case X86ISD::FMADD: return "X86ISD::FMADD"; 11351 case X86ISD::FMSUB: return "X86ISD::FMSUB"; 11352 case X86ISD::FNMADD: return "X86ISD::FNMADD"; 11353 case X86ISD::FNMSUB: return "X86ISD::FNMSUB"; 11354 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB"; 11355 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD"; 11356 } 11357} 11358 11359// isLegalAddressingMode - Return true if the addressing mode represented 11360// by AM is legal for this target, for a load/store of the specified type. 11361bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 11362 Type *Ty) const { 11363 // X86 supports extremely general addressing modes. 11364 CodeModel::Model M = getTargetMachine().getCodeModel(); 11365 Reloc::Model R = getTargetMachine().getRelocationModel(); 11366 11367 // X86 allows a sign-extended 32-bit immediate field as a displacement. 11368 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL)) 11369 return false; 11370 11371 if (AM.BaseGV) { 11372 unsigned GVFlags = 11373 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine()); 11374 11375 // If a reference to this global requires an extra load, we can't fold it. 11376 if (isGlobalStubReference(GVFlags)) 11377 return false; 11378 11379 // If BaseGV requires a register for the PIC base, we cannot also have a 11380 // BaseReg specified. 11381 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags)) 11382 return false; 11383 11384 // If lower 4G is not available, then we must use rip-relative addressing. 11385 if ((M != CodeModel::Small || R != Reloc::Static) && 11386 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1)) 11387 return false; 11388 } 11389 11390 switch (AM.Scale) { 11391 case 0: 11392 case 1: 11393 case 2: 11394 case 4: 11395 case 8: 11396 // These scales always work. 11397 break; 11398 case 3: 11399 case 5: 11400 case 9: 11401 // These scales are formed with basereg+scalereg. Only accept if there is 11402 // no basereg yet. 11403 if (AM.HasBaseReg) 11404 return false; 11405 break; 11406 default: // Other stuff never works. 11407 return false; 11408 } 11409 11410 return true; 11411} 11412 11413 11414bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 11415 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 11416 return false; 11417 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 11418 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 11419 if (NumBits1 <= NumBits2) 11420 return false; 11421 return true; 11422} 11423 11424bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const { 11425 return Imm == (int32_t)Imm; 11426} 11427 11428bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const { 11429 // Can also use sub to handle negated immediates. 11430 return Imm == (int32_t)Imm; 11431} 11432 11433bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 11434 if (!VT1.isInteger() || !VT2.isInteger()) 11435 return false; 11436 unsigned NumBits1 = VT1.getSizeInBits(); 11437 unsigned NumBits2 = VT2.getSizeInBits(); 11438 if (NumBits1 <= NumBits2) 11439 return false; 11440 return true; 11441} 11442 11443bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 11444 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 11445 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit(); 11446} 11447 11448bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 11449 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 11450 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit(); 11451} 11452 11453bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const { 11454 // i16 instructions are longer (0x66 prefix) and potentially slower. 11455 return !(VT1 == MVT::i32 && VT2 == MVT::i16); 11456} 11457 11458/// isShuffleMaskLegal - Targets can use this to indicate that they only 11459/// support *some* VECTOR_SHUFFLE operations, those with specific masks. 11460/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 11461/// are assumed to be legal. 11462bool 11463X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 11464 EVT VT) const { 11465 // Very little shuffling can be done for 64-bit vectors right now. 11466 if (VT.getSizeInBits() == 64) 11467 return false; 11468 11469 // FIXME: pshufb, blends, shifts. 11470 return (VT.getVectorNumElements() == 2 || 11471 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 11472 isMOVLMask(M, VT) || 11473 isSHUFPMask(M, VT, Subtarget->hasAVX()) || 11474 isPSHUFDMask(M, VT) || 11475 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) || 11476 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) || 11477 isPALIGNRMask(M, VT, Subtarget) || 11478 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) || 11479 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) || 11480 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) || 11481 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2())); 11482} 11483 11484bool 11485X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask, 11486 EVT VT) const { 11487 unsigned NumElts = VT.getVectorNumElements(); 11488 // FIXME: This collection of masks seems suspect. 11489 if (NumElts == 2) 11490 return true; 11491 if (NumElts == 4 && VT.getSizeInBits() == 128) { 11492 return (isMOVLMask(Mask, VT) || 11493 isCommutedMOVLMask(Mask, VT, true) || 11494 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) || 11495 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true)); 11496 } 11497 return false; 11498} 11499 11500//===----------------------------------------------------------------------===// 11501// X86 Scheduler Hooks 11502//===----------------------------------------------------------------------===// 11503 11504// private utility function 11505MachineBasicBlock * 11506X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr, 11507 MachineBasicBlock *MBB, 11508 unsigned regOpc, 11509 unsigned immOpc, 11510 unsigned LoadOpc, 11511 unsigned CXchgOpc, 11512 unsigned notOpc, 11513 unsigned EAXreg, 11514 const TargetRegisterClass *RC, 11515 bool Invert) const { 11516 // For the atomic bitwise operator, we generate 11517 // thisMBB: 11518 // newMBB: 11519 // ld t1 = [bitinstr.addr] 11520 // op t2 = t1, [bitinstr.val] 11521 // not t3 = t2 (if Invert) 11522 // mov EAX = t1 11523 // lcs dest = [bitinstr.addr], t3 [EAX is implicit] 11524 // bz newMBB 11525 // fallthrough -->nextMBB 11526 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11527 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11528 MachineFunction::iterator MBBIter = MBB; 11529 ++MBBIter; 11530 11531 /// First build the CFG 11532 MachineFunction *F = MBB->getParent(); 11533 MachineBasicBlock *thisMBB = MBB; 11534 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 11535 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 11536 F->insert(MBBIter, newMBB); 11537 F->insert(MBBIter, nextMBB); 11538 11539 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 11540 nextMBB->splice(nextMBB->begin(), thisMBB, 11541 llvm::next(MachineBasicBlock::iterator(bInstr)), 11542 thisMBB->end()); 11543 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11544 11545 // Update thisMBB to fall through to newMBB 11546 thisMBB->addSuccessor(newMBB); 11547 11548 // newMBB jumps to itself and fall through to nextMBB 11549 newMBB->addSuccessor(nextMBB); 11550 newMBB->addSuccessor(newMBB); 11551 11552 // Insert instructions into newMBB based on incoming instruction 11553 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 && 11554 "unexpected number of operands"); 11555 DebugLoc dl = bInstr->getDebugLoc(); 11556 MachineOperand& destOper = bInstr->getOperand(0); 11557 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 11558 int numArgs = bInstr->getNumOperands() - 1; 11559 for (int i=0; i < numArgs; ++i) 11560 argOpers[i] = &bInstr->getOperand(i+1); 11561 11562 // x86 address has 4 operands: base, index, scale, and displacement 11563 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 11564 int valArgIndx = lastAddrIndx + 1; 11565 11566 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 11567 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1); 11568 for (int i=0; i <= lastAddrIndx; ++i) 11569 (*MIB).addOperand(*argOpers[i]); 11570 11571 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 11572 assert((argOpers[valArgIndx]->isReg() || 11573 argOpers[valArgIndx]->isImm()) && 11574 "invalid operand"); 11575 if (argOpers[valArgIndx]->isReg()) 11576 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2); 11577 else 11578 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2); 11579 MIB.addReg(t1); 11580 (*MIB).addOperand(*argOpers[valArgIndx]); 11581 11582 unsigned t3 = F->getRegInfo().createVirtualRegister(RC); 11583 if (Invert) { 11584 MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2); 11585 } 11586 else 11587 t3 = t2; 11588 11589 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg); 11590 MIB.addReg(t1); 11591 11592 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc)); 11593 for (int i=0; i <= lastAddrIndx; ++i) 11594 (*MIB).addOperand(*argOpers[i]); 11595 MIB.addReg(t3); 11596 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 11597 (*MIB).setMemRefs(bInstr->memoperands_begin(), 11598 bInstr->memoperands_end()); 11599 11600 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 11601 MIB.addReg(EAXreg); 11602 11603 // insert branch 11604 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 11605 11606 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 11607 return nextMBB; 11608} 11609 11610// private utility function: 64 bit atomics on 32 bit host. 11611MachineBasicBlock * 11612X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr, 11613 MachineBasicBlock *MBB, 11614 unsigned regOpcL, 11615 unsigned regOpcH, 11616 unsigned immOpcL, 11617 unsigned immOpcH, 11618 bool Invert) const { 11619 // For the atomic bitwise operator, we generate 11620 // thisMBB (instructions are in pairs, except cmpxchg8b) 11621 // ld t1,t2 = [bitinstr.addr] 11622 // newMBB: 11623 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4) 11624 // op t5, t6 <- out1, out2, [bitinstr.val] 11625 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val]) 11626 // neg t7, t8 < t5, t6 (if Invert) 11627 // mov ECX, EBX <- t5, t6 11628 // mov EAX, EDX <- t1, t2 11629 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit] 11630 // mov t3, t4 <- EAX, EDX 11631 // bz newMBB 11632 // result in out1, out2 11633 // fallthrough -->nextMBB 11634 11635 const TargetRegisterClass *RC = &X86::GR32RegClass; 11636 const unsigned LoadOpc = X86::MOV32rm; 11637 const unsigned NotOpc = X86::NOT32r; 11638 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11639 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11640 MachineFunction::iterator MBBIter = MBB; 11641 ++MBBIter; 11642 11643 /// First build the CFG 11644 MachineFunction *F = MBB->getParent(); 11645 MachineBasicBlock *thisMBB = MBB; 11646 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 11647 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 11648 F->insert(MBBIter, newMBB); 11649 F->insert(MBBIter, nextMBB); 11650 11651 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 11652 nextMBB->splice(nextMBB->begin(), thisMBB, 11653 llvm::next(MachineBasicBlock::iterator(bInstr)), 11654 thisMBB->end()); 11655 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11656 11657 // Update thisMBB to fall through to newMBB 11658 thisMBB->addSuccessor(newMBB); 11659 11660 // newMBB jumps to itself and fall through to nextMBB 11661 newMBB->addSuccessor(nextMBB); 11662 newMBB->addSuccessor(newMBB); 11663 11664 DebugLoc dl = bInstr->getDebugLoc(); 11665 // Insert instructions into newMBB based on incoming instruction 11666 // There are 8 "real" operands plus 9 implicit def/uses, ignored here. 11667 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 && 11668 "unexpected number of operands"); 11669 MachineOperand& dest1Oper = bInstr->getOperand(0); 11670 MachineOperand& dest2Oper = bInstr->getOperand(1); 11671 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 11672 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) { 11673 argOpers[i] = &bInstr->getOperand(i+2); 11674 11675 // We use some of the operands multiple times, so conservatively just 11676 // clear any kill flags that might be present. 11677 if (argOpers[i]->isReg() && argOpers[i]->isUse()) 11678 argOpers[i]->setIsKill(false); 11679 } 11680 11681 // x86 address has 5 operands: base, index, scale, displacement, and segment. 11682 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 11683 11684 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 11685 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1); 11686 for (int i=0; i <= lastAddrIndx; ++i) 11687 (*MIB).addOperand(*argOpers[i]); 11688 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 11689 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2); 11690 // add 4 to displacement. 11691 for (int i=0; i <= lastAddrIndx-2; ++i) 11692 (*MIB).addOperand(*argOpers[i]); 11693 MachineOperand newOp3 = *(argOpers[3]); 11694 if (newOp3.isImm()) 11695 newOp3.setImm(newOp3.getImm()+4); 11696 else 11697 newOp3.setOffset(newOp3.getOffset()+4); 11698 (*MIB).addOperand(newOp3); 11699 (*MIB).addOperand(*argOpers[lastAddrIndx]); 11700 11701 // t3/4 are defined later, at the bottom of the loop 11702 unsigned t3 = F->getRegInfo().createVirtualRegister(RC); 11703 unsigned t4 = F->getRegInfo().createVirtualRegister(RC); 11704 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg()) 11705 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB); 11706 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg()) 11707 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB); 11708 11709 // The subsequent operations should be using the destination registers of 11710 // the PHI instructions. 11711 t1 = dest1Oper.getReg(); 11712 t2 = dest2Oper.getReg(); 11713 11714 int valArgIndx = lastAddrIndx + 1; 11715 assert((argOpers[valArgIndx]->isReg() || 11716 argOpers[valArgIndx]->isImm()) && 11717 "invalid operand"); 11718 unsigned t5 = F->getRegInfo().createVirtualRegister(RC); 11719 unsigned t6 = F->getRegInfo().createVirtualRegister(RC); 11720 if (argOpers[valArgIndx]->isReg()) 11721 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5); 11722 else 11723 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5); 11724 if (regOpcL != X86::MOV32rr) 11725 MIB.addReg(t1); 11726 (*MIB).addOperand(*argOpers[valArgIndx]); 11727 assert(argOpers[valArgIndx + 1]->isReg() == 11728 argOpers[valArgIndx]->isReg()); 11729 assert(argOpers[valArgIndx + 1]->isImm() == 11730 argOpers[valArgIndx]->isImm()); 11731 if (argOpers[valArgIndx + 1]->isReg()) 11732 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6); 11733 else 11734 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6); 11735 if (regOpcH != X86::MOV32rr) 11736 MIB.addReg(t2); 11737 (*MIB).addOperand(*argOpers[valArgIndx + 1]); 11738 11739 unsigned t7, t8; 11740 if (Invert) { 11741 t7 = F->getRegInfo().createVirtualRegister(RC); 11742 t8 = F->getRegInfo().createVirtualRegister(RC); 11743 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5); 11744 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6); 11745 } else { 11746 t7 = t5; 11747 t8 = t6; 11748 } 11749 11750 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 11751 MIB.addReg(t1); 11752 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX); 11753 MIB.addReg(t2); 11754 11755 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX); 11756 MIB.addReg(t7); 11757 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX); 11758 MIB.addReg(t8); 11759 11760 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B)); 11761 for (int i=0; i <= lastAddrIndx; ++i) 11762 (*MIB).addOperand(*argOpers[i]); 11763 11764 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 11765 (*MIB).setMemRefs(bInstr->memoperands_begin(), 11766 bInstr->memoperands_end()); 11767 11768 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3); 11769 MIB.addReg(X86::EAX); 11770 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4); 11771 MIB.addReg(X86::EDX); 11772 11773 // insert branch 11774 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 11775 11776 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 11777 return nextMBB; 11778} 11779 11780// private utility function 11781MachineBasicBlock * 11782X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr, 11783 MachineBasicBlock *MBB, 11784 unsigned cmovOpc) const { 11785 // For the atomic min/max operator, we generate 11786 // thisMBB: 11787 // newMBB: 11788 // ld t1 = [min/max.addr] 11789 // mov t2 = [min/max.val] 11790 // cmp t1, t2 11791 // cmov[cond] t2 = t1 11792 // mov EAX = t1 11793 // lcs dest = [bitinstr.addr], t2 [EAX is implicit] 11794 // bz newMBB 11795 // fallthrough -->nextMBB 11796 // 11797 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11798 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11799 MachineFunction::iterator MBBIter = MBB; 11800 ++MBBIter; 11801 11802 /// First build the CFG 11803 MachineFunction *F = MBB->getParent(); 11804 MachineBasicBlock *thisMBB = MBB; 11805 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 11806 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 11807 F->insert(MBBIter, newMBB); 11808 F->insert(MBBIter, nextMBB); 11809 11810 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 11811 nextMBB->splice(nextMBB->begin(), thisMBB, 11812 llvm::next(MachineBasicBlock::iterator(mInstr)), 11813 thisMBB->end()); 11814 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11815 11816 // Update thisMBB to fall through to newMBB 11817 thisMBB->addSuccessor(newMBB); 11818 11819 // newMBB jumps to newMBB and fall through to nextMBB 11820 newMBB->addSuccessor(nextMBB); 11821 newMBB->addSuccessor(newMBB); 11822 11823 DebugLoc dl = mInstr->getDebugLoc(); 11824 // Insert instructions into newMBB based on incoming instruction 11825 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 && 11826 "unexpected number of operands"); 11827 MachineOperand& destOper = mInstr->getOperand(0); 11828 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 11829 int numArgs = mInstr->getNumOperands() - 1; 11830 for (int i=0; i < numArgs; ++i) 11831 argOpers[i] = &mInstr->getOperand(i+1); 11832 11833 // x86 address has 4 operands: base, index, scale, and displacement 11834 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 11835 int valArgIndx = lastAddrIndx + 1; 11836 11837 unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass); 11838 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1); 11839 for (int i=0; i <= lastAddrIndx; ++i) 11840 (*MIB).addOperand(*argOpers[i]); 11841 11842 // We only support register and immediate values 11843 assert((argOpers[valArgIndx]->isReg() || 11844 argOpers[valArgIndx]->isImm()) && 11845 "invalid operand"); 11846 11847 unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass); 11848 if (argOpers[valArgIndx]->isReg()) 11849 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2); 11850 else 11851 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2); 11852 (*MIB).addOperand(*argOpers[valArgIndx]); 11853 11854 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 11855 MIB.addReg(t1); 11856 11857 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr)); 11858 MIB.addReg(t1); 11859 MIB.addReg(t2); 11860 11861 // Generate movc 11862 unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass); 11863 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3); 11864 MIB.addReg(t2); 11865 MIB.addReg(t1); 11866 11867 // Cmp and exchange if none has modified the memory location 11868 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32)); 11869 for (int i=0; i <= lastAddrIndx; ++i) 11870 (*MIB).addOperand(*argOpers[i]); 11871 MIB.addReg(t3); 11872 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 11873 (*MIB).setMemRefs(mInstr->memoperands_begin(), 11874 mInstr->memoperands_end()); 11875 11876 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 11877 MIB.addReg(X86::EAX); 11878 11879 // insert branch 11880 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 11881 11882 mInstr->eraseFromParent(); // The pseudo instruction is gone now. 11883 return nextMBB; 11884} 11885 11886// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8 11887// or XMM0_V32I8 in AVX all of this code can be replaced with that 11888// in the .td file. 11889MachineBasicBlock * 11890X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB, 11891 unsigned numArgs, bool memArg) const { 11892 assert(Subtarget->hasSSE42() && 11893 "Target must have SSE4.2 or AVX features enabled"); 11894 11895 DebugLoc dl = MI->getDebugLoc(); 11896 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11897 unsigned Opc; 11898 if (!Subtarget->hasAVX()) { 11899 if (memArg) 11900 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm; 11901 else 11902 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr; 11903 } else { 11904 if (memArg) 11905 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm; 11906 else 11907 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr; 11908 } 11909 11910 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc)); 11911 for (unsigned i = 0; i < numArgs; ++i) { 11912 MachineOperand &Op = MI->getOperand(i+1); 11913 if (!(Op.isReg() && Op.isImplicit())) 11914 MIB.addOperand(Op); 11915 } 11916 BuildMI(*BB, MI, dl, 11917 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg()) 11918 .addReg(X86::XMM0); 11919 11920 MI->eraseFromParent(); 11921 return BB; 11922} 11923 11924MachineBasicBlock * 11925X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const { 11926 DebugLoc dl = MI->getDebugLoc(); 11927 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11928 11929 // Address into RAX/EAX, other two args into ECX, EDX. 11930 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r; 11931 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 11932 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg); 11933 for (int i = 0; i < X86::AddrNumOperands; ++i) 11934 MIB.addOperand(MI->getOperand(i)); 11935 11936 unsigned ValOps = X86::AddrNumOperands; 11937 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 11938 .addReg(MI->getOperand(ValOps).getReg()); 11939 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX) 11940 .addReg(MI->getOperand(ValOps+1).getReg()); 11941 11942 // The instruction doesn't actually take any operands though. 11943 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr)); 11944 11945 MI->eraseFromParent(); // The pseudo is gone now. 11946 return BB; 11947} 11948 11949MachineBasicBlock * 11950X86TargetLowering::EmitVAARG64WithCustomInserter( 11951 MachineInstr *MI, 11952 MachineBasicBlock *MBB) const { 11953 // Emit va_arg instruction on X86-64. 11954 11955 // Operands to this pseudo-instruction: 11956 // 0 ) Output : destination address (reg) 11957 // 1-5) Input : va_list address (addr, i64mem) 11958 // 6 ) ArgSize : Size (in bytes) of vararg type 11959 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset 11960 // 8 ) Align : Alignment of type 11961 // 9 ) EFLAGS (implicit-def) 11962 11963 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!"); 11964 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands"); 11965 11966 unsigned DestReg = MI->getOperand(0).getReg(); 11967 MachineOperand &Base = MI->getOperand(1); 11968 MachineOperand &Scale = MI->getOperand(2); 11969 MachineOperand &Index = MI->getOperand(3); 11970 MachineOperand &Disp = MI->getOperand(4); 11971 MachineOperand &Segment = MI->getOperand(5); 11972 unsigned ArgSize = MI->getOperand(6).getImm(); 11973 unsigned ArgMode = MI->getOperand(7).getImm(); 11974 unsigned Align = MI->getOperand(8).getImm(); 11975 11976 // Memory Reference 11977 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand"); 11978 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 11979 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 11980 11981 // Machine Information 11982 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11983 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 11984 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64); 11985 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32); 11986 DebugLoc DL = MI->getDebugLoc(); 11987 11988 // struct va_list { 11989 // i32 gp_offset 11990 // i32 fp_offset 11991 // i64 overflow_area (address) 11992 // i64 reg_save_area (address) 11993 // } 11994 // sizeof(va_list) = 24 11995 // alignment(va_list) = 8 11996 11997 unsigned TotalNumIntRegs = 6; 11998 unsigned TotalNumXMMRegs = 8; 11999 bool UseGPOffset = (ArgMode == 1); 12000 bool UseFPOffset = (ArgMode == 2); 12001 unsigned MaxOffset = TotalNumIntRegs * 8 + 12002 (UseFPOffset ? TotalNumXMMRegs * 16 : 0); 12003 12004 /* Align ArgSize to a multiple of 8 */ 12005 unsigned ArgSizeA8 = (ArgSize + 7) & ~7; 12006 bool NeedsAlign = (Align > 8); 12007 12008 MachineBasicBlock *thisMBB = MBB; 12009 MachineBasicBlock *overflowMBB; 12010 MachineBasicBlock *offsetMBB; 12011 MachineBasicBlock *endMBB; 12012 12013 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB 12014 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB 12015 unsigned OffsetReg = 0; 12016 12017 if (!UseGPOffset && !UseFPOffset) { 12018 // If we only pull from the overflow region, we don't create a branch. 12019 // We don't need to alter control flow. 12020 OffsetDestReg = 0; // unused 12021 OverflowDestReg = DestReg; 12022 12023 offsetMBB = NULL; 12024 overflowMBB = thisMBB; 12025 endMBB = thisMBB; 12026 } else { 12027 // First emit code to check if gp_offset (or fp_offset) is below the bound. 12028 // If so, pull the argument from reg_save_area. (branch to offsetMBB) 12029 // If not, pull from overflow_area. (branch to overflowMBB) 12030 // 12031 // thisMBB 12032 // | . 12033 // | . 12034 // offsetMBB overflowMBB 12035 // | . 12036 // | . 12037 // endMBB 12038 12039 // Registers for the PHI in endMBB 12040 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass); 12041 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass); 12042 12043 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 12044 MachineFunction *MF = MBB->getParent(); 12045 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB); 12046 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB); 12047 endMBB = MF->CreateMachineBasicBlock(LLVM_BB); 12048 12049 MachineFunction::iterator MBBIter = MBB; 12050 ++MBBIter; 12051 12052 // Insert the new basic blocks 12053 MF->insert(MBBIter, offsetMBB); 12054 MF->insert(MBBIter, overflowMBB); 12055 MF->insert(MBBIter, endMBB); 12056 12057 // Transfer the remainder of MBB and its successor edges to endMBB. 12058 endMBB->splice(endMBB->begin(), thisMBB, 12059 llvm::next(MachineBasicBlock::iterator(MI)), 12060 thisMBB->end()); 12061 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 12062 12063 // Make offsetMBB and overflowMBB successors of thisMBB 12064 thisMBB->addSuccessor(offsetMBB); 12065 thisMBB->addSuccessor(overflowMBB); 12066 12067 // endMBB is a successor of both offsetMBB and overflowMBB 12068 offsetMBB->addSuccessor(endMBB); 12069 overflowMBB->addSuccessor(endMBB); 12070 12071 // Load the offset value into a register 12072 OffsetReg = MRI.createVirtualRegister(OffsetRegClass); 12073 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg) 12074 .addOperand(Base) 12075 .addOperand(Scale) 12076 .addOperand(Index) 12077 .addDisp(Disp, UseFPOffset ? 4 : 0) 12078 .addOperand(Segment) 12079 .setMemRefs(MMOBegin, MMOEnd); 12080 12081 // Check if there is enough room left to pull this argument. 12082 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri)) 12083 .addReg(OffsetReg) 12084 .addImm(MaxOffset + 8 - ArgSizeA8); 12085 12086 // Branch to "overflowMBB" if offset >= max 12087 // Fall through to "offsetMBB" otherwise 12088 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE))) 12089 .addMBB(overflowMBB); 12090 } 12091 12092 // In offsetMBB, emit code to use the reg_save_area. 12093 if (offsetMBB) { 12094 assert(OffsetReg != 0); 12095 12096 // Read the reg_save_area address. 12097 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass); 12098 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg) 12099 .addOperand(Base) 12100 .addOperand(Scale) 12101 .addOperand(Index) 12102 .addDisp(Disp, 16) 12103 .addOperand(Segment) 12104 .setMemRefs(MMOBegin, MMOEnd); 12105 12106 // Zero-extend the offset 12107 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass); 12108 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64) 12109 .addImm(0) 12110 .addReg(OffsetReg) 12111 .addImm(X86::sub_32bit); 12112 12113 // Add the offset to the reg_save_area to get the final address. 12114 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg) 12115 .addReg(OffsetReg64) 12116 .addReg(RegSaveReg); 12117 12118 // Compute the offset for the next argument 12119 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass); 12120 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg) 12121 .addReg(OffsetReg) 12122 .addImm(UseFPOffset ? 16 : 8); 12123 12124 // Store it back into the va_list. 12125 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr)) 12126 .addOperand(Base) 12127 .addOperand(Scale) 12128 .addOperand(Index) 12129 .addDisp(Disp, UseFPOffset ? 4 : 0) 12130 .addOperand(Segment) 12131 .addReg(NextOffsetReg) 12132 .setMemRefs(MMOBegin, MMOEnd); 12133 12134 // Jump to endMBB 12135 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4)) 12136 .addMBB(endMBB); 12137 } 12138 12139 // 12140 // Emit code to use overflow area 12141 // 12142 12143 // Load the overflow_area address into a register. 12144 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass); 12145 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg) 12146 .addOperand(Base) 12147 .addOperand(Scale) 12148 .addOperand(Index) 12149 .addDisp(Disp, 8) 12150 .addOperand(Segment) 12151 .setMemRefs(MMOBegin, MMOEnd); 12152 12153 // If we need to align it, do so. Otherwise, just copy the address 12154 // to OverflowDestReg. 12155 if (NeedsAlign) { 12156 // Align the overflow address 12157 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2"); 12158 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass); 12159 12160 // aligned_addr = (addr + (align-1)) & ~(align-1) 12161 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg) 12162 .addReg(OverflowAddrReg) 12163 .addImm(Align-1); 12164 12165 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg) 12166 .addReg(TmpReg) 12167 .addImm(~(uint64_t)(Align-1)); 12168 } else { 12169 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg) 12170 .addReg(OverflowAddrReg); 12171 } 12172 12173 // Compute the next overflow address after this argument. 12174 // (the overflow address should be kept 8-byte aligned) 12175 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass); 12176 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg) 12177 .addReg(OverflowDestReg) 12178 .addImm(ArgSizeA8); 12179 12180 // Store the new overflow address. 12181 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr)) 12182 .addOperand(Base) 12183 .addOperand(Scale) 12184 .addOperand(Index) 12185 .addDisp(Disp, 8) 12186 .addOperand(Segment) 12187 .addReg(NextAddrReg) 12188 .setMemRefs(MMOBegin, MMOEnd); 12189 12190 // If we branched, emit the PHI to the front of endMBB. 12191 if (offsetMBB) { 12192 BuildMI(*endMBB, endMBB->begin(), DL, 12193 TII->get(X86::PHI), DestReg) 12194 .addReg(OffsetDestReg).addMBB(offsetMBB) 12195 .addReg(OverflowDestReg).addMBB(overflowMBB); 12196 } 12197 12198 // Erase the pseudo instruction 12199 MI->eraseFromParent(); 12200 12201 return endMBB; 12202} 12203 12204MachineBasicBlock * 12205X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter( 12206 MachineInstr *MI, 12207 MachineBasicBlock *MBB) const { 12208 // Emit code to save XMM registers to the stack. The ABI says that the 12209 // number of registers to save is given in %al, so it's theoretically 12210 // possible to do an indirect jump trick to avoid saving all of them, 12211 // however this code takes a simpler approach and just executes all 12212 // of the stores if %al is non-zero. It's less code, and it's probably 12213 // easier on the hardware branch predictor, and stores aren't all that 12214 // expensive anyway. 12215 12216 // Create the new basic blocks. One block contains all the XMM stores, 12217 // and one block is the final destination regardless of whether any 12218 // stores were performed. 12219 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 12220 MachineFunction *F = MBB->getParent(); 12221 MachineFunction::iterator MBBIter = MBB; 12222 ++MBBIter; 12223 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB); 12224 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB); 12225 F->insert(MBBIter, XMMSaveMBB); 12226 F->insert(MBBIter, EndMBB); 12227 12228 // Transfer the remainder of MBB and its successor edges to EndMBB. 12229 EndMBB->splice(EndMBB->begin(), MBB, 12230 llvm::next(MachineBasicBlock::iterator(MI)), 12231 MBB->end()); 12232 EndMBB->transferSuccessorsAndUpdatePHIs(MBB); 12233 12234 // The original block will now fall through to the XMM save block. 12235 MBB->addSuccessor(XMMSaveMBB); 12236 // The XMMSaveMBB will fall through to the end block. 12237 XMMSaveMBB->addSuccessor(EndMBB); 12238 12239 // Now add the instructions. 12240 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12241 DebugLoc DL = MI->getDebugLoc(); 12242 12243 unsigned CountReg = MI->getOperand(0).getReg(); 12244 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm(); 12245 int64_t VarArgsFPOffset = MI->getOperand(2).getImm(); 12246 12247 if (!Subtarget->isTargetWin64()) { 12248 // If %al is 0, branch around the XMM save block. 12249 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg); 12250 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB); 12251 MBB->addSuccessor(EndMBB); 12252 } 12253 12254 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr; 12255 // In the XMM save block, save all the XMM argument registers. 12256 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) { 12257 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset; 12258 MachineMemOperand *MMO = 12259 F->getMachineMemOperand( 12260 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset), 12261 MachineMemOperand::MOStore, 12262 /*Size=*/16, /*Align=*/16); 12263 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc)) 12264 .addFrameIndex(RegSaveFrameIndex) 12265 .addImm(/*Scale=*/1) 12266 .addReg(/*IndexReg=*/0) 12267 .addImm(/*Disp=*/Offset) 12268 .addReg(/*Segment=*/0) 12269 .addReg(MI->getOperand(i).getReg()) 12270 .addMemOperand(MMO); 12271 } 12272 12273 MI->eraseFromParent(); // The pseudo instruction is gone now. 12274 12275 return EndMBB; 12276} 12277 12278// The EFLAGS operand of SelectItr might be missing a kill marker 12279// because there were multiple uses of EFLAGS, and ISel didn't know 12280// which to mark. Figure out whether SelectItr should have had a 12281// kill marker, and set it if it should. Returns the correct kill 12282// marker value. 12283static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr, 12284 MachineBasicBlock* BB, 12285 const TargetRegisterInfo* TRI) { 12286 // Scan forward through BB for a use/def of EFLAGS. 12287 MachineBasicBlock::iterator miI(llvm::next(SelectItr)); 12288 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 12289 const MachineInstr& mi = *miI; 12290 if (mi.readsRegister(X86::EFLAGS)) 12291 return false; 12292 if (mi.definesRegister(X86::EFLAGS)) 12293 break; // Should have kill-flag - update below. 12294 } 12295 12296 // If we hit the end of the block, check whether EFLAGS is live into a 12297 // successor. 12298 if (miI == BB->end()) { 12299 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 12300 sEnd = BB->succ_end(); 12301 sItr != sEnd; ++sItr) { 12302 MachineBasicBlock* succ = *sItr; 12303 if (succ->isLiveIn(X86::EFLAGS)) 12304 return false; 12305 } 12306 } 12307 12308 // We found a def, or hit the end of the basic block and EFLAGS wasn't live 12309 // out. SelectMI should have a kill flag on EFLAGS. 12310 SelectItr->addRegisterKilled(X86::EFLAGS, TRI); 12311 return true; 12312} 12313 12314MachineBasicBlock * 12315X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, 12316 MachineBasicBlock *BB) const { 12317 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12318 DebugLoc DL = MI->getDebugLoc(); 12319 12320 // To "insert" a SELECT_CC instruction, we actually have to insert the 12321 // diamond control-flow pattern. The incoming instruction knows the 12322 // destination vreg to set, the condition code register to branch on, the 12323 // true/false values to select between, and a branch opcode to use. 12324 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 12325 MachineFunction::iterator It = BB; 12326 ++It; 12327 12328 // thisMBB: 12329 // ... 12330 // TrueVal = ... 12331 // cmpTY ccX, r1, r2 12332 // bCC copy1MBB 12333 // fallthrough --> copy0MBB 12334 MachineBasicBlock *thisMBB = BB; 12335 MachineFunction *F = BB->getParent(); 12336 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 12337 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12338 F->insert(It, copy0MBB); 12339 F->insert(It, sinkMBB); 12340 12341 // If the EFLAGS register isn't dead in the terminator, then claim that it's 12342 // live into the sink and copy blocks. 12343 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo(); 12344 if (!MI->killsRegister(X86::EFLAGS) && 12345 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) { 12346 copy0MBB->addLiveIn(X86::EFLAGS); 12347 sinkMBB->addLiveIn(X86::EFLAGS); 12348 } 12349 12350 // Transfer the remainder of BB and its successor edges to sinkMBB. 12351 sinkMBB->splice(sinkMBB->begin(), BB, 12352 llvm::next(MachineBasicBlock::iterator(MI)), 12353 BB->end()); 12354 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12355 12356 // Add the true and fallthrough blocks as its successors. 12357 BB->addSuccessor(copy0MBB); 12358 BB->addSuccessor(sinkMBB); 12359 12360 // Create the conditional branch instruction. 12361 unsigned Opc = 12362 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm()); 12363 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB); 12364 12365 // copy0MBB: 12366 // %FalseValue = ... 12367 // # fallthrough to sinkMBB 12368 copy0MBB->addSuccessor(sinkMBB); 12369 12370 // sinkMBB: 12371 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 12372 // ... 12373 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 12374 TII->get(X86::PHI), MI->getOperand(0).getReg()) 12375 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 12376 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 12377 12378 MI->eraseFromParent(); // The pseudo instruction is gone now. 12379 return sinkMBB; 12380} 12381 12382MachineBasicBlock * 12383X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB, 12384 bool Is64Bit) const { 12385 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12386 DebugLoc DL = MI->getDebugLoc(); 12387 MachineFunction *MF = BB->getParent(); 12388 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 12389 12390 assert(getTargetMachine().Options.EnableSegmentedStacks); 12391 12392 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS; 12393 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30; 12394 12395 // BB: 12396 // ... [Till the alloca] 12397 // If stacklet is not large enough, jump to mallocMBB 12398 // 12399 // bumpMBB: 12400 // Allocate by subtracting from RSP 12401 // Jump to continueMBB 12402 // 12403 // mallocMBB: 12404 // Allocate by call to runtime 12405 // 12406 // continueMBB: 12407 // ... 12408 // [rest of original BB] 12409 // 12410 12411 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB); 12412 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB); 12413 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB); 12414 12415 MachineRegisterInfo &MRI = MF->getRegInfo(); 12416 const TargetRegisterClass *AddrRegClass = 12417 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32); 12418 12419 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass), 12420 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass), 12421 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass), 12422 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass), 12423 sizeVReg = MI->getOperand(1).getReg(), 12424 physSPReg = Is64Bit ? X86::RSP : X86::ESP; 12425 12426 MachineFunction::iterator MBBIter = BB; 12427 ++MBBIter; 12428 12429 MF->insert(MBBIter, bumpMBB); 12430 MF->insert(MBBIter, mallocMBB); 12431 MF->insert(MBBIter, continueMBB); 12432 12433 continueMBB->splice(continueMBB->begin(), BB, llvm::next 12434 (MachineBasicBlock::iterator(MI)), BB->end()); 12435 continueMBB->transferSuccessorsAndUpdatePHIs(BB); 12436 12437 // Add code to the main basic block to check if the stack limit has been hit, 12438 // and if so, jump to mallocMBB otherwise to bumpMBB. 12439 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg); 12440 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg) 12441 .addReg(tmpSPVReg).addReg(sizeVReg); 12442 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr)) 12443 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg) 12444 .addReg(SPLimitVReg); 12445 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB); 12446 12447 // bumpMBB simply decreases the stack pointer, since we know the current 12448 // stacklet has enough space. 12449 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg) 12450 .addReg(SPLimitVReg); 12451 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg) 12452 .addReg(SPLimitVReg); 12453 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 12454 12455 // Calls into a routine in libgcc to allocate more space from the heap. 12456 const uint32_t *RegMask = 12457 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C); 12458 if (Is64Bit) { 12459 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI) 12460 .addReg(sizeVReg); 12461 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32)) 12462 .addExternalSymbol("__morestack_allocate_stack_space") 12463 .addRegMask(RegMask) 12464 .addReg(X86::RDI, RegState::Implicit) 12465 .addReg(X86::RAX, RegState::ImplicitDefine); 12466 } else { 12467 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg) 12468 .addImm(12); 12469 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg); 12470 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32)) 12471 .addExternalSymbol("__morestack_allocate_stack_space") 12472 .addRegMask(RegMask) 12473 .addReg(X86::EAX, RegState::ImplicitDefine); 12474 } 12475 12476 if (!Is64Bit) 12477 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg) 12478 .addImm(16); 12479 12480 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg) 12481 .addReg(Is64Bit ? X86::RAX : X86::EAX); 12482 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 12483 12484 // Set up the CFG correctly. 12485 BB->addSuccessor(bumpMBB); 12486 BB->addSuccessor(mallocMBB); 12487 mallocMBB->addSuccessor(continueMBB); 12488 bumpMBB->addSuccessor(continueMBB); 12489 12490 // Take care of the PHI nodes. 12491 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI), 12492 MI->getOperand(0).getReg()) 12493 .addReg(mallocPtrVReg).addMBB(mallocMBB) 12494 .addReg(bumpSPPtrVReg).addMBB(bumpMBB); 12495 12496 // Delete the original pseudo instruction. 12497 MI->eraseFromParent(); 12498 12499 // And we're done. 12500 return continueMBB; 12501} 12502 12503MachineBasicBlock * 12504X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI, 12505 MachineBasicBlock *BB) const { 12506 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12507 DebugLoc DL = MI->getDebugLoc(); 12508 12509 assert(!Subtarget->isTargetEnvMacho()); 12510 12511 // The lowering is pretty easy: we're just emitting the call to _alloca. The 12512 // non-trivial part is impdef of ESP. 12513 12514 if (Subtarget->isTargetWin64()) { 12515 if (Subtarget->isTargetCygMing()) { 12516 // ___chkstk(Mingw64): 12517 // Clobbers R10, R11, RAX and EFLAGS. 12518 // Updates RSP. 12519 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 12520 .addExternalSymbol("___chkstk") 12521 .addReg(X86::RAX, RegState::Implicit) 12522 .addReg(X86::RSP, RegState::Implicit) 12523 .addReg(X86::RAX, RegState::Define | RegState::Implicit) 12524 .addReg(X86::RSP, RegState::Define | RegState::Implicit) 12525 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 12526 } else { 12527 // __chkstk(MSVCRT): does not update stack pointer. 12528 // Clobbers R10, R11 and EFLAGS. 12529 // FIXME: RAX(allocated size) might be reused and not killed. 12530 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 12531 .addExternalSymbol("__chkstk") 12532 .addReg(X86::RAX, RegState::Implicit) 12533 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 12534 // RAX has the offset to subtracted from RSP. 12535 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP) 12536 .addReg(X86::RSP) 12537 .addReg(X86::RAX); 12538 } 12539 } else { 12540 const char *StackProbeSymbol = 12541 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca"; 12542 12543 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32)) 12544 .addExternalSymbol(StackProbeSymbol) 12545 .addReg(X86::EAX, RegState::Implicit) 12546 .addReg(X86::ESP, RegState::Implicit) 12547 .addReg(X86::EAX, RegState::Define | RegState::Implicit) 12548 .addReg(X86::ESP, RegState::Define | RegState::Implicit) 12549 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 12550 } 12551 12552 MI->eraseFromParent(); // The pseudo instruction is gone now. 12553 return BB; 12554} 12555 12556MachineBasicBlock * 12557X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI, 12558 MachineBasicBlock *BB) const { 12559 // This is pretty easy. We're taking the value that we received from 12560 // our load from the relocation, sticking it in either RDI (x86-64) 12561 // or EAX and doing an indirect call. The return value will then 12562 // be in the normal return register. 12563 const X86InstrInfo *TII 12564 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo()); 12565 DebugLoc DL = MI->getDebugLoc(); 12566 MachineFunction *F = BB->getParent(); 12567 12568 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?"); 12569 assert(MI->getOperand(3).isGlobal() && "This should be a global"); 12570 12571 // Get a register mask for the lowered call. 12572 // FIXME: The 32-bit calls have non-standard calling conventions. Use a 12573 // proper register mask. 12574 const uint32_t *RegMask = 12575 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C); 12576 if (Subtarget->is64Bit()) { 12577 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 12578 TII->get(X86::MOV64rm), X86::RDI) 12579 .addReg(X86::RIP) 12580 .addImm(0).addReg(0) 12581 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 12582 MI->getOperand(3).getTargetFlags()) 12583 .addReg(0); 12584 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m)); 12585 addDirectMem(MIB, X86::RDI); 12586 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask); 12587 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) { 12588 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 12589 TII->get(X86::MOV32rm), X86::EAX) 12590 .addReg(0) 12591 .addImm(0).addReg(0) 12592 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 12593 MI->getOperand(3).getTargetFlags()) 12594 .addReg(0); 12595 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 12596 addDirectMem(MIB, X86::EAX); 12597 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask); 12598 } else { 12599 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 12600 TII->get(X86::MOV32rm), X86::EAX) 12601 .addReg(TII->getGlobalBaseReg(F)) 12602 .addImm(0).addReg(0) 12603 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 12604 MI->getOperand(3).getTargetFlags()) 12605 .addReg(0); 12606 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 12607 addDirectMem(MIB, X86::EAX); 12608 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask); 12609 } 12610 12611 MI->eraseFromParent(); // The pseudo instruction is gone now. 12612 return BB; 12613} 12614 12615MachineBasicBlock * 12616X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 12617 MachineBasicBlock *BB) const { 12618 switch (MI->getOpcode()) { 12619 default: llvm_unreachable("Unexpected instr type to insert"); 12620 case X86::TAILJMPd64: 12621 case X86::TAILJMPr64: 12622 case X86::TAILJMPm64: 12623 llvm_unreachable("TAILJMP64 would not be touched here."); 12624 case X86::TCRETURNdi64: 12625 case X86::TCRETURNri64: 12626 case X86::TCRETURNmi64: 12627 return BB; 12628 case X86::WIN_ALLOCA: 12629 return EmitLoweredWinAlloca(MI, BB); 12630 case X86::SEG_ALLOCA_32: 12631 return EmitLoweredSegAlloca(MI, BB, false); 12632 case X86::SEG_ALLOCA_64: 12633 return EmitLoweredSegAlloca(MI, BB, true); 12634 case X86::TLSCall_32: 12635 case X86::TLSCall_64: 12636 return EmitLoweredTLSCall(MI, BB); 12637 case X86::CMOV_GR8: 12638 case X86::CMOV_FR32: 12639 case X86::CMOV_FR64: 12640 case X86::CMOV_V4F32: 12641 case X86::CMOV_V2F64: 12642 case X86::CMOV_V2I64: 12643 case X86::CMOV_V8F32: 12644 case X86::CMOV_V4F64: 12645 case X86::CMOV_V4I64: 12646 case X86::CMOV_GR16: 12647 case X86::CMOV_GR32: 12648 case X86::CMOV_RFP32: 12649 case X86::CMOV_RFP64: 12650 case X86::CMOV_RFP80: 12651 return EmitLoweredSelect(MI, BB); 12652 12653 case X86::FP32_TO_INT16_IN_MEM: 12654 case X86::FP32_TO_INT32_IN_MEM: 12655 case X86::FP32_TO_INT64_IN_MEM: 12656 case X86::FP64_TO_INT16_IN_MEM: 12657 case X86::FP64_TO_INT32_IN_MEM: 12658 case X86::FP64_TO_INT64_IN_MEM: 12659 case X86::FP80_TO_INT16_IN_MEM: 12660 case X86::FP80_TO_INT32_IN_MEM: 12661 case X86::FP80_TO_INT64_IN_MEM: { 12662 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12663 DebugLoc DL = MI->getDebugLoc(); 12664 12665 // Change the floating point control register to use "round towards zero" 12666 // mode when truncating to an integer value. 12667 MachineFunction *F = BB->getParent(); 12668 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false); 12669 addFrameReference(BuildMI(*BB, MI, DL, 12670 TII->get(X86::FNSTCW16m)), CWFrameIdx); 12671 12672 // Load the old value of the high byte of the control word... 12673 unsigned OldCW = 12674 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass); 12675 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW), 12676 CWFrameIdx); 12677 12678 // Set the high part to be round to zero... 12679 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx) 12680 .addImm(0xC7F); 12681 12682 // Reload the modified control word now... 12683 addFrameReference(BuildMI(*BB, MI, DL, 12684 TII->get(X86::FLDCW16m)), CWFrameIdx); 12685 12686 // Restore the memory image of control word to original value 12687 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx) 12688 .addReg(OldCW); 12689 12690 // Get the X86 opcode to use. 12691 unsigned Opc; 12692 switch (MI->getOpcode()) { 12693 default: llvm_unreachable("illegal opcode!"); 12694 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break; 12695 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break; 12696 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break; 12697 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break; 12698 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break; 12699 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break; 12700 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break; 12701 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break; 12702 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break; 12703 } 12704 12705 X86AddressMode AM; 12706 MachineOperand &Op = MI->getOperand(0); 12707 if (Op.isReg()) { 12708 AM.BaseType = X86AddressMode::RegBase; 12709 AM.Base.Reg = Op.getReg(); 12710 } else { 12711 AM.BaseType = X86AddressMode::FrameIndexBase; 12712 AM.Base.FrameIndex = Op.getIndex(); 12713 } 12714 Op = MI->getOperand(1); 12715 if (Op.isImm()) 12716 AM.Scale = Op.getImm(); 12717 Op = MI->getOperand(2); 12718 if (Op.isImm()) 12719 AM.IndexReg = Op.getImm(); 12720 Op = MI->getOperand(3); 12721 if (Op.isGlobal()) { 12722 AM.GV = Op.getGlobal(); 12723 } else { 12724 AM.Disp = Op.getImm(); 12725 } 12726 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM) 12727 .addReg(MI->getOperand(X86::AddrNumOperands).getReg()); 12728 12729 // Reload the original control word now. 12730 addFrameReference(BuildMI(*BB, MI, DL, 12731 TII->get(X86::FLDCW16m)), CWFrameIdx); 12732 12733 MI->eraseFromParent(); // The pseudo instruction is gone now. 12734 return BB; 12735 } 12736 // String/text processing lowering. 12737 case X86::PCMPISTRM128REG: 12738 case X86::VPCMPISTRM128REG: 12739 return EmitPCMP(MI, BB, 3, false /* in-mem */); 12740 case X86::PCMPISTRM128MEM: 12741 case X86::VPCMPISTRM128MEM: 12742 return EmitPCMP(MI, BB, 3, true /* in-mem */); 12743 case X86::PCMPESTRM128REG: 12744 case X86::VPCMPESTRM128REG: 12745 return EmitPCMP(MI, BB, 5, false /* in mem */); 12746 case X86::PCMPESTRM128MEM: 12747 case X86::VPCMPESTRM128MEM: 12748 return EmitPCMP(MI, BB, 5, true /* in mem */); 12749 12750 // Thread synchronization. 12751 case X86::MONITOR: 12752 return EmitMonitor(MI, BB); 12753 12754 // Atomic Lowering. 12755 case X86::ATOMAND32: 12756 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 12757 X86::AND32ri, X86::MOV32rm, 12758 X86::LCMPXCHG32, 12759 X86::NOT32r, X86::EAX, 12760 &X86::GR32RegClass); 12761 case X86::ATOMOR32: 12762 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr, 12763 X86::OR32ri, X86::MOV32rm, 12764 X86::LCMPXCHG32, 12765 X86::NOT32r, X86::EAX, 12766 &X86::GR32RegClass); 12767 case X86::ATOMXOR32: 12768 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr, 12769 X86::XOR32ri, X86::MOV32rm, 12770 X86::LCMPXCHG32, 12771 X86::NOT32r, X86::EAX, 12772 &X86::GR32RegClass); 12773 case X86::ATOMNAND32: 12774 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 12775 X86::AND32ri, X86::MOV32rm, 12776 X86::LCMPXCHG32, 12777 X86::NOT32r, X86::EAX, 12778 &X86::GR32RegClass, true); 12779 case X86::ATOMMIN32: 12780 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr); 12781 case X86::ATOMMAX32: 12782 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr); 12783 case X86::ATOMUMIN32: 12784 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr); 12785 case X86::ATOMUMAX32: 12786 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr); 12787 12788 case X86::ATOMAND16: 12789 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 12790 X86::AND16ri, X86::MOV16rm, 12791 X86::LCMPXCHG16, 12792 X86::NOT16r, X86::AX, 12793 &X86::GR16RegClass); 12794 case X86::ATOMOR16: 12795 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr, 12796 X86::OR16ri, X86::MOV16rm, 12797 X86::LCMPXCHG16, 12798 X86::NOT16r, X86::AX, 12799 &X86::GR16RegClass); 12800 case X86::ATOMXOR16: 12801 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr, 12802 X86::XOR16ri, X86::MOV16rm, 12803 X86::LCMPXCHG16, 12804 X86::NOT16r, X86::AX, 12805 &X86::GR16RegClass); 12806 case X86::ATOMNAND16: 12807 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 12808 X86::AND16ri, X86::MOV16rm, 12809 X86::LCMPXCHG16, 12810 X86::NOT16r, X86::AX, 12811 &X86::GR16RegClass, true); 12812 case X86::ATOMMIN16: 12813 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr); 12814 case X86::ATOMMAX16: 12815 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr); 12816 case X86::ATOMUMIN16: 12817 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr); 12818 case X86::ATOMUMAX16: 12819 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr); 12820 12821 case X86::ATOMAND8: 12822 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 12823 X86::AND8ri, X86::MOV8rm, 12824 X86::LCMPXCHG8, 12825 X86::NOT8r, X86::AL, 12826 &X86::GR8RegClass); 12827 case X86::ATOMOR8: 12828 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr, 12829 X86::OR8ri, X86::MOV8rm, 12830 X86::LCMPXCHG8, 12831 X86::NOT8r, X86::AL, 12832 &X86::GR8RegClass); 12833 case X86::ATOMXOR8: 12834 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr, 12835 X86::XOR8ri, X86::MOV8rm, 12836 X86::LCMPXCHG8, 12837 X86::NOT8r, X86::AL, 12838 &X86::GR8RegClass); 12839 case X86::ATOMNAND8: 12840 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 12841 X86::AND8ri, X86::MOV8rm, 12842 X86::LCMPXCHG8, 12843 X86::NOT8r, X86::AL, 12844 &X86::GR8RegClass, true); 12845 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way. 12846 // This group is for 64-bit host. 12847 case X86::ATOMAND64: 12848 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 12849 X86::AND64ri32, X86::MOV64rm, 12850 X86::LCMPXCHG64, 12851 X86::NOT64r, X86::RAX, 12852 &X86::GR64RegClass); 12853 case X86::ATOMOR64: 12854 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr, 12855 X86::OR64ri32, X86::MOV64rm, 12856 X86::LCMPXCHG64, 12857 X86::NOT64r, X86::RAX, 12858 &X86::GR64RegClass); 12859 case X86::ATOMXOR64: 12860 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr, 12861 X86::XOR64ri32, X86::MOV64rm, 12862 X86::LCMPXCHG64, 12863 X86::NOT64r, X86::RAX, 12864 &X86::GR64RegClass); 12865 case X86::ATOMNAND64: 12866 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 12867 X86::AND64ri32, X86::MOV64rm, 12868 X86::LCMPXCHG64, 12869 X86::NOT64r, X86::RAX, 12870 &X86::GR64RegClass, true); 12871 case X86::ATOMMIN64: 12872 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr); 12873 case X86::ATOMMAX64: 12874 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr); 12875 case X86::ATOMUMIN64: 12876 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr); 12877 case X86::ATOMUMAX64: 12878 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr); 12879 12880 // This group does 64-bit operations on a 32-bit host. 12881 case X86::ATOMAND6432: 12882 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12883 X86::AND32rr, X86::AND32rr, 12884 X86::AND32ri, X86::AND32ri, 12885 false); 12886 case X86::ATOMOR6432: 12887 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12888 X86::OR32rr, X86::OR32rr, 12889 X86::OR32ri, X86::OR32ri, 12890 false); 12891 case X86::ATOMXOR6432: 12892 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12893 X86::XOR32rr, X86::XOR32rr, 12894 X86::XOR32ri, X86::XOR32ri, 12895 false); 12896 case X86::ATOMNAND6432: 12897 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12898 X86::AND32rr, X86::AND32rr, 12899 X86::AND32ri, X86::AND32ri, 12900 true); 12901 case X86::ATOMADD6432: 12902 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12903 X86::ADD32rr, X86::ADC32rr, 12904 X86::ADD32ri, X86::ADC32ri, 12905 false); 12906 case X86::ATOMSUB6432: 12907 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12908 X86::SUB32rr, X86::SBB32rr, 12909 X86::SUB32ri, X86::SBB32ri, 12910 false); 12911 case X86::ATOMSWAP6432: 12912 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12913 X86::MOV32rr, X86::MOV32rr, 12914 X86::MOV32ri, X86::MOV32ri, 12915 false); 12916 case X86::VASTART_SAVE_XMM_REGS: 12917 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB); 12918 12919 case X86::VAARG_64: 12920 return EmitVAARG64WithCustomInserter(MI, BB); 12921 } 12922} 12923 12924//===----------------------------------------------------------------------===// 12925// X86 Optimization Hooks 12926//===----------------------------------------------------------------------===// 12927 12928void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 12929 APInt &KnownZero, 12930 APInt &KnownOne, 12931 const SelectionDAG &DAG, 12932 unsigned Depth) const { 12933 unsigned BitWidth = KnownZero.getBitWidth(); 12934 unsigned Opc = Op.getOpcode(); 12935 assert((Opc >= ISD::BUILTIN_OP_END || 12936 Opc == ISD::INTRINSIC_WO_CHAIN || 12937 Opc == ISD::INTRINSIC_W_CHAIN || 12938 Opc == ISD::INTRINSIC_VOID) && 12939 "Should use MaskedValueIsZero if you don't know whether Op" 12940 " is a target node!"); 12941 12942 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything. 12943 switch (Opc) { 12944 default: break; 12945 case X86ISD::ADD: 12946 case X86ISD::SUB: 12947 case X86ISD::ADC: 12948 case X86ISD::SBB: 12949 case X86ISD::SMUL: 12950 case X86ISD::UMUL: 12951 case X86ISD::INC: 12952 case X86ISD::DEC: 12953 case X86ISD::OR: 12954 case X86ISD::XOR: 12955 case X86ISD::AND: 12956 // These nodes' second result is a boolean. 12957 if (Op.getResNo() == 0) 12958 break; 12959 // Fallthrough 12960 case X86ISD::SETCC: 12961 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 12962 break; 12963 case ISD::INTRINSIC_WO_CHAIN: { 12964 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12965 unsigned NumLoBits = 0; 12966 switch (IntId) { 12967 default: break; 12968 case Intrinsic::x86_sse_movmsk_ps: 12969 case Intrinsic::x86_avx_movmsk_ps_256: 12970 case Intrinsic::x86_sse2_movmsk_pd: 12971 case Intrinsic::x86_avx_movmsk_pd_256: 12972 case Intrinsic::x86_mmx_pmovmskb: 12973 case Intrinsic::x86_sse2_pmovmskb_128: 12974 case Intrinsic::x86_avx2_pmovmskb: { 12975 // High bits of movmskp{s|d}, pmovmskb are known zero. 12976 switch (IntId) { 12977 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 12978 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break; 12979 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break; 12980 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break; 12981 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break; 12982 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break; 12983 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break; 12984 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break; 12985 } 12986 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits); 12987 break; 12988 } 12989 } 12990 break; 12991 } 12992 } 12993} 12994 12995unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 12996 unsigned Depth) const { 12997 // SETCC_CARRY sets the dest to ~0 for true or 0 for false. 12998 if (Op.getOpcode() == X86ISD::SETCC_CARRY) 12999 return Op.getValueType().getScalarType().getSizeInBits(); 13000 13001 // Fallback case. 13002 return 1; 13003} 13004 13005/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 13006/// node is a GlobalAddress + offset. 13007bool X86TargetLowering::isGAPlusOffset(SDNode *N, 13008 const GlobalValue* &GA, 13009 int64_t &Offset) const { 13010 if (N->getOpcode() == X86ISD::Wrapper) { 13011 if (isa<GlobalAddressSDNode>(N->getOperand(0))) { 13012 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal(); 13013 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset(); 13014 return true; 13015 } 13016 } 13017 return TargetLowering::isGAPlusOffset(N, GA, Offset); 13018} 13019 13020/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the 13021/// same as extracting the high 128-bit part of 256-bit vector and then 13022/// inserting the result into the low part of a new 256-bit vector 13023static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) { 13024 EVT VT = SVOp->getValueType(0); 13025 unsigned NumElems = VT.getVectorNumElements(); 13026 13027 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 13028 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j) 13029 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 13030 SVOp->getMaskElt(j) >= 0) 13031 return false; 13032 13033 return true; 13034} 13035 13036/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the 13037/// same as extracting the low 128-bit part of 256-bit vector and then 13038/// inserting the result into the high part of a new 256-bit vector 13039static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) { 13040 EVT VT = SVOp->getValueType(0); 13041 unsigned NumElems = VT.getVectorNumElements(); 13042 13043 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 13044 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j) 13045 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 13046 SVOp->getMaskElt(j) >= 0) 13047 return false; 13048 13049 return true; 13050} 13051 13052/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors. 13053static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG, 13054 TargetLowering::DAGCombinerInfo &DCI, 13055 const X86Subtarget* Subtarget) { 13056 DebugLoc dl = N->getDebugLoc(); 13057 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 13058 SDValue V1 = SVOp->getOperand(0); 13059 SDValue V2 = SVOp->getOperand(1); 13060 EVT VT = SVOp->getValueType(0); 13061 unsigned NumElems = VT.getVectorNumElements(); 13062 13063 if (V1.getOpcode() == ISD::CONCAT_VECTORS && 13064 V2.getOpcode() == ISD::CONCAT_VECTORS) { 13065 // 13066 // 0,0,0,... 13067 // | 13068 // V UNDEF BUILD_VECTOR UNDEF 13069 // \ / \ / 13070 // CONCAT_VECTOR CONCAT_VECTOR 13071 // \ / 13072 // \ / 13073 // RESULT: V + zero extended 13074 // 13075 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR || 13076 V2.getOperand(1).getOpcode() != ISD::UNDEF || 13077 V1.getOperand(1).getOpcode() != ISD::UNDEF) 13078 return SDValue(); 13079 13080 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode())) 13081 return SDValue(); 13082 13083 // To match the shuffle mask, the first half of the mask should 13084 // be exactly the first vector, and all the rest a splat with the 13085 // first element of the second one. 13086 for (unsigned i = 0; i != NumElems/2; ++i) 13087 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) || 13088 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems)) 13089 return SDValue(); 13090 13091 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD. 13092 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) { 13093 if (Ld->hasNUsesOfValue(1, 0)) { 13094 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other); 13095 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() }; 13096 SDValue ResNode = 13097 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2, 13098 Ld->getMemoryVT(), 13099 Ld->getPointerInfo(), 13100 Ld->getAlignment(), 13101 false/*isVolatile*/, true/*ReadMem*/, 13102 false/*WriteMem*/); 13103 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode); 13104 } 13105 } 13106 13107 // Emit a zeroed vector and insert the desired subvector on its 13108 // first half. 13109 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl); 13110 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl); 13111 return DCI.CombineTo(N, InsV); 13112 } 13113 13114 //===--------------------------------------------------------------------===// 13115 // Combine some shuffles into subvector extracts and inserts: 13116 // 13117 13118 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 13119 if (isShuffleHigh128VectorInsertLow(SVOp)) { 13120 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl); 13121 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl); 13122 return DCI.CombineTo(N, InsV); 13123 } 13124 13125 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 13126 if (isShuffleLow128VectorInsertHigh(SVOp)) { 13127 SDValue V = Extract128BitVector(V1, 0, DAG, dl); 13128 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl); 13129 return DCI.CombineTo(N, InsV); 13130 } 13131 13132 return SDValue(); 13133} 13134 13135/// PerformShuffleCombine - Performs several different shuffle combines. 13136static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG, 13137 TargetLowering::DAGCombinerInfo &DCI, 13138 const X86Subtarget *Subtarget) { 13139 DebugLoc dl = N->getDebugLoc(); 13140 EVT VT = N->getValueType(0); 13141 13142 // Don't create instructions with illegal types after legalize types has run. 13143 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13144 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType())) 13145 return SDValue(); 13146 13147 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode 13148 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 && 13149 N->getOpcode() == ISD::VECTOR_SHUFFLE) 13150 return PerformShuffleCombine256(N, DAG, DCI, Subtarget); 13151 13152 // Only handle 128 wide vector from here on. 13153 if (VT.getSizeInBits() != 128) 13154 return SDValue(); 13155 13156 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3, 13157 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are 13158 // consecutive, non-overlapping, and in the right order. 13159 SmallVector<SDValue, 16> Elts; 13160 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 13161 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0)); 13162 13163 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG); 13164} 13165 13166 13167/// DCI, PerformTruncateCombine - Converts truncate operation to 13168/// a sequence of vector shuffle operations. 13169/// It is possible when we truncate 256-bit vector to 128-bit vector 13170 13171SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG, 13172 DAGCombinerInfo &DCI) const { 13173 if (!DCI.isBeforeLegalizeOps()) 13174 return SDValue(); 13175 13176 if (!Subtarget->hasAVX()) 13177 return SDValue(); 13178 13179 EVT VT = N->getValueType(0); 13180 SDValue Op = N->getOperand(0); 13181 EVT OpVT = Op.getValueType(); 13182 DebugLoc dl = N->getDebugLoc(); 13183 13184 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) { 13185 13186 if (Subtarget->hasAVX2()) { 13187 // AVX2: v4i64 -> v4i32 13188 13189 // VPERMD 13190 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1}; 13191 13192 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op); 13193 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32), 13194 ShufMask); 13195 13196 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op, 13197 DAG.getIntPtrConstant(0)); 13198 } 13199 13200 // AVX: v4i64 -> v4i32 13201 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op, 13202 DAG.getIntPtrConstant(0)); 13203 13204 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op, 13205 DAG.getIntPtrConstant(2)); 13206 13207 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo); 13208 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi); 13209 13210 // PSHUFD 13211 static const int ShufMask1[] = {0, 2, 0, 0}; 13212 13213 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1); 13214 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1); 13215 13216 // MOVLHPS 13217 static const int ShufMask2[] = {0, 1, 4, 5}; 13218 13219 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2); 13220 } 13221 13222 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) { 13223 13224 if (Subtarget->hasAVX2()) { 13225 // AVX2: v8i32 -> v8i16 13226 13227 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op); 13228 13229 // PSHUFB 13230 SmallVector<SDValue,32> pshufbMask; 13231 for (unsigned i = 0; i < 2; ++i) { 13232 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8)); 13233 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8)); 13234 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8)); 13235 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8)); 13236 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8)); 13237 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8)); 13238 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8)); 13239 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8)); 13240 for (unsigned j = 0; j < 8; ++j) 13241 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 13242 } 13243 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8, 13244 &pshufbMask[0], 32); 13245 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV); 13246 13247 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op); 13248 13249 static const int ShufMask[] = {0, 2, -1, -1}; 13250 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64), 13251 &ShufMask[0]); 13252 13253 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op, 13254 DAG.getIntPtrConstant(0)); 13255 13256 return DAG.getNode(ISD::BITCAST, dl, VT, Op); 13257 } 13258 13259 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op, 13260 DAG.getIntPtrConstant(0)); 13261 13262 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op, 13263 DAG.getIntPtrConstant(4)); 13264 13265 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo); 13266 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi); 13267 13268 // PSHUFB 13269 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13, 13270 -1, -1, -1, -1, -1, -1, -1, -1}; 13271 13272 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8), 13273 ShufMask1); 13274 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8), 13275 ShufMask1); 13276 13277 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo); 13278 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi); 13279 13280 // MOVLHPS 13281 static const int ShufMask2[] = {0, 1, 4, 5}; 13282 13283 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2); 13284 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res); 13285 } 13286 13287 return SDValue(); 13288} 13289 13290/// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target 13291/// specific shuffle of a load can be folded into a single element load. 13292/// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but 13293/// shuffles have been customed lowered so we need to handle those here. 13294static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG, 13295 TargetLowering::DAGCombinerInfo &DCI) { 13296 if (DCI.isBeforeLegalizeOps()) 13297 return SDValue(); 13298 13299 SDValue InVec = N->getOperand(0); 13300 SDValue EltNo = N->getOperand(1); 13301 13302 if (!isa<ConstantSDNode>(EltNo)) 13303 return SDValue(); 13304 13305 EVT VT = InVec.getValueType(); 13306 13307 bool HasShuffleIntoBitcast = false; 13308 if (InVec.getOpcode() == ISD::BITCAST) { 13309 // Don't duplicate a load with other uses. 13310 if (!InVec.hasOneUse()) 13311 return SDValue(); 13312 EVT BCVT = InVec.getOperand(0).getValueType(); 13313 if (BCVT.getVectorNumElements() != VT.getVectorNumElements()) 13314 return SDValue(); 13315 InVec = InVec.getOperand(0); 13316 HasShuffleIntoBitcast = true; 13317 } 13318 13319 if (!isTargetShuffle(InVec.getOpcode())) 13320 return SDValue(); 13321 13322 // Don't duplicate a load with other uses. 13323 if (!InVec.hasOneUse()) 13324 return SDValue(); 13325 13326 SmallVector<int, 16> ShuffleMask; 13327 bool UnaryShuffle; 13328 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask, 13329 UnaryShuffle)) 13330 return SDValue(); 13331 13332 // Select the input vector, guarding against out of range extract vector. 13333 unsigned NumElems = VT.getVectorNumElements(); 13334 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 13335 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt]; 13336 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0) 13337 : InVec.getOperand(1); 13338 13339 // If inputs to shuffle are the same for both ops, then allow 2 uses 13340 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1; 13341 13342 if (LdNode.getOpcode() == ISD::BITCAST) { 13343 // Don't duplicate a load with other uses. 13344 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0)) 13345 return SDValue(); 13346 13347 AllowedUses = 1; // only allow 1 load use if we have a bitcast 13348 LdNode = LdNode.getOperand(0); 13349 } 13350 13351 if (!ISD::isNormalLoad(LdNode.getNode())) 13352 return SDValue(); 13353 13354 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode); 13355 13356 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile()) 13357 return SDValue(); 13358 13359 if (HasShuffleIntoBitcast) { 13360 // If there's a bitcast before the shuffle, check if the load type and 13361 // alignment is valid. 13362 unsigned Align = LN0->getAlignment(); 13363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13364 unsigned NewAlign = TLI.getTargetData()-> 13365 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 13366 13367 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT)) 13368 return SDValue(); 13369 } 13370 13371 // All checks match so transform back to vector_shuffle so that DAG combiner 13372 // can finish the job 13373 DebugLoc dl = N->getDebugLoc(); 13374 13375 // Create shuffle node taking into account the case that its a unary shuffle 13376 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1); 13377 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl, 13378 InVec.getOperand(0), Shuffle, 13379 &ShuffleMask[0]); 13380 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 13381 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle, 13382 EltNo); 13383} 13384 13385/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index 13386/// generation and convert it from being a bunch of shuffles and extracts 13387/// to a simple store and scalar loads to extract the elements. 13388static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG, 13389 TargetLowering::DAGCombinerInfo &DCI) { 13390 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI); 13391 if (NewOp.getNode()) 13392 return NewOp; 13393 13394 SDValue InputVector = N->getOperand(0); 13395 13396 // Only operate on vectors of 4 elements, where the alternative shuffling 13397 // gets to be more expensive. 13398 if (InputVector.getValueType() != MVT::v4i32) 13399 return SDValue(); 13400 13401 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a 13402 // single use which is a sign-extend or zero-extend, and all elements are 13403 // used. 13404 SmallVector<SDNode *, 4> Uses; 13405 unsigned ExtractedElements = 0; 13406 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(), 13407 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) { 13408 if (UI.getUse().getResNo() != InputVector.getResNo()) 13409 return SDValue(); 13410 13411 SDNode *Extract = *UI; 13412 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13413 return SDValue(); 13414 13415 if (Extract->getValueType(0) != MVT::i32) 13416 return SDValue(); 13417 if (!Extract->hasOneUse()) 13418 return SDValue(); 13419 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND && 13420 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND) 13421 return SDValue(); 13422 if (!isa<ConstantSDNode>(Extract->getOperand(1))) 13423 return SDValue(); 13424 13425 // Record which element was extracted. 13426 ExtractedElements |= 13427 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue(); 13428 13429 Uses.push_back(Extract); 13430 } 13431 13432 // If not all the elements were used, this may not be worthwhile. 13433 if (ExtractedElements != 15) 13434 return SDValue(); 13435 13436 // Ok, we've now decided to do the transformation. 13437 DebugLoc dl = InputVector.getDebugLoc(); 13438 13439 // Store the value to a temporary stack slot. 13440 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType()); 13441 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, 13442 MachinePointerInfo(), false, false, 0); 13443 13444 // Replace each use (extract) with a load of the appropriate element. 13445 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(), 13446 UE = Uses.end(); UI != UE; ++UI) { 13447 SDNode *Extract = *UI; 13448 13449 // cOMpute the element's address. 13450 SDValue Idx = Extract->getOperand(1); 13451 unsigned EltSize = 13452 InputVector.getValueType().getVectorElementType().getSizeInBits()/8; 13453 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue(); 13454 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13455 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy()); 13456 13457 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), 13458 StackPtr, OffsetVal); 13459 13460 // Load the scalar. 13461 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, 13462 ScalarAddr, MachinePointerInfo(), 13463 false, false, false, 0); 13464 13465 // Replace the exact with the load. 13466 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar); 13467 } 13468 13469 // The replacement was made in place; don't return anything. 13470 return SDValue(); 13471} 13472 13473/// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT 13474/// nodes. 13475static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG, 13476 TargetLowering::DAGCombinerInfo &DCI, 13477 const X86Subtarget *Subtarget) { 13478 DebugLoc DL = N->getDebugLoc(); 13479 SDValue Cond = N->getOperand(0); 13480 // Get the LHS/RHS of the select. 13481 SDValue LHS = N->getOperand(1); 13482 SDValue RHS = N->getOperand(2); 13483 EVT VT = LHS.getValueType(); 13484 13485 // If we have SSE[12] support, try to form min/max nodes. SSE min/max 13486 // instructions match the semantics of the common C idiom x<y?x:y but not 13487 // x<=y?x:y, because of how they handle negative zero (which can be 13488 // ignored in unsafe-math mode). 13489 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() && 13490 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) && 13491 (Subtarget->hasSSE2() || 13492 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) { 13493 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 13494 13495 unsigned Opcode = 0; 13496 // Check for x CC y ? x : y. 13497 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) && 13498 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 13499 switch (CC) { 13500 default: break; 13501 case ISD::SETULT: 13502 // Converting this to a min would handle NaNs incorrectly, and swapping 13503 // the operands would cause it to handle comparisons between positive 13504 // and negative zero incorrectly. 13505 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 13506 if (!DAG.getTarget().Options.UnsafeFPMath && 13507 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 13508 break; 13509 std::swap(LHS, RHS); 13510 } 13511 Opcode = X86ISD::FMIN; 13512 break; 13513 case ISD::SETOLE: 13514 // Converting this to a min would handle comparisons between positive 13515 // and negative zero incorrectly. 13516 if (!DAG.getTarget().Options.UnsafeFPMath && 13517 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 13518 break; 13519 Opcode = X86ISD::FMIN; 13520 break; 13521 case ISD::SETULE: 13522 // Converting this to a min would handle both negative zeros and NaNs 13523 // incorrectly, but we can swap the operands to fix both. 13524 std::swap(LHS, RHS); 13525 case ISD::SETOLT: 13526 case ISD::SETLT: 13527 case ISD::SETLE: 13528 Opcode = X86ISD::FMIN; 13529 break; 13530 13531 case ISD::SETOGE: 13532 // Converting this to a max would handle comparisons between positive 13533 // and negative zero incorrectly. 13534 if (!DAG.getTarget().Options.UnsafeFPMath && 13535 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 13536 break; 13537 Opcode = X86ISD::FMAX; 13538 break; 13539 case ISD::SETUGT: 13540 // Converting this to a max would handle NaNs incorrectly, and swapping 13541 // the operands would cause it to handle comparisons between positive 13542 // and negative zero incorrectly. 13543 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 13544 if (!DAG.getTarget().Options.UnsafeFPMath && 13545 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 13546 break; 13547 std::swap(LHS, RHS); 13548 } 13549 Opcode = X86ISD::FMAX; 13550 break; 13551 case ISD::SETUGE: 13552 // Converting this to a max would handle both negative zeros and NaNs 13553 // incorrectly, but we can swap the operands to fix both. 13554 std::swap(LHS, RHS); 13555 case ISD::SETOGT: 13556 case ISD::SETGT: 13557 case ISD::SETGE: 13558 Opcode = X86ISD::FMAX; 13559 break; 13560 } 13561 // Check for x CC y ? y : x -- a min/max with reversed arms. 13562 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) && 13563 DAG.isEqualTo(RHS, Cond.getOperand(0))) { 13564 switch (CC) { 13565 default: break; 13566 case ISD::SETOGE: 13567 // Converting this to a min would handle comparisons between positive 13568 // and negative zero incorrectly, and swapping the operands would 13569 // cause it to handle NaNs incorrectly. 13570 if (!DAG.getTarget().Options.UnsafeFPMath && 13571 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) { 13572 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 13573 break; 13574 std::swap(LHS, RHS); 13575 } 13576 Opcode = X86ISD::FMIN; 13577 break; 13578 case ISD::SETUGT: 13579 // Converting this to a min would handle NaNs incorrectly. 13580 if (!DAG.getTarget().Options.UnsafeFPMath && 13581 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) 13582 break; 13583 Opcode = X86ISD::FMIN; 13584 break; 13585 case ISD::SETUGE: 13586 // Converting this to a min would handle both negative zeros and NaNs 13587 // incorrectly, but we can swap the operands to fix both. 13588 std::swap(LHS, RHS); 13589 case ISD::SETOGT: 13590 case ISD::SETGT: 13591 case ISD::SETGE: 13592 Opcode = X86ISD::FMIN; 13593 break; 13594 13595 case ISD::SETULT: 13596 // Converting this to a max would handle NaNs incorrectly. 13597 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 13598 break; 13599 Opcode = X86ISD::FMAX; 13600 break; 13601 case ISD::SETOLE: 13602 // Converting this to a max would handle comparisons between positive 13603 // and negative zero incorrectly, and swapping the operands would 13604 // cause it to handle NaNs incorrectly. 13605 if (!DAG.getTarget().Options.UnsafeFPMath && 13606 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) { 13607 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 13608 break; 13609 std::swap(LHS, RHS); 13610 } 13611 Opcode = X86ISD::FMAX; 13612 break; 13613 case ISD::SETULE: 13614 // Converting this to a max would handle both negative zeros and NaNs 13615 // incorrectly, but we can swap the operands to fix both. 13616 std::swap(LHS, RHS); 13617 case ISD::SETOLT: 13618 case ISD::SETLT: 13619 case ISD::SETLE: 13620 Opcode = X86ISD::FMAX; 13621 break; 13622 } 13623 } 13624 13625 if (Opcode) 13626 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS); 13627 } 13628 13629 // If this is a select between two integer constants, try to do some 13630 // optimizations. 13631 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) { 13632 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS)) 13633 // Don't do this for crazy integer types. 13634 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) { 13635 // If this is efficiently invertible, canonicalize the LHSC/RHSC values 13636 // so that TrueC (the true value) is larger than FalseC. 13637 bool NeedsCondInvert = false; 13638 13639 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) && 13640 // Efficiently invertible. 13641 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible. 13642 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible. 13643 isa<ConstantSDNode>(Cond.getOperand(1))))) { 13644 NeedsCondInvert = true; 13645 std::swap(TrueC, FalseC); 13646 } 13647 13648 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0. 13649 if (FalseC->getAPIntValue() == 0 && 13650 TrueC->getAPIntValue().isPowerOf2()) { 13651 if (NeedsCondInvert) // Invert the condition if needed. 13652 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 13653 DAG.getConstant(1, Cond.getValueType())); 13654 13655 // Zero extend the condition if needed. 13656 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond); 13657 13658 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 13659 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond, 13660 DAG.getConstant(ShAmt, MVT::i8)); 13661 } 13662 13663 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. 13664 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 13665 if (NeedsCondInvert) // Invert the condition if needed. 13666 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 13667 DAG.getConstant(1, Cond.getValueType())); 13668 13669 // Zero extend the condition if needed. 13670 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 13671 FalseC->getValueType(0), Cond); 13672 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 13673 SDValue(FalseC, 0)); 13674 } 13675 13676 // Optimize cases that will turn into an LEA instruction. This requires 13677 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 13678 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 13679 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 13680 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 13681 13682 bool isFastMultiplier = false; 13683 if (Diff < 10) { 13684 switch ((unsigned char)Diff) { 13685 default: break; 13686 case 1: // result = add base, cond 13687 case 2: // result = lea base( , cond*2) 13688 case 3: // result = lea base(cond, cond*2) 13689 case 4: // result = lea base( , cond*4) 13690 case 5: // result = lea base(cond, cond*4) 13691 case 8: // result = lea base( , cond*8) 13692 case 9: // result = lea base(cond, cond*8) 13693 isFastMultiplier = true; 13694 break; 13695 } 13696 } 13697 13698 if (isFastMultiplier) { 13699 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 13700 if (NeedsCondInvert) // Invert the condition if needed. 13701 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 13702 DAG.getConstant(1, Cond.getValueType())); 13703 13704 // Zero extend the condition if needed. 13705 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 13706 Cond); 13707 // Scale the condition by the difference. 13708 if (Diff != 1) 13709 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 13710 DAG.getConstant(Diff, Cond.getValueType())); 13711 13712 // Add the base if non-zero. 13713 if (FalseC->getAPIntValue() != 0) 13714 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 13715 SDValue(FalseC, 0)); 13716 return Cond; 13717 } 13718 } 13719 } 13720 } 13721 13722 // Canonicalize max and min: 13723 // (x > y) ? x : y -> (x >= y) ? x : y 13724 // (x < y) ? x : y -> (x <= y) ? x : y 13725 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates 13726 // the need for an extra compare 13727 // against zero. e.g. 13728 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0 13729 // subl %esi, %edi 13730 // testl %edi, %edi 13731 // movl $0, %eax 13732 // cmovgl %edi, %eax 13733 // => 13734 // xorl %eax, %eax 13735 // subl %esi, $edi 13736 // cmovsl %eax, %edi 13737 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC && 13738 DAG.isEqualTo(LHS, Cond.getOperand(0)) && 13739 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 13740 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 13741 switch (CC) { 13742 default: break; 13743 case ISD::SETLT: 13744 case ISD::SETGT: { 13745 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE; 13746 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(), 13747 Cond.getOperand(0), Cond.getOperand(1), NewCC); 13748 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS); 13749 } 13750 } 13751 } 13752 13753 // If we know that this node is legal then we know that it is going to be 13754 // matched by one of the SSE/AVX BLEND instructions. These instructions only 13755 // depend on the highest bit in each word. Try to use SimplifyDemandedBits 13756 // to simplify previous instructions. 13757 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13758 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() && 13759 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) { 13760 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits(); 13761 13762 // Don't optimize vector selects that map to mask-registers. 13763 if (BitWidth == 1) 13764 return SDValue(); 13765 13766 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size"); 13767 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1); 13768 13769 APInt KnownZero, KnownOne; 13770 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(), 13771 DCI.isBeforeLegalizeOps()); 13772 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) || 13773 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO)) 13774 DCI.CommitTargetLoweringOpt(TLO); 13775 } 13776 13777 return SDValue(); 13778} 13779 13780// Check whether a boolean test is testing a boolean value generated by 13781// X86ISD::SETCC. If so, return the operand of that SETCC and proper condition 13782// code. 13783// 13784// Simplify the following patterns: 13785// (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or 13786// (Op (CMP (SETCC Cond EFLAGS) 0) NEQ) 13787// to (Op EFLAGS Cond) 13788// 13789// (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or 13790// (Op (CMP (SETCC Cond EFLAGS) 1) NEQ) 13791// to (Op EFLAGS !Cond) 13792// 13793// where Op could be BRCOND or CMOV. 13794// 13795static SDValue BoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) { 13796 // Quit if not CMP and SUB with its value result used. 13797 if (Cmp.getOpcode() != X86ISD::CMP && 13798 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0))) 13799 return SDValue(); 13800 13801 // Quit if not used as a boolean value. 13802 if (CC != X86::COND_E && CC != X86::COND_NE) 13803 return SDValue(); 13804 13805 // Check CMP operands. One of them should be 0 or 1 and the other should be 13806 // an SetCC or extended from it. 13807 SDValue Op1 = Cmp.getOperand(0); 13808 SDValue Op2 = Cmp.getOperand(1); 13809 13810 SDValue SetCC; 13811 const ConstantSDNode* C = 0; 13812 bool needOppositeCond = (CC == X86::COND_E); 13813 13814 if ((C = dyn_cast<ConstantSDNode>(Op1))) 13815 SetCC = Op2; 13816 else if ((C = dyn_cast<ConstantSDNode>(Op2))) 13817 SetCC = Op1; 13818 else // Quit if all operands are not constants. 13819 return SDValue(); 13820 13821 if (C->getZExtValue() == 1) 13822 needOppositeCond = !needOppositeCond; 13823 else if (C->getZExtValue() != 0) 13824 // Quit if the constant is neither 0 or 1. 13825 return SDValue(); 13826 13827 // Skip 'zext' node. 13828 if (SetCC.getOpcode() == ISD::ZERO_EXTEND) 13829 SetCC = SetCC.getOperand(0); 13830 13831 // Quit if not SETCC. 13832 // FIXME: So far we only handle the boolean value generated from SETCC. If 13833 // there is other ways to generate boolean values, we need handle them here 13834 // as well. 13835 if (SetCC.getOpcode() != X86ISD::SETCC) 13836 return SDValue(); 13837 13838 // Set the condition code or opposite one if necessary. 13839 CC = X86::CondCode(SetCC.getConstantOperandVal(0)); 13840 if (needOppositeCond) 13841 CC = X86::GetOppositeBranchCondition(CC); 13842 13843 return SetCC.getOperand(1); 13844} 13845 13846static bool IsValidFCMOVCondition(X86::CondCode CC) { 13847 switch (CC) { 13848 default: 13849 return false; 13850 case X86::COND_B: 13851 case X86::COND_BE: 13852 case X86::COND_E: 13853 case X86::COND_P: 13854 case X86::COND_AE: 13855 case X86::COND_A: 13856 case X86::COND_NE: 13857 case X86::COND_NP: 13858 return true; 13859 } 13860} 13861 13862/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL] 13863static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG, 13864 TargetLowering::DAGCombinerInfo &DCI) { 13865 DebugLoc DL = N->getDebugLoc(); 13866 13867 // If the flag operand isn't dead, don't touch this CMOV. 13868 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty()) 13869 return SDValue(); 13870 13871 SDValue FalseOp = N->getOperand(0); 13872 SDValue TrueOp = N->getOperand(1); 13873 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2); 13874 SDValue Cond = N->getOperand(3); 13875 13876 if (CC == X86::COND_E || CC == X86::COND_NE) { 13877 switch (Cond.getOpcode()) { 13878 default: break; 13879 case X86ISD::BSR: 13880 case X86ISD::BSF: 13881 // If operand of BSR / BSF are proven never zero, then ZF cannot be set. 13882 if (DAG.isKnownNeverZero(Cond.getOperand(0))) 13883 return (CC == X86::COND_E) ? FalseOp : TrueOp; 13884 } 13885 } 13886 13887 SDValue Flags; 13888 13889 Flags = BoolTestSetCCCombine(Cond, CC); 13890 if (Flags.getNode() && 13891 // Extra check as FCMOV only supports a subset of X86 cond. 13892 (FalseOp.getValueType() != MVT::f80 || IsValidFCMOVCondition(CC))) { 13893 SDValue Ops[] = { FalseOp, TrueOp, 13894 DAG.getConstant(CC, MVT::i8), Flags }; 13895 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), 13896 Ops, array_lengthof(Ops)); 13897 } 13898 13899 // If this is a select between two integer constants, try to do some 13900 // optimizations. Note that the operands are ordered the opposite of SELECT 13901 // operands. 13902 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) { 13903 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) { 13904 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is 13905 // larger than FalseC (the false value). 13906 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) { 13907 CC = X86::GetOppositeBranchCondition(CC); 13908 std::swap(TrueC, FalseC); 13909 } 13910 13911 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0. 13912 // This is efficient for any integer data type (including i8/i16) and 13913 // shift amount. 13914 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) { 13915 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 13916 DAG.getConstant(CC, MVT::i8), Cond); 13917 13918 // Zero extend the condition if needed. 13919 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond); 13920 13921 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 13922 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond, 13923 DAG.getConstant(ShAmt, MVT::i8)); 13924 if (N->getNumValues() == 2) // Dead flag value? 13925 return DCI.CombineTo(N, Cond, SDValue()); 13926 return Cond; 13927 } 13928 13929 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient 13930 // for any integer data type, including i8/i16. 13931 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 13932 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 13933 DAG.getConstant(CC, MVT::i8), Cond); 13934 13935 // Zero extend the condition if needed. 13936 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 13937 FalseC->getValueType(0), Cond); 13938 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 13939 SDValue(FalseC, 0)); 13940 13941 if (N->getNumValues() == 2) // Dead flag value? 13942 return DCI.CombineTo(N, Cond, SDValue()); 13943 return Cond; 13944 } 13945 13946 // Optimize cases that will turn into an LEA instruction. This requires 13947 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 13948 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 13949 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 13950 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 13951 13952 bool isFastMultiplier = false; 13953 if (Diff < 10) { 13954 switch ((unsigned char)Diff) { 13955 default: break; 13956 case 1: // result = add base, cond 13957 case 2: // result = lea base( , cond*2) 13958 case 3: // result = lea base(cond, cond*2) 13959 case 4: // result = lea base( , cond*4) 13960 case 5: // result = lea base(cond, cond*4) 13961 case 8: // result = lea base( , cond*8) 13962 case 9: // result = lea base(cond, cond*8) 13963 isFastMultiplier = true; 13964 break; 13965 } 13966 } 13967 13968 if (isFastMultiplier) { 13969 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 13970 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 13971 DAG.getConstant(CC, MVT::i8), Cond); 13972 // Zero extend the condition if needed. 13973 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 13974 Cond); 13975 // Scale the condition by the difference. 13976 if (Diff != 1) 13977 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 13978 DAG.getConstant(Diff, Cond.getValueType())); 13979 13980 // Add the base if non-zero. 13981 if (FalseC->getAPIntValue() != 0) 13982 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 13983 SDValue(FalseC, 0)); 13984 if (N->getNumValues() == 2) // Dead flag value? 13985 return DCI.CombineTo(N, Cond, SDValue()); 13986 return Cond; 13987 } 13988 } 13989 } 13990 } 13991 return SDValue(); 13992} 13993 13994 13995/// PerformMulCombine - Optimize a single multiply with constant into two 13996/// in order to implement it with two cheaper instructions, e.g. 13997/// LEA + SHL, LEA + LEA. 13998static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG, 13999 TargetLowering::DAGCombinerInfo &DCI) { 14000 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14001 return SDValue(); 14002 14003 EVT VT = N->getValueType(0); 14004 if (VT != MVT::i64) 14005 return SDValue(); 14006 14007 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14008 if (!C) 14009 return SDValue(); 14010 uint64_t MulAmt = C->getZExtValue(); 14011 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9) 14012 return SDValue(); 14013 14014 uint64_t MulAmt1 = 0; 14015 uint64_t MulAmt2 = 0; 14016 if ((MulAmt % 9) == 0) { 14017 MulAmt1 = 9; 14018 MulAmt2 = MulAmt / 9; 14019 } else if ((MulAmt % 5) == 0) { 14020 MulAmt1 = 5; 14021 MulAmt2 = MulAmt / 5; 14022 } else if ((MulAmt % 3) == 0) { 14023 MulAmt1 = 3; 14024 MulAmt2 = MulAmt / 3; 14025 } 14026 if (MulAmt2 && 14027 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){ 14028 DebugLoc DL = N->getDebugLoc(); 14029 14030 if (isPowerOf2_64(MulAmt2) && 14031 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD)) 14032 // If second multiplifer is pow2, issue it first. We want the multiply by 14033 // 3, 5, or 9 to be folded into the addressing mode unless the lone use 14034 // is an add. 14035 std::swap(MulAmt1, MulAmt2); 14036 14037 SDValue NewMul; 14038 if (isPowerOf2_64(MulAmt1)) 14039 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 14040 DAG.getConstant(Log2_64(MulAmt1), MVT::i8)); 14041 else 14042 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0), 14043 DAG.getConstant(MulAmt1, VT)); 14044 14045 if (isPowerOf2_64(MulAmt2)) 14046 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul, 14047 DAG.getConstant(Log2_64(MulAmt2), MVT::i8)); 14048 else 14049 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul, 14050 DAG.getConstant(MulAmt2, VT)); 14051 14052 // Do not add new nodes to DAG combiner worklist. 14053 DCI.CombineTo(N, NewMul, false); 14054 } 14055 return SDValue(); 14056} 14057 14058static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) { 14059 SDValue N0 = N->getOperand(0); 14060 SDValue N1 = N->getOperand(1); 14061 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 14062 EVT VT = N0.getValueType(); 14063 14064 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2)) 14065 // since the result of setcc_c is all zero's or all ones. 14066 if (VT.isInteger() && !VT.isVector() && 14067 N1C && N0.getOpcode() == ISD::AND && 14068 N0.getOperand(1).getOpcode() == ISD::Constant) { 14069 SDValue N00 = N0.getOperand(0); 14070 if (N00.getOpcode() == X86ISD::SETCC_CARRY || 14071 ((N00.getOpcode() == ISD::ANY_EXTEND || 14072 N00.getOpcode() == ISD::ZERO_EXTEND) && 14073 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) { 14074 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 14075 APInt ShAmt = N1C->getAPIntValue(); 14076 Mask = Mask.shl(ShAmt); 14077 if (Mask != 0) 14078 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 14079 N00, DAG.getConstant(Mask, VT)); 14080 } 14081 } 14082 14083 14084 // Hardware support for vector shifts is sparse which makes us scalarize the 14085 // vector operations in many cases. Also, on sandybridge ADD is faster than 14086 // shl. 14087 // (shl V, 1) -> add V,V 14088 if (isSplatVector(N1.getNode())) { 14089 assert(N0.getValueType().isVector() && "Invalid vector shift type"); 14090 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0)); 14091 // We shift all of the values by one. In many cases we do not have 14092 // hardware support for this operation. This is better expressed as an ADD 14093 // of two values. 14094 if (N1C && (1 == N1C->getZExtValue())) { 14095 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0); 14096 } 14097 } 14098 14099 return SDValue(); 14100} 14101 14102/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts 14103/// when possible. 14104static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG, 14105 TargetLowering::DAGCombinerInfo &DCI, 14106 const X86Subtarget *Subtarget) { 14107 EVT VT = N->getValueType(0); 14108 if (N->getOpcode() == ISD::SHL) { 14109 SDValue V = PerformSHLCombine(N, DAG); 14110 if (V.getNode()) return V; 14111 } 14112 14113 // On X86 with SSE2 support, we can transform this to a vector shift if 14114 // all elements are shifted by the same amount. We can't do this in legalize 14115 // because the a constant vector is typically transformed to a constant pool 14116 // so we have no knowledge of the shift amount. 14117 if (!Subtarget->hasSSE2()) 14118 return SDValue(); 14119 14120 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 && 14121 (!Subtarget->hasAVX2() || 14122 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16))) 14123 return SDValue(); 14124 14125 SDValue ShAmtOp = N->getOperand(1); 14126 EVT EltVT = VT.getVectorElementType(); 14127 DebugLoc DL = N->getDebugLoc(); 14128 SDValue BaseShAmt = SDValue(); 14129 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) { 14130 unsigned NumElts = VT.getVectorNumElements(); 14131 unsigned i = 0; 14132 for (; i != NumElts; ++i) { 14133 SDValue Arg = ShAmtOp.getOperand(i); 14134 if (Arg.getOpcode() == ISD::UNDEF) continue; 14135 BaseShAmt = Arg; 14136 break; 14137 } 14138 // Handle the case where the build_vector is all undef 14139 // FIXME: Should DAG allow this? 14140 if (i == NumElts) 14141 return SDValue(); 14142 14143 for (; i != NumElts; ++i) { 14144 SDValue Arg = ShAmtOp.getOperand(i); 14145 if (Arg.getOpcode() == ISD::UNDEF) continue; 14146 if (Arg != BaseShAmt) { 14147 return SDValue(); 14148 } 14149 } 14150 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE && 14151 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) { 14152 SDValue InVec = ShAmtOp.getOperand(0); 14153 if (InVec.getOpcode() == ISD::BUILD_VECTOR) { 14154 unsigned NumElts = InVec.getValueType().getVectorNumElements(); 14155 unsigned i = 0; 14156 for (; i != NumElts; ++i) { 14157 SDValue Arg = InVec.getOperand(i); 14158 if (Arg.getOpcode() == ISD::UNDEF) continue; 14159 BaseShAmt = Arg; 14160 break; 14161 } 14162 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) { 14163 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) { 14164 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex(); 14165 if (C->getZExtValue() == SplatIdx) 14166 BaseShAmt = InVec.getOperand(1); 14167 } 14168 } 14169 if (BaseShAmt.getNode() == 0) { 14170 // Don't create instructions with illegal types after legalize 14171 // types has run. 14172 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) && 14173 !DCI.isBeforeLegalize()) 14174 return SDValue(); 14175 14176 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp, 14177 DAG.getIntPtrConstant(0)); 14178 } 14179 } else 14180 return SDValue(); 14181 14182 // The shift amount is an i32. 14183 if (EltVT.bitsGT(MVT::i32)) 14184 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt); 14185 else if (EltVT.bitsLT(MVT::i32)) 14186 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt); 14187 14188 // The shift amount is identical so we can do a vector shift. 14189 SDValue ValOp = N->getOperand(0); 14190 switch (N->getOpcode()) { 14191 default: 14192 llvm_unreachable("Unknown shift opcode!"); 14193 case ISD::SHL: 14194 switch (VT.getSimpleVT().SimpleTy) { 14195 default: return SDValue(); 14196 case MVT::v2i64: 14197 case MVT::v4i32: 14198 case MVT::v8i16: 14199 case MVT::v4i64: 14200 case MVT::v8i32: 14201 case MVT::v16i16: 14202 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG); 14203 } 14204 case ISD::SRA: 14205 switch (VT.getSimpleVT().SimpleTy) { 14206 default: return SDValue(); 14207 case MVT::v4i32: 14208 case MVT::v8i16: 14209 case MVT::v8i32: 14210 case MVT::v16i16: 14211 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG); 14212 } 14213 case ISD::SRL: 14214 switch (VT.getSimpleVT().SimpleTy) { 14215 default: return SDValue(); 14216 case MVT::v2i64: 14217 case MVT::v4i32: 14218 case MVT::v8i16: 14219 case MVT::v4i64: 14220 case MVT::v8i32: 14221 case MVT::v16i16: 14222 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG); 14223 } 14224 } 14225} 14226 14227 14228// CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..)) 14229// where both setccs reference the same FP CMP, and rewrite for CMPEQSS 14230// and friends. Likewise for OR -> CMPNEQSS. 14231static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG, 14232 TargetLowering::DAGCombinerInfo &DCI, 14233 const X86Subtarget *Subtarget) { 14234 unsigned opcode; 14235 14236 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but 14237 // we're requiring SSE2 for both. 14238 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) { 14239 SDValue N0 = N->getOperand(0); 14240 SDValue N1 = N->getOperand(1); 14241 SDValue CMP0 = N0->getOperand(1); 14242 SDValue CMP1 = N1->getOperand(1); 14243 DebugLoc DL = N->getDebugLoc(); 14244 14245 // The SETCCs should both refer to the same CMP. 14246 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1) 14247 return SDValue(); 14248 14249 SDValue CMP00 = CMP0->getOperand(0); 14250 SDValue CMP01 = CMP0->getOperand(1); 14251 EVT VT = CMP00.getValueType(); 14252 14253 if (VT == MVT::f32 || VT == MVT::f64) { 14254 bool ExpectingFlags = false; 14255 // Check for any users that want flags: 14256 for (SDNode::use_iterator UI = N->use_begin(), 14257 UE = N->use_end(); 14258 !ExpectingFlags && UI != UE; ++UI) 14259 switch (UI->getOpcode()) { 14260 default: 14261 case ISD::BR_CC: 14262 case ISD::BRCOND: 14263 case ISD::SELECT: 14264 ExpectingFlags = true; 14265 break; 14266 case ISD::CopyToReg: 14267 case ISD::SIGN_EXTEND: 14268 case ISD::ZERO_EXTEND: 14269 case ISD::ANY_EXTEND: 14270 break; 14271 } 14272 14273 if (!ExpectingFlags) { 14274 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0); 14275 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0); 14276 14277 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) { 14278 X86::CondCode tmp = cc0; 14279 cc0 = cc1; 14280 cc1 = tmp; 14281 } 14282 14283 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) || 14284 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) { 14285 bool is64BitFP = (CMP00.getValueType() == MVT::f64); 14286 X86ISD::NodeType NTOperator = is64BitFP ? 14287 X86ISD::FSETCCsd : X86ISD::FSETCCss; 14288 // FIXME: need symbolic constants for these magic numbers. 14289 // See X86ATTInstPrinter.cpp:printSSECC(). 14290 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4; 14291 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01, 14292 DAG.getConstant(x86cc, MVT::i8)); 14293 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32, 14294 OnesOrZeroesF); 14295 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI, 14296 DAG.getConstant(1, MVT::i32)); 14297 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed); 14298 return OneBitOfTruth; 14299 } 14300 } 14301 } 14302 } 14303 return SDValue(); 14304} 14305 14306/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector 14307/// so it can be folded inside ANDNP. 14308static bool CanFoldXORWithAllOnes(const SDNode *N) { 14309 EVT VT = N->getValueType(0); 14310 14311 // Match direct AllOnes for 128 and 256-bit vectors 14312 if (ISD::isBuildVectorAllOnes(N)) 14313 return true; 14314 14315 // Look through a bit convert. 14316 if (N->getOpcode() == ISD::BITCAST) 14317 N = N->getOperand(0).getNode(); 14318 14319 // Sometimes the operand may come from a insert_subvector building a 256-bit 14320 // allones vector 14321 if (VT.getSizeInBits() == 256 && 14322 N->getOpcode() == ISD::INSERT_SUBVECTOR) { 14323 SDValue V1 = N->getOperand(0); 14324 SDValue V2 = N->getOperand(1); 14325 14326 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR && 14327 V1.getOperand(0).getOpcode() == ISD::UNDEF && 14328 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) && 14329 ISD::isBuildVectorAllOnes(V2.getNode())) 14330 return true; 14331 } 14332 14333 return false; 14334} 14335 14336static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG, 14337 TargetLowering::DAGCombinerInfo &DCI, 14338 const X86Subtarget *Subtarget) { 14339 if (DCI.isBeforeLegalizeOps()) 14340 return SDValue(); 14341 14342 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 14343 if (R.getNode()) 14344 return R; 14345 14346 EVT VT = N->getValueType(0); 14347 14348 // Create ANDN, BLSI, and BLSR instructions 14349 // BLSI is X & (-X) 14350 // BLSR is X & (X-1) 14351 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) { 14352 SDValue N0 = N->getOperand(0); 14353 SDValue N1 = N->getOperand(1); 14354 DebugLoc DL = N->getDebugLoc(); 14355 14356 // Check LHS for not 14357 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1))) 14358 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1); 14359 // Check RHS for not 14360 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1))) 14361 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0); 14362 14363 // Check LHS for neg 14364 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 && 14365 isZero(N0.getOperand(0))) 14366 return DAG.getNode(X86ISD::BLSI, DL, VT, N1); 14367 14368 // Check RHS for neg 14369 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 && 14370 isZero(N1.getOperand(0))) 14371 return DAG.getNode(X86ISD::BLSI, DL, VT, N0); 14372 14373 // Check LHS for X-1 14374 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 && 14375 isAllOnes(N0.getOperand(1))) 14376 return DAG.getNode(X86ISD::BLSR, DL, VT, N1); 14377 14378 // Check RHS for X-1 14379 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 && 14380 isAllOnes(N1.getOperand(1))) 14381 return DAG.getNode(X86ISD::BLSR, DL, VT, N0); 14382 14383 return SDValue(); 14384 } 14385 14386 // Want to form ANDNP nodes: 14387 // 1) In the hopes of then easily combining them with OR and AND nodes 14388 // to form PBLEND/PSIGN. 14389 // 2) To match ANDN packed intrinsics 14390 if (VT != MVT::v2i64 && VT != MVT::v4i64) 14391 return SDValue(); 14392 14393 SDValue N0 = N->getOperand(0); 14394 SDValue N1 = N->getOperand(1); 14395 DebugLoc DL = N->getDebugLoc(); 14396 14397 // Check LHS for vnot 14398 if (N0.getOpcode() == ISD::XOR && 14399 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode())) 14400 CanFoldXORWithAllOnes(N0.getOperand(1).getNode())) 14401 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1); 14402 14403 // Check RHS for vnot 14404 if (N1.getOpcode() == ISD::XOR && 14405 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode())) 14406 CanFoldXORWithAllOnes(N1.getOperand(1).getNode())) 14407 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0); 14408 14409 return SDValue(); 14410} 14411 14412static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG, 14413 TargetLowering::DAGCombinerInfo &DCI, 14414 const X86Subtarget *Subtarget) { 14415 if (DCI.isBeforeLegalizeOps()) 14416 return SDValue(); 14417 14418 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 14419 if (R.getNode()) 14420 return R; 14421 14422 EVT VT = N->getValueType(0); 14423 14424 SDValue N0 = N->getOperand(0); 14425 SDValue N1 = N->getOperand(1); 14426 14427 // look for psign/blend 14428 if (VT == MVT::v2i64 || VT == MVT::v4i64) { 14429 if (!Subtarget->hasSSSE3() || 14430 (VT == MVT::v4i64 && !Subtarget->hasAVX2())) 14431 return SDValue(); 14432 14433 // Canonicalize pandn to RHS 14434 if (N0.getOpcode() == X86ISD::ANDNP) 14435 std::swap(N0, N1); 14436 // or (and (m, y), (pandn m, x)) 14437 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) { 14438 SDValue Mask = N1.getOperand(0); 14439 SDValue X = N1.getOperand(1); 14440 SDValue Y; 14441 if (N0.getOperand(0) == Mask) 14442 Y = N0.getOperand(1); 14443 if (N0.getOperand(1) == Mask) 14444 Y = N0.getOperand(0); 14445 14446 // Check to see if the mask appeared in both the AND and ANDNP and 14447 if (!Y.getNode()) 14448 return SDValue(); 14449 14450 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them. 14451 // Look through mask bitcast. 14452 if (Mask.getOpcode() == ISD::BITCAST) 14453 Mask = Mask.getOperand(0); 14454 if (X.getOpcode() == ISD::BITCAST) 14455 X = X.getOperand(0); 14456 if (Y.getOpcode() == ISD::BITCAST) 14457 Y = Y.getOperand(0); 14458 14459 EVT MaskVT = Mask.getValueType(); 14460 14461 // Validate that the Mask operand is a vector sra node. 14462 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but 14463 // there is no psrai.b 14464 if (Mask.getOpcode() != X86ISD::VSRAI) 14465 return SDValue(); 14466 14467 // Check that the SRA is all signbits. 14468 SDValue SraC = Mask.getOperand(1); 14469 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue(); 14470 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits(); 14471 if ((SraAmt + 1) != EltBits) 14472 return SDValue(); 14473 14474 DebugLoc DL = N->getDebugLoc(); 14475 14476 // Now we know we at least have a plendvb with the mask val. See if 14477 // we can form a psignb/w/d. 14478 // psign = x.type == y.type == mask.type && y = sub(0, x); 14479 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X && 14480 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) && 14481 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) { 14482 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) && 14483 "Unsupported VT for PSIGN"); 14484 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0)); 14485 return DAG.getNode(ISD::BITCAST, DL, VT, Mask); 14486 } 14487 // PBLENDVB only available on SSE 4.1 14488 if (!Subtarget->hasSSE41()) 14489 return SDValue(); 14490 14491 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8; 14492 14493 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X); 14494 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y); 14495 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask); 14496 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X); 14497 return DAG.getNode(ISD::BITCAST, DL, VT, Mask); 14498 } 14499 } 14500 14501 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 14502 return SDValue(); 14503 14504 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c) 14505 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 14506 std::swap(N0, N1); 14507 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 14508 return SDValue(); 14509 if (!N0.hasOneUse() || !N1.hasOneUse()) 14510 return SDValue(); 14511 14512 SDValue ShAmt0 = N0.getOperand(1); 14513 if (ShAmt0.getValueType() != MVT::i8) 14514 return SDValue(); 14515 SDValue ShAmt1 = N1.getOperand(1); 14516 if (ShAmt1.getValueType() != MVT::i8) 14517 return SDValue(); 14518 if (ShAmt0.getOpcode() == ISD::TRUNCATE) 14519 ShAmt0 = ShAmt0.getOperand(0); 14520 if (ShAmt1.getOpcode() == ISD::TRUNCATE) 14521 ShAmt1 = ShAmt1.getOperand(0); 14522 14523 DebugLoc DL = N->getDebugLoc(); 14524 unsigned Opc = X86ISD::SHLD; 14525 SDValue Op0 = N0.getOperand(0); 14526 SDValue Op1 = N1.getOperand(0); 14527 if (ShAmt0.getOpcode() == ISD::SUB) { 14528 Opc = X86ISD::SHRD; 14529 std::swap(Op0, Op1); 14530 std::swap(ShAmt0, ShAmt1); 14531 } 14532 14533 unsigned Bits = VT.getSizeInBits(); 14534 if (ShAmt1.getOpcode() == ISD::SUB) { 14535 SDValue Sum = ShAmt1.getOperand(0); 14536 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) { 14537 SDValue ShAmt1Op1 = ShAmt1.getOperand(1); 14538 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE) 14539 ShAmt1Op1 = ShAmt1Op1.getOperand(0); 14540 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0) 14541 return DAG.getNode(Opc, DL, VT, 14542 Op0, Op1, 14543 DAG.getNode(ISD::TRUNCATE, DL, 14544 MVT::i8, ShAmt0)); 14545 } 14546 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) { 14547 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0); 14548 if (ShAmt0C && 14549 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits) 14550 return DAG.getNode(Opc, DL, VT, 14551 N0.getOperand(0), N1.getOperand(0), 14552 DAG.getNode(ISD::TRUNCATE, DL, 14553 MVT::i8, ShAmt0)); 14554 } 14555 14556 return SDValue(); 14557} 14558 14559// Generate NEG and CMOV for integer abs. 14560static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 14561 EVT VT = N->getValueType(0); 14562 14563 // Since X86 does not have CMOV for 8-bit integer, we don't convert 14564 // 8-bit integer abs to NEG and CMOV. 14565 if (VT.isInteger() && VT.getSizeInBits() == 8) 14566 return SDValue(); 14567 14568 SDValue N0 = N->getOperand(0); 14569 SDValue N1 = N->getOperand(1); 14570 DebugLoc DL = N->getDebugLoc(); 14571 14572 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 14573 // and change it to SUB and CMOV. 14574 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 14575 N0.getOpcode() == ISD::ADD && 14576 N0.getOperand(1) == N1 && 14577 N1.getOpcode() == ISD::SRA && 14578 N1.getOperand(0) == N0.getOperand(0)) 14579 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 14580 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) { 14581 // Generate SUB & CMOV. 14582 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32), 14583 DAG.getConstant(0, VT), N0.getOperand(0)); 14584 14585 SDValue Ops[] = { N0.getOperand(0), Neg, 14586 DAG.getConstant(X86::COND_GE, MVT::i8), 14587 SDValue(Neg.getNode(), 1) }; 14588 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), 14589 Ops, array_lengthof(Ops)); 14590 } 14591 return SDValue(); 14592} 14593 14594// PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes 14595static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG, 14596 TargetLowering::DAGCombinerInfo &DCI, 14597 const X86Subtarget *Subtarget) { 14598 if (DCI.isBeforeLegalizeOps()) 14599 return SDValue(); 14600 14601 if (Subtarget->hasCMov()) { 14602 SDValue RV = performIntegerAbsCombine(N, DAG); 14603 if (RV.getNode()) 14604 return RV; 14605 } 14606 14607 // Try forming BMI if it is available. 14608 if (!Subtarget->hasBMI()) 14609 return SDValue(); 14610 14611 EVT VT = N->getValueType(0); 14612 14613 if (VT != MVT::i32 && VT != MVT::i64) 14614 return SDValue(); 14615 14616 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions"); 14617 14618 // Create BLSMSK instructions by finding X ^ (X-1) 14619 SDValue N0 = N->getOperand(0); 14620 SDValue N1 = N->getOperand(1); 14621 DebugLoc DL = N->getDebugLoc(); 14622 14623 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 && 14624 isAllOnes(N0.getOperand(1))) 14625 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1); 14626 14627 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 && 14628 isAllOnes(N1.getOperand(1))) 14629 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0); 14630 14631 return SDValue(); 14632} 14633 14634/// PerformLOADCombine - Do target-specific dag combines on LOAD nodes. 14635static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG, 14636 TargetLowering::DAGCombinerInfo &DCI, 14637 const X86Subtarget *Subtarget) { 14638 LoadSDNode *Ld = cast<LoadSDNode>(N); 14639 EVT RegVT = Ld->getValueType(0); 14640 EVT MemVT = Ld->getMemoryVT(); 14641 DebugLoc dl = Ld->getDebugLoc(); 14642 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14643 14644 ISD::LoadExtType Ext = Ld->getExtensionType(); 14645 14646 // If this is a vector EXT Load then attempt to optimize it using a 14647 // shuffle. We need SSE4 for the shuffles. 14648 // TODO: It is possible to support ZExt by zeroing the undef values 14649 // during the shuffle phase or after the shuffle. 14650 if (RegVT.isVector() && RegVT.isInteger() && 14651 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) { 14652 assert(MemVT != RegVT && "Cannot extend to the same type"); 14653 assert(MemVT.isVector() && "Must load a vector from memory"); 14654 14655 unsigned NumElems = RegVT.getVectorNumElements(); 14656 unsigned RegSz = RegVT.getSizeInBits(); 14657 unsigned MemSz = MemVT.getSizeInBits(); 14658 assert(RegSz > MemSz && "Register size must be greater than the mem size"); 14659 14660 // All sizes must be a power of two. 14661 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) 14662 return SDValue(); 14663 14664 // Attempt to load the original value using scalar loads. 14665 // Find the largest scalar type that divides the total loaded size. 14666 MVT SclrLoadTy = MVT::i8; 14667 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 14668 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 14669 MVT Tp = (MVT::SimpleValueType)tp; 14670 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) { 14671 SclrLoadTy = Tp; 14672 } 14673 } 14674 14675 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64. 14676 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 && 14677 (64 <= MemSz)) 14678 SclrLoadTy = MVT::f64; 14679 14680 // Calculate the number of scalar loads that we need to perform 14681 // in order to load our vector from memory. 14682 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits(); 14683 14684 // Represent our vector as a sequence of elements which are the 14685 // largest scalar that we can load. 14686 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy, 14687 RegSz/SclrLoadTy.getSizeInBits()); 14688 14689 // Represent the data using the same element type that is stored in 14690 // memory. In practice, we ''widen'' MemVT. 14691 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), 14692 RegSz/MemVT.getScalarType().getSizeInBits()); 14693 14694 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() && 14695 "Invalid vector type"); 14696 14697 // We can't shuffle using an illegal type. 14698 if (!TLI.isTypeLegal(WideVecVT)) 14699 return SDValue(); 14700 14701 SmallVector<SDValue, 8> Chains; 14702 SDValue Ptr = Ld->getBasePtr(); 14703 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8, 14704 TLI.getPointerTy()); 14705 SDValue Res = DAG.getUNDEF(LoadUnitVecVT); 14706 14707 for (unsigned i = 0; i < NumLoads; ++i) { 14708 // Perform a single load. 14709 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), 14710 Ptr, Ld->getPointerInfo(), 14711 Ld->isVolatile(), Ld->isNonTemporal(), 14712 Ld->isInvariant(), Ld->getAlignment()); 14713 Chains.push_back(ScalarLoad.getValue(1)); 14714 // Create the first element type using SCALAR_TO_VECTOR in order to avoid 14715 // another round of DAGCombining. 14716 if (i == 0) 14717 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad); 14718 else 14719 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res, 14720 ScalarLoad, DAG.getIntPtrConstant(i)); 14721 14722 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14723 } 14724 14725 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], 14726 Chains.size()); 14727 14728 // Bitcast the loaded value to a vector of the original element type, in 14729 // the size of the target vector type. 14730 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res); 14731 unsigned SizeRatio = RegSz/MemSz; 14732 14733 // Redistribute the loaded elements into the different locations. 14734 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 14735 for (unsigned i = 0; i != NumElems; ++i) 14736 ShuffleVec[i*SizeRatio] = i; 14737 14738 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec, 14739 DAG.getUNDEF(WideVecVT), 14740 &ShuffleVec[0]); 14741 14742 // Bitcast to the requested type. 14743 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff); 14744 // Replace the original load with the new sequence 14745 // and return the new chain. 14746 return DCI.CombineTo(N, Shuff, TF, true); 14747 } 14748 14749 return SDValue(); 14750} 14751 14752/// PerformSTORECombine - Do target-specific dag combines on STORE nodes. 14753static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG, 14754 const X86Subtarget *Subtarget) { 14755 StoreSDNode *St = cast<StoreSDNode>(N); 14756 EVT VT = St->getValue().getValueType(); 14757 EVT StVT = St->getMemoryVT(); 14758 DebugLoc dl = St->getDebugLoc(); 14759 SDValue StoredVal = St->getOperand(1); 14760 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14761 14762 // If we are saving a concatenation of two XMM registers, perform two stores. 14763 // On Sandy Bridge, 256-bit memory operations are executed by two 14764 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit 14765 // memory operation. 14766 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2() && 14767 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS && 14768 StoredVal.getNumOperands() == 2) { 14769 SDValue Value0 = StoredVal.getOperand(0); 14770 SDValue Value1 = StoredVal.getOperand(1); 14771 14772 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy()); 14773 SDValue Ptr0 = St->getBasePtr(); 14774 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride); 14775 14776 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0, 14777 St->getPointerInfo(), St->isVolatile(), 14778 St->isNonTemporal(), St->getAlignment()); 14779 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1, 14780 St->getPointerInfo(), St->isVolatile(), 14781 St->isNonTemporal(), St->getAlignment()); 14782 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1); 14783 } 14784 14785 // Optimize trunc store (of multiple scalars) to shuffle and store. 14786 // First, pack all of the elements in one place. Next, store to memory 14787 // in fewer chunks. 14788 if (St->isTruncatingStore() && VT.isVector()) { 14789 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14790 unsigned NumElems = VT.getVectorNumElements(); 14791 assert(StVT != VT && "Cannot truncate to the same type"); 14792 unsigned FromSz = VT.getVectorElementType().getSizeInBits(); 14793 unsigned ToSz = StVT.getVectorElementType().getSizeInBits(); 14794 14795 // From, To sizes and ElemCount must be pow of two 14796 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue(); 14797 // We are going to use the original vector elt for storing. 14798 // Accumulated smaller vector elements must be a multiple of the store size. 14799 if (0 != (NumElems * FromSz) % ToSz) return SDValue(); 14800 14801 unsigned SizeRatio = FromSz / ToSz; 14802 14803 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits()); 14804 14805 // Create a type on which we perform the shuffle 14806 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), 14807 StVT.getScalarType(), NumElems*SizeRatio); 14808 14809 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 14810 14811 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue()); 14812 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 14813 for (unsigned i = 0; i != NumElems; ++i) 14814 ShuffleVec[i] = i * SizeRatio; 14815 14816 // Can't shuffle using an illegal type. 14817 if (!TLI.isTypeLegal(WideVecVT)) 14818 return SDValue(); 14819 14820 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec, 14821 DAG.getUNDEF(WideVecVT), 14822 &ShuffleVec[0]); 14823 // At this point all of the data is stored at the bottom of the 14824 // register. We now need to save it to mem. 14825 14826 // Find the largest store unit 14827 MVT StoreType = MVT::i8; 14828 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 14829 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 14830 MVT Tp = (MVT::SimpleValueType)tp; 14831 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz) 14832 StoreType = Tp; 14833 } 14834 14835 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64. 14836 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 && 14837 (64 <= NumElems * ToSz)) 14838 StoreType = MVT::f64; 14839 14840 // Bitcast the original vector into a vector of store-size units 14841 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 14842 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits()); 14843 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 14844 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff); 14845 SmallVector<SDValue, 8> Chains; 14846 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, 14847 TLI.getPointerTy()); 14848 SDValue Ptr = St->getBasePtr(); 14849 14850 // Perform one or more big stores into memory. 14851 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) { 14852 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 14853 StoreType, ShuffWide, 14854 DAG.getIntPtrConstant(i)); 14855 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr, 14856 St->getPointerInfo(), St->isVolatile(), 14857 St->isNonTemporal(), St->getAlignment()); 14858 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14859 Chains.push_back(Ch); 14860 } 14861 14862 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], 14863 Chains.size()); 14864 } 14865 14866 14867 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering 14868 // the FP state in cases where an emms may be missing. 14869 // A preferable solution to the general problem is to figure out the right 14870 // places to insert EMMS. This qualifies as a quick hack. 14871 14872 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode. 14873 if (VT.getSizeInBits() != 64) 14874 return SDValue(); 14875 14876 const Function *F = DAG.getMachineFunction().getFunction(); 14877 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat); 14878 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps 14879 && Subtarget->hasSSE2(); 14880 if ((VT.isVector() || 14881 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) && 14882 isa<LoadSDNode>(St->getValue()) && 14883 !cast<LoadSDNode>(St->getValue())->isVolatile() && 14884 St->getChain().hasOneUse() && !St->isVolatile()) { 14885 SDNode* LdVal = St->getValue().getNode(); 14886 LoadSDNode *Ld = 0; 14887 int TokenFactorIndex = -1; 14888 SmallVector<SDValue, 8> Ops; 14889 SDNode* ChainVal = St->getChain().getNode(); 14890 // Must be a store of a load. We currently handle two cases: the load 14891 // is a direct child, and it's under an intervening TokenFactor. It is 14892 // possible to dig deeper under nested TokenFactors. 14893 if (ChainVal == LdVal) 14894 Ld = cast<LoadSDNode>(St->getChain()); 14895 else if (St->getValue().hasOneUse() && 14896 ChainVal->getOpcode() == ISD::TokenFactor) { 14897 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) { 14898 if (ChainVal->getOperand(i).getNode() == LdVal) { 14899 TokenFactorIndex = i; 14900 Ld = cast<LoadSDNode>(St->getValue()); 14901 } else 14902 Ops.push_back(ChainVal->getOperand(i)); 14903 } 14904 } 14905 14906 if (!Ld || !ISD::isNormalLoad(Ld)) 14907 return SDValue(); 14908 14909 // If this is not the MMX case, i.e. we are just turning i64 load/store 14910 // into f64 load/store, avoid the transformation if there are multiple 14911 // uses of the loaded value. 14912 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0)) 14913 return SDValue(); 14914 14915 DebugLoc LdDL = Ld->getDebugLoc(); 14916 DebugLoc StDL = N->getDebugLoc(); 14917 // If we are a 64-bit capable x86, lower to a single movq load/store pair. 14918 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store 14919 // pair instead. 14920 if (Subtarget->is64Bit() || F64IsLegal) { 14921 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64; 14922 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(), 14923 Ld->getPointerInfo(), Ld->isVolatile(), 14924 Ld->isNonTemporal(), Ld->isInvariant(), 14925 Ld->getAlignment()); 14926 SDValue NewChain = NewLd.getValue(1); 14927 if (TokenFactorIndex != -1) { 14928 Ops.push_back(NewChain); 14929 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 14930 Ops.size()); 14931 } 14932 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(), 14933 St->getPointerInfo(), 14934 St->isVolatile(), St->isNonTemporal(), 14935 St->getAlignment()); 14936 } 14937 14938 // Otherwise, lower to two pairs of 32-bit loads / stores. 14939 SDValue LoAddr = Ld->getBasePtr(); 14940 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr, 14941 DAG.getConstant(4, MVT::i32)); 14942 14943 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr, 14944 Ld->getPointerInfo(), 14945 Ld->isVolatile(), Ld->isNonTemporal(), 14946 Ld->isInvariant(), Ld->getAlignment()); 14947 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr, 14948 Ld->getPointerInfo().getWithOffset(4), 14949 Ld->isVolatile(), Ld->isNonTemporal(), 14950 Ld->isInvariant(), 14951 MinAlign(Ld->getAlignment(), 4)); 14952 14953 SDValue NewChain = LoLd.getValue(1); 14954 if (TokenFactorIndex != -1) { 14955 Ops.push_back(LoLd); 14956 Ops.push_back(HiLd); 14957 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 14958 Ops.size()); 14959 } 14960 14961 LoAddr = St->getBasePtr(); 14962 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr, 14963 DAG.getConstant(4, MVT::i32)); 14964 14965 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr, 14966 St->getPointerInfo(), 14967 St->isVolatile(), St->isNonTemporal(), 14968 St->getAlignment()); 14969 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr, 14970 St->getPointerInfo().getWithOffset(4), 14971 St->isVolatile(), 14972 St->isNonTemporal(), 14973 MinAlign(St->getAlignment(), 4)); 14974 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt); 14975 } 14976 return SDValue(); 14977} 14978 14979/// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal" 14980/// and return the operands for the horizontal operation in LHS and RHS. A 14981/// horizontal operation performs the binary operation on successive elements 14982/// of its first operand, then on successive elements of its second operand, 14983/// returning the resulting values in a vector. For example, if 14984/// A = < float a0, float a1, float a2, float a3 > 14985/// and 14986/// B = < float b0, float b1, float b2, float b3 > 14987/// then the result of doing a horizontal operation on A and B is 14988/// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >. 14989/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form 14990/// A horizontal-op B, for some already available A and B, and if so then LHS is 14991/// set to A, RHS to B, and the routine returns 'true'. 14992/// Note that the binary operation should have the property that if one of the 14993/// operands is UNDEF then the result is UNDEF. 14994static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) { 14995 // Look for the following pattern: if 14996 // A = < float a0, float a1, float a2, float a3 > 14997 // B = < float b0, float b1, float b2, float b3 > 14998 // and 14999 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6> 15000 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7> 15001 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 > 15002 // which is A horizontal-op B. 15003 15004 // At least one of the operands should be a vector shuffle. 15005 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 15006 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) 15007 return false; 15008 15009 EVT VT = LHS.getValueType(); 15010 15011 assert((VT.is128BitVector() || VT.is256BitVector()) && 15012 "Unsupported vector type for horizontal add/sub"); 15013 15014 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to 15015 // operate independently on 128-bit lanes. 15016 unsigned NumElts = VT.getVectorNumElements(); 15017 unsigned NumLanes = VT.getSizeInBits()/128; 15018 unsigned NumLaneElts = NumElts / NumLanes; 15019 assert((NumLaneElts % 2 == 0) && 15020 "Vector type should have an even number of elements in each lane"); 15021 unsigned HalfLaneElts = NumLaneElts/2; 15022 15023 // View LHS in the form 15024 // LHS = VECTOR_SHUFFLE A, B, LMask 15025 // If LHS is not a shuffle then pretend it is the shuffle 15026 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1> 15027 // NOTE: in what follows a default initialized SDValue represents an UNDEF of 15028 // type VT. 15029 SDValue A, B; 15030 SmallVector<int, 16> LMask(NumElts); 15031 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) { 15032 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF) 15033 A = LHS.getOperand(0); 15034 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF) 15035 B = LHS.getOperand(1); 15036 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(); 15037 std::copy(Mask.begin(), Mask.end(), LMask.begin()); 15038 } else { 15039 if (LHS.getOpcode() != ISD::UNDEF) 15040 A = LHS; 15041 for (unsigned i = 0; i != NumElts; ++i) 15042 LMask[i] = i; 15043 } 15044 15045 // Likewise, view RHS in the form 15046 // RHS = VECTOR_SHUFFLE C, D, RMask 15047 SDValue C, D; 15048 SmallVector<int, 16> RMask(NumElts); 15049 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) { 15050 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF) 15051 C = RHS.getOperand(0); 15052 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF) 15053 D = RHS.getOperand(1); 15054 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(); 15055 std::copy(Mask.begin(), Mask.end(), RMask.begin()); 15056 } else { 15057 if (RHS.getOpcode() != ISD::UNDEF) 15058 C = RHS; 15059 for (unsigned i = 0; i != NumElts; ++i) 15060 RMask[i] = i; 15061 } 15062 15063 // Check that the shuffles are both shuffling the same vectors. 15064 if (!(A == C && B == D) && !(A == D && B == C)) 15065 return false; 15066 15067 // If everything is UNDEF then bail out: it would be better to fold to UNDEF. 15068 if (!A.getNode() && !B.getNode()) 15069 return false; 15070 15071 // If A and B occur in reverse order in RHS, then "swap" them (which means 15072 // rewriting the mask). 15073 if (A != C) 15074 CommuteVectorShuffleMask(RMask, NumElts); 15075 15076 // At this point LHS and RHS are equivalent to 15077 // LHS = VECTOR_SHUFFLE A, B, LMask 15078 // RHS = VECTOR_SHUFFLE A, B, RMask 15079 // Check that the masks correspond to performing a horizontal operation. 15080 for (unsigned i = 0; i != NumElts; ++i) { 15081 int LIdx = LMask[i], RIdx = RMask[i]; 15082 15083 // Ignore any UNDEF components. 15084 if (LIdx < 0 || RIdx < 0 || 15085 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) || 15086 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts))) 15087 continue; 15088 15089 // Check that successive elements are being operated on. If not, this is 15090 // not a horizontal operation. 15091 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs 15092 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts; 15093 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart; 15094 if (!(LIdx == Index && RIdx == Index + 1) && 15095 !(IsCommutative && LIdx == Index + 1 && RIdx == Index)) 15096 return false; 15097 } 15098 15099 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it. 15100 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it. 15101 return true; 15102} 15103 15104/// PerformFADDCombine - Do target-specific dag combines on floating point adds. 15105static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG, 15106 const X86Subtarget *Subtarget) { 15107 EVT VT = N->getValueType(0); 15108 SDValue LHS = N->getOperand(0); 15109 SDValue RHS = N->getOperand(1); 15110 15111 // Try to synthesize horizontal adds from adds of shuffles. 15112 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) || 15113 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) && 15114 isHorizontalBinOp(LHS, RHS, true)) 15115 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS); 15116 return SDValue(); 15117} 15118 15119/// PerformFSUBCombine - Do target-specific dag combines on floating point subs. 15120static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG, 15121 const X86Subtarget *Subtarget) { 15122 EVT VT = N->getValueType(0); 15123 SDValue LHS = N->getOperand(0); 15124 SDValue RHS = N->getOperand(1); 15125 15126 // Try to synthesize horizontal subs from subs of shuffles. 15127 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) || 15128 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) && 15129 isHorizontalBinOp(LHS, RHS, false)) 15130 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS); 15131 return SDValue(); 15132} 15133 15134/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and 15135/// X86ISD::FXOR nodes. 15136static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) { 15137 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR); 15138 // F[X]OR(0.0, x) -> x 15139 // F[X]OR(x, 0.0) -> x 15140 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 15141 if (C->getValueAPF().isPosZero()) 15142 return N->getOperand(1); 15143 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 15144 if (C->getValueAPF().isPosZero()) 15145 return N->getOperand(0); 15146 return SDValue(); 15147} 15148 15149/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes. 15150static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) { 15151 // FAND(0.0, x) -> 0.0 15152 // FAND(x, 0.0) -> 0.0 15153 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 15154 if (C->getValueAPF().isPosZero()) 15155 return N->getOperand(0); 15156 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 15157 if (C->getValueAPF().isPosZero()) 15158 return N->getOperand(1); 15159 return SDValue(); 15160} 15161 15162static SDValue PerformBTCombine(SDNode *N, 15163 SelectionDAG &DAG, 15164 TargetLowering::DAGCombinerInfo &DCI) { 15165 // BT ignores high bits in the bit index operand. 15166 SDValue Op1 = N->getOperand(1); 15167 if (Op1.hasOneUse()) { 15168 unsigned BitWidth = Op1.getValueSizeInBits(); 15169 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth)); 15170 APInt KnownZero, KnownOne; 15171 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 15172 !DCI.isBeforeLegalizeOps()); 15173 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15174 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) || 15175 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO)) 15176 DCI.CommitTargetLoweringOpt(TLO); 15177 } 15178 return SDValue(); 15179} 15180 15181static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) { 15182 SDValue Op = N->getOperand(0); 15183 if (Op.getOpcode() == ISD::BITCAST) 15184 Op = Op.getOperand(0); 15185 EVT VT = N->getValueType(0), OpVT = Op.getValueType(); 15186 if (Op.getOpcode() == X86ISD::VZEXT_LOAD && 15187 VT.getVectorElementType().getSizeInBits() == 15188 OpVT.getVectorElementType().getSizeInBits()) { 15189 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op); 15190 } 15191 return SDValue(); 15192} 15193 15194static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG, 15195 TargetLowering::DAGCombinerInfo &DCI, 15196 const X86Subtarget *Subtarget) { 15197 if (!DCI.isBeforeLegalizeOps()) 15198 return SDValue(); 15199 15200 if (!Subtarget->hasAVX()) 15201 return SDValue(); 15202 15203 EVT VT = N->getValueType(0); 15204 SDValue Op = N->getOperand(0); 15205 EVT OpVT = Op.getValueType(); 15206 DebugLoc dl = N->getDebugLoc(); 15207 15208 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) || 15209 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) { 15210 15211 if (Subtarget->hasAVX2()) 15212 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op); 15213 15214 // Optimize vectors in AVX mode 15215 // Sign extend v8i16 to v8i32 and 15216 // v4i32 to v4i64 15217 // 15218 // Divide input vector into two parts 15219 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1} 15220 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32 15221 // concat the vectors to original VT 15222 15223 unsigned NumElems = OpVT.getVectorNumElements(); 15224 SmallVector<int,8> ShufMask1(NumElems, -1); 15225 for (unsigned i = 0; i != NumElems/2; ++i) 15226 ShufMask1[i] = i; 15227 15228 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT), 15229 &ShufMask1[0]); 15230 15231 SmallVector<int,8> ShufMask2(NumElems, -1); 15232 for (unsigned i = 0; i != NumElems/2; ++i) 15233 ShufMask2[i] = i + NumElems/2; 15234 15235 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT), 15236 &ShufMask2[0]); 15237 15238 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 15239 VT.getVectorNumElements()/2); 15240 15241 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo); 15242 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi); 15243 15244 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi); 15245 } 15246 return SDValue(); 15247} 15248 15249static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG, 15250 const X86Subtarget* Subtarget) { 15251 DebugLoc dl = N->getDebugLoc(); 15252 EVT VT = N->getValueType(0); 15253 15254 EVT ScalarVT = VT.getScalarType(); 15255 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasFMA()) 15256 return SDValue(); 15257 15258 SDValue A = N->getOperand(0); 15259 SDValue B = N->getOperand(1); 15260 SDValue C = N->getOperand(2); 15261 15262 bool NegA = (A.getOpcode() == ISD::FNEG); 15263 bool NegB = (B.getOpcode() == ISD::FNEG); 15264 bool NegC = (C.getOpcode() == ISD::FNEG); 15265 15266 // Negative multiplication when NegA xor NegB 15267 bool NegMul = (NegA != NegB); 15268 if (NegA) 15269 A = A.getOperand(0); 15270 if (NegB) 15271 B = B.getOperand(0); 15272 if (NegC) 15273 C = C.getOperand(0); 15274 15275 unsigned Opcode; 15276 if (!NegMul) 15277 Opcode = (!NegC)? X86ISD::FMADD : X86ISD::FMSUB; 15278 else 15279 Opcode = (!NegC)? X86ISD::FNMADD : X86ISD::FNMSUB; 15280 return DAG.getNode(Opcode, dl, VT, A, B, C); 15281} 15282 15283static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG, 15284 TargetLowering::DAGCombinerInfo &DCI, 15285 const X86Subtarget *Subtarget) { 15286 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) -> 15287 // (and (i32 x86isd::setcc_carry), 1) 15288 // This eliminates the zext. This transformation is necessary because 15289 // ISD::SETCC is always legalized to i8. 15290 DebugLoc dl = N->getDebugLoc(); 15291 SDValue N0 = N->getOperand(0); 15292 EVT VT = N->getValueType(0); 15293 EVT OpVT = N0.getValueType(); 15294 15295 if (N0.getOpcode() == ISD::AND && 15296 N0.hasOneUse() && 15297 N0.getOperand(0).hasOneUse()) { 15298 SDValue N00 = N0.getOperand(0); 15299 if (N00.getOpcode() != X86ISD::SETCC_CARRY) 15300 return SDValue(); 15301 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 15302 if (!C || C->getZExtValue() != 1) 15303 return SDValue(); 15304 return DAG.getNode(ISD::AND, dl, VT, 15305 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, 15306 N00.getOperand(0), N00.getOperand(1)), 15307 DAG.getConstant(1, VT)); 15308 } 15309 15310 // Optimize vectors in AVX mode: 15311 // 15312 // v8i16 -> v8i32 15313 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32. 15314 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32. 15315 // Concat upper and lower parts. 15316 // 15317 // v4i32 -> v4i64 15318 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64. 15319 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64. 15320 // Concat upper and lower parts. 15321 // 15322 if (!DCI.isBeforeLegalizeOps()) 15323 return SDValue(); 15324 15325 if (!Subtarget->hasAVX()) 15326 return SDValue(); 15327 15328 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) || 15329 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) { 15330 15331 if (Subtarget->hasAVX2()) 15332 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0); 15333 15334 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl); 15335 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec); 15336 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec); 15337 15338 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 15339 VT.getVectorNumElements()/2); 15340 15341 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo); 15342 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi); 15343 15344 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi); 15345 } 15346 15347 return SDValue(); 15348} 15349 15350// Optimize x == -y --> x+y == 0 15351// x != -y --> x+y != 0 15352static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) { 15353 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 15354 SDValue LHS = N->getOperand(0); 15355 SDValue RHS = N->getOperand(1); 15356 15357 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB) 15358 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0))) 15359 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) { 15360 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(), 15361 LHS.getValueType(), RHS, LHS.getOperand(1)); 15362 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0), 15363 addV, DAG.getConstant(0, addV.getValueType()), CC); 15364 } 15365 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB) 15366 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0))) 15367 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) { 15368 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(), 15369 RHS.getValueType(), LHS, RHS.getOperand(1)); 15370 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0), 15371 addV, DAG.getConstant(0, addV.getValueType()), CC); 15372 } 15373 return SDValue(); 15374} 15375 15376// Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT 15377static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) { 15378 DebugLoc DL = N->getDebugLoc(); 15379 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0)); 15380 SDValue EFLAGS = N->getOperand(1); 15381 15382 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without 15383 // a zext and produces an all-ones bit which is more useful than 0/1 in some 15384 // cases. 15385 if (CC == X86::COND_B) 15386 return DAG.getNode(ISD::AND, DL, MVT::i8, 15387 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8, 15388 DAG.getConstant(CC, MVT::i8), EFLAGS), 15389 DAG.getConstant(1, MVT::i8)); 15390 15391 SDValue Flags; 15392 15393 Flags = BoolTestSetCCCombine(EFLAGS, CC); 15394 if (Flags.getNode()) { 15395 SDValue Cond = DAG.getConstant(CC, MVT::i8); 15396 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags); 15397 } 15398 15399 return SDValue(); 15400} 15401 15402// Optimize branch condition evaluation. 15403// 15404static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG, 15405 TargetLowering::DAGCombinerInfo &DCI, 15406 const X86Subtarget *Subtarget) { 15407 DebugLoc DL = N->getDebugLoc(); 15408 SDValue Chain = N->getOperand(0); 15409 SDValue Dest = N->getOperand(1); 15410 SDValue EFLAGS = N->getOperand(3); 15411 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2)); 15412 15413 SDValue Flags; 15414 15415 Flags = BoolTestSetCCCombine(EFLAGS, CC); 15416 if (Flags.getNode()) { 15417 SDValue Cond = DAG.getConstant(CC, MVT::i8); 15418 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond, 15419 Flags); 15420 } 15421 15422 return SDValue(); 15423} 15424 15425static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) { 15426 SDValue Op0 = N->getOperand(0); 15427 EVT InVT = Op0->getValueType(0); 15428 15429 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32)) 15430 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) { 15431 DebugLoc dl = N->getDebugLoc(); 15432 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32; 15433 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0); 15434 // Notice that we use SINT_TO_FP because we know that the high bits 15435 // are zero and SINT_TO_FP is better supported by the hardware. 15436 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P); 15437 } 15438 15439 return SDValue(); 15440} 15441 15442static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG, 15443 const X86TargetLowering *XTLI) { 15444 SDValue Op0 = N->getOperand(0); 15445 EVT InVT = Op0->getValueType(0); 15446 15447 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32)) 15448 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) { 15449 DebugLoc dl = N->getDebugLoc(); 15450 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32; 15451 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0); 15452 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P); 15453 } 15454 15455 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have 15456 // a 32-bit target where SSE doesn't support i64->FP operations. 15457 if (Op0.getOpcode() == ISD::LOAD) { 15458 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode()); 15459 EVT VT = Ld->getValueType(0); 15460 if (!Ld->isVolatile() && !N->getValueType(0).isVector() && 15461 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() && 15462 !XTLI->getSubtarget()->is64Bit() && 15463 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 15464 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0), 15465 Ld->getChain(), Op0, DAG); 15466 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1)); 15467 return FILDChain; 15468 } 15469 } 15470 return SDValue(); 15471} 15472 15473static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) { 15474 EVT VT = N->getValueType(0); 15475 15476 // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT() 15477 if (VT == MVT::v8i8 || VT == MVT::v4i8) { 15478 DebugLoc dl = N->getDebugLoc(); 15479 MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32; 15480 SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0)); 15481 return DAG.getNode(ISD::TRUNCATE, dl, VT, I); 15482 } 15483 15484 return SDValue(); 15485} 15486 15487// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS 15488static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG, 15489 X86TargetLowering::DAGCombinerInfo &DCI) { 15490 // If the LHS and RHS of the ADC node are zero, then it can't overflow and 15491 // the result is either zero or one (depending on the input carry bit). 15492 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1. 15493 if (X86::isZeroNode(N->getOperand(0)) && 15494 X86::isZeroNode(N->getOperand(1)) && 15495 // We don't have a good way to replace an EFLAGS use, so only do this when 15496 // dead right now. 15497 SDValue(N, 1).use_empty()) { 15498 DebugLoc DL = N->getDebugLoc(); 15499 EVT VT = N->getValueType(0); 15500 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1)); 15501 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT, 15502 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, 15503 DAG.getConstant(X86::COND_B,MVT::i8), 15504 N->getOperand(2)), 15505 DAG.getConstant(1, VT)); 15506 return DCI.CombineTo(N, Res1, CarryOut); 15507 } 15508 15509 return SDValue(); 15510} 15511 15512// fold (add Y, (sete X, 0)) -> adc 0, Y 15513// (add Y, (setne X, 0)) -> sbb -1, Y 15514// (sub (sete X, 0), Y) -> sbb 0, Y 15515// (sub (setne X, 0), Y) -> adc -1, Y 15516static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) { 15517 DebugLoc DL = N->getDebugLoc(); 15518 15519 // Look through ZExts. 15520 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0); 15521 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse()) 15522 return SDValue(); 15523 15524 SDValue SetCC = Ext.getOperand(0); 15525 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse()) 15526 return SDValue(); 15527 15528 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0); 15529 if (CC != X86::COND_E && CC != X86::COND_NE) 15530 return SDValue(); 15531 15532 SDValue Cmp = SetCC.getOperand(1); 15533 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() || 15534 !X86::isZeroNode(Cmp.getOperand(1)) || 15535 !Cmp.getOperand(0).getValueType().isInteger()) 15536 return SDValue(); 15537 15538 SDValue CmpOp0 = Cmp.getOperand(0); 15539 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0, 15540 DAG.getConstant(1, CmpOp0.getValueType())); 15541 15542 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1); 15543 if (CC == X86::COND_NE) 15544 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB, 15545 DL, OtherVal.getValueType(), OtherVal, 15546 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp); 15547 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC, 15548 DL, OtherVal.getValueType(), OtherVal, 15549 DAG.getConstant(0, OtherVal.getValueType()), NewCmp); 15550} 15551 15552/// PerformADDCombine - Do target-specific dag combines on integer adds. 15553static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG, 15554 const X86Subtarget *Subtarget) { 15555 EVT VT = N->getValueType(0); 15556 SDValue Op0 = N->getOperand(0); 15557 SDValue Op1 = N->getOperand(1); 15558 15559 // Try to synthesize horizontal adds from adds of shuffles. 15560 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) || 15561 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) && 15562 isHorizontalBinOp(Op0, Op1, true)) 15563 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1); 15564 15565 return OptimizeConditionalInDecrement(N, DAG); 15566} 15567 15568static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG, 15569 const X86Subtarget *Subtarget) { 15570 SDValue Op0 = N->getOperand(0); 15571 SDValue Op1 = N->getOperand(1); 15572 15573 // X86 can't encode an immediate LHS of a sub. See if we can push the 15574 // negation into a preceding instruction. 15575 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) { 15576 // If the RHS of the sub is a XOR with one use and a constant, invert the 15577 // immediate. Then add one to the LHS of the sub so we can turn 15578 // X-Y -> X+~Y+1, saving one register. 15579 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR && 15580 isa<ConstantSDNode>(Op1.getOperand(1))) { 15581 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue(); 15582 EVT VT = Op0.getValueType(); 15583 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT, 15584 Op1.getOperand(0), 15585 DAG.getConstant(~XorC, VT)); 15586 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor, 15587 DAG.getConstant(C->getAPIntValue()+1, VT)); 15588 } 15589 } 15590 15591 // Try to synthesize horizontal adds from adds of shuffles. 15592 EVT VT = N->getValueType(0); 15593 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) || 15594 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) && 15595 isHorizontalBinOp(Op0, Op1, true)) 15596 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1); 15597 15598 return OptimizeConditionalInDecrement(N, DAG); 15599} 15600 15601SDValue X86TargetLowering::PerformDAGCombine(SDNode *N, 15602 DAGCombinerInfo &DCI) const { 15603 SelectionDAG &DAG = DCI.DAG; 15604 switch (N->getOpcode()) { 15605 default: break; 15606 case ISD::EXTRACT_VECTOR_ELT: 15607 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI); 15608 case ISD::VSELECT: 15609 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget); 15610 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI); 15611 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget); 15612 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget); 15613 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI); 15614 case ISD::MUL: return PerformMulCombine(N, DAG, DCI); 15615 case ISD::SHL: 15616 case ISD::SRA: 15617 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget); 15618 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget); 15619 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget); 15620 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget); 15621 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget); 15622 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget); 15623 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG); 15624 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this); 15625 case ISD::FP_TO_SINT: return PerformFP_TO_SINTCombine(N, DAG); 15626 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget); 15627 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget); 15628 case X86ISD::FXOR: 15629 case X86ISD::FOR: return PerformFORCombine(N, DAG); 15630 case X86ISD::FAND: return PerformFANDCombine(N, DAG); 15631 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI); 15632 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG); 15633 case ISD::ANY_EXTEND: 15634 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget); 15635 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget); 15636 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG, DCI); 15637 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG); 15638 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG); 15639 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget); 15640 case X86ISD::SHUFP: // Handle all target specific shuffles 15641 case X86ISD::PALIGN: 15642 case X86ISD::UNPCKH: 15643 case X86ISD::UNPCKL: 15644 case X86ISD::MOVHLPS: 15645 case X86ISD::MOVLHPS: 15646 case X86ISD::PSHUFD: 15647 case X86ISD::PSHUFHW: 15648 case X86ISD::PSHUFLW: 15649 case X86ISD::MOVSS: 15650 case X86ISD::MOVSD: 15651 case X86ISD::VPERMILP: 15652 case X86ISD::VPERM2X128: 15653 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget); 15654 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget); 15655 } 15656 15657 return SDValue(); 15658} 15659 15660/// isTypeDesirableForOp - Return true if the target has native support for 15661/// the specified value type and it is 'desirable' to use the type for the 15662/// given node type. e.g. On x86 i16 is legal, but undesirable since i16 15663/// instruction encodings are longer and some i16 instructions are slow. 15664bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const { 15665 if (!isTypeLegal(VT)) 15666 return false; 15667 if (VT != MVT::i16) 15668 return true; 15669 15670 switch (Opc) { 15671 default: 15672 return true; 15673 case ISD::LOAD: 15674 case ISD::SIGN_EXTEND: 15675 case ISD::ZERO_EXTEND: 15676 case ISD::ANY_EXTEND: 15677 case ISD::SHL: 15678 case ISD::SRL: 15679 case ISD::SUB: 15680 case ISD::ADD: 15681 case ISD::MUL: 15682 case ISD::AND: 15683 case ISD::OR: 15684 case ISD::XOR: 15685 return false; 15686 } 15687} 15688 15689/// IsDesirableToPromoteOp - This method query the target whether it is 15690/// beneficial for dag combiner to promote the specified node. If true, it 15691/// should return the desired promotion type by reference. 15692bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const { 15693 EVT VT = Op.getValueType(); 15694 if (VT != MVT::i16) 15695 return false; 15696 15697 bool Promote = false; 15698 bool Commute = false; 15699 switch (Op.getOpcode()) { 15700 default: break; 15701 case ISD::LOAD: { 15702 LoadSDNode *LD = cast<LoadSDNode>(Op); 15703 // If the non-extending load has a single use and it's not live out, then it 15704 // might be folded. 15705 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&& 15706 Op.hasOneUse()*/) { 15707 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 15708 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 15709 // The only case where we'd want to promote LOAD (rather then it being 15710 // promoted as an operand is when it's only use is liveout. 15711 if (UI->getOpcode() != ISD::CopyToReg) 15712 return false; 15713 } 15714 } 15715 Promote = true; 15716 break; 15717 } 15718 case ISD::SIGN_EXTEND: 15719 case ISD::ZERO_EXTEND: 15720 case ISD::ANY_EXTEND: 15721 Promote = true; 15722 break; 15723 case ISD::SHL: 15724 case ISD::SRL: { 15725 SDValue N0 = Op.getOperand(0); 15726 // Look out for (store (shl (load), x)). 15727 if (MayFoldLoad(N0) && MayFoldIntoStore(Op)) 15728 return false; 15729 Promote = true; 15730 break; 15731 } 15732 case ISD::ADD: 15733 case ISD::MUL: 15734 case ISD::AND: 15735 case ISD::OR: 15736 case ISD::XOR: 15737 Commute = true; 15738 // fallthrough 15739 case ISD::SUB: { 15740 SDValue N0 = Op.getOperand(0); 15741 SDValue N1 = Op.getOperand(1); 15742 if (!Commute && MayFoldLoad(N1)) 15743 return false; 15744 // Avoid disabling potential load folding opportunities. 15745 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op))) 15746 return false; 15747 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op))) 15748 return false; 15749 Promote = true; 15750 } 15751 } 15752 15753 PVT = MVT::i32; 15754 return Promote; 15755} 15756 15757//===----------------------------------------------------------------------===// 15758// X86 Inline Assembly Support 15759//===----------------------------------------------------------------------===// 15760 15761namespace { 15762 // Helper to match a string separated by whitespace. 15763 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) { 15764 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace. 15765 15766 for (unsigned i = 0, e = args.size(); i != e; ++i) { 15767 StringRef piece(*args[i]); 15768 if (!s.startswith(piece)) // Check if the piece matches. 15769 return false; 15770 15771 s = s.substr(piece.size()); 15772 StringRef::size_type pos = s.find_first_not_of(" \t"); 15773 if (pos == 0) // We matched a prefix. 15774 return false; 15775 15776 s = s.substr(pos); 15777 } 15778 15779 return s.empty(); 15780 } 15781 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={}; 15782} 15783 15784bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const { 15785 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 15786 15787 std::string AsmStr = IA->getAsmString(); 15788 15789 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 15790 if (!Ty || Ty->getBitWidth() % 16 != 0) 15791 return false; 15792 15793 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a" 15794 SmallVector<StringRef, 4> AsmPieces; 15795 SplitString(AsmStr, AsmPieces, ";\n"); 15796 15797 switch (AsmPieces.size()) { 15798 default: return false; 15799 case 1: 15800 // FIXME: this should verify that we are targeting a 486 or better. If not, 15801 // we will turn this bswap into something that will be lowered to logical 15802 // ops instead of emitting the bswap asm. For now, we don't support 486 or 15803 // lower so don't worry about this. 15804 // bswap $0 15805 if (matchAsm(AsmPieces[0], "bswap", "$0") || 15806 matchAsm(AsmPieces[0], "bswapl", "$0") || 15807 matchAsm(AsmPieces[0], "bswapq", "$0") || 15808 matchAsm(AsmPieces[0], "bswap", "${0:q}") || 15809 matchAsm(AsmPieces[0], "bswapl", "${0:q}") || 15810 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) { 15811 // No need to check constraints, nothing other than the equivalent of 15812 // "=r,0" would be valid here. 15813 return IntrinsicLowering::LowerToByteSwap(CI); 15814 } 15815 15816 // rorw $$8, ${0:w} --> llvm.bswap.i16 15817 if (CI->getType()->isIntegerTy(16) && 15818 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 && 15819 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") || 15820 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) { 15821 AsmPieces.clear(); 15822 const std::string &ConstraintsStr = IA->getConstraintString(); 15823 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 15824 std::sort(AsmPieces.begin(), AsmPieces.end()); 15825 if (AsmPieces.size() == 4 && 15826 AsmPieces[0] == "~{cc}" && 15827 AsmPieces[1] == "~{dirflag}" && 15828 AsmPieces[2] == "~{flags}" && 15829 AsmPieces[3] == "~{fpsr}") 15830 return IntrinsicLowering::LowerToByteSwap(CI); 15831 } 15832 break; 15833 case 3: 15834 if (CI->getType()->isIntegerTy(32) && 15835 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 && 15836 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") && 15837 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") && 15838 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) { 15839 AsmPieces.clear(); 15840 const std::string &ConstraintsStr = IA->getConstraintString(); 15841 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 15842 std::sort(AsmPieces.begin(), AsmPieces.end()); 15843 if (AsmPieces.size() == 4 && 15844 AsmPieces[0] == "~{cc}" && 15845 AsmPieces[1] == "~{dirflag}" && 15846 AsmPieces[2] == "~{flags}" && 15847 AsmPieces[3] == "~{fpsr}") 15848 return IntrinsicLowering::LowerToByteSwap(CI); 15849 } 15850 15851 if (CI->getType()->isIntegerTy(64)) { 15852 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints(); 15853 if (Constraints.size() >= 2 && 15854 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" && 15855 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") { 15856 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64 15857 if (matchAsm(AsmPieces[0], "bswap", "%eax") && 15858 matchAsm(AsmPieces[1], "bswap", "%edx") && 15859 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx")) 15860 return IntrinsicLowering::LowerToByteSwap(CI); 15861 } 15862 } 15863 break; 15864 } 15865 return false; 15866} 15867 15868 15869 15870/// getConstraintType - Given a constraint letter, return the type of 15871/// constraint it is for this target. 15872X86TargetLowering::ConstraintType 15873X86TargetLowering::getConstraintType(const std::string &Constraint) const { 15874 if (Constraint.size() == 1) { 15875 switch (Constraint[0]) { 15876 case 'R': 15877 case 'q': 15878 case 'Q': 15879 case 'f': 15880 case 't': 15881 case 'u': 15882 case 'y': 15883 case 'x': 15884 case 'Y': 15885 case 'l': 15886 return C_RegisterClass; 15887 case 'a': 15888 case 'b': 15889 case 'c': 15890 case 'd': 15891 case 'S': 15892 case 'D': 15893 case 'A': 15894 return C_Register; 15895 case 'I': 15896 case 'J': 15897 case 'K': 15898 case 'L': 15899 case 'M': 15900 case 'N': 15901 case 'G': 15902 case 'C': 15903 case 'e': 15904 case 'Z': 15905 return C_Other; 15906 default: 15907 break; 15908 } 15909 } 15910 return TargetLowering::getConstraintType(Constraint); 15911} 15912 15913/// Examine constraint type and operand type and determine a weight value. 15914/// This object must already have been set up with the operand type 15915/// and the current alternative constraint selected. 15916TargetLowering::ConstraintWeight 15917 X86TargetLowering::getSingleConstraintMatchWeight( 15918 AsmOperandInfo &info, const char *constraint) const { 15919 ConstraintWeight weight = CW_Invalid; 15920 Value *CallOperandVal = info.CallOperandVal; 15921 // If we don't have a value, we can't do a match, 15922 // but allow it at the lowest weight. 15923 if (CallOperandVal == NULL) 15924 return CW_Default; 15925 Type *type = CallOperandVal->getType(); 15926 // Look at the constraint type. 15927 switch (*constraint) { 15928 default: 15929 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15930 case 'R': 15931 case 'q': 15932 case 'Q': 15933 case 'a': 15934 case 'b': 15935 case 'c': 15936 case 'd': 15937 case 'S': 15938 case 'D': 15939 case 'A': 15940 if (CallOperandVal->getType()->isIntegerTy()) 15941 weight = CW_SpecificReg; 15942 break; 15943 case 'f': 15944 case 't': 15945 case 'u': 15946 if (type->isFloatingPointTy()) 15947 weight = CW_SpecificReg; 15948 break; 15949 case 'y': 15950 if (type->isX86_MMXTy() && Subtarget->hasMMX()) 15951 weight = CW_SpecificReg; 15952 break; 15953 case 'x': 15954 case 'Y': 15955 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) || 15956 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX())) 15957 weight = CW_Register; 15958 break; 15959 case 'I': 15960 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) { 15961 if (C->getZExtValue() <= 31) 15962 weight = CW_Constant; 15963 } 15964 break; 15965 case 'J': 15966 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15967 if (C->getZExtValue() <= 63) 15968 weight = CW_Constant; 15969 } 15970 break; 15971 case 'K': 15972 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15973 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f)) 15974 weight = CW_Constant; 15975 } 15976 break; 15977 case 'L': 15978 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15979 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff)) 15980 weight = CW_Constant; 15981 } 15982 break; 15983 case 'M': 15984 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15985 if (C->getZExtValue() <= 3) 15986 weight = CW_Constant; 15987 } 15988 break; 15989 case 'N': 15990 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15991 if (C->getZExtValue() <= 0xff) 15992 weight = CW_Constant; 15993 } 15994 break; 15995 case 'G': 15996 case 'C': 15997 if (dyn_cast<ConstantFP>(CallOperandVal)) { 15998 weight = CW_Constant; 15999 } 16000 break; 16001 case 'e': 16002 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 16003 if ((C->getSExtValue() >= -0x80000000LL) && 16004 (C->getSExtValue() <= 0x7fffffffLL)) 16005 weight = CW_Constant; 16006 } 16007 break; 16008 case 'Z': 16009 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 16010 if (C->getZExtValue() <= 0xffffffff) 16011 weight = CW_Constant; 16012 } 16013 break; 16014 } 16015 return weight; 16016} 16017 16018/// LowerXConstraint - try to replace an X constraint, which matches anything, 16019/// with another that has more specific requirements based on the type of the 16020/// corresponding operand. 16021const char *X86TargetLowering:: 16022LowerXConstraint(EVT ConstraintVT) const { 16023 // FP X constraints get lowered to SSE1/2 registers if available, otherwise 16024 // 'f' like normal targets. 16025 if (ConstraintVT.isFloatingPoint()) { 16026 if (Subtarget->hasSSE2()) 16027 return "Y"; 16028 if (Subtarget->hasSSE1()) 16029 return "x"; 16030 } 16031 16032 return TargetLowering::LowerXConstraint(ConstraintVT); 16033} 16034 16035/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 16036/// vector. If it is invalid, don't add anything to Ops. 16037void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 16038 std::string &Constraint, 16039 std::vector<SDValue>&Ops, 16040 SelectionDAG &DAG) const { 16041 SDValue Result(0, 0); 16042 16043 // Only support length 1 constraints for now. 16044 if (Constraint.length() > 1) return; 16045 16046 char ConstraintLetter = Constraint[0]; 16047 switch (ConstraintLetter) { 16048 default: break; 16049 case 'I': 16050 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 16051 if (C->getZExtValue() <= 31) { 16052 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 16053 break; 16054 } 16055 } 16056 return; 16057 case 'J': 16058 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 16059 if (C->getZExtValue() <= 63) { 16060 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 16061 break; 16062 } 16063 } 16064 return; 16065 case 'K': 16066 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 16067 if ((int8_t)C->getSExtValue() == C->getSExtValue()) { 16068 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 16069 break; 16070 } 16071 } 16072 return; 16073 case 'N': 16074 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 16075 if (C->getZExtValue() <= 255) { 16076 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 16077 break; 16078 } 16079 } 16080 return; 16081 case 'e': { 16082 // 32-bit signed value 16083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 16084 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 16085 C->getSExtValue())) { 16086 // Widen to 64 bits here to get it sign extended. 16087 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64); 16088 break; 16089 } 16090 // FIXME gcc accepts some relocatable values here too, but only in certain 16091 // memory models; it's complicated. 16092 } 16093 return; 16094 } 16095 case 'Z': { 16096 // 32-bit unsigned value 16097 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 16098 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 16099 C->getZExtValue())) { 16100 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 16101 break; 16102 } 16103 } 16104 // FIXME gcc accepts some relocatable values here too, but only in certain 16105 // memory models; it's complicated. 16106 return; 16107 } 16108 case 'i': { 16109 // Literal immediates are always ok. 16110 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) { 16111 // Widen to 64 bits here to get it sign extended. 16112 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64); 16113 break; 16114 } 16115 16116 // In any sort of PIC mode addresses need to be computed at runtime by 16117 // adding in a register or some sort of table lookup. These can't 16118 // be used as immediates. 16119 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC()) 16120 return; 16121 16122 // If we are in non-pic codegen mode, we allow the address of a global (with 16123 // an optional displacement) to be used with 'i'. 16124 GlobalAddressSDNode *GA = 0; 16125 int64_t Offset = 0; 16126 16127 // Match either (GA), (GA+C), (GA+C1+C2), etc. 16128 while (1) { 16129 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) { 16130 Offset += GA->getOffset(); 16131 break; 16132 } else if (Op.getOpcode() == ISD::ADD) { 16133 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 16134 Offset += C->getZExtValue(); 16135 Op = Op.getOperand(0); 16136 continue; 16137 } 16138 } else if (Op.getOpcode() == ISD::SUB) { 16139 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 16140 Offset += -C->getZExtValue(); 16141 Op = Op.getOperand(0); 16142 continue; 16143 } 16144 } 16145 16146 // Otherwise, this isn't something we can handle, reject it. 16147 return; 16148 } 16149 16150 const GlobalValue *GV = GA->getGlobal(); 16151 // If we require an extra load to get this address, as in PIC mode, we 16152 // can't accept it. 16153 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV, 16154 getTargetMachine()))) 16155 return; 16156 16157 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), 16158 GA->getValueType(0), Offset); 16159 break; 16160 } 16161 } 16162 16163 if (Result.getNode()) { 16164 Ops.push_back(Result); 16165 return; 16166 } 16167 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 16168} 16169 16170std::pair<unsigned, const TargetRegisterClass*> 16171X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 16172 EVT VT) const { 16173 // First, see if this is a constraint that directly corresponds to an LLVM 16174 // register class. 16175 if (Constraint.size() == 1) { 16176 // GCC Constraint Letters 16177 switch (Constraint[0]) { 16178 default: break; 16179 // TODO: Slight differences here in allocation order and leaving 16180 // RIP in the class. Do they matter any more here than they do 16181 // in the normal allocation? 16182 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode. 16183 if (Subtarget->is64Bit()) { 16184 if (VT == MVT::i32 || VT == MVT::f32) 16185 return std::make_pair(0U, &X86::GR32RegClass); 16186 if (VT == MVT::i16) 16187 return std::make_pair(0U, &X86::GR16RegClass); 16188 if (VT == MVT::i8 || VT == MVT::i1) 16189 return std::make_pair(0U, &X86::GR8RegClass); 16190 if (VT == MVT::i64 || VT == MVT::f64) 16191 return std::make_pair(0U, &X86::GR64RegClass); 16192 break; 16193 } 16194 // 32-bit fallthrough 16195 case 'Q': // Q_REGS 16196 if (VT == MVT::i32 || VT == MVT::f32) 16197 return std::make_pair(0U, &X86::GR32_ABCDRegClass); 16198 if (VT == MVT::i16) 16199 return std::make_pair(0U, &X86::GR16_ABCDRegClass); 16200 if (VT == MVT::i8 || VT == MVT::i1) 16201 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass); 16202 if (VT == MVT::i64) 16203 return std::make_pair(0U, &X86::GR64_ABCDRegClass); 16204 break; 16205 case 'r': // GENERAL_REGS 16206 case 'l': // INDEX_REGS 16207 if (VT == MVT::i8 || VT == MVT::i1) 16208 return std::make_pair(0U, &X86::GR8RegClass); 16209 if (VT == MVT::i16) 16210 return std::make_pair(0U, &X86::GR16RegClass); 16211 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit()) 16212 return std::make_pair(0U, &X86::GR32RegClass); 16213 return std::make_pair(0U, &X86::GR64RegClass); 16214 case 'R': // LEGACY_REGS 16215 if (VT == MVT::i8 || VT == MVT::i1) 16216 return std::make_pair(0U, &X86::GR8_NOREXRegClass); 16217 if (VT == MVT::i16) 16218 return std::make_pair(0U, &X86::GR16_NOREXRegClass); 16219 if (VT == MVT::i32 || !Subtarget->is64Bit()) 16220 return std::make_pair(0U, &X86::GR32_NOREXRegClass); 16221 return std::make_pair(0U, &X86::GR64_NOREXRegClass); 16222 case 'f': // FP Stack registers. 16223 // If SSE is enabled for this VT, use f80 to ensure the isel moves the 16224 // value to the correct fpstack register class. 16225 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT)) 16226 return std::make_pair(0U, &X86::RFP32RegClass); 16227 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT)) 16228 return std::make_pair(0U, &X86::RFP64RegClass); 16229 return std::make_pair(0U, &X86::RFP80RegClass); 16230 case 'y': // MMX_REGS if MMX allowed. 16231 if (!Subtarget->hasMMX()) break; 16232 return std::make_pair(0U, &X86::VR64RegClass); 16233 case 'Y': // SSE_REGS if SSE2 allowed 16234 if (!Subtarget->hasSSE2()) break; 16235 // FALL THROUGH. 16236 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed 16237 if (!Subtarget->hasSSE1()) break; 16238 16239 switch (VT.getSimpleVT().SimpleTy) { 16240 default: break; 16241 // Scalar SSE types. 16242 case MVT::f32: 16243 case MVT::i32: 16244 return std::make_pair(0U, &X86::FR32RegClass); 16245 case MVT::f64: 16246 case MVT::i64: 16247 return std::make_pair(0U, &X86::FR64RegClass); 16248 // Vector types. 16249 case MVT::v16i8: 16250 case MVT::v8i16: 16251 case MVT::v4i32: 16252 case MVT::v2i64: 16253 case MVT::v4f32: 16254 case MVT::v2f64: 16255 return std::make_pair(0U, &X86::VR128RegClass); 16256 // AVX types. 16257 case MVT::v32i8: 16258 case MVT::v16i16: 16259 case MVT::v8i32: 16260 case MVT::v4i64: 16261 case MVT::v8f32: 16262 case MVT::v4f64: 16263 return std::make_pair(0U, &X86::VR256RegClass); 16264 } 16265 break; 16266 } 16267 } 16268 16269 // Use the default implementation in TargetLowering to convert the register 16270 // constraint into a member of a register class. 16271 std::pair<unsigned, const TargetRegisterClass*> Res; 16272 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 16273 16274 // Not found as a standard register? 16275 if (Res.second == 0) { 16276 // Map st(0) -> st(7) -> ST0 16277 if (Constraint.size() == 7 && Constraint[0] == '{' && 16278 tolower(Constraint[1]) == 's' && 16279 tolower(Constraint[2]) == 't' && 16280 Constraint[3] == '(' && 16281 (Constraint[4] >= '0' && Constraint[4] <= '7') && 16282 Constraint[5] == ')' && 16283 Constraint[6] == '}') { 16284 16285 Res.first = X86::ST0+Constraint[4]-'0'; 16286 Res.second = &X86::RFP80RegClass; 16287 return Res; 16288 } 16289 16290 // GCC allows "st(0)" to be called just plain "st". 16291 if (StringRef("{st}").equals_lower(Constraint)) { 16292 Res.first = X86::ST0; 16293 Res.second = &X86::RFP80RegClass; 16294 return Res; 16295 } 16296 16297 // flags -> EFLAGS 16298 if (StringRef("{flags}").equals_lower(Constraint)) { 16299 Res.first = X86::EFLAGS; 16300 Res.second = &X86::CCRRegClass; 16301 return Res; 16302 } 16303 16304 // 'A' means EAX + EDX. 16305 if (Constraint == "A") { 16306 Res.first = X86::EAX; 16307 Res.second = &X86::GR32_ADRegClass; 16308 return Res; 16309 } 16310 return Res; 16311 } 16312 16313 // Otherwise, check to see if this is a register class of the wrong value 16314 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to 16315 // turn into {ax},{dx}. 16316 if (Res.second->hasType(VT)) 16317 return Res; // Correct type already, nothing to do. 16318 16319 // All of the single-register GCC register classes map their values onto 16320 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we 16321 // really want an 8-bit or 32-bit register, map to the appropriate register 16322 // class and return the appropriate register. 16323 if (Res.second == &X86::GR16RegClass) { 16324 if (VT == MVT::i8) { 16325 unsigned DestReg = 0; 16326 switch (Res.first) { 16327 default: break; 16328 case X86::AX: DestReg = X86::AL; break; 16329 case X86::DX: DestReg = X86::DL; break; 16330 case X86::CX: DestReg = X86::CL; break; 16331 case X86::BX: DestReg = X86::BL; break; 16332 } 16333 if (DestReg) { 16334 Res.first = DestReg; 16335 Res.second = &X86::GR8RegClass; 16336 } 16337 } else if (VT == MVT::i32) { 16338 unsigned DestReg = 0; 16339 switch (Res.first) { 16340 default: break; 16341 case X86::AX: DestReg = X86::EAX; break; 16342 case X86::DX: DestReg = X86::EDX; break; 16343 case X86::CX: DestReg = X86::ECX; break; 16344 case X86::BX: DestReg = X86::EBX; break; 16345 case X86::SI: DestReg = X86::ESI; break; 16346 case X86::DI: DestReg = X86::EDI; break; 16347 case X86::BP: DestReg = X86::EBP; break; 16348 case X86::SP: DestReg = X86::ESP; break; 16349 } 16350 if (DestReg) { 16351 Res.first = DestReg; 16352 Res.second = &X86::GR32RegClass; 16353 } 16354 } else if (VT == MVT::i64) { 16355 unsigned DestReg = 0; 16356 switch (Res.first) { 16357 default: break; 16358 case X86::AX: DestReg = X86::RAX; break; 16359 case X86::DX: DestReg = X86::RDX; break; 16360 case X86::CX: DestReg = X86::RCX; break; 16361 case X86::BX: DestReg = X86::RBX; break; 16362 case X86::SI: DestReg = X86::RSI; break; 16363 case X86::DI: DestReg = X86::RDI; break; 16364 case X86::BP: DestReg = X86::RBP; break; 16365 case X86::SP: DestReg = X86::RSP; break; 16366 } 16367 if (DestReg) { 16368 Res.first = DestReg; 16369 Res.second = &X86::GR64RegClass; 16370 } 16371 } 16372 } else if (Res.second == &X86::FR32RegClass || 16373 Res.second == &X86::FR64RegClass || 16374 Res.second == &X86::VR128RegClass) { 16375 // Handle references to XMM physical registers that got mapped into the 16376 // wrong class. This can happen with constraints like {xmm0} where the 16377 // target independent register mapper will just pick the first match it can 16378 // find, ignoring the required type. 16379 16380 if (VT == MVT::f32 || VT == MVT::i32) 16381 Res.second = &X86::FR32RegClass; 16382 else if (VT == MVT::f64 || VT == MVT::i64) 16383 Res.second = &X86::FR64RegClass; 16384 else if (X86::VR128RegClass.hasType(VT)) 16385 Res.second = &X86::VR128RegClass; 16386 else if (X86::VR256RegClass.hasType(VT)) 16387 Res.second = &X86::VR256RegClass; 16388 } 16389 16390 return Res; 16391} 16392