1 //===-- PPCISelLowering.cpp - PPC 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 implements the PPCISelLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "PPCISelLowering.h" 15 #include "MCTargetDesc/PPCPredicates.h" 16 #include "PPCCallingConv.h" 17 #include "PPCMachineFunctionInfo.h" 18 #include "PPCPerfectShuffle.h" 19 #include "PPCTargetMachine.h" 20 #include "PPCTargetObjectFile.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/StringSwitch.h" 23 #include "llvm/ADT/Triple.h" 24 #include "llvm/CodeGen/CallingConvLower.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/CodeGen/MachineInstrBuilder.h" 28 #include "llvm/CodeGen/MachineLoopInfo.h" 29 #include "llvm/CodeGen/MachineRegisterInfo.h" 30 #include "llvm/CodeGen/SelectionDAG.h" 31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 32 #include "llvm/IR/CallingConv.h" 33 #include "llvm/IR/Constants.h" 34 #include "llvm/IR/DerivedTypes.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/IR/Intrinsics.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 #include "llvm/Target/TargetOptions.h" 42 using namespace llvm; 43 44 // FIXME: Remove this once soft-float is supported. 45 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic", 46 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden); 47 48 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 49 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 50 51 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 52 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 53 54 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 55 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 56 57 // FIXME: Remove this once the bug has been fixed! 58 extern cl::opt<bool> ANDIGlueBug; 59 60 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 61 const PPCSubtarget &STI) 62 : TargetLowering(TM), Subtarget(STI) { 63 // Use _setjmp/_longjmp instead of setjmp/longjmp. 64 setUseUnderscoreSetJmp(true); 65 setUseUnderscoreLongJmp(true); 66 67 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 68 // arguments are at least 4/8 bytes aligned. 69 bool isPPC64 = Subtarget.isPPC64(); 70 setMinStackArgumentAlignment(isPPC64 ? 8:4); 71 72 // Set up the register classes. 73 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 74 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 75 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 76 77 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD 78 for (MVT VT : MVT::integer_valuetypes()) { 79 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 80 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 81 } 82 83 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 84 85 // PowerPC has pre-inc load and store's. 86 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 87 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 88 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 89 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 90 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 91 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 92 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 93 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 94 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 95 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 96 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 97 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 98 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 99 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 100 101 if (Subtarget.useCRBits()) { 102 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 103 104 if (isPPC64 || Subtarget.hasFPCVT()) { 105 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 106 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 107 isPPC64 ? MVT::i64 : MVT::i32); 108 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 109 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 110 isPPC64 ? MVT::i64 : MVT::i32); 111 } else { 112 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 113 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 114 } 115 116 // PowerPC does not support direct load / store of condition registers 117 setOperationAction(ISD::LOAD, MVT::i1, Custom); 118 setOperationAction(ISD::STORE, MVT::i1, Custom); 119 120 // FIXME: Remove this once the ANDI glue bug is fixed: 121 if (ANDIGlueBug) 122 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 123 124 for (MVT VT : MVT::integer_valuetypes()) { 125 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 126 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 127 setTruncStoreAction(VT, MVT::i1, Expand); 128 } 129 130 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 131 } 132 133 // This is used in the ppcf128->int sequence. Note it has different semantics 134 // from FP_ROUND: that rounds to nearest, this rounds to zero. 135 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom); 136 137 // We do not currently implement these libm ops for PowerPC. 138 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 139 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 140 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 141 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 142 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 143 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 144 145 // PowerPC has no SREM/UREM instructions 146 setOperationAction(ISD::SREM, MVT::i32, Expand); 147 setOperationAction(ISD::UREM, MVT::i32, Expand); 148 setOperationAction(ISD::SREM, MVT::i64, Expand); 149 setOperationAction(ISD::UREM, MVT::i64, Expand); 150 151 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 152 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 153 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 154 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 155 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 156 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 157 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 158 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 159 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 160 161 // We don't support sin/cos/sqrt/fmod/pow 162 setOperationAction(ISD::FSIN , MVT::f64, Expand); 163 setOperationAction(ISD::FCOS , MVT::f64, Expand); 164 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 165 setOperationAction(ISD::FREM , MVT::f64, Expand); 166 setOperationAction(ISD::FPOW , MVT::f64, Expand); 167 setOperationAction(ISD::FMA , MVT::f64, Legal); 168 setOperationAction(ISD::FSIN , MVT::f32, Expand); 169 setOperationAction(ISD::FCOS , MVT::f32, Expand); 170 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 171 setOperationAction(ISD::FREM , MVT::f32, Expand); 172 setOperationAction(ISD::FPOW , MVT::f32, Expand); 173 setOperationAction(ISD::FMA , MVT::f32, Legal); 174 175 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 176 177 // If we're enabling GP optimizations, use hardware square root 178 if (!Subtarget.hasFSQRT() && 179 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 180 Subtarget.hasFRE())) 181 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 182 183 if (!Subtarget.hasFSQRT() && 184 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 185 Subtarget.hasFRES())) 186 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 187 188 if (Subtarget.hasFCPSGN()) { 189 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 190 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 191 } else { 192 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 193 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 194 } 195 196 if (Subtarget.hasFPRND()) { 197 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 198 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 199 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 200 setOperationAction(ISD::FROUND, MVT::f64, Legal); 201 202 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 203 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 204 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 205 setOperationAction(ISD::FROUND, MVT::f32, Legal); 206 } 207 208 // PowerPC does not have BSWAP, CTPOP or CTTZ 209 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 210 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 211 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand); 212 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand); 213 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 214 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 215 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand); 216 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand); 217 218 if (Subtarget.hasPOPCNTD()) { 219 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 220 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 221 } else { 222 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 223 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 224 } 225 226 // PowerPC does not have ROTR 227 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 228 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 229 230 if (!Subtarget.useCRBits()) { 231 // PowerPC does not have Select 232 setOperationAction(ISD::SELECT, MVT::i32, Expand); 233 setOperationAction(ISD::SELECT, MVT::i64, Expand); 234 setOperationAction(ISD::SELECT, MVT::f32, Expand); 235 setOperationAction(ISD::SELECT, MVT::f64, Expand); 236 } 237 238 // PowerPC wants to turn select_cc of FP into fsel when possible. 239 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 240 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 241 242 // PowerPC wants to optimize integer setcc a bit 243 if (!Subtarget.useCRBits()) 244 setOperationAction(ISD::SETCC, MVT::i32, Custom); 245 246 // PowerPC does not have BRCOND which requires SetCC 247 if (!Subtarget.useCRBits()) 248 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 249 250 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 251 252 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 253 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 254 255 // PowerPC does not have [U|S]INT_TO_FP 256 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 257 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 258 259 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 260 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 261 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 262 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 263 264 // We cannot sextinreg(i1). Expand to shifts. 265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 266 267 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 268 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 269 // support continuation, user-level threading, and etc.. As a result, no 270 // other SjLj exception interfaces are implemented and please don't build 271 // your own exception handling based on them. 272 // LLVM/Clang supports zero-cost DWARF exception handling. 273 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 274 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 275 276 // We want to legalize GlobalAddress and ConstantPool nodes into the 277 // appropriate instructions to materialize the address. 278 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 279 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 280 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 281 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 282 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 283 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 284 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 285 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 286 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 287 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 288 289 // TRAP is legal. 290 setOperationAction(ISD::TRAP, MVT::Other, Legal); 291 292 // TRAMPOLINE is custom lowered. 293 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 294 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 295 296 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 297 setOperationAction(ISD::VASTART , MVT::Other, Custom); 298 299 if (Subtarget.isSVR4ABI()) { 300 if (isPPC64) { 301 // VAARG always uses double-word chunks, so promote anything smaller. 302 setOperationAction(ISD::VAARG, MVT::i1, Promote); 303 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 304 setOperationAction(ISD::VAARG, MVT::i8, Promote); 305 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 306 setOperationAction(ISD::VAARG, MVT::i16, Promote); 307 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 308 setOperationAction(ISD::VAARG, MVT::i32, Promote); 309 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 310 setOperationAction(ISD::VAARG, MVT::Other, Expand); 311 } else { 312 // VAARG is custom lowered with the 32-bit SVR4 ABI. 313 setOperationAction(ISD::VAARG, MVT::Other, Custom); 314 setOperationAction(ISD::VAARG, MVT::i64, Custom); 315 } 316 } else 317 setOperationAction(ISD::VAARG, MVT::Other, Expand); 318 319 if (Subtarget.isSVR4ABI() && !isPPC64) 320 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 321 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 322 else 323 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 324 325 // Use the default implementation. 326 setOperationAction(ISD::VAEND , MVT::Other, Expand); 327 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 328 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 330 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 331 332 // We want to custom lower some of our intrinsics. 333 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 334 335 // To handle counter-based loop conditions. 336 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 337 338 // Comparisons that require checking two conditions. 339 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 340 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 341 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 342 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 343 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 344 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 345 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 346 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 347 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 348 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 349 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 350 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 351 352 if (Subtarget.has64BitSupport()) { 353 // They also have instructions for converting between i64 and fp. 354 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 355 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 356 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 357 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 358 // This is just the low 32 bits of a (signed) fp->i64 conversion. 359 // We cannot do this with Promote because i64 is not a legal type. 360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 361 362 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 363 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 364 } else { 365 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 366 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 367 } 368 369 // With the instructions enabled under FPCVT, we can do everything. 370 if (Subtarget.hasFPCVT()) { 371 if (Subtarget.has64BitSupport()) { 372 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 373 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 374 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 375 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 376 } 377 378 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 379 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 380 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 381 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 382 } 383 384 if (Subtarget.use64BitRegs()) { 385 // 64-bit PowerPC implementations can support i64 types directly 386 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 387 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 388 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 389 // 64-bit PowerPC wants to expand i128 shifts itself. 390 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 391 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 392 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 393 } else { 394 // 32-bit PowerPC wants to expand i64 shifts itself. 395 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 396 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 397 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 398 } 399 400 if (Subtarget.hasAltivec()) { 401 // First set operation action for all vector types to expand. Then we 402 // will selectively turn on ones that can be effectively codegen'd. 403 for (MVT VT : MVT::vector_valuetypes()) { 404 // add/sub are legal for all supported vector VT's. 405 setOperationAction(ISD::ADD , VT, Legal); 406 setOperationAction(ISD::SUB , VT, Legal); 407 408 // Vector instructions introduced in P8 409 if (Subtarget.hasP8Altivec()) { 410 setOperationAction(ISD::CTPOP, VT, Legal); 411 setOperationAction(ISD::CTLZ, VT, Legal); 412 } 413 else { 414 setOperationAction(ISD::CTPOP, VT, Expand); 415 setOperationAction(ISD::CTLZ, VT, Expand); 416 } 417 418 // We promote all shuffles to v16i8. 419 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 420 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 421 422 // We promote all non-typed operations to v4i32. 423 setOperationAction(ISD::AND , VT, Promote); 424 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 425 setOperationAction(ISD::OR , VT, Promote); 426 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 427 setOperationAction(ISD::XOR , VT, Promote); 428 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 429 setOperationAction(ISD::LOAD , VT, Promote); 430 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 431 setOperationAction(ISD::SELECT, VT, Promote); 432 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 433 setOperationAction(ISD::STORE, VT, Promote); 434 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 435 436 // No other operations are legal. 437 setOperationAction(ISD::MUL , VT, Expand); 438 setOperationAction(ISD::SDIV, VT, Expand); 439 setOperationAction(ISD::SREM, VT, Expand); 440 setOperationAction(ISD::UDIV, VT, Expand); 441 setOperationAction(ISD::UREM, VT, Expand); 442 setOperationAction(ISD::FDIV, VT, Expand); 443 setOperationAction(ISD::FREM, VT, Expand); 444 setOperationAction(ISD::FNEG, VT, Expand); 445 setOperationAction(ISD::FSQRT, VT, Expand); 446 setOperationAction(ISD::FLOG, VT, Expand); 447 setOperationAction(ISD::FLOG10, VT, Expand); 448 setOperationAction(ISD::FLOG2, VT, Expand); 449 setOperationAction(ISD::FEXP, VT, Expand); 450 setOperationAction(ISD::FEXP2, VT, Expand); 451 setOperationAction(ISD::FSIN, VT, Expand); 452 setOperationAction(ISD::FCOS, VT, Expand); 453 setOperationAction(ISD::FABS, VT, Expand); 454 setOperationAction(ISD::FPOWI, VT, Expand); 455 setOperationAction(ISD::FFLOOR, VT, Expand); 456 setOperationAction(ISD::FCEIL, VT, Expand); 457 setOperationAction(ISD::FTRUNC, VT, Expand); 458 setOperationAction(ISD::FRINT, VT, Expand); 459 setOperationAction(ISD::FNEARBYINT, VT, Expand); 460 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 461 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 462 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 463 setOperationAction(ISD::MULHU, VT, Expand); 464 setOperationAction(ISD::MULHS, VT, Expand); 465 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 466 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 467 setOperationAction(ISD::UDIVREM, VT, Expand); 468 setOperationAction(ISD::SDIVREM, VT, Expand); 469 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 470 setOperationAction(ISD::FPOW, VT, Expand); 471 setOperationAction(ISD::BSWAP, VT, Expand); 472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand); 473 setOperationAction(ISD::CTTZ, VT, Expand); 474 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand); 475 setOperationAction(ISD::VSELECT, VT, Expand); 476 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 477 478 for (MVT InnerVT : MVT::vector_valuetypes()) { 479 setTruncStoreAction(VT, InnerVT, Expand); 480 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 481 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 482 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 483 } 484 } 485 486 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 487 // with merges, splats, etc. 488 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 489 490 setOperationAction(ISD::AND , MVT::v4i32, Legal); 491 setOperationAction(ISD::OR , MVT::v4i32, Legal); 492 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 493 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 494 setOperationAction(ISD::SELECT, MVT::v4i32, 495 Subtarget.useCRBits() ? Legal : Expand); 496 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 497 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 498 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 499 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 500 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 501 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 502 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 503 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 504 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 505 506 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 507 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 508 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 509 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 510 511 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 512 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 513 514 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 515 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 516 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 517 } 518 519 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 520 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 521 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 522 523 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 524 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 525 526 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 527 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 528 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 529 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 530 531 // Altivec does not contain unordered floating-point compare instructions 532 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 533 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 534 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 535 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 536 537 if (Subtarget.hasVSX()) { 538 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 539 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 540 541 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 542 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 543 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 544 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 545 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 546 547 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 548 549 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 550 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 551 552 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 553 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 554 555 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 556 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal); 557 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 558 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 559 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 560 561 // Share the Altivec comparison restrictions. 562 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 563 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 564 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 565 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 566 567 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 568 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 569 570 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 571 572 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 573 574 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 575 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 576 577 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 578 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 579 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 580 581 if (Subtarget.hasP8Altivec()) { 582 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 583 } 584 else { 585 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 586 587 // VSX v2i64 only supports non-arithmetic operations. 588 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 589 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 590 } 591 592 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 593 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 594 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 595 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 596 597 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 598 599 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 600 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 601 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 602 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 603 604 // Vector operation legalization checks the result type of 605 // SIGN_EXTEND_INREG, overall legalization checks the inner type. 606 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 607 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 608 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 609 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 610 611 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 612 } 613 614 if (Subtarget.hasP8Altivec()) 615 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 616 } 617 618 if (Subtarget.hasQPX()) { 619 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 620 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 621 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 622 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 623 624 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 625 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 626 627 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 628 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 629 630 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 631 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 632 633 if (!Subtarget.useCRBits()) 634 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 635 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 636 637 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 638 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 639 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 640 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 641 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 642 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 643 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 644 645 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 646 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 647 648 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 649 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 650 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 651 652 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 653 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 654 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 655 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 656 setOperationAction(ISD::FPOWI , MVT::v4f64, Expand); 657 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 658 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 659 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 660 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 661 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 662 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 663 664 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 665 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 666 667 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 668 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 669 670 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 671 672 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 673 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 674 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 675 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 676 677 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 678 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 679 680 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 681 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 682 683 if (!Subtarget.useCRBits()) 684 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 685 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 686 687 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 688 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 689 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 690 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 691 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 692 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 693 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 694 695 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 696 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 697 698 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 699 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 700 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 701 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 702 setOperationAction(ISD::FPOWI , MVT::v4f32, Expand); 703 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 704 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 705 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 706 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 707 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 708 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 709 710 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 711 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 712 713 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 714 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 715 716 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 717 718 setOperationAction(ISD::AND , MVT::v4i1, Legal); 719 setOperationAction(ISD::OR , MVT::v4i1, Legal); 720 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 721 722 if (!Subtarget.useCRBits()) 723 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 724 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 725 726 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 727 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 728 729 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 730 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 731 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 732 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 733 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 734 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 735 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 736 737 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 738 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 739 740 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 741 742 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 743 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 744 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 745 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 746 747 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 748 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 749 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 750 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 751 752 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 753 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 754 755 // These need to set FE_INEXACT, and so cannot be vectorized here. 756 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 757 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 758 759 if (TM.Options.UnsafeFPMath) { 760 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 761 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 762 763 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 764 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 765 } else { 766 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 767 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 768 769 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 770 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 771 } 772 } 773 774 if (Subtarget.has64BitSupport()) 775 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 776 777 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 778 779 if (!isPPC64) { 780 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 781 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 782 } 783 784 setBooleanContents(ZeroOrOneBooleanContent); 785 786 if (Subtarget.hasAltivec()) { 787 // Altivec instructions set fields to all zeros or all ones. 788 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 789 } 790 791 if (!isPPC64) { 792 // These libcalls are not available in 32-bit. 793 setLibcallName(RTLIB::SHL_I128, nullptr); 794 setLibcallName(RTLIB::SRL_I128, nullptr); 795 setLibcallName(RTLIB::SRA_I128, nullptr); 796 } 797 798 if (isPPC64) { 799 setStackPointerRegisterToSaveRestore(PPC::X1); 800 setExceptionPointerRegister(PPC::X3); 801 setExceptionSelectorRegister(PPC::X4); 802 } else { 803 setStackPointerRegisterToSaveRestore(PPC::R1); 804 setExceptionPointerRegister(PPC::R3); 805 setExceptionSelectorRegister(PPC::R4); 806 } 807 808 // We have target-specific dag combine patterns for the following nodes: 809 setTargetDAGCombine(ISD::SINT_TO_FP); 810 if (Subtarget.hasFPCVT()) 811 setTargetDAGCombine(ISD::UINT_TO_FP); 812 setTargetDAGCombine(ISD::LOAD); 813 setTargetDAGCombine(ISD::STORE); 814 setTargetDAGCombine(ISD::BR_CC); 815 if (Subtarget.useCRBits()) 816 setTargetDAGCombine(ISD::BRCOND); 817 setTargetDAGCombine(ISD::BSWAP); 818 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 819 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 820 setTargetDAGCombine(ISD::INTRINSIC_VOID); 821 822 setTargetDAGCombine(ISD::SIGN_EXTEND); 823 setTargetDAGCombine(ISD::ZERO_EXTEND); 824 setTargetDAGCombine(ISD::ANY_EXTEND); 825 826 if (Subtarget.useCRBits()) { 827 setTargetDAGCombine(ISD::TRUNCATE); 828 setTargetDAGCombine(ISD::SETCC); 829 setTargetDAGCombine(ISD::SELECT_CC); 830 } 831 832 // Use reciprocal estimates. 833 if (TM.Options.UnsafeFPMath) { 834 setTargetDAGCombine(ISD::FDIV); 835 setTargetDAGCombine(ISD::FSQRT); 836 } 837 838 // Darwin long double math library functions have $LDBL128 appended. 839 if (Subtarget.isDarwin()) { 840 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 841 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 842 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 843 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 844 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 845 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 846 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 847 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 848 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 849 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 850 } 851 852 // With 32 condition bits, we don't need to sink (and duplicate) compares 853 // aggressively in CodeGenPrep. 854 if (Subtarget.useCRBits()) { 855 setHasMultipleConditionRegisters(); 856 setJumpIsExpensive(); 857 } 858 859 setMinFunctionAlignment(2); 860 if (Subtarget.isDarwin()) 861 setPrefFunctionAlignment(4); 862 863 switch (Subtarget.getDarwinDirective()) { 864 default: break; 865 case PPC::DIR_970: 866 case PPC::DIR_A2: 867 case PPC::DIR_E500mc: 868 case PPC::DIR_E5500: 869 case PPC::DIR_PWR4: 870 case PPC::DIR_PWR5: 871 case PPC::DIR_PWR5X: 872 case PPC::DIR_PWR6: 873 case PPC::DIR_PWR6X: 874 case PPC::DIR_PWR7: 875 case PPC::DIR_PWR8: 876 setPrefFunctionAlignment(4); 877 setPrefLoopAlignment(4); 878 break; 879 } 880 881 setInsertFencesForAtomic(true); 882 883 if (Subtarget.enableMachineScheduler()) 884 setSchedulingPreference(Sched::Source); 885 else 886 setSchedulingPreference(Sched::Hybrid); 887 888 computeRegisterProperties(STI.getRegisterInfo()); 889 890 // The Freescale cores do better with aggressive inlining of memcpy and 891 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 892 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 893 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 894 MaxStoresPerMemset = 32; 895 MaxStoresPerMemsetOptSize = 16; 896 MaxStoresPerMemcpy = 32; 897 MaxStoresPerMemcpyOptSize = 8; 898 MaxStoresPerMemmove = 32; 899 MaxStoresPerMemmoveOptSize = 8; 900 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 901 // The A2 also benefits from (very) aggressive inlining of memcpy and 902 // friends. The overhead of a the function call, even when warm, can be 903 // over one hundred cycles. 904 MaxStoresPerMemset = 128; 905 MaxStoresPerMemcpy = 128; 906 MaxStoresPerMemmove = 128; 907 } 908 } 909 910 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 911 /// the desired ByVal argument alignment. 912 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 913 unsigned MaxMaxAlign) { 914 if (MaxAlign == MaxMaxAlign) 915 return; 916 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 917 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 918 MaxAlign = 32; 919 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 920 MaxAlign = 16; 921 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 922 unsigned EltAlign = 0; 923 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 924 if (EltAlign > MaxAlign) 925 MaxAlign = EltAlign; 926 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 927 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 928 unsigned EltAlign = 0; 929 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign); 930 if (EltAlign > MaxAlign) 931 MaxAlign = EltAlign; 932 if (MaxAlign == MaxMaxAlign) 933 break; 934 } 935 } 936 } 937 938 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 939 /// function arguments in the caller parameter area. 940 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const { 941 // Darwin passes everything on 4 byte boundary. 942 if (Subtarget.isDarwin()) 943 return 4; 944 945 // 16byte and wider vectors are passed on 16byte boundary. 946 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 947 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 948 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 949 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 950 return Align; 951 } 952 953 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 954 switch (Opcode) { 955 default: return nullptr; 956 case PPCISD::FSEL: return "PPCISD::FSEL"; 957 case PPCISD::FCFID: return "PPCISD::FCFID"; 958 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 959 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 960 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 961 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 962 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 963 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 964 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 965 case PPCISD::FRE: return "PPCISD::FRE"; 966 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 967 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 968 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 969 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 970 case PPCISD::VPERM: return "PPCISD::VPERM"; 971 case PPCISD::CMPB: return "PPCISD::CMPB"; 972 case PPCISD::Hi: return "PPCISD::Hi"; 973 case PPCISD::Lo: return "PPCISD::Lo"; 974 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 975 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 976 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 977 case PPCISD::SRL: return "PPCISD::SRL"; 978 case PPCISD::SRA: return "PPCISD::SRA"; 979 case PPCISD::SHL: return "PPCISD::SHL"; 980 case PPCISD::CALL: return "PPCISD::CALL"; 981 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 982 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 983 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 984 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 985 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 986 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 987 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 988 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 989 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 990 case PPCISD::VCMP: return "PPCISD::VCMP"; 991 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 992 case PPCISD::LBRX: return "PPCISD::LBRX"; 993 case PPCISD::STBRX: return "PPCISD::STBRX"; 994 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 995 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 996 case PPCISD::LARX: return "PPCISD::LARX"; 997 case PPCISD::STCX: return "PPCISD::STCX"; 998 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 999 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1000 case PPCISD::BDZ: return "PPCISD::BDZ"; 1001 case PPCISD::MFFS: return "PPCISD::MFFS"; 1002 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1003 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1004 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1005 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1006 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1007 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1008 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1009 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1010 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1011 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1012 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1013 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1014 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1015 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1016 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1017 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1018 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1019 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1020 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1021 case PPCISD::SC: return "PPCISD::SC"; 1022 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1023 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1024 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1025 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1026 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1027 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1028 } 1029 } 1030 1031 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const { 1032 if (!VT.isVector()) 1033 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1034 1035 if (Subtarget.hasQPX()) 1036 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1037 1038 return VT.changeVectorElementTypeToInteger(); 1039 } 1040 1041 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1042 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1043 return true; 1044 } 1045 1046 //===----------------------------------------------------------------------===// 1047 // Node matching predicates, for use by the tblgen matching code. 1048 //===----------------------------------------------------------------------===// 1049 1050 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1051 static bool isFloatingPointZero(SDValue Op) { 1052 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1053 return CFP->getValueAPF().isZero(); 1054 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1055 // Maybe this has already been legalized into the constant pool? 1056 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1057 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1058 return CFP->getValueAPF().isZero(); 1059 } 1060 return false; 1061 } 1062 1063 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1064 /// true if Op is undef or if it matches the specified value. 1065 static bool isConstantOrUndef(int Op, int Val) { 1066 return Op < 0 || Op == Val; 1067 } 1068 1069 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1070 /// VPKUHUM instruction. 1071 /// The ShuffleKind distinguishes between big-endian operations with 1072 /// two different inputs (0), either-endian operations with two identical 1073 /// inputs (1), and little-endian operantion with two different inputs (2). 1074 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1075 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1076 SelectionDAG &DAG) { 1077 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian(); 1078 if (ShuffleKind == 0) { 1079 if (IsLE) 1080 return false; 1081 for (unsigned i = 0; i != 16; ++i) 1082 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1083 return false; 1084 } else if (ShuffleKind == 2) { 1085 if (!IsLE) 1086 return false; 1087 for (unsigned i = 0; i != 16; ++i) 1088 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1089 return false; 1090 } else if (ShuffleKind == 1) { 1091 unsigned j = IsLE ? 0 : 1; 1092 for (unsigned i = 0; i != 8; ++i) 1093 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1094 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1095 return false; 1096 } 1097 return true; 1098 } 1099 1100 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1101 /// VPKUWUM instruction. 1102 /// The ShuffleKind distinguishes between big-endian operations with 1103 /// two different inputs (0), either-endian operations with two identical 1104 /// inputs (1), and little-endian operantion with two different inputs (2). 1105 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1106 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1107 SelectionDAG &DAG) { 1108 bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian(); 1109 if (ShuffleKind == 0) { 1110 if (IsLE) 1111 return false; 1112 for (unsigned i = 0; i != 16; i += 2) 1113 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1114 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1115 return false; 1116 } else if (ShuffleKind == 2) { 1117 if (!IsLE) 1118 return false; 1119 for (unsigned i = 0; i != 16; i += 2) 1120 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1121 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1122 return false; 1123 } else if (ShuffleKind == 1) { 1124 unsigned j = IsLE ? 0 : 2; 1125 for (unsigned i = 0; i != 8; i += 2) 1126 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1127 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1128 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1129 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1130 return false; 1131 } 1132 return true; 1133 } 1134 1135 /// isVMerge - Common function, used to match vmrg* shuffles. 1136 /// 1137 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1138 unsigned LHSStart, unsigned RHSStart) { 1139 if (N->getValueType(0) != MVT::v16i8) 1140 return false; 1141 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1142 "Unsupported merge size!"); 1143 1144 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1145 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1146 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1147 LHSStart+j+i*UnitSize) || 1148 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1149 RHSStart+j+i*UnitSize)) 1150 return false; 1151 } 1152 return true; 1153 } 1154 1155 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1156 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1157 /// The ShuffleKind distinguishes between big-endian merges with two 1158 /// different inputs (0), either-endian merges with two identical inputs (1), 1159 /// and little-endian merges with two different inputs (2). For the latter, 1160 /// the input operands are swapped (see PPCInstrAltivec.td). 1161 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1162 unsigned ShuffleKind, SelectionDAG &DAG) { 1163 if (DAG.getTarget().getDataLayout()->isLittleEndian()) { 1164 if (ShuffleKind == 1) // unary 1165 return isVMerge(N, UnitSize, 0, 0); 1166 else if (ShuffleKind == 2) // swapped 1167 return isVMerge(N, UnitSize, 0, 16); 1168 else 1169 return false; 1170 } else { 1171 if (ShuffleKind == 1) // unary 1172 return isVMerge(N, UnitSize, 8, 8); 1173 else if (ShuffleKind == 0) // normal 1174 return isVMerge(N, UnitSize, 8, 24); 1175 else 1176 return false; 1177 } 1178 } 1179 1180 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1181 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1182 /// The ShuffleKind distinguishes between big-endian merges with two 1183 /// different inputs (0), either-endian merges with two identical inputs (1), 1184 /// and little-endian merges with two different inputs (2). For the latter, 1185 /// the input operands are swapped (see PPCInstrAltivec.td). 1186 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1187 unsigned ShuffleKind, SelectionDAG &DAG) { 1188 if (DAG.getTarget().getDataLayout()->isLittleEndian()) { 1189 if (ShuffleKind == 1) // unary 1190 return isVMerge(N, UnitSize, 8, 8); 1191 else if (ShuffleKind == 2) // swapped 1192 return isVMerge(N, UnitSize, 8, 24); 1193 else 1194 return false; 1195 } else { 1196 if (ShuffleKind == 1) // unary 1197 return isVMerge(N, UnitSize, 0, 0); 1198 else if (ShuffleKind == 0) // normal 1199 return isVMerge(N, UnitSize, 0, 16); 1200 else 1201 return false; 1202 } 1203 } 1204 1205 1206 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1207 /// amount, otherwise return -1. 1208 /// The ShuffleKind distinguishes between big-endian operations with two 1209 /// different inputs (0), either-endian operations with two identical inputs 1210 /// (1), and little-endian operations with two different inputs (2). For the 1211 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1212 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1213 SelectionDAG &DAG) { 1214 if (N->getValueType(0) != MVT::v16i8) 1215 return -1; 1216 1217 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1218 1219 // Find the first non-undef value in the shuffle mask. 1220 unsigned i; 1221 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1222 /*search*/; 1223 1224 if (i == 16) return -1; // all undef. 1225 1226 // Otherwise, check to see if the rest of the elements are consecutively 1227 // numbered from this value. 1228 unsigned ShiftAmt = SVOp->getMaskElt(i); 1229 if (ShiftAmt < i) return -1; 1230 1231 ShiftAmt -= i; 1232 bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian(); 1233 1234 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1235 // Check the rest of the elements to see if they are consecutive. 1236 for (++i; i != 16; ++i) 1237 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1238 return -1; 1239 } else if (ShuffleKind == 1) { 1240 // Check the rest of the elements to see if they are consecutive. 1241 for (++i; i != 16; ++i) 1242 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1243 return -1; 1244 } else 1245 return -1; 1246 1247 if (ShuffleKind == 2 && isLE) 1248 ShiftAmt = 16 - ShiftAmt; 1249 1250 return ShiftAmt; 1251 } 1252 1253 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1254 /// specifies a splat of a single element that is suitable for input to 1255 /// VSPLTB/VSPLTH/VSPLTW. 1256 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1257 assert(N->getValueType(0) == MVT::v16i8 && 1258 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1259 1260 // This is a splat operation if each element of the permute is the same, and 1261 // if the value doesn't reference the second vector. 1262 unsigned ElementBase = N->getMaskElt(0); 1263 1264 // FIXME: Handle UNDEF elements too! 1265 if (ElementBase >= 16) 1266 return false; 1267 1268 // Check that the indices are consecutive, in the case of a multi-byte element 1269 // splatted with a v16i8 mask. 1270 for (unsigned i = 1; i != EltSize; ++i) 1271 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1272 return false; 1273 1274 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1275 if (N->getMaskElt(i) < 0) continue; 1276 for (unsigned j = 0; j != EltSize; ++j) 1277 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1278 return false; 1279 } 1280 return true; 1281 } 1282 1283 /// isAllNegativeZeroVector - Returns true if all elements of build_vector 1284 /// are -0.0. 1285 bool PPC::isAllNegativeZeroVector(SDNode *N) { 1286 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N); 1287 1288 APInt APVal, APUndef; 1289 unsigned BitSize; 1290 bool HasAnyUndefs; 1291 1292 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true)) 1293 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 1294 return CFP->getValueAPF().isNegZero(); 1295 1296 return false; 1297 } 1298 1299 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 1300 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 1301 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 1302 SelectionDAG &DAG) { 1303 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1304 assert(isSplatShuffleMask(SVOp, EltSize)); 1305 if (DAG.getTarget().getDataLayout()->isLittleEndian()) 1306 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 1307 else 1308 return SVOp->getMaskElt(0) / EltSize; 1309 } 1310 1311 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 1312 /// by using a vspltis[bhw] instruction of the specified element size, return 1313 /// the constant being splatted. The ByteSize field indicates the number of 1314 /// bytes of each element [124] -> [bhw]. 1315 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 1316 SDValue OpVal(nullptr, 0); 1317 1318 // If ByteSize of the splat is bigger than the element size of the 1319 // build_vector, then we have a case where we are checking for a splat where 1320 // multiple elements of the buildvector are folded together into a single 1321 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 1322 unsigned EltSize = 16/N->getNumOperands(); 1323 if (EltSize < ByteSize) { 1324 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 1325 SDValue UniquedVals[4]; 1326 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 1327 1328 // See if all of the elements in the buildvector agree across. 1329 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1330 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 1331 // If the element isn't a constant, bail fully out. 1332 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 1333 1334 1335 if (!UniquedVals[i&(Multiple-1)].getNode()) 1336 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 1337 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 1338 return SDValue(); // no match. 1339 } 1340 1341 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 1342 // either constant or undef values that are identical for each chunk. See 1343 // if these chunks can form into a larger vspltis*. 1344 1345 // Check to see if all of the leading entries are either 0 or -1. If 1346 // neither, then this won't fit into the immediate field. 1347 bool LeadingZero = true; 1348 bool LeadingOnes = true; 1349 for (unsigned i = 0; i != Multiple-1; ++i) { 1350 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 1351 1352 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue(); 1353 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue(); 1354 } 1355 // Finally, check the least significant entry. 1356 if (LeadingZero) { 1357 if (!UniquedVals[Multiple-1].getNode()) 1358 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef 1359 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 1360 if (Val < 16) 1361 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4) 1362 } 1363 if (LeadingOnes) { 1364 if (!UniquedVals[Multiple-1].getNode()) 1365 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef 1366 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 1367 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 1368 return DAG.getTargetConstant(Val, MVT::i32); 1369 } 1370 1371 return SDValue(); 1372 } 1373 1374 // Check to see if this buildvec has a single non-undef value in its elements. 1375 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1376 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 1377 if (!OpVal.getNode()) 1378 OpVal = N->getOperand(i); 1379 else if (OpVal != N->getOperand(i)) 1380 return SDValue(); 1381 } 1382 1383 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 1384 1385 unsigned ValSizeInBytes = EltSize; 1386 uint64_t Value = 0; 1387 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 1388 Value = CN->getZExtValue(); 1389 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 1390 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 1391 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 1392 } 1393 1394 // If the splat value is larger than the element value, then we can never do 1395 // this splat. The only case that we could fit the replicated bits into our 1396 // immediate field for would be zero, and we prefer to use vxor for it. 1397 if (ValSizeInBytes < ByteSize) return SDValue(); 1398 1399 // If the element value is larger than the splat value, cut it in half and 1400 // check to see if the two halves are equal. Continue doing this until we 1401 // get to ByteSize. This allows us to handle 0x01010101 as 0x01. 1402 while (ValSizeInBytes > ByteSize) { 1403 ValSizeInBytes >>= 1; 1404 1405 // If the top half equals the bottom half, we're still ok. 1406 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) != 1407 (Value & ((1 << (8*ValSizeInBytes))-1))) 1408 return SDValue(); 1409 } 1410 1411 // Properly sign extend the value. 1412 int MaskVal = SignExtend32(Value, ByteSize * 8); 1413 1414 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 1415 if (MaskVal == 0) return SDValue(); 1416 1417 // Finally, if this value fits in a 5 bit sext field, return it 1418 if (SignExtend32<5>(MaskVal) == MaskVal) 1419 return DAG.getTargetConstant(MaskVal, MVT::i32); 1420 return SDValue(); 1421 } 1422 1423 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 1424 /// amount, otherwise return -1. 1425 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 1426 EVT VT = N->getValueType(0); 1427 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 1428 return -1; 1429 1430 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1431 1432 // Find the first non-undef value in the shuffle mask. 1433 unsigned i; 1434 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 1435 /*search*/; 1436 1437 if (i == 4) return -1; // all undef. 1438 1439 // Otherwise, check to see if the rest of the elements are consecutively 1440 // numbered from this value. 1441 unsigned ShiftAmt = SVOp->getMaskElt(i); 1442 if (ShiftAmt < i) return -1; 1443 ShiftAmt -= i; 1444 1445 // Check the rest of the elements to see if they are consecutive. 1446 for (++i; i != 4; ++i) 1447 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1448 return -1; 1449 1450 return ShiftAmt; 1451 } 1452 1453 //===----------------------------------------------------------------------===// 1454 // Addressing Mode Selection 1455 //===----------------------------------------------------------------------===// 1456 1457 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 1458 /// or 64-bit immediate, and if the value can be accurately represented as a 1459 /// sign extension from a 16-bit value. If so, this returns true and the 1460 /// immediate. 1461 static bool isIntS16Immediate(SDNode *N, short &Imm) { 1462 if (!isa<ConstantSDNode>(N)) 1463 return false; 1464 1465 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue(); 1466 if (N->getValueType(0) == MVT::i32) 1467 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 1468 else 1469 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 1470 } 1471 static bool isIntS16Immediate(SDValue Op, short &Imm) { 1472 return isIntS16Immediate(Op.getNode(), Imm); 1473 } 1474 1475 1476 /// SelectAddressRegReg - Given the specified addressed, check to see if it 1477 /// can be represented as an indexed [r+r] operation. Returns false if it 1478 /// can be more efficiently represented with [r+imm]. 1479 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 1480 SDValue &Index, 1481 SelectionDAG &DAG) const { 1482 short imm = 0; 1483 if (N.getOpcode() == ISD::ADD) { 1484 if (isIntS16Immediate(N.getOperand(1), imm)) 1485 return false; // r+i 1486 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 1487 return false; // r+i 1488 1489 Base = N.getOperand(0); 1490 Index = N.getOperand(1); 1491 return true; 1492 } else if (N.getOpcode() == ISD::OR) { 1493 if (isIntS16Immediate(N.getOperand(1), imm)) 1494 return false; // r+i can fold it if we can. 1495 1496 // If this is an or of disjoint bitfields, we can codegen this as an add 1497 // (for better address arithmetic) if the LHS and RHS of the OR are provably 1498 // disjoint. 1499 APInt LHSKnownZero, LHSKnownOne; 1500 APInt RHSKnownZero, RHSKnownOne; 1501 DAG.computeKnownBits(N.getOperand(0), 1502 LHSKnownZero, LHSKnownOne); 1503 1504 if (LHSKnownZero.getBoolValue()) { 1505 DAG.computeKnownBits(N.getOperand(1), 1506 RHSKnownZero, RHSKnownOne); 1507 // If all of the bits are known zero on the LHS or RHS, the add won't 1508 // carry. 1509 if (~(LHSKnownZero | RHSKnownZero) == 0) { 1510 Base = N.getOperand(0); 1511 Index = N.getOperand(1); 1512 return true; 1513 } 1514 } 1515 } 1516 1517 return false; 1518 } 1519 1520 // If we happen to be doing an i64 load or store into a stack slot that has 1521 // less than a 4-byte alignment, then the frame-index elimination may need to 1522 // use an indexed load or store instruction (because the offset may not be a 1523 // multiple of 4). The extra register needed to hold the offset comes from the 1524 // register scavenger, and it is possible that the scavenger will need to use 1525 // an emergency spill slot. As a result, we need to make sure that a spill slot 1526 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 1527 // stack slot. 1528 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 1529 // FIXME: This does not handle the LWA case. 1530 if (VT != MVT::i64) 1531 return; 1532 1533 // NOTE: We'll exclude negative FIs here, which come from argument 1534 // lowering, because there are no known test cases triggering this problem 1535 // using packed structures (or similar). We can remove this exclusion if 1536 // we find such a test case. The reason why this is so test-case driven is 1537 // because this entire 'fixup' is only to prevent crashes (from the 1538 // register scavenger) on not-really-valid inputs. For example, if we have: 1539 // %a = alloca i1 1540 // %b = bitcast i1* %a to i64* 1541 // store i64* a, i64 b 1542 // then the store should really be marked as 'align 1', but is not. If it 1543 // were marked as 'align 1' then the indexed form would have been 1544 // instruction-selected initially, and the problem this 'fixup' is preventing 1545 // won't happen regardless. 1546 if (FrameIdx < 0) 1547 return; 1548 1549 MachineFunction &MF = DAG.getMachineFunction(); 1550 MachineFrameInfo *MFI = MF.getFrameInfo(); 1551 1552 unsigned Align = MFI->getObjectAlignment(FrameIdx); 1553 if (Align >= 4) 1554 return; 1555 1556 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1557 FuncInfo->setHasNonRISpills(); 1558 } 1559 1560 /// Returns true if the address N can be represented by a base register plus 1561 /// a signed 16-bit displacement [r+imm], and if it is not better 1562 /// represented as reg+reg. If Aligned is true, only accept displacements 1563 /// suitable for STD and friends, i.e. multiples of 4. 1564 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 1565 SDValue &Base, 1566 SelectionDAG &DAG, 1567 bool Aligned) const { 1568 // FIXME dl should come from parent load or store, not from address 1569 SDLoc dl(N); 1570 // If this can be more profitably realized as r+r, fail. 1571 if (SelectAddressRegReg(N, Disp, Base, DAG)) 1572 return false; 1573 1574 if (N.getOpcode() == ISD::ADD) { 1575 short imm = 0; 1576 if (isIntS16Immediate(N.getOperand(1), imm) && 1577 (!Aligned || (imm & 3) == 0)) { 1578 Disp = DAG.getTargetConstant(imm, N.getValueType()); 1579 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 1580 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1581 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 1582 } else { 1583 Base = N.getOperand(0); 1584 } 1585 return true; // [r+i] 1586 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 1587 // Match LOAD (ADD (X, Lo(G))). 1588 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 1589 && "Cannot handle constant offsets yet!"); 1590 Disp = N.getOperand(1).getOperand(0); // The global address. 1591 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 1592 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 1593 Disp.getOpcode() == ISD::TargetConstantPool || 1594 Disp.getOpcode() == ISD::TargetJumpTable); 1595 Base = N.getOperand(0); 1596 return true; // [&g+r] 1597 } 1598 } else if (N.getOpcode() == ISD::OR) { 1599 short imm = 0; 1600 if (isIntS16Immediate(N.getOperand(1), imm) && 1601 (!Aligned || (imm & 3) == 0)) { 1602 // If this is an or of disjoint bitfields, we can codegen this as an add 1603 // (for better address arithmetic) if the LHS and RHS of the OR are 1604 // provably disjoint. 1605 APInt LHSKnownZero, LHSKnownOne; 1606 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne); 1607 1608 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 1609 // If all of the bits are known zero on the LHS or RHS, the add won't 1610 // carry. 1611 if (FrameIndexSDNode *FI = 1612 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 1613 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1614 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 1615 } else { 1616 Base = N.getOperand(0); 1617 } 1618 Disp = DAG.getTargetConstant(imm, N.getValueType()); 1619 return true; 1620 } 1621 } 1622 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 1623 // Loading from a constant address. 1624 1625 // If this address fits entirely in a 16-bit sext immediate field, codegen 1626 // this as "d, 0" 1627 short Imm; 1628 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) { 1629 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0)); 1630 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 1631 CN->getValueType(0)); 1632 return true; 1633 } 1634 1635 // Handle 32-bit sext immediates with LIS + addr mode. 1636 if ((CN->getValueType(0) == MVT::i32 || 1637 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 1638 (!Aligned || (CN->getZExtValue() & 3) == 0)) { 1639 int Addr = (int)CN->getZExtValue(); 1640 1641 // Otherwise, break this down into an LIS + disp. 1642 Disp = DAG.getTargetConstant((short)Addr, MVT::i32); 1643 1644 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32); 1645 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 1646 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 1647 return true; 1648 } 1649 } 1650 1651 Disp = DAG.getTargetConstant(0, getPointerTy()); 1652 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 1653 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1654 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 1655 } else 1656 Base = N; 1657 return true; // [r+0] 1658 } 1659 1660 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 1661 /// represented as an indexed [r+r] operation. 1662 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 1663 SDValue &Index, 1664 SelectionDAG &DAG) const { 1665 // Check to see if we can easily represent this as an [r+r] address. This 1666 // will fail if it thinks that the address is more profitably represented as 1667 // reg+imm, e.g. where imm = 0. 1668 if (SelectAddressRegReg(N, Base, Index, DAG)) 1669 return true; 1670 1671 // If the operand is an addition, always emit this as [r+r], since this is 1672 // better (for code size, and execution, as the memop does the add for free) 1673 // than emitting an explicit add. 1674 if (N.getOpcode() == ISD::ADD) { 1675 Base = N.getOperand(0); 1676 Index = N.getOperand(1); 1677 return true; 1678 } 1679 1680 // Otherwise, do it the hard way, using R0 as the base register. 1681 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 1682 N.getValueType()); 1683 Index = N; 1684 return true; 1685 } 1686 1687 /// getPreIndexedAddressParts - returns true by value, base pointer and 1688 /// offset pointer and addressing mode by reference if the node's address 1689 /// can be legally represented as pre-indexed load / store address. 1690 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 1691 SDValue &Offset, 1692 ISD::MemIndexedMode &AM, 1693 SelectionDAG &DAG) const { 1694 if (DisablePPCPreinc) return false; 1695 1696 bool isLoad = true; 1697 SDValue Ptr; 1698 EVT VT; 1699 unsigned Alignment; 1700 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 1701 Ptr = LD->getBasePtr(); 1702 VT = LD->getMemoryVT(); 1703 Alignment = LD->getAlignment(); 1704 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 1705 Ptr = ST->getBasePtr(); 1706 VT = ST->getMemoryVT(); 1707 Alignment = ST->getAlignment(); 1708 isLoad = false; 1709 } else 1710 return false; 1711 1712 // PowerPC doesn't have preinc load/store instructions for vectors (except 1713 // for QPX, which does have preinc r+r forms). 1714 if (VT.isVector()) { 1715 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 1716 return false; 1717 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 1718 AM = ISD::PRE_INC; 1719 return true; 1720 } 1721 } 1722 1723 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 1724 1725 // Common code will reject creating a pre-inc form if the base pointer 1726 // is a frame index, or if N is a store and the base pointer is either 1727 // the same as or a predecessor of the value being stored. Check for 1728 // those situations here, and try with swapped Base/Offset instead. 1729 bool Swap = false; 1730 1731 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 1732 Swap = true; 1733 else if (!isLoad) { 1734 SDValue Val = cast<StoreSDNode>(N)->getValue(); 1735 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 1736 Swap = true; 1737 } 1738 1739 if (Swap) 1740 std::swap(Base, Offset); 1741 1742 AM = ISD::PRE_INC; 1743 return true; 1744 } 1745 1746 // LDU/STU can only handle immediates that are a multiple of 4. 1747 if (VT != MVT::i64) { 1748 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false)) 1749 return false; 1750 } else { 1751 // LDU/STU need an address with at least 4-byte alignment. 1752 if (Alignment < 4) 1753 return false; 1754 1755 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true)) 1756 return false; 1757 } 1758 1759 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 1760 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 1761 // sext i32 to i64 when addr mode is r+i. 1762 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 1763 LD->getExtensionType() == ISD::SEXTLOAD && 1764 isa<ConstantSDNode>(Offset)) 1765 return false; 1766 } 1767 1768 AM = ISD::PRE_INC; 1769 return true; 1770 } 1771 1772 //===----------------------------------------------------------------------===// 1773 // LowerOperation implementation 1774 //===----------------------------------------------------------------------===// 1775 1776 /// GetLabelAccessInfo - Return true if we should reference labels using a 1777 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags. 1778 static bool GetLabelAccessInfo(const TargetMachine &TM, 1779 const PPCSubtarget &Subtarget, 1780 unsigned &HiOpFlags, unsigned &LoOpFlags, 1781 const GlobalValue *GV = nullptr) { 1782 HiOpFlags = PPCII::MO_HA; 1783 LoOpFlags = PPCII::MO_LO; 1784 1785 // Don't use the pic base if not in PIC relocation model. 1786 bool isPIC = TM.getRelocationModel() == Reloc::PIC_; 1787 1788 if (isPIC) { 1789 HiOpFlags |= PPCII::MO_PIC_FLAG; 1790 LoOpFlags |= PPCII::MO_PIC_FLAG; 1791 } 1792 1793 // If this is a reference to a global value that requires a non-lazy-ptr, make 1794 // sure that instruction lowering adds it. 1795 if (GV && Subtarget.hasLazyResolverStub(GV)) { 1796 HiOpFlags |= PPCII::MO_NLP_FLAG; 1797 LoOpFlags |= PPCII::MO_NLP_FLAG; 1798 1799 if (GV->hasHiddenVisibility()) { 1800 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 1801 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 1802 } 1803 } 1804 1805 return isPIC; 1806 } 1807 1808 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 1809 SelectionDAG &DAG) { 1810 EVT PtrVT = HiPart.getValueType(); 1811 SDValue Zero = DAG.getConstant(0, PtrVT); 1812 SDLoc DL(HiPart); 1813 1814 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 1815 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 1816 1817 // With PIC, the first instruction is actually "GR+hi(&G)". 1818 if (isPIC) 1819 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 1820 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 1821 1822 // Generate non-pic code that has direct accesses to the constant pool. 1823 // The address of the global is just (hi(&g)+lo(&g)). 1824 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 1825 } 1826 1827 static void setUsesTOCBasePtr(MachineFunction &MF) { 1828 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1829 FuncInfo->setUsesTOCBasePtr(); 1830 } 1831 1832 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 1833 setUsesTOCBasePtr(DAG.getMachineFunction()); 1834 } 1835 1836 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit, 1837 SDValue GA) { 1838 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 1839 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 1840 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 1841 1842 SDValue Ops[] = { GA, Reg }; 1843 return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl, 1844 DAG.getVTList(VT, MVT::Other), Ops, VT, 1845 MachinePointerInfo::getGOT(), 0, false, true, 1846 false, 0); 1847 } 1848 1849 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 1850 SelectionDAG &DAG) const { 1851 EVT PtrVT = Op.getValueType(); 1852 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 1853 const Constant *C = CP->getConstVal(); 1854 1855 // 64-bit SVR4 ABI code is always position-independent. 1856 // The actual address of the GlobalValue is stored in the TOC. 1857 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 1858 setUsesTOCBasePtr(DAG); 1859 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 1860 return getTOCEntry(DAG, SDLoc(CP), true, GA); 1861 } 1862 1863 unsigned MOHiFlag, MOLoFlag; 1864 bool isPIC = 1865 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag); 1866 1867 if (isPIC && Subtarget.isSVR4ABI()) { 1868 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 1869 PPCII::MO_PIC_FLAG); 1870 return getTOCEntry(DAG, SDLoc(CP), false, GA); 1871 } 1872 1873 SDValue CPIHi = 1874 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 1875 SDValue CPILo = 1876 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 1877 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG); 1878 } 1879 1880 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 1881 EVT PtrVT = Op.getValueType(); 1882 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 1883 1884 // 64-bit SVR4 ABI code is always position-independent. 1885 // The actual address of the GlobalValue is stored in the TOC. 1886 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 1887 setUsesTOCBasePtr(DAG); 1888 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 1889 return getTOCEntry(DAG, SDLoc(JT), true, GA); 1890 } 1891 1892 unsigned MOHiFlag, MOLoFlag; 1893 bool isPIC = 1894 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag); 1895 1896 if (isPIC && Subtarget.isSVR4ABI()) { 1897 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 1898 PPCII::MO_PIC_FLAG); 1899 return getTOCEntry(DAG, SDLoc(GA), false, GA); 1900 } 1901 1902 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 1903 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 1904 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG); 1905 } 1906 1907 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 1908 SelectionDAG &DAG) const { 1909 EVT PtrVT = Op.getValueType(); 1910 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 1911 const BlockAddress *BA = BASDN->getBlockAddress(); 1912 1913 // 64-bit SVR4 ABI code is always position-independent. 1914 // The actual BlockAddress is stored in the TOC. 1915 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 1916 setUsesTOCBasePtr(DAG); 1917 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 1918 return getTOCEntry(DAG, SDLoc(BASDN), true, GA); 1919 } 1920 1921 unsigned MOHiFlag, MOLoFlag; 1922 bool isPIC = 1923 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag); 1924 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 1925 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 1926 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG); 1927 } 1928 1929 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 1930 SelectionDAG &DAG) const { 1931 1932 // FIXME: TLS addresses currently use medium model code sequences, 1933 // which is the most useful form. Eventually support for small and 1934 // large models could be added if users need it, at the cost of 1935 // additional complexity. 1936 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 1937 SDLoc dl(GA); 1938 const GlobalValue *GV = GA->getGlobal(); 1939 EVT PtrVT = getPointerTy(); 1940 bool is64bit = Subtarget.isPPC64(); 1941 const Module *M = DAG.getMachineFunction().getFunction()->getParent(); 1942 PICLevel::Level picLevel = M->getPICLevel(); 1943 1944 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 1945 1946 if (Model == TLSModel::LocalExec) { 1947 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 1948 PPCII::MO_TPREL_HA); 1949 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 1950 PPCII::MO_TPREL_LO); 1951 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2, 1952 is64bit ? MVT::i64 : MVT::i32); 1953 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 1954 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 1955 } 1956 1957 if (Model == TLSModel::InitialExec) { 1958 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 1959 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 1960 PPCII::MO_TLS); 1961 SDValue GOTPtr; 1962 if (is64bit) { 1963 setUsesTOCBasePtr(DAG); 1964 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 1965 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 1966 PtrVT, GOTReg, TGA); 1967 } else 1968 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 1969 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 1970 PtrVT, TGA, GOTPtr); 1971 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 1972 } 1973 1974 if (Model == TLSModel::GeneralDynamic) { 1975 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 1976 SDValue GOTPtr; 1977 if (is64bit) { 1978 setUsesTOCBasePtr(DAG); 1979 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 1980 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 1981 GOTReg, TGA); 1982 } else { 1983 if (picLevel == PICLevel::Small) 1984 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 1985 else 1986 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 1987 } 1988 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 1989 GOTPtr, TGA, TGA); 1990 } 1991 1992 if (Model == TLSModel::LocalDynamic) { 1993 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 1994 SDValue GOTPtr; 1995 if (is64bit) { 1996 setUsesTOCBasePtr(DAG); 1997 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 1998 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 1999 GOTReg, TGA); 2000 } else { 2001 if (picLevel == PICLevel::Small) 2002 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2003 else 2004 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2005 } 2006 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2007 PtrVT, GOTPtr, TGA, TGA); 2008 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2009 PtrVT, TLSAddr, TGA); 2010 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2011 } 2012 2013 llvm_unreachable("Unknown TLS model!"); 2014 } 2015 2016 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2017 SelectionDAG &DAG) const { 2018 EVT PtrVT = Op.getValueType(); 2019 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2020 SDLoc DL(GSDN); 2021 const GlobalValue *GV = GSDN->getGlobal(); 2022 2023 // 64-bit SVR4 ABI code is always position-independent. 2024 // The actual address of the GlobalValue is stored in the TOC. 2025 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2026 setUsesTOCBasePtr(DAG); 2027 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2028 return getTOCEntry(DAG, DL, true, GA); 2029 } 2030 2031 unsigned MOHiFlag, MOLoFlag; 2032 bool isPIC = 2033 GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV); 2034 2035 if (isPIC && Subtarget.isSVR4ABI()) { 2036 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2037 GSDN->getOffset(), 2038 PPCII::MO_PIC_FLAG); 2039 return getTOCEntry(DAG, DL, false, GA); 2040 } 2041 2042 SDValue GAHi = 2043 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2044 SDValue GALo = 2045 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2046 2047 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG); 2048 2049 // If the global reference is actually to a non-lazy-pointer, we have to do an 2050 // extra load to get the address of the global. 2051 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2052 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(), 2053 false, false, false, 0); 2054 return Ptr; 2055 } 2056 2057 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2058 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2059 SDLoc dl(Op); 2060 2061 if (Op.getValueType() == MVT::v2i64) { 2062 // When the operands themselves are v2i64 values, we need to do something 2063 // special because VSX has no underlying comparison operations for these. 2064 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2065 // Equality can be handled by casting to the legal type for Altivec 2066 // comparisons, everything else needs to be expanded. 2067 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2068 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2069 DAG.getSetCC(dl, MVT::v4i32, 2070 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2071 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2072 CC)); 2073 } 2074 2075 return SDValue(); 2076 } 2077 2078 // We handle most of these in the usual way. 2079 return Op; 2080 } 2081 2082 // If we're comparing for equality to zero, expose the fact that this is 2083 // implented as a ctlz/srl pair on ppc, so that the dag combiner can 2084 // fold the new nodes. 2085 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2086 if (C->isNullValue() && CC == ISD::SETEQ) { 2087 EVT VT = Op.getOperand(0).getValueType(); 2088 SDValue Zext = Op.getOperand(0); 2089 if (VT.bitsLT(MVT::i32)) { 2090 VT = MVT::i32; 2091 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 2092 } 2093 unsigned Log2b = Log2_32(VT.getSizeInBits()); 2094 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 2095 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 2096 DAG.getConstant(Log2b, MVT::i32)); 2097 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 2098 } 2099 // Leave comparisons against 0 and -1 alone for now, since they're usually 2100 // optimized. FIXME: revisit this when we can custom lower all setcc 2101 // optimizations. 2102 if (C->isAllOnesValue() || C->isNullValue()) 2103 return SDValue(); 2104 } 2105 2106 // If we have an integer seteq/setne, turn it into a compare against zero 2107 // by xor'ing the rhs with the lhs, which is faster than setting a 2108 // condition register, reading it back out, and masking the correct bit. The 2109 // normal approach here uses sub to do this instead of xor. Using xor exposes 2110 // the result to other bit-twiddling opportunities. 2111 EVT LHSVT = Op.getOperand(0).getValueType(); 2112 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2113 EVT VT = Op.getValueType(); 2114 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2115 Op.getOperand(1)); 2116 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC); 2117 } 2118 return SDValue(); 2119 } 2120 2121 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG, 2122 const PPCSubtarget &Subtarget) const { 2123 SDNode *Node = Op.getNode(); 2124 EVT VT = Node->getValueType(0); 2125 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2126 SDValue InChain = Node->getOperand(0); 2127 SDValue VAListPtr = Node->getOperand(1); 2128 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2129 SDLoc dl(Node); 2130 2131 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2132 2133 // gpr_index 2134 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2135 VAListPtr, MachinePointerInfo(SV), MVT::i8, 2136 false, false, false, 0); 2137 InChain = GprIndex.getValue(1); 2138 2139 if (VT == MVT::i64) { 2140 // Check if GprIndex is even 2141 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2142 DAG.getConstant(1, MVT::i32)); 2143 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2144 DAG.getConstant(0, MVT::i32), ISD::SETNE); 2145 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2146 DAG.getConstant(1, MVT::i32)); 2147 // Align GprIndex to be even if it isn't 2148 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2149 GprIndex); 2150 } 2151 2152 // fpr index is 1 byte after gpr 2153 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2154 DAG.getConstant(1, MVT::i32)); 2155 2156 // fpr 2157 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2158 FprPtr, MachinePointerInfo(SV), MVT::i8, 2159 false, false, false, 0); 2160 InChain = FprIndex.getValue(1); 2161 2162 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2163 DAG.getConstant(8, MVT::i32)); 2164 2165 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2166 DAG.getConstant(4, MVT::i32)); 2167 2168 // areas 2169 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, 2170 MachinePointerInfo(), false, false, 2171 false, 0); 2172 InChain = OverflowArea.getValue(1); 2173 2174 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, 2175 MachinePointerInfo(), false, false, 2176 false, 0); 2177 InChain = RegSaveArea.getValue(1); 2178 2179 // select overflow_area if index > 8 2180 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2181 DAG.getConstant(8, MVT::i32), ISD::SETLT); 2182 2183 // adjustment constant gpr_index * 4/8 2184 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2185 VT.isInteger() ? GprIndex : FprIndex, 2186 DAG.getConstant(VT.isInteger() ? 4 : 8, 2187 MVT::i32)); 2188 2189 // OurReg = RegSaveArea + RegConstant 2190 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2191 RegConstant); 2192 2193 // Floating types are 32 bytes into RegSaveArea 2194 if (VT.isFloatingPoint()) 2195 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 2196 DAG.getConstant(32, MVT::i32)); 2197 2198 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 2199 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 2200 VT.isInteger() ? GprIndex : FprIndex, 2201 DAG.getConstant(VT == MVT::i64 ? 2 : 1, 2202 MVT::i32)); 2203 2204 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 2205 VT.isInteger() ? VAListPtr : FprPtr, 2206 MachinePointerInfo(SV), 2207 MVT::i8, false, false, 0); 2208 2209 // determine if we should load from reg_save_area or overflow_area 2210 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 2211 2212 // increase overflow_area by 4/8 if gpr/fpr > 8 2213 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 2214 DAG.getConstant(VT.isInteger() ? 4 : 8, 2215 MVT::i32)); 2216 2217 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 2218 OverflowAreaPlusN); 2219 2220 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, 2221 OverflowAreaPtr, 2222 MachinePointerInfo(), 2223 MVT::i32, false, false, 0); 2224 2225 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(), 2226 false, false, false, 0); 2227 } 2228 2229 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG, 2230 const PPCSubtarget &Subtarget) const { 2231 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 2232 2233 // We have to copy the entire va_list struct: 2234 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 2235 return DAG.getMemcpy(Op.getOperand(0), Op, 2236 Op.getOperand(1), Op.getOperand(2), 2237 DAG.getConstant(12, MVT::i32), 8, false, true, 2238 MachinePointerInfo(), MachinePointerInfo()); 2239 } 2240 2241 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 2242 SelectionDAG &DAG) const { 2243 return Op.getOperand(0); 2244 } 2245 2246 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 2247 SelectionDAG &DAG) const { 2248 SDValue Chain = Op.getOperand(0); 2249 SDValue Trmp = Op.getOperand(1); // trampoline 2250 SDValue FPtr = Op.getOperand(2); // nested function 2251 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 2252 SDLoc dl(Op); 2253 2254 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2255 bool isPPC64 = (PtrVT == MVT::i64); 2256 Type *IntPtrTy = 2257 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType( 2258 *DAG.getContext()); 2259 2260 TargetLowering::ArgListTy Args; 2261 TargetLowering::ArgListEntry Entry; 2262 2263 Entry.Ty = IntPtrTy; 2264 Entry.Node = Trmp; Args.push_back(Entry); 2265 2266 // TrampSize == (isPPC64 ? 48 : 40); 2267 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, 2268 isPPC64 ? MVT::i64 : MVT::i32); 2269 Args.push_back(Entry); 2270 2271 Entry.Node = FPtr; Args.push_back(Entry); 2272 Entry.Node = Nest; Args.push_back(Entry); 2273 2274 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 2275 TargetLowering::CallLoweringInfo CLI(DAG); 2276 CLI.setDebugLoc(dl).setChain(Chain) 2277 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), 2278 DAG.getExternalSymbol("__trampoline_setup", PtrVT), 2279 std::move(Args), 0); 2280 2281 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2282 return CallResult.second; 2283 } 2284 2285 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG, 2286 const PPCSubtarget &Subtarget) const { 2287 MachineFunction &MF = DAG.getMachineFunction(); 2288 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2289 2290 SDLoc dl(Op); 2291 2292 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 2293 // vastart just stores the address of the VarArgsFrameIndex slot into the 2294 // memory location argument. 2295 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2296 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2297 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2298 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2299 MachinePointerInfo(SV), 2300 false, false, 0); 2301 } 2302 2303 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 2304 // We suppose the given va_list is already allocated. 2305 // 2306 // typedef struct { 2307 // char gpr; /* index into the array of 8 GPRs 2308 // * stored in the register save area 2309 // * gpr=0 corresponds to r3, 2310 // * gpr=1 to r4, etc. 2311 // */ 2312 // char fpr; /* index into the array of 8 FPRs 2313 // * stored in the register save area 2314 // * fpr=0 corresponds to f1, 2315 // * fpr=1 to f2, etc. 2316 // */ 2317 // char *overflow_arg_area; 2318 // /* location on stack that holds 2319 // * the next overflow argument 2320 // */ 2321 // char *reg_save_area; 2322 // /* where r3:r10 and f1:f8 (if saved) 2323 // * are stored 2324 // */ 2325 // } va_list[1]; 2326 2327 2328 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32); 2329 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32); 2330 2331 2332 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2333 2334 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 2335 PtrVT); 2336 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 2337 PtrVT); 2338 2339 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 2340 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT); 2341 2342 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 2343 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT); 2344 2345 uint64_t FPROffset = 1; 2346 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT); 2347 2348 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2349 2350 // Store first byte : number of int regs 2351 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, 2352 Op.getOperand(1), 2353 MachinePointerInfo(SV), 2354 MVT::i8, false, false, 0); 2355 uint64_t nextOffset = FPROffset; 2356 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 2357 ConstFPROffset); 2358 2359 // Store second byte : number of float regs 2360 SDValue secondStore = 2361 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 2362 MachinePointerInfo(SV, nextOffset), MVT::i8, 2363 false, false, 0); 2364 nextOffset += StackOffset; 2365 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 2366 2367 // Store second word : arguments given on stack 2368 SDValue thirdStore = 2369 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 2370 MachinePointerInfo(SV, nextOffset), 2371 false, false, 0); 2372 nextOffset += FrameOffset; 2373 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 2374 2375 // Store third word : arguments given in registers 2376 return DAG.getStore(thirdStore, dl, FR, nextPtr, 2377 MachinePointerInfo(SV, nextOffset), 2378 false, false, 0); 2379 2380 } 2381 2382 #include "PPCGenCallingConv.inc" 2383 2384 // Function whose sole purpose is to kill compiler warnings 2385 // stemming from unused functions included from PPCGenCallingConv.inc. 2386 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { 2387 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; 2388 } 2389 2390 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 2391 CCValAssign::LocInfo &LocInfo, 2392 ISD::ArgFlagsTy &ArgFlags, 2393 CCState &State) { 2394 return true; 2395 } 2396 2397 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 2398 MVT &LocVT, 2399 CCValAssign::LocInfo &LocInfo, 2400 ISD::ArgFlagsTy &ArgFlags, 2401 CCState &State) { 2402 static const MCPhysReg ArgRegs[] = { 2403 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 2404 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 2405 }; 2406 const unsigned NumArgRegs = array_lengthof(ArgRegs); 2407 2408 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 2409 2410 // Skip one register if the first unallocated register has an even register 2411 // number and there are still argument registers available which have not been 2412 // allocated yet. RegNum is actually an index into ArgRegs, which means we 2413 // need to skip a register if RegNum is odd. 2414 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 2415 State.AllocateReg(ArgRegs[RegNum]); 2416 } 2417 2418 // Always return false here, as this function only makes sure that the first 2419 // unallocated register has an odd register number and does not actually 2420 // allocate a register for the current argument. 2421 return false; 2422 } 2423 2424 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 2425 MVT &LocVT, 2426 CCValAssign::LocInfo &LocInfo, 2427 ISD::ArgFlagsTy &ArgFlags, 2428 CCState &State) { 2429 static const MCPhysReg ArgRegs[] = { 2430 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 2431 PPC::F8 2432 }; 2433 2434 const unsigned NumArgRegs = array_lengthof(ArgRegs); 2435 2436 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 2437 2438 // If there is only one Floating-point register left we need to put both f64 2439 // values of a split ppc_fp128 value on the stack. 2440 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 2441 State.AllocateReg(ArgRegs[RegNum]); 2442 } 2443 2444 // Always return false here, as this function only makes sure that the two f64 2445 // values a ppc_fp128 value is split into are both passed in registers or both 2446 // passed on the stack and does not actually allocate a register for the 2447 // current argument. 2448 return false; 2449 } 2450 2451 /// FPR - The set of FP registers that should be allocated for arguments, 2452 /// on Darwin. 2453 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 2454 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 2455 PPC::F11, PPC::F12, PPC::F13}; 2456 2457 /// QFPR - The set of QPX registers that should be allocated for arguments. 2458 static const MCPhysReg QFPR[] = { 2459 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 2460 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 2461 2462 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 2463 /// the stack. 2464 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 2465 unsigned PtrByteSize) { 2466 unsigned ArgSize = ArgVT.getStoreSize(); 2467 if (Flags.isByVal()) 2468 ArgSize = Flags.getByValSize(); 2469 2470 // Round up to multiples of the pointer size, except for array members, 2471 // which are always packed. 2472 if (!Flags.isInConsecutiveRegs()) 2473 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2474 2475 return ArgSize; 2476 } 2477 2478 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 2479 /// on the stack. 2480 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 2481 ISD::ArgFlagsTy Flags, 2482 unsigned PtrByteSize) { 2483 unsigned Align = PtrByteSize; 2484 2485 // Altivec parameters are padded to a 16 byte boundary. 2486 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 2487 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 2488 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) 2489 Align = 16; 2490 // QPX vector types stored in double-precision are padded to a 32 byte 2491 // boundary. 2492 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 2493 Align = 32; 2494 2495 // ByVal parameters are aligned as requested. 2496 if (Flags.isByVal()) { 2497 unsigned BVAlign = Flags.getByValAlign(); 2498 if (BVAlign > PtrByteSize) { 2499 if (BVAlign % PtrByteSize != 0) 2500 llvm_unreachable( 2501 "ByVal alignment is not a multiple of the pointer size"); 2502 2503 Align = BVAlign; 2504 } 2505 } 2506 2507 // Array members are always packed to their original alignment. 2508 if (Flags.isInConsecutiveRegs()) { 2509 // If the array member was split into multiple registers, the first 2510 // needs to be aligned to the size of the full type. (Except for 2511 // ppcf128, which is only aligned as its f64 components.) 2512 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 2513 Align = OrigVT.getStoreSize(); 2514 else 2515 Align = ArgVT.getStoreSize(); 2516 } 2517 2518 return Align; 2519 } 2520 2521 /// CalculateStackSlotUsed - Return whether this argument will use its 2522 /// stack slot (instead of being passed in registers). ArgOffset, 2523 /// AvailableFPRs, and AvailableVRs must hold the current argument 2524 /// position, and will be updated to account for this argument. 2525 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 2526 ISD::ArgFlagsTy Flags, 2527 unsigned PtrByteSize, 2528 unsigned LinkageSize, 2529 unsigned ParamAreaSize, 2530 unsigned &ArgOffset, 2531 unsigned &AvailableFPRs, 2532 unsigned &AvailableVRs, bool HasQPX) { 2533 bool UseMemory = false; 2534 2535 // Respect alignment of argument on the stack. 2536 unsigned Align = 2537 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 2538 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 2539 // If there's no space left in the argument save area, we must 2540 // use memory (this check also catches zero-sized arguments). 2541 if (ArgOffset >= LinkageSize + ParamAreaSize) 2542 UseMemory = true; 2543 2544 // Allocate argument on the stack. 2545 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 2546 if (Flags.isInConsecutiveRegsLast()) 2547 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2548 // If we overran the argument save area, we must use memory 2549 // (this check catches arguments passed partially in memory) 2550 if (ArgOffset > LinkageSize + ParamAreaSize) 2551 UseMemory = true; 2552 2553 // However, if the argument is actually passed in an FPR or a VR, 2554 // we don't use memory after all. 2555 if (!Flags.isByVal()) { 2556 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 2557 // QPX registers overlap with the scalar FP registers. 2558 (HasQPX && (ArgVT == MVT::v4f32 || 2559 ArgVT == MVT::v4f64 || 2560 ArgVT == MVT::v4i1))) 2561 if (AvailableFPRs > 0) { 2562 --AvailableFPRs; 2563 return false; 2564 } 2565 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 2566 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 2567 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) 2568 if (AvailableVRs > 0) { 2569 --AvailableVRs; 2570 return false; 2571 } 2572 } 2573 2574 return UseMemory; 2575 } 2576 2577 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 2578 /// ensure minimum alignment required for target. 2579 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 2580 unsigned NumBytes) { 2581 unsigned TargetAlign = Lowering->getStackAlignment(); 2582 unsigned AlignMask = TargetAlign - 1; 2583 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 2584 return NumBytes; 2585 } 2586 2587 SDValue 2588 PPCTargetLowering::LowerFormalArguments(SDValue Chain, 2589 CallingConv::ID CallConv, bool isVarArg, 2590 const SmallVectorImpl<ISD::InputArg> 2591 &Ins, 2592 SDLoc dl, SelectionDAG &DAG, 2593 SmallVectorImpl<SDValue> &InVals) 2594 const { 2595 if (Subtarget.isSVR4ABI()) { 2596 if (Subtarget.isPPC64()) 2597 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 2598 dl, DAG, InVals); 2599 else 2600 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 2601 dl, DAG, InVals); 2602 } else { 2603 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 2604 dl, DAG, InVals); 2605 } 2606 } 2607 2608 SDValue 2609 PPCTargetLowering::LowerFormalArguments_32SVR4( 2610 SDValue Chain, 2611 CallingConv::ID CallConv, bool isVarArg, 2612 const SmallVectorImpl<ISD::InputArg> 2613 &Ins, 2614 SDLoc dl, SelectionDAG &DAG, 2615 SmallVectorImpl<SDValue> &InVals) const { 2616 2617 // 32-bit SVR4 ABI Stack Frame Layout: 2618 // +-----------------------------------+ 2619 // +--> | Back chain | 2620 // | +-----------------------------------+ 2621 // | | Floating-point register save area | 2622 // | +-----------------------------------+ 2623 // | | General register save area | 2624 // | +-----------------------------------+ 2625 // | | CR save word | 2626 // | +-----------------------------------+ 2627 // | | VRSAVE save word | 2628 // | +-----------------------------------+ 2629 // | | Alignment padding | 2630 // | +-----------------------------------+ 2631 // | | Vector register save area | 2632 // | +-----------------------------------+ 2633 // | | Local variable space | 2634 // | +-----------------------------------+ 2635 // | | Parameter list area | 2636 // | +-----------------------------------+ 2637 // | | LR save word | 2638 // | +-----------------------------------+ 2639 // SP--> +--- | Back chain | 2640 // +-----------------------------------+ 2641 // 2642 // Specifications: 2643 // System V Application Binary Interface PowerPC Processor Supplement 2644 // AltiVec Technology Programming Interface Manual 2645 2646 MachineFunction &MF = DAG.getMachineFunction(); 2647 MachineFrameInfo *MFI = MF.getFrameInfo(); 2648 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2649 2650 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2651 // Potential tail calls could cause overwriting of argument stack slots. 2652 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 2653 (CallConv == CallingConv::Fast)); 2654 unsigned PtrByteSize = 4; 2655 2656 // Assign locations to all of the incoming arguments. 2657 SmallVector<CCValAssign, 16> ArgLocs; 2658 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2659 *DAG.getContext()); 2660 2661 // Reserve space for the linkage area on the stack. 2662 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 2663 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 2664 2665 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 2666 2667 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2668 CCValAssign &VA = ArgLocs[i]; 2669 2670 // Arguments stored in registers. 2671 if (VA.isRegLoc()) { 2672 const TargetRegisterClass *RC; 2673 EVT ValVT = VA.getValVT(); 2674 2675 switch (ValVT.getSimpleVT().SimpleTy) { 2676 default: 2677 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 2678 case MVT::i1: 2679 case MVT::i32: 2680 RC = &PPC::GPRCRegClass; 2681 break; 2682 case MVT::f32: 2683 RC = &PPC::F4RCRegClass; 2684 break; 2685 case MVT::f64: 2686 if (Subtarget.hasVSX()) 2687 RC = &PPC::VSFRCRegClass; 2688 else 2689 RC = &PPC::F8RCRegClass; 2690 break; 2691 case MVT::v16i8: 2692 case MVT::v8i16: 2693 case MVT::v4i32: 2694 RC = &PPC::VRRCRegClass; 2695 break; 2696 case MVT::v4f32: 2697 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 2698 break; 2699 case MVT::v2f64: 2700 case MVT::v2i64: 2701 RC = &PPC::VSHRCRegClass; 2702 break; 2703 case MVT::v4f64: 2704 RC = &PPC::QFRCRegClass; 2705 break; 2706 case MVT::v4i1: 2707 RC = &PPC::QBRCRegClass; 2708 break; 2709 } 2710 2711 // Transform the arguments stored in physical registers into virtual ones. 2712 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2713 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 2714 ValVT == MVT::i1 ? MVT::i32 : ValVT); 2715 2716 if (ValVT == MVT::i1) 2717 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 2718 2719 InVals.push_back(ArgValue); 2720 } else { 2721 // Argument stored in memory. 2722 assert(VA.isMemLoc()); 2723 2724 unsigned ArgSize = VA.getLocVT().getStoreSize(); 2725 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(), 2726 isImmutable); 2727 2728 // Create load nodes to retrieve arguments from the stack. 2729 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2730 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 2731 MachinePointerInfo(), 2732 false, false, false, 0)); 2733 } 2734 } 2735 2736 // Assign locations to all of the incoming aggregate by value arguments. 2737 // Aggregates passed by value are stored in the local variable space of the 2738 // caller's stack frame, right above the parameter list area. 2739 SmallVector<CCValAssign, 16> ByValArgLocs; 2740 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 2741 ByValArgLocs, *DAG.getContext()); 2742 2743 // Reserve stack space for the allocations in CCInfo. 2744 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 2745 2746 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 2747 2748 // Area that is at least reserved in the caller of this function. 2749 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 2750 MinReservedArea = std::max(MinReservedArea, LinkageSize); 2751 2752 // Set the size that is at least reserved in caller of this function. Tail 2753 // call optimized function's reserved stack space needs to be aligned so that 2754 // taking the difference between two stack areas will result in an aligned 2755 // stack. 2756 MinReservedArea = 2757 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 2758 FuncInfo->setMinReservedArea(MinReservedArea); 2759 2760 SmallVector<SDValue, 8> MemOps; 2761 2762 // If the function takes variable number of arguments, make a frame index for 2763 // the start of the first vararg value... for expansion of llvm.va_start. 2764 if (isVarArg) { 2765 static const MCPhysReg GPArgRegs[] = { 2766 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 2767 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 2768 }; 2769 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 2770 2771 static const MCPhysReg FPArgRegs[] = { 2772 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 2773 PPC::F8 2774 }; 2775 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 2776 if (DisablePPCFloatInVariadic) 2777 NumFPArgRegs = 0; 2778 2779 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 2780 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 2781 2782 // Make room for NumGPArgRegs and NumFPArgRegs. 2783 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 2784 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 2785 2786 FuncInfo->setVarArgsStackOffset( 2787 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8, 2788 CCInfo.getNextStackOffset(), true)); 2789 2790 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false)); 2791 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2792 2793 // The fixed integer arguments of a variadic function are stored to the 2794 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing 2795 // the result of va_next. 2796 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 2797 // Get an existing live-in vreg, or add a new one. 2798 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 2799 if (!VReg) 2800 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 2801 2802 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2803 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2804 MachinePointerInfo(), false, false, 0); 2805 MemOps.push_back(Store); 2806 // Increment the address by four for the next argument to store 2807 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT); 2808 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 2809 } 2810 2811 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 2812 // is set. 2813 // The double arguments are stored to the VarArgsFrameIndex 2814 // on the stack. 2815 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 2816 // Get an existing live-in vreg, or add a new one. 2817 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 2818 if (!VReg) 2819 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 2820 2821 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 2822 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2823 MachinePointerInfo(), false, false, 0); 2824 MemOps.push_back(Store); 2825 // Increment the address by eight for the next argument to store 2826 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, 2827 PtrVT); 2828 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 2829 } 2830 } 2831 2832 if (!MemOps.empty()) 2833 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 2834 2835 return Chain; 2836 } 2837 2838 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 2839 // value to MVT::i64 and then truncate to the correct register size. 2840 SDValue 2841 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT, 2842 SelectionDAG &DAG, SDValue ArgVal, 2843 SDLoc dl) const { 2844 if (Flags.isSExt()) 2845 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 2846 DAG.getValueType(ObjectVT)); 2847 else if (Flags.isZExt()) 2848 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 2849 DAG.getValueType(ObjectVT)); 2850 2851 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 2852 } 2853 2854 SDValue 2855 PPCTargetLowering::LowerFormalArguments_64SVR4( 2856 SDValue Chain, 2857 CallingConv::ID CallConv, bool isVarArg, 2858 const SmallVectorImpl<ISD::InputArg> 2859 &Ins, 2860 SDLoc dl, SelectionDAG &DAG, 2861 SmallVectorImpl<SDValue> &InVals) const { 2862 // TODO: add description of PPC stack frame format, or at least some docs. 2863 // 2864 bool isELFv2ABI = Subtarget.isELFv2ABI(); 2865 bool isLittleEndian = Subtarget.isLittleEndian(); 2866 MachineFunction &MF = DAG.getMachineFunction(); 2867 MachineFrameInfo *MFI = MF.getFrameInfo(); 2868 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2869 2870 assert(!(CallConv == CallingConv::Fast && isVarArg) && 2871 "fastcc not supported on varargs functions"); 2872 2873 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2874 // Potential tail calls could cause overwriting of argument stack slots. 2875 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 2876 (CallConv == CallingConv::Fast)); 2877 unsigned PtrByteSize = 8; 2878 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 2879 2880 static const MCPhysReg GPR[] = { 2881 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 2882 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 2883 }; 2884 static const MCPhysReg VR[] = { 2885 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 2886 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 2887 }; 2888 static const MCPhysReg VSRH[] = { 2889 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8, 2890 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13 2891 }; 2892 2893 const unsigned Num_GPR_Regs = array_lengthof(GPR); 2894 const unsigned Num_FPR_Regs = 13; 2895 const unsigned Num_VR_Regs = array_lengthof(VR); 2896 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 2897 2898 // Do a first pass over the arguments to determine whether the ABI 2899 // guarantees that our caller has allocated the parameter save area 2900 // on its stack frame. In the ELFv1 ABI, this is always the case; 2901 // in the ELFv2 ABI, it is true if this is a vararg function or if 2902 // any parameter is located in a stack slot. 2903 2904 bool HasParameterArea = !isELFv2ABI || isVarArg; 2905 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 2906 unsigned NumBytes = LinkageSize; 2907 unsigned AvailableFPRs = Num_FPR_Regs; 2908 unsigned AvailableVRs = Num_VR_Regs; 2909 for (unsigned i = 0, e = Ins.size(); i != e; ++i) 2910 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 2911 PtrByteSize, LinkageSize, ParamAreaSize, 2912 NumBytes, AvailableFPRs, AvailableVRs, 2913 Subtarget.hasQPX())) 2914 HasParameterArea = true; 2915 2916 // Add DAG nodes to load the arguments or copy them out of registers. On 2917 // entry to a function on PPC, the arguments start after the linkage area, 2918 // although the first ones are often in registers. 2919 2920 unsigned ArgOffset = LinkageSize; 2921 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 2922 unsigned &QFPR_idx = FPR_idx; 2923 SmallVector<SDValue, 8> MemOps; 2924 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 2925 unsigned CurArgIdx = 0; 2926 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 2927 SDValue ArgVal; 2928 bool needsLoad = false; 2929 EVT ObjectVT = Ins[ArgNo].VT; 2930 EVT OrigVT = Ins[ArgNo].ArgVT; 2931 unsigned ObjSize = ObjectVT.getStoreSize(); 2932 unsigned ArgSize = ObjSize; 2933 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 2934 if (Ins[ArgNo].isOrigArg()) { 2935 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 2936 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 2937 } 2938 // We re-align the argument offset for each argument, except when using the 2939 // fast calling convention, when we need to make sure we do that only when 2940 // we'll actually use a stack slot. 2941 unsigned CurArgOffset, Align; 2942 auto ComputeArgOffset = [&]() { 2943 /* Respect alignment of argument on the stack. */ 2944 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 2945 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 2946 CurArgOffset = ArgOffset; 2947 }; 2948 2949 if (CallConv != CallingConv::Fast) { 2950 ComputeArgOffset(); 2951 2952 /* Compute GPR index associated with argument offset. */ 2953 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 2954 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 2955 } 2956 2957 // FIXME the codegen can be much improved in some cases. 2958 // We do not have to keep everything in memory. 2959 if (Flags.isByVal()) { 2960 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 2961 2962 if (CallConv == CallingConv::Fast) 2963 ComputeArgOffset(); 2964 2965 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 2966 ObjSize = Flags.getByValSize(); 2967 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2968 // Empty aggregate parameters do not take up registers. Examples: 2969 // struct { } a; 2970 // union { } b; 2971 // int c[0]; 2972 // etc. However, we have to provide a place-holder in InVals, so 2973 // pretend we have an 8-byte item at the current address for that 2974 // purpose. 2975 if (!ObjSize) { 2976 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true); 2977 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2978 InVals.push_back(FIN); 2979 continue; 2980 } 2981 2982 // Create a stack object covering all stack doublewords occupied 2983 // by the argument. If the argument is (fully or partially) on 2984 // the stack, or if the argument is fully in registers but the 2985 // caller has allocated the parameter save anyway, we can refer 2986 // directly to the caller's stack frame. Otherwise, create a 2987 // local copy in our own frame. 2988 int FI; 2989 if (HasParameterArea || 2990 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 2991 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true); 2992 else 2993 FI = MFI->CreateStackObject(ArgSize, Align, false); 2994 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2995 2996 // Handle aggregates smaller than 8 bytes. 2997 if (ObjSize < PtrByteSize) { 2998 // The value of the object is its address, which differs from the 2999 // address of the enclosing doubleword on big-endian systems. 3000 SDValue Arg = FIN; 3001 if (!isLittleEndian) { 3002 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT); 3003 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3004 } 3005 InVals.push_back(Arg); 3006 3007 if (GPR_idx != Num_GPR_Regs) { 3008 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3009 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3010 SDValue Store; 3011 3012 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3013 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3014 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3015 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3016 MachinePointerInfo(FuncArg), 3017 ObjType, false, false, 0); 3018 } else { 3019 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3020 // store the whole register as-is to the parameter save area 3021 // slot. 3022 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3023 MachinePointerInfo(FuncArg), 3024 false, false, 0); 3025 } 3026 3027 MemOps.push_back(Store); 3028 } 3029 // Whether we copied from a register or not, advance the offset 3030 // into the parameter save area by a full doubleword. 3031 ArgOffset += PtrByteSize; 3032 continue; 3033 } 3034 3035 // The value of the object is its address, which is the address of 3036 // its first stack doubleword. 3037 InVals.push_back(FIN); 3038 3039 // Store whatever pieces of the object are in registers to memory. 3040 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3041 if (GPR_idx == Num_GPR_Regs) 3042 break; 3043 3044 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3045 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3046 SDValue Addr = FIN; 3047 if (j) { 3048 SDValue Off = DAG.getConstant(j, PtrVT); 3049 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3050 } 3051 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3052 MachinePointerInfo(FuncArg, j), 3053 false, false, 0); 3054 MemOps.push_back(Store); 3055 ++GPR_idx; 3056 } 3057 ArgOffset += ArgSize; 3058 continue; 3059 } 3060 3061 switch (ObjectVT.getSimpleVT().SimpleTy) { 3062 default: llvm_unreachable("Unhandled argument type!"); 3063 case MVT::i1: 3064 case MVT::i32: 3065 case MVT::i64: 3066 // These can be scalar arguments or elements of an integer array type 3067 // passed directly. Clang may use those instead of "byval" aggregate 3068 // types to avoid forcing arguments to memory unnecessarily. 3069 if (GPR_idx != Num_GPR_Regs) { 3070 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3071 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3072 3073 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3074 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3075 // value to MVT::i64 and then truncate to the correct register size. 3076 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3077 } else { 3078 if (CallConv == CallingConv::Fast) 3079 ComputeArgOffset(); 3080 3081 needsLoad = true; 3082 ArgSize = PtrByteSize; 3083 } 3084 if (CallConv != CallingConv::Fast || needsLoad) 3085 ArgOffset += 8; 3086 break; 3087 3088 case MVT::f32: 3089 case MVT::f64: 3090 // These can be scalar arguments or elements of a float array type 3091 // passed directly. The latter are used to implement ELFv2 homogenous 3092 // float aggregates. 3093 if (FPR_idx != Num_FPR_Regs) { 3094 unsigned VReg; 3095 3096 if (ObjectVT == MVT::f32) 3097 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 3098 else 3099 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3100 ? &PPC::VSFRCRegClass 3101 : &PPC::F8RCRegClass); 3102 3103 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3104 ++FPR_idx; 3105 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3106 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3107 // once we support fp <-> gpr moves. 3108 3109 // This can only ever happen in the presence of f32 array types, 3110 // since otherwise we never run out of FPRs before running out 3111 // of GPRs. 3112 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3113 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3114 3115 if (ObjectVT == MVT::f32) { 3116 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3117 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3118 DAG.getConstant(32, MVT::i32)); 3119 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3120 } 3121 3122 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3123 } else { 3124 if (CallConv == CallingConv::Fast) 3125 ComputeArgOffset(); 3126 3127 needsLoad = true; 3128 } 3129 3130 // When passing an array of floats, the array occupies consecutive 3131 // space in the argument area; only round up to the next doubleword 3132 // at the end of the array. Otherwise, each float takes 8 bytes. 3133 if (CallConv != CallingConv::Fast || needsLoad) { 3134 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3135 ArgOffset += ArgSize; 3136 if (Flags.isInConsecutiveRegsLast()) 3137 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3138 } 3139 break; 3140 case MVT::v4f32: 3141 case MVT::v4i32: 3142 case MVT::v8i16: 3143 case MVT::v16i8: 3144 case MVT::v2f64: 3145 case MVT::v2i64: 3146 if (!Subtarget.hasQPX()) { 3147 // These can be scalar arguments or elements of a vector array type 3148 // passed directly. The latter are used to implement ELFv2 homogenous 3149 // vector aggregates. 3150 if (VR_idx != Num_VR_Regs) { 3151 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ? 3152 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) : 3153 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3154 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3155 ++VR_idx; 3156 } else { 3157 if (CallConv == CallingConv::Fast) 3158 ComputeArgOffset(); 3159 3160 needsLoad = true; 3161 } 3162 if (CallConv != CallingConv::Fast || needsLoad) 3163 ArgOffset += 16; 3164 break; 3165 } // not QPX 3166 3167 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3168 "Invalid QPX parameter type"); 3169 /* fall through */ 3170 3171 case MVT::v4f64: 3172 case MVT::v4i1: 3173 // QPX vectors are treated like their scalar floating-point subregisters 3174 // (except that they're larger). 3175 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3176 if (QFPR_idx != Num_QFPR_Regs) { 3177 const TargetRegisterClass *RC; 3178 switch (ObjectVT.getSimpleVT().SimpleTy) { 3179 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3180 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3181 default: RC = &PPC::QBRCRegClass; break; 3182 } 3183 3184 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3185 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3186 ++QFPR_idx; 3187 } else { 3188 if (CallConv == CallingConv::Fast) 3189 ComputeArgOffset(); 3190 needsLoad = true; 3191 } 3192 if (CallConv != CallingConv::Fast || needsLoad) 3193 ArgOffset += Sz; 3194 break; 3195 } 3196 3197 // We need to load the argument to a virtual register if we determined 3198 // above that we ran out of physical registers of the appropriate type. 3199 if (needsLoad) { 3200 if (ObjSize < ArgSize && !isLittleEndian) 3201 CurArgOffset += ArgSize - ObjSize; 3202 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3203 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3204 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(), 3205 false, false, false, 0); 3206 } 3207 3208 InVals.push_back(ArgVal); 3209 } 3210 3211 // Area that is at least reserved in the caller of this function. 3212 unsigned MinReservedArea; 3213 if (HasParameterArea) 3214 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 3215 else 3216 MinReservedArea = LinkageSize; 3217 3218 // Set the size that is at least reserved in caller of this function. Tail 3219 // call optimized functions' reserved stack space needs to be aligned so that 3220 // taking the difference between two stack areas will result in an aligned 3221 // stack. 3222 MinReservedArea = 3223 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3224 FuncInfo->setMinReservedArea(MinReservedArea); 3225 3226 // If the function takes variable number of arguments, make a frame index for 3227 // the start of the first vararg value... for expansion of llvm.va_start. 3228 if (isVarArg) { 3229 int Depth = ArgOffset; 3230 3231 FuncInfo->setVarArgsFrameIndex( 3232 MFI->CreateFixedObject(PtrByteSize, Depth, true)); 3233 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3234 3235 // If this function is vararg, store any remaining integer argument regs 3236 // to their spots on the stack so that they may be loaded by deferencing the 3237 // result of va_next. 3238 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3239 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 3240 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3241 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3242 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3243 MachinePointerInfo(), false, false, 0); 3244 MemOps.push_back(Store); 3245 // Increment the address by four for the next argument to store 3246 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT); 3247 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3248 } 3249 } 3250 3251 if (!MemOps.empty()) 3252 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3253 3254 return Chain; 3255 } 3256 3257 SDValue 3258 PPCTargetLowering::LowerFormalArguments_Darwin( 3259 SDValue Chain, 3260 CallingConv::ID CallConv, bool isVarArg, 3261 const SmallVectorImpl<ISD::InputArg> 3262 &Ins, 3263 SDLoc dl, SelectionDAG &DAG, 3264 SmallVectorImpl<SDValue> &InVals) const { 3265 // TODO: add description of PPC stack frame format, or at least some docs. 3266 // 3267 MachineFunction &MF = DAG.getMachineFunction(); 3268 MachineFrameInfo *MFI = MF.getFrameInfo(); 3269 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3270 3271 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3272 bool isPPC64 = PtrVT == MVT::i64; 3273 // Potential tail calls could cause overwriting of argument stack slots. 3274 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3275 (CallConv == CallingConv::Fast)); 3276 unsigned PtrByteSize = isPPC64 ? 8 : 4; 3277 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3278 unsigned ArgOffset = LinkageSize; 3279 // Area that is at least reserved in caller of this function. 3280 unsigned MinReservedArea = ArgOffset; 3281 3282 static const MCPhysReg GPR_32[] = { // 32-bit registers. 3283 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3284 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3285 }; 3286 static const MCPhysReg GPR_64[] = { // 64-bit registers. 3287 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3288 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3289 }; 3290 static const MCPhysReg VR[] = { 3291 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3292 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3293 }; 3294 3295 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 3296 const unsigned Num_FPR_Regs = 13; 3297 const unsigned Num_VR_Regs = array_lengthof( VR); 3298 3299 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3300 3301 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 3302 3303 // In 32-bit non-varargs functions, the stack space for vectors is after the 3304 // stack space for non-vectors. We do not use this space unless we have 3305 // too many vectors to fit in registers, something that only occurs in 3306 // constructed examples:), but we have to walk the arglist to figure 3307 // that out...for the pathological case, compute VecArgOffset as the 3308 // start of the vector parameter area. Computing VecArgOffset is the 3309 // entire point of the following loop. 3310 unsigned VecArgOffset = ArgOffset; 3311 if (!isVarArg && !isPPC64) { 3312 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 3313 ++ArgNo) { 3314 EVT ObjectVT = Ins[ArgNo].VT; 3315 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3316 3317 if (Flags.isByVal()) { 3318 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 3319 unsigned ObjSize = Flags.getByValSize(); 3320 unsigned ArgSize = 3321 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3322 VecArgOffset += ArgSize; 3323 continue; 3324 } 3325 3326 switch(ObjectVT.getSimpleVT().SimpleTy) { 3327 default: llvm_unreachable("Unhandled argument type!"); 3328 case MVT::i1: 3329 case MVT::i32: 3330 case MVT::f32: 3331 VecArgOffset += 4; 3332 break; 3333 case MVT::i64: // PPC64 3334 case MVT::f64: 3335 // FIXME: We are guaranteed to be !isPPC64 at this point. 3336 // Does MVT::i64 apply? 3337 VecArgOffset += 8; 3338 break; 3339 case MVT::v4f32: 3340 case MVT::v4i32: 3341 case MVT::v8i16: 3342 case MVT::v16i8: 3343 // Nothing to do, we're only looking at Nonvector args here. 3344 break; 3345 } 3346 } 3347 } 3348 // We've found where the vector parameter area in memory is. Skip the 3349 // first 12 parameters; these don't use that memory. 3350 VecArgOffset = ((VecArgOffset+15)/16)*16; 3351 VecArgOffset += 12*16; 3352 3353 // Add DAG nodes to load the arguments or copy them out of registers. On 3354 // entry to a function on PPC, the arguments start after the linkage area, 3355 // although the first ones are often in registers. 3356 3357 SmallVector<SDValue, 8> MemOps; 3358 unsigned nAltivecParamsAtEnd = 0; 3359 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 3360 unsigned CurArgIdx = 0; 3361 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3362 SDValue ArgVal; 3363 bool needsLoad = false; 3364 EVT ObjectVT = Ins[ArgNo].VT; 3365 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 3366 unsigned ArgSize = ObjSize; 3367 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3368 if (Ins[ArgNo].isOrigArg()) { 3369 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3370 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3371 } 3372 unsigned CurArgOffset = ArgOffset; 3373 3374 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 3375 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 3376 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 3377 if (isVarArg || isPPC64) { 3378 MinReservedArea = ((MinReservedArea+15)/16)*16; 3379 MinReservedArea += CalculateStackSlotSize(ObjectVT, 3380 Flags, 3381 PtrByteSize); 3382 } else nAltivecParamsAtEnd++; 3383 } else 3384 // Calculate min reserved area. 3385 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 3386 Flags, 3387 PtrByteSize); 3388 3389 // FIXME the codegen can be much improved in some cases. 3390 // We do not have to keep everything in memory. 3391 if (Flags.isByVal()) { 3392 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3393 3394 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3395 ObjSize = Flags.getByValSize(); 3396 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3397 // Objects of size 1 and 2 are right justified, everything else is 3398 // left justified. This means the memory address is adjusted forwards. 3399 if (ObjSize==1 || ObjSize==2) { 3400 CurArgOffset = CurArgOffset + (4 - ObjSize); 3401 } 3402 // The value of the object is its address. 3403 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true); 3404 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3405 InVals.push_back(FIN); 3406 if (ObjSize==1 || ObjSize==2) { 3407 if (GPR_idx != Num_GPR_Regs) { 3408 unsigned VReg; 3409 if (isPPC64) 3410 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3411 else 3412 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3413 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3414 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 3415 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 3416 MachinePointerInfo(FuncArg), 3417 ObjType, false, false, 0); 3418 MemOps.push_back(Store); 3419 ++GPR_idx; 3420 } 3421 3422 ArgOffset += PtrByteSize; 3423 3424 continue; 3425 } 3426 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3427 // Store whatever pieces of the object are in registers 3428 // to memory. ArgOffset will be the address of the beginning 3429 // of the object. 3430 if (GPR_idx != Num_GPR_Regs) { 3431 unsigned VReg; 3432 if (isPPC64) 3433 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3434 else 3435 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3436 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true); 3437 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3438 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3439 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3440 MachinePointerInfo(FuncArg, j), 3441 false, false, 0); 3442 MemOps.push_back(Store); 3443 ++GPR_idx; 3444 ArgOffset += PtrByteSize; 3445 } else { 3446 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 3447 break; 3448 } 3449 } 3450 continue; 3451 } 3452 3453 switch (ObjectVT.getSimpleVT().SimpleTy) { 3454 default: llvm_unreachable("Unhandled argument type!"); 3455 case MVT::i1: 3456 case MVT::i32: 3457 if (!isPPC64) { 3458 if (GPR_idx != Num_GPR_Regs) { 3459 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3460 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3461 3462 if (ObjectVT == MVT::i1) 3463 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 3464 3465 ++GPR_idx; 3466 } else { 3467 needsLoad = true; 3468 ArgSize = PtrByteSize; 3469 } 3470 // All int arguments reserve stack space in the Darwin ABI. 3471 ArgOffset += PtrByteSize; 3472 break; 3473 } 3474 // FALLTHROUGH 3475 case MVT::i64: // PPC64 3476 if (GPR_idx != Num_GPR_Regs) { 3477 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3478 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3479 3480 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3481 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3482 // value to MVT::i64 and then truncate to the correct register size. 3483 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3484 3485 ++GPR_idx; 3486 } else { 3487 needsLoad = true; 3488 ArgSize = PtrByteSize; 3489 } 3490 // All int arguments reserve stack space in the Darwin ABI. 3491 ArgOffset += 8; 3492 break; 3493 3494 case MVT::f32: 3495 case MVT::f64: 3496 // Every 4 bytes of argument space consumes one of the GPRs available for 3497 // argument passing. 3498 if (GPR_idx != Num_GPR_Regs) { 3499 ++GPR_idx; 3500 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 3501 ++GPR_idx; 3502 } 3503 if (FPR_idx != Num_FPR_Regs) { 3504 unsigned VReg; 3505 3506 if (ObjectVT == MVT::f32) 3507 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 3508 else 3509 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 3510 3511 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3512 ++FPR_idx; 3513 } else { 3514 needsLoad = true; 3515 } 3516 3517 // All FP arguments reserve stack space in the Darwin ABI. 3518 ArgOffset += isPPC64 ? 8 : ObjSize; 3519 break; 3520 case MVT::v4f32: 3521 case MVT::v4i32: 3522 case MVT::v8i16: 3523 case MVT::v16i8: 3524 // Note that vector arguments in registers don't reserve stack space, 3525 // except in varargs functions. 3526 if (VR_idx != Num_VR_Regs) { 3527 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3528 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3529 if (isVarArg) { 3530 while ((ArgOffset % 16) != 0) { 3531 ArgOffset += PtrByteSize; 3532 if (GPR_idx != Num_GPR_Regs) 3533 GPR_idx++; 3534 } 3535 ArgOffset += 16; 3536 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 3537 } 3538 ++VR_idx; 3539 } else { 3540 if (!isVarArg && !isPPC64) { 3541 // Vectors go after all the nonvectors. 3542 CurArgOffset = VecArgOffset; 3543 VecArgOffset += 16; 3544 } else { 3545 // Vectors are aligned. 3546 ArgOffset = ((ArgOffset+15)/16)*16; 3547 CurArgOffset = ArgOffset; 3548 ArgOffset += 16; 3549 } 3550 needsLoad = true; 3551 } 3552 break; 3553 } 3554 3555 // We need to load the argument to a virtual register if we determined above 3556 // that we ran out of physical registers of the appropriate type. 3557 if (needsLoad) { 3558 int FI = MFI->CreateFixedObject(ObjSize, 3559 CurArgOffset + (ArgSize - ObjSize), 3560 isImmutable); 3561 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3562 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(), 3563 false, false, false, 0); 3564 } 3565 3566 InVals.push_back(ArgVal); 3567 } 3568 3569 // Allow for Altivec parameters at the end, if needed. 3570 if (nAltivecParamsAtEnd) { 3571 MinReservedArea = ((MinReservedArea+15)/16)*16; 3572 MinReservedArea += 16*nAltivecParamsAtEnd; 3573 } 3574 3575 // Area that is at least reserved in the caller of this function. 3576 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 3577 3578 // Set the size that is at least reserved in caller of this function. Tail 3579 // call optimized functions' reserved stack space needs to be aligned so that 3580 // taking the difference between two stack areas will result in an aligned 3581 // stack. 3582 MinReservedArea = 3583 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3584 FuncInfo->setMinReservedArea(MinReservedArea); 3585 3586 // If the function takes variable number of arguments, make a frame index for 3587 // the start of the first vararg value... for expansion of llvm.va_start. 3588 if (isVarArg) { 3589 int Depth = ArgOffset; 3590 3591 FuncInfo->setVarArgsFrameIndex( 3592 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8, 3593 Depth, true)); 3594 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3595 3596 // If this function is vararg, store any remaining integer argument regs 3597 // to their spots on the stack so that they may be loaded by deferencing the 3598 // result of va_next. 3599 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 3600 unsigned VReg; 3601 3602 if (isPPC64) 3603 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3604 else 3605 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 3606 3607 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3608 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3609 MachinePointerInfo(), false, false, 0); 3610 MemOps.push_back(Store); 3611 // Increment the address by four for the next argument to store 3612 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT); 3613 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3614 } 3615 } 3616 3617 if (!MemOps.empty()) 3618 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3619 3620 return Chain; 3621 } 3622 3623 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 3624 /// adjusted to accommodate the arguments for the tailcall. 3625 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 3626 unsigned ParamSize) { 3627 3628 if (!isTailCall) return 0; 3629 3630 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 3631 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 3632 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 3633 // Remember only if the new adjustement is bigger. 3634 if (SPDiff < FI->getTailCallSPDelta()) 3635 FI->setTailCallSPDelta(SPDiff); 3636 3637 return SPDiff; 3638 } 3639 3640 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 3641 /// for tail call optimization. Targets which want to do tail call 3642 /// optimization should implement this function. 3643 bool 3644 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 3645 CallingConv::ID CalleeCC, 3646 bool isVarArg, 3647 const SmallVectorImpl<ISD::InputArg> &Ins, 3648 SelectionDAG& DAG) const { 3649 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 3650 return false; 3651 3652 // Variable argument functions are not supported. 3653 if (isVarArg) 3654 return false; 3655 3656 MachineFunction &MF = DAG.getMachineFunction(); 3657 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 3658 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 3659 // Functions containing by val parameters are not supported. 3660 for (unsigned i = 0; i != Ins.size(); i++) { 3661 ISD::ArgFlagsTy Flags = Ins[i].Flags; 3662 if (Flags.isByVal()) return false; 3663 } 3664 3665 // Non-PIC/GOT tail calls are supported. 3666 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 3667 return true; 3668 3669 // At the moment we can only do local tail calls (in same module, hidden 3670 // or protected) if we are generating PIC. 3671 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 3672 return G->getGlobal()->hasHiddenVisibility() 3673 || G->getGlobal()->hasProtectedVisibility(); 3674 } 3675 3676 return false; 3677 } 3678 3679 /// isCallCompatibleAddress - Return the immediate to use if the specified 3680 /// 32-bit value is representable in the immediate field of a BxA instruction. 3681 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 3682 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 3683 if (!C) return nullptr; 3684 3685 int Addr = C->getZExtValue(); 3686 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 3687 SignExtend32<26>(Addr) != Addr) 3688 return nullptr; // Top 6 bits have to be sext of immediate. 3689 3690 return DAG.getConstant((int)C->getZExtValue() >> 2, 3691 DAG.getTargetLoweringInfo().getPointerTy()).getNode(); 3692 } 3693 3694 namespace { 3695 3696 struct TailCallArgumentInfo { 3697 SDValue Arg; 3698 SDValue FrameIdxOp; 3699 int FrameIdx; 3700 3701 TailCallArgumentInfo() : FrameIdx(0) {} 3702 }; 3703 3704 } 3705 3706 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 3707 static void 3708 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG, 3709 SDValue Chain, 3710 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 3711 SmallVectorImpl<SDValue> &MemOpChains, 3712 SDLoc dl) { 3713 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 3714 SDValue Arg = TailCallArgs[i].Arg; 3715 SDValue FIN = TailCallArgs[i].FrameIdxOp; 3716 int FI = TailCallArgs[i].FrameIdx; 3717 // Store relative to framepointer. 3718 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN, 3719 MachinePointerInfo::getFixedStack(FI), 3720 false, false, 0)); 3721 } 3722 } 3723 3724 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 3725 /// the appropriate stack slot for the tail call optimized function call. 3726 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, 3727 MachineFunction &MF, 3728 SDValue Chain, 3729 SDValue OldRetAddr, 3730 SDValue OldFP, 3731 int SPDiff, 3732 bool isPPC64, 3733 bool isDarwinABI, 3734 SDLoc dl) { 3735 if (SPDiff) { 3736 // Calculate the new stack slot for the return address. 3737 int SlotSize = isPPC64 ? 8 : 4; 3738 const PPCFrameLowering *FL = 3739 MF.getSubtarget<PPCSubtarget>().getFrameLowering(); 3740 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 3741 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize, 3742 NewRetAddrLoc, true); 3743 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 3744 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 3745 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 3746 MachinePointerInfo::getFixedStack(NewRetAddr), 3747 false, false, 0); 3748 3749 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 3750 // slot as the FP is never overwritten. 3751 if (isDarwinABI) { 3752 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 3753 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc, 3754 true); 3755 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 3756 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 3757 MachinePointerInfo::getFixedStack(NewFPIdx), 3758 false, false, 0); 3759 } 3760 } 3761 return Chain; 3762 } 3763 3764 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 3765 /// the position of the argument. 3766 static void 3767 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 3768 SDValue Arg, int SPDiff, unsigned ArgOffset, 3769 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 3770 int Offset = ArgOffset + SPDiff; 3771 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8; 3772 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 3773 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 3774 SDValue FIN = DAG.getFrameIndex(FI, VT); 3775 TailCallArgumentInfo Info; 3776 Info.Arg = Arg; 3777 Info.FrameIdxOp = FIN; 3778 Info.FrameIdx = FI; 3779 TailCallArguments.push_back(Info); 3780 } 3781 3782 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 3783 /// stack slot. Returns the chain as result and the loaded frame pointers in 3784 /// LROpOut/FPOpout. Used when tail calling. 3785 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG, 3786 int SPDiff, 3787 SDValue Chain, 3788 SDValue &LROpOut, 3789 SDValue &FPOpOut, 3790 bool isDarwinABI, 3791 SDLoc dl) const { 3792 if (SPDiff) { 3793 // Load the LR and FP stack slot for later adjusting. 3794 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 3795 LROpOut = getReturnAddrFrameIndex(DAG); 3796 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(), 3797 false, false, false, 0); 3798 Chain = SDValue(LROpOut.getNode(), 1); 3799 3800 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 3801 // slot as the FP is never overwritten. 3802 if (isDarwinABI) { 3803 FPOpOut = getFramePointerFrameIndex(DAG); 3804 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(), 3805 false, false, false, 0); 3806 Chain = SDValue(FPOpOut.getNode(), 1); 3807 } 3808 } 3809 return Chain; 3810 } 3811 3812 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 3813 /// by "Src" to address "Dst" of size "Size". Alignment information is 3814 /// specified by the specific parameter attribute. The copy will be passed as 3815 /// a byval function parameter. 3816 /// Sometimes what we are copying is the end of a larger object, the part that 3817 /// does not fit in registers. 3818 static SDValue 3819 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 3820 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 3821 SDLoc dl) { 3822 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 3823 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 3824 false, false, MachinePointerInfo(), 3825 MachinePointerInfo()); 3826 } 3827 3828 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 3829 /// tail calls. 3830 static void 3831 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, 3832 SDValue Arg, SDValue PtrOff, int SPDiff, 3833 unsigned ArgOffset, bool isPPC64, bool isTailCall, 3834 bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 3835 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, 3836 SDLoc dl) { 3837 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3838 if (!isTailCall) { 3839 if (isVector) { 3840 SDValue StackPtr; 3841 if (isPPC64) 3842 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 3843 else 3844 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 3845 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 3846 DAG.getConstant(ArgOffset, PtrVT)); 3847 } 3848 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, 3849 MachinePointerInfo(), false, false, 0)); 3850 // Calculate and remember argument location. 3851 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 3852 TailCallArguments); 3853 } 3854 3855 static 3856 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 3857 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes, 3858 SDValue LROp, SDValue FPOp, bool isDarwinABI, 3859 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 3860 MachineFunction &MF = DAG.getMachineFunction(); 3861 3862 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 3863 // might overwrite each other in case of tail call optimization. 3864 SmallVector<SDValue, 8> MemOpChains2; 3865 // Do not flag preceding copytoreg stuff together with the following stuff. 3866 InFlag = SDValue(); 3867 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 3868 MemOpChains2, dl); 3869 if (!MemOpChains2.empty()) 3870 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 3871 3872 // Store the return address to the appropriate stack slot. 3873 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff, 3874 isPPC64, isDarwinABI, dl); 3875 3876 // Emit callseq_end just before tailcall node. 3877 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 3878 DAG.getIntPtrConstant(0, true), InFlag, dl); 3879 InFlag = Chain.getValue(1); 3880 } 3881 3882 // Is this global address that of a function that can be called by name? (as 3883 // opposed to something that must hold a descriptor for an indirect call). 3884 static bool isFunctionGlobalAddress(SDValue Callee) { 3885 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3886 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 3887 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 3888 return false; 3889 3890 return G->getGlobal()->getType()->getElementType()->isFunctionTy(); 3891 } 3892 3893 return false; 3894 } 3895 3896 static 3897 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, 3898 SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff, 3899 bool isTailCall, bool IsPatchPoint, 3900 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass, 3901 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 3902 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) { 3903 3904 bool isPPC64 = Subtarget.isPPC64(); 3905 bool isSVR4ABI = Subtarget.isSVR4ABI(); 3906 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3907 3908 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3909 NodeTys.push_back(MVT::Other); // Returns a chain 3910 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 3911 3912 unsigned CallOpc = PPCISD::CALL; 3913 3914 bool needIndirectCall = true; 3915 if (!isSVR4ABI || !isPPC64) 3916 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 3917 // If this is an absolute destination address, use the munged value. 3918 Callee = SDValue(Dest, 0); 3919 needIndirectCall = false; 3920 } 3921 3922 if (isFunctionGlobalAddress(Callee)) { 3923 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 3924 // A call to a TLS address is actually an indirect call to a 3925 // thread-specific pointer. 3926 unsigned OpFlags = 0; 3927 if ((DAG.getTarget().getRelocationModel() != Reloc::Static && 3928 (Subtarget.getTargetTriple().isMacOSX() && 3929 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) && 3930 (G->getGlobal()->isDeclaration() || 3931 G->getGlobal()->isWeakForLinker())) || 3932 (Subtarget.isTargetELF() && !isPPC64 && 3933 !G->getGlobal()->hasLocalLinkage() && 3934 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) { 3935 // PC-relative references to external symbols should go through $stub, 3936 // unless we're building with the leopard linker or later, which 3937 // automatically synthesizes these stubs. 3938 OpFlags = PPCII::MO_PLT_OR_STUB; 3939 } 3940 3941 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 3942 // every direct call is) turn it into a TargetGlobalAddress / 3943 // TargetExternalSymbol node so that legalize doesn't hack it. 3944 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 3945 Callee.getValueType(), 0, OpFlags); 3946 needIndirectCall = false; 3947 } 3948 3949 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3950 unsigned char OpFlags = 0; 3951 3952 if ((DAG.getTarget().getRelocationModel() != Reloc::Static && 3953 (Subtarget.getTargetTriple().isMacOSX() && 3954 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) || 3955 (Subtarget.isTargetELF() && !isPPC64 && 3956 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) { 3957 // PC-relative references to external symbols should go through $stub, 3958 // unless we're building with the leopard linker or later, which 3959 // automatically synthesizes these stubs. 3960 OpFlags = PPCII::MO_PLT_OR_STUB; 3961 } 3962 3963 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 3964 OpFlags); 3965 needIndirectCall = false; 3966 } 3967 3968 if (IsPatchPoint) { 3969 // We'll form an invalid direct call when lowering a patchpoint; the full 3970 // sequence for an indirect call is complicated, and many of the 3971 // instructions introduced might have side effects (and, thus, can't be 3972 // removed later). The call itself will be removed as soon as the 3973 // argument/return lowering is complete, so the fact that it has the wrong 3974 // kind of operands should not really matter. 3975 needIndirectCall = false; 3976 } 3977 3978 if (needIndirectCall) { 3979 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 3980 // to do the call, we can't use PPCISD::CALL. 3981 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 3982 3983 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 3984 // Function pointers in the 64-bit SVR4 ABI do not point to the function 3985 // entry point, but to the function descriptor (the function entry point 3986 // address is part of the function descriptor though). 3987 // The function descriptor is a three doubleword structure with the 3988 // following fields: function entry point, TOC base address and 3989 // environment pointer. 3990 // Thus for a call through a function pointer, the following actions need 3991 // to be performed: 3992 // 1. Save the TOC of the caller in the TOC save area of its stack 3993 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 3994 // 2. Load the address of the function entry point from the function 3995 // descriptor. 3996 // 3. Load the TOC of the callee from the function descriptor into r2. 3997 // 4. Load the environment pointer from the function descriptor into 3998 // r11. 3999 // 5. Branch to the function entry point address. 4000 // 6. On return of the callee, the TOC of the caller needs to be 4001 // restored (this is done in FinishCall()). 4002 // 4003 // The loads are scheduled at the beginning of the call sequence, and the 4004 // register copies are flagged together to ensure that no other 4005 // operations can be scheduled in between. E.g. without flagging the 4006 // copies together, a TOC access in the caller could be scheduled between 4007 // the assignment of the callee TOC and the branch to the callee, which 4008 // results in the TOC access going through the TOC of the callee instead 4009 // of going through the TOC of the caller, which leads to incorrect code. 4010 4011 // Load the address of the function entry point from the function 4012 // descriptor. 4013 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 4014 if (LDChain.getValueType() == MVT::Glue) 4015 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 4016 4017 bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors(); 4018 4019 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr); 4020 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 4021 false, false, LoadsInv, 8); 4022 4023 // Load environment pointer into r11. 4024 SDValue PtrOff = DAG.getIntPtrConstant(16); 4025 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 4026 SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, 4027 MPI.getWithOffset(16), false, false, 4028 LoadsInv, 8); 4029 4030 SDValue TOCOff = DAG.getIntPtrConstant(8); 4031 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 4032 SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, 4033 MPI.getWithOffset(8), false, false, 4034 LoadsInv, 8); 4035 4036 setUsesTOCBasePtr(DAG); 4037 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 4038 InFlag); 4039 Chain = TOCVal.getValue(0); 4040 InFlag = TOCVal.getValue(1); 4041 4042 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 4043 InFlag); 4044 4045 Chain = EnvVal.getValue(0); 4046 InFlag = EnvVal.getValue(1); 4047 4048 MTCTROps[0] = Chain; 4049 MTCTROps[1] = LoadFuncPtr; 4050 MTCTROps[2] = InFlag; 4051 } 4052 4053 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 4054 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 4055 InFlag = Chain.getValue(1); 4056 4057 NodeTys.clear(); 4058 NodeTys.push_back(MVT::Other); 4059 NodeTys.push_back(MVT::Glue); 4060 Ops.push_back(Chain); 4061 CallOpc = PPCISD::BCTRL; 4062 Callee.setNode(nullptr); 4063 // Add use of X11 (holding environment pointer) 4064 if (isSVR4ABI && isPPC64 && !isELFv2ABI) 4065 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 4066 // Add CTR register as callee so a bctr can be emitted later. 4067 if (isTailCall) 4068 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 4069 } 4070 4071 // If this is a direct call, pass the chain and the callee. 4072 if (Callee.getNode()) { 4073 Ops.push_back(Chain); 4074 Ops.push_back(Callee); 4075 } 4076 // If this is a tail call add stack pointer delta. 4077 if (isTailCall) 4078 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32)); 4079 4080 // Add argument registers to the end of the list so that they are known live 4081 // into the call. 4082 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 4083 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 4084 RegsToPass[i].second.getValueType())); 4085 4086 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 4087 // into the call. 4088 if (isSVR4ABI && isPPC64 && !IsPatchPoint) { 4089 setUsesTOCBasePtr(DAG); 4090 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 4091 } 4092 4093 return CallOpc; 4094 } 4095 4096 static 4097 bool isLocalCall(const SDValue &Callee) 4098 { 4099 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4100 return !G->getGlobal()->isDeclaration() && 4101 !G->getGlobal()->isWeakForLinker(); 4102 return false; 4103 } 4104 4105 SDValue 4106 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 4107 CallingConv::ID CallConv, bool isVarArg, 4108 const SmallVectorImpl<ISD::InputArg> &Ins, 4109 SDLoc dl, SelectionDAG &DAG, 4110 SmallVectorImpl<SDValue> &InVals) const { 4111 4112 SmallVector<CCValAssign, 16> RVLocs; 4113 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4114 *DAG.getContext()); 4115 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC); 4116 4117 // Copy all of the result registers out of their specified physreg. 4118 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4119 CCValAssign &VA = RVLocs[i]; 4120 assert(VA.isRegLoc() && "Can only return in registers!"); 4121 4122 SDValue Val = DAG.getCopyFromReg(Chain, dl, 4123 VA.getLocReg(), VA.getLocVT(), InFlag); 4124 Chain = Val.getValue(1); 4125 InFlag = Val.getValue(2); 4126 4127 switch (VA.getLocInfo()) { 4128 default: llvm_unreachable("Unknown loc info!"); 4129 case CCValAssign::Full: break; 4130 case CCValAssign::AExt: 4131 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4132 break; 4133 case CCValAssign::ZExt: 4134 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4135 DAG.getValueType(VA.getValVT())); 4136 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4137 break; 4138 case CCValAssign::SExt: 4139 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 4140 DAG.getValueType(VA.getValVT())); 4141 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4142 break; 4143 } 4144 4145 InVals.push_back(Val); 4146 } 4147 4148 return Chain; 4149 } 4150 4151 SDValue 4152 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl, 4153 bool isTailCall, bool isVarArg, bool IsPatchPoint, 4154 SelectionDAG &DAG, 4155 SmallVector<std::pair<unsigned, SDValue>, 8> 4156 &RegsToPass, 4157 SDValue InFlag, SDValue Chain, 4158 SDValue CallSeqStart, SDValue &Callee, 4159 int SPDiff, unsigned NumBytes, 4160 const SmallVectorImpl<ISD::InputArg> &Ins, 4161 SmallVectorImpl<SDValue> &InVals, 4162 ImmutableCallSite *CS) const { 4163 4164 std::vector<EVT> NodeTys; 4165 SmallVector<SDValue, 8> Ops; 4166 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 4167 SPDiff, isTailCall, IsPatchPoint, RegsToPass, 4168 Ops, NodeTys, CS, Subtarget); 4169 4170 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 4171 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 4172 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 4173 4174 // When performing tail call optimization the callee pops its arguments off 4175 // the stack. Account for this here so these bytes can be pushed back on in 4176 // PPCFrameLowering::eliminateCallFramePseudoInstr. 4177 int BytesCalleePops = 4178 (CallConv == CallingConv::Fast && 4179 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 4180 4181 // Add a register mask operand representing the call-preserved registers. 4182 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4183 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv); 4184 assert(Mask && "Missing call preserved mask for calling convention"); 4185 Ops.push_back(DAG.getRegisterMask(Mask)); 4186 4187 if (InFlag.getNode()) 4188 Ops.push_back(InFlag); 4189 4190 // Emit tail call. 4191 if (isTailCall) { 4192 assert(((Callee.getOpcode() == ISD::Register && 4193 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 4194 Callee.getOpcode() == ISD::TargetExternalSymbol || 4195 Callee.getOpcode() == ISD::TargetGlobalAddress || 4196 isa<ConstantSDNode>(Callee)) && 4197 "Expecting an global address, external symbol, absolute value or register"); 4198 4199 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 4200 } 4201 4202 // Add a NOP immediately after the branch instruction when using the 64-bit 4203 // SVR4 ABI. At link time, if caller and callee are in a different module and 4204 // thus have a different TOC, the call will be replaced with a call to a stub 4205 // function which saves the current TOC, loads the TOC of the callee and 4206 // branches to the callee. The NOP will be replaced with a load instruction 4207 // which restores the TOC of the caller from the TOC save slot of the current 4208 // stack frame. If caller and callee belong to the same module (and have the 4209 // same TOC), the NOP will remain unchanged. 4210 4211 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 4212 !IsPatchPoint) { 4213 if (CallOpc == PPCISD::BCTRL) { 4214 // This is a call through a function pointer. 4215 // Restore the caller TOC from the save area into R2. 4216 // See PrepareCall() for more information about calls through function 4217 // pointers in the 64-bit SVR4 ABI. 4218 // We are using a target-specific load with r2 hard coded, because the 4219 // result of a target-independent load would never go directly into r2, 4220 // since r2 is a reserved register (which prevents the register allocator 4221 // from allocating it), resulting in an additional register being 4222 // allocated and an unnecessary move instruction being generated. 4223 CallOpc = PPCISD::BCTRL_LOAD_TOC; 4224 4225 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 4226 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 4227 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 4228 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset); 4229 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 4230 4231 // The address needs to go after the chain input but before the flag (or 4232 // any other variadic arguments). 4233 Ops.insert(std::next(Ops.begin()), AddTOC); 4234 } else if ((CallOpc == PPCISD::CALL) && 4235 (!isLocalCall(Callee) || 4236 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) 4237 // Otherwise insert NOP for non-local calls. 4238 CallOpc = PPCISD::CALL_NOP; 4239 } 4240 4241 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 4242 InFlag = Chain.getValue(1); 4243 4244 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 4245 DAG.getIntPtrConstant(BytesCalleePops, true), 4246 InFlag, dl); 4247 if (!Ins.empty()) 4248 InFlag = Chain.getValue(1); 4249 4250 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 4251 Ins, dl, DAG, InVals); 4252 } 4253 4254 SDValue 4255 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 4256 SmallVectorImpl<SDValue> &InVals) const { 4257 SelectionDAG &DAG = CLI.DAG; 4258 SDLoc &dl = CLI.DL; 4259 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 4260 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 4261 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 4262 SDValue Chain = CLI.Chain; 4263 SDValue Callee = CLI.Callee; 4264 bool &isTailCall = CLI.IsTailCall; 4265 CallingConv::ID CallConv = CLI.CallConv; 4266 bool isVarArg = CLI.IsVarArg; 4267 bool IsPatchPoint = CLI.IsPatchPoint; 4268 ImmutableCallSite *CS = CLI.CS; 4269 4270 if (isTailCall) 4271 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 4272 Ins, DAG); 4273 4274 if (!isTailCall && CS && CS->isMustTailCall()) 4275 report_fatal_error("failed to perform tail call elimination on a call " 4276 "site marked musttail"); 4277 4278 if (Subtarget.isSVR4ABI()) { 4279 if (Subtarget.isPPC64()) 4280 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 4281 isTailCall, IsPatchPoint, Outs, OutVals, Ins, 4282 dl, DAG, InVals, CS); 4283 else 4284 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 4285 isTailCall, IsPatchPoint, Outs, OutVals, Ins, 4286 dl, DAG, InVals, CS); 4287 } 4288 4289 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 4290 isTailCall, IsPatchPoint, Outs, OutVals, Ins, 4291 dl, DAG, InVals, CS); 4292 } 4293 4294 SDValue 4295 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee, 4296 CallingConv::ID CallConv, bool isVarArg, 4297 bool isTailCall, bool IsPatchPoint, 4298 const SmallVectorImpl<ISD::OutputArg> &Outs, 4299 const SmallVectorImpl<SDValue> &OutVals, 4300 const SmallVectorImpl<ISD::InputArg> &Ins, 4301 SDLoc dl, SelectionDAG &DAG, 4302 SmallVectorImpl<SDValue> &InVals, 4303 ImmutableCallSite *CS) const { 4304 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 4305 // of the 32-bit SVR4 ABI stack frame layout. 4306 4307 assert((CallConv == CallingConv::C || 4308 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 4309 4310 unsigned PtrByteSize = 4; 4311 4312 MachineFunction &MF = DAG.getMachineFunction(); 4313 4314 // Mark this function as potentially containing a function that contains a 4315 // tail call. As a consequence the frame pointer will be used for dynamicalloc 4316 // and restoring the callers stack pointer in this functions epilog. This is 4317 // done because by tail calling the called function might overwrite the value 4318 // in this function's (MF) stack pointer stack slot 0(SP). 4319 if (getTargetMachine().Options.GuaranteedTailCallOpt && 4320 CallConv == CallingConv::Fast) 4321 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 4322 4323 // Count how many bytes are to be pushed on the stack, including the linkage 4324 // area, parameter list area and the part of the local variable space which 4325 // contains copies of aggregates which are passed by value. 4326 4327 // Assign locations to all of the outgoing arguments. 4328 SmallVector<CCValAssign, 16> ArgLocs; 4329 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4330 *DAG.getContext()); 4331 4332 // Reserve space for the linkage area on the stack. 4333 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 4334 PtrByteSize); 4335 4336 if (isVarArg) { 4337 // Handle fixed and variable vector arguments differently. 4338 // Fixed vector arguments go into registers as long as registers are 4339 // available. Variable vector arguments always go into memory. 4340 unsigned NumArgs = Outs.size(); 4341 4342 for (unsigned i = 0; i != NumArgs; ++i) { 4343 MVT ArgVT = Outs[i].VT; 4344 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 4345 bool Result; 4346 4347 if (Outs[i].IsFixed) { 4348 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 4349 CCInfo); 4350 } else { 4351 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 4352 ArgFlags, CCInfo); 4353 } 4354 4355 if (Result) { 4356 #ifndef NDEBUG 4357 errs() << "Call operand #" << i << " has unhandled type " 4358 << EVT(ArgVT).getEVTString() << "\n"; 4359 #endif 4360 llvm_unreachable(nullptr); 4361 } 4362 } 4363 } else { 4364 // All arguments are treated the same. 4365 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 4366 } 4367 4368 // Assign locations to all of the outgoing aggregate by value arguments. 4369 SmallVector<CCValAssign, 16> ByValArgLocs; 4370 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 4371 ByValArgLocs, *DAG.getContext()); 4372 4373 // Reserve stack space for the allocations in CCInfo. 4374 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 4375 4376 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 4377 4378 // Size of the linkage area, parameter list area and the part of the local 4379 // space variable where copies of aggregates which are passed by value are 4380 // stored. 4381 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 4382 4383 // Calculate by how many bytes the stack has to be adjusted in case of tail 4384 // call optimization. 4385 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 4386 4387 // Adjust the stack pointer for the new arguments... 4388 // These operations are automatically eliminated by the prolog/epilog pass 4389 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), 4390 dl); 4391 SDValue CallSeqStart = Chain; 4392 4393 // Load the return address and frame pointer so it can be moved somewhere else 4394 // later. 4395 SDValue LROp, FPOp; 4396 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false, 4397 dl); 4398 4399 // Set up a copy of the stack pointer for use loading and storing any 4400 // arguments that may not fit in the registers available for argument 4401 // passing. 4402 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4403 4404 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 4405 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 4406 SmallVector<SDValue, 8> MemOpChains; 4407 4408 bool seenFloatArg = false; 4409 // Walk the register/memloc assignments, inserting copies/loads. 4410 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 4411 i != e; 4412 ++i) { 4413 CCValAssign &VA = ArgLocs[i]; 4414 SDValue Arg = OutVals[i]; 4415 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4416 4417 if (Flags.isByVal()) { 4418 // Argument is an aggregate which is passed by value, thus we need to 4419 // create a copy of it in the local variable space of the current stack 4420 // frame (which is the stack frame of the caller) and pass the address of 4421 // this copy to the callee. 4422 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 4423 CCValAssign &ByValVA = ByValArgLocs[j++]; 4424 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 4425 4426 // Memory reserved in the local variable space of the callers stack frame. 4427 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 4428 4429 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 4430 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 4431 4432 // Create a copy of the argument in the local area of the current 4433 // stack frame. 4434 SDValue MemcpyCall = 4435 CreateCopyOfByValArgument(Arg, PtrOff, 4436 CallSeqStart.getNode()->getOperand(0), 4437 Flags, DAG, dl); 4438 4439 // This must go outside the CALLSEQ_START..END. 4440 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, 4441 CallSeqStart.getNode()->getOperand(1), 4442 SDLoc(MemcpyCall)); 4443 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 4444 NewCallSeqStart.getNode()); 4445 Chain = CallSeqStart = NewCallSeqStart; 4446 4447 // Pass the address of the aggregate copy on the stack either in a 4448 // physical register or in the parameter list area of the current stack 4449 // frame to the callee. 4450 Arg = PtrOff; 4451 } 4452 4453 if (VA.isRegLoc()) { 4454 if (Arg.getValueType() == MVT::i1) 4455 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg); 4456 4457 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 4458 // Put argument in a physical register. 4459 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 4460 } else { 4461 // Put argument in the parameter list area of the current stack frame. 4462 assert(VA.isMemLoc()); 4463 unsigned LocMemOffset = VA.getLocMemOffset(); 4464 4465 if (!isTailCall) { 4466 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 4467 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 4468 4469 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, 4470 MachinePointerInfo(), 4471 false, false, 0)); 4472 } else { 4473 // Calculate and remember argument location. 4474 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 4475 TailCallArguments); 4476 } 4477 } 4478 } 4479 4480 if (!MemOpChains.empty()) 4481 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 4482 4483 // Build a sequence of copy-to-reg nodes chained together with token chain 4484 // and flag operands which copy the outgoing args into the appropriate regs. 4485 SDValue InFlag; 4486 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 4487 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 4488 RegsToPass[i].second, InFlag); 4489 InFlag = Chain.getValue(1); 4490 } 4491 4492 // Set CR bit 6 to true if this is a vararg call with floating args passed in 4493 // registers. 4494 if (isVarArg) { 4495 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 4496 SDValue Ops[] = { Chain, InFlag }; 4497 4498 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 4499 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 4500 4501 InFlag = Chain.getValue(1); 4502 } 4503 4504 if (isTailCall) 4505 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp, 4506 false, TailCallArguments); 4507 4508 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG, 4509 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 4510 NumBytes, Ins, InVals, CS); 4511 } 4512 4513 // Copy an argument into memory, being careful to do this outside the 4514 // call sequence for the call to which the argument belongs. 4515 SDValue 4516 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff, 4517 SDValue CallSeqStart, 4518 ISD::ArgFlagsTy Flags, 4519 SelectionDAG &DAG, 4520 SDLoc dl) const { 4521 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 4522 CallSeqStart.getNode()->getOperand(0), 4523 Flags, DAG, dl); 4524 // The MEMCPY must go outside the CALLSEQ_START..END. 4525 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, 4526 CallSeqStart.getNode()->getOperand(1), 4527 SDLoc(MemcpyCall)); 4528 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 4529 NewCallSeqStart.getNode()); 4530 return NewCallSeqStart; 4531 } 4532 4533 SDValue 4534 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee, 4535 CallingConv::ID CallConv, bool isVarArg, 4536 bool isTailCall, bool IsPatchPoint, 4537 const SmallVectorImpl<ISD::OutputArg> &Outs, 4538 const SmallVectorImpl<SDValue> &OutVals, 4539 const SmallVectorImpl<ISD::InputArg> &Ins, 4540 SDLoc dl, SelectionDAG &DAG, 4541 SmallVectorImpl<SDValue> &InVals, 4542 ImmutableCallSite *CS) const { 4543 4544 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4545 bool isLittleEndian = Subtarget.isLittleEndian(); 4546 unsigned NumOps = Outs.size(); 4547 4548 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 4549 unsigned PtrByteSize = 8; 4550 4551 MachineFunction &MF = DAG.getMachineFunction(); 4552 4553 // Mark this function as potentially containing a function that contains a 4554 // tail call. As a consequence the frame pointer will be used for dynamicalloc 4555 // and restoring the callers stack pointer in this functions epilog. This is 4556 // done because by tail calling the called function might overwrite the value 4557 // in this function's (MF) stack pointer stack slot 0(SP). 4558 if (getTargetMachine().Options.GuaranteedTailCallOpt && 4559 CallConv == CallingConv::Fast) 4560 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 4561 4562 assert(!(CallConv == CallingConv::Fast && isVarArg) && 4563 "fastcc not supported on varargs functions"); 4564 4565 // Count how many bytes are to be pushed on the stack, including the linkage 4566 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 4567 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 4568 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 4569 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4570 unsigned NumBytes = LinkageSize; 4571 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4572 unsigned &QFPR_idx = FPR_idx; 4573 4574 static const MCPhysReg GPR[] = { 4575 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4576 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4577 }; 4578 static const MCPhysReg VR[] = { 4579 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4580 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4581 }; 4582 static const MCPhysReg VSRH[] = { 4583 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8, 4584 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13 4585 }; 4586 4587 const unsigned NumGPRs = array_lengthof(GPR); 4588 const unsigned NumFPRs = 13; 4589 const unsigned NumVRs = array_lengthof(VR); 4590 const unsigned NumQFPRs = NumFPRs; 4591 4592 // When using the fast calling convention, we don't provide backing for 4593 // arguments that will be in registers. 4594 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 4595 4596 // Add up all the space actually used. 4597 for (unsigned i = 0; i != NumOps; ++i) { 4598 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4599 EVT ArgVT = Outs[i].VT; 4600 EVT OrigVT = Outs[i].ArgVT; 4601 4602 if (CallConv == CallingConv::Fast) { 4603 if (Flags.isByVal()) 4604 NumGPRsUsed += (Flags.getByValSize()+7)/8; 4605 else 4606 switch (ArgVT.getSimpleVT().SimpleTy) { 4607 default: llvm_unreachable("Unexpected ValueType for argument!"); 4608 case MVT::i1: 4609 case MVT::i32: 4610 case MVT::i64: 4611 if (++NumGPRsUsed <= NumGPRs) 4612 continue; 4613 break; 4614 case MVT::v4i32: 4615 case MVT::v8i16: 4616 case MVT::v16i8: 4617 case MVT::v2f64: 4618 case MVT::v2i64: 4619 if (++NumVRsUsed <= NumVRs) 4620 continue; 4621 break; 4622 case MVT::v4f32: 4623 // When using QPX, this is handled like a FP register, otherwise, it 4624 // is an Altivec register. 4625 if (Subtarget.hasQPX()) { 4626 if (++NumFPRsUsed <= NumFPRs) 4627 continue; 4628 } else { 4629 if (++NumVRsUsed <= NumVRs) 4630 continue; 4631 } 4632 break; 4633 case MVT::f32: 4634 case MVT::f64: 4635 case MVT::v4f64: // QPX 4636 case MVT::v4i1: // QPX 4637 if (++NumFPRsUsed <= NumFPRs) 4638 continue; 4639 break; 4640 } 4641 } 4642 4643 /* Respect alignment of argument on the stack. */ 4644 unsigned Align = 4645 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 4646 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 4647 4648 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 4649 if (Flags.isInConsecutiveRegsLast()) 4650 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4651 } 4652 4653 unsigned NumBytesActuallyUsed = NumBytes; 4654 4655 // The prolog code of the callee may store up to 8 GPR argument registers to 4656 // the stack, allowing va_start to index over them in memory if its varargs. 4657 // Because we cannot tell if this is needed on the caller side, we have to 4658 // conservatively assume that it is needed. As such, make sure we have at 4659 // least enough stack space for the caller to store the 8 GPRs. 4660 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area. 4661 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 4662 4663 // Tail call needs the stack to be aligned. 4664 if (getTargetMachine().Options.GuaranteedTailCallOpt && 4665 CallConv == CallingConv::Fast) 4666 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 4667 4668 // Calculate by how many bytes the stack has to be adjusted in case of tail 4669 // call optimization. 4670 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 4671 4672 // To protect arguments on the stack from being clobbered in a tail call, 4673 // force all the loads to happen before doing any other lowering. 4674 if (isTailCall) 4675 Chain = DAG.getStackArgumentTokenFactor(Chain); 4676 4677 // Adjust the stack pointer for the new arguments... 4678 // These operations are automatically eliminated by the prolog/epilog pass 4679 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), 4680 dl); 4681 SDValue CallSeqStart = Chain; 4682 4683 // Load the return address and frame pointer so it can be move somewhere else 4684 // later. 4685 SDValue LROp, FPOp; 4686 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true, 4687 dl); 4688 4689 // Set up a copy of the stack pointer for use loading and storing any 4690 // arguments that may not fit in the registers available for argument 4691 // passing. 4692 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4693 4694 // Figure out which arguments are going to go in registers, and which in 4695 // memory. Also, if this is a vararg function, floating point operations 4696 // must be stored to our stack, and loaded into integer regs as well, if 4697 // any integer regs are available for argument passing. 4698 unsigned ArgOffset = LinkageSize; 4699 4700 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 4701 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 4702 4703 SmallVector<SDValue, 8> MemOpChains; 4704 for (unsigned i = 0; i != NumOps; ++i) { 4705 SDValue Arg = OutVals[i]; 4706 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4707 EVT ArgVT = Outs[i].VT; 4708 EVT OrigVT = Outs[i].ArgVT; 4709 4710 // PtrOff will be used to store the current argument to the stack if a 4711 // register cannot be found for it. 4712 SDValue PtrOff; 4713 4714 // We re-align the argument offset for each argument, except when using the 4715 // fast calling convention, when we need to make sure we do that only when 4716 // we'll actually use a stack slot. 4717 auto ComputePtrOff = [&]() { 4718 /* Respect alignment of argument on the stack. */ 4719 unsigned Align = 4720 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 4721 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 4722 4723 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType()); 4724 4725 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 4726 }; 4727 4728 if (CallConv != CallingConv::Fast) { 4729 ComputePtrOff(); 4730 4731 /* Compute GPR index associated with argument offset. */ 4732 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4733 GPR_idx = std::min(GPR_idx, NumGPRs); 4734 } 4735 4736 // Promote integers to 64-bit values. 4737 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 4738 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 4739 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4740 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 4741 } 4742 4743 // FIXME memcpy is used way more than necessary. Correctness first. 4744 // Note: "by value" is code for passing a structure by value, not 4745 // basic types. 4746 if (Flags.isByVal()) { 4747 // Note: Size includes alignment padding, so 4748 // struct x { short a; char b; } 4749 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 4750 // These are the proper values we need for right-justifying the 4751 // aggregate in a parameter register. 4752 unsigned Size = Flags.getByValSize(); 4753 4754 // An empty aggregate parameter takes up no storage and no 4755 // registers. 4756 if (Size == 0) 4757 continue; 4758 4759 if (CallConv == CallingConv::Fast) 4760 ComputePtrOff(); 4761 4762 // All aggregates smaller than 8 bytes must be passed right-justified. 4763 if (Size==1 || Size==2 || Size==4) { 4764 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 4765 if (GPR_idx != NumGPRs) { 4766 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 4767 MachinePointerInfo(), VT, 4768 false, false, false, 0); 4769 MemOpChains.push_back(Load.getValue(1)); 4770 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4771 4772 ArgOffset += PtrByteSize; 4773 continue; 4774 } 4775 } 4776 4777 if (GPR_idx == NumGPRs && Size < 8) { 4778 SDValue AddPtr = PtrOff; 4779 if (!isLittleEndian) { 4780 SDValue Const = DAG.getConstant(PtrByteSize - Size, 4781 PtrOff.getValueType()); 4782 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 4783 } 4784 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 4785 CallSeqStart, 4786 Flags, DAG, dl); 4787 ArgOffset += PtrByteSize; 4788 continue; 4789 } 4790 // Copy entire object into memory. There are cases where gcc-generated 4791 // code assumes it is there, even if it could be put entirely into 4792 // registers. (This is not what the doc says.) 4793 4794 // FIXME: The above statement is likely due to a misunderstanding of the 4795 // documents. All arguments must be copied into the parameter area BY 4796 // THE CALLEE in the event that the callee takes the address of any 4797 // formal argument. That has not yet been implemented. However, it is 4798 // reasonable to use the stack area as a staging area for the register 4799 // load. 4800 4801 // Skip this for small aggregates, as we will use the same slot for a 4802 // right-justified copy, below. 4803 if (Size >= 8) 4804 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 4805 CallSeqStart, 4806 Flags, DAG, dl); 4807 4808 // When a register is available, pass a small aggregate right-justified. 4809 if (Size < 8 && GPR_idx != NumGPRs) { 4810 // The easiest way to get this right-justified in a register 4811 // is to copy the structure into the rightmost portion of a 4812 // local variable slot, then load the whole slot into the 4813 // register. 4814 // FIXME: The memcpy seems to produce pretty awful code for 4815 // small aggregates, particularly for packed ones. 4816 // FIXME: It would be preferable to use the slot in the 4817 // parameter save area instead of a new local variable. 4818 SDValue AddPtr = PtrOff; 4819 if (!isLittleEndian) { 4820 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType()); 4821 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 4822 } 4823 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 4824 CallSeqStart, 4825 Flags, DAG, dl); 4826 4827 // Load the slot into the register. 4828 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff, 4829 MachinePointerInfo(), 4830 false, false, false, 0); 4831 MemOpChains.push_back(Load.getValue(1)); 4832 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4833 4834 // Done with this argument. 4835 ArgOffset += PtrByteSize; 4836 continue; 4837 } 4838 4839 // For aggregates larger than PtrByteSize, copy the pieces of the 4840 // object that fit into registers from the parameter save area. 4841 for (unsigned j=0; j<Size; j+=PtrByteSize) { 4842 SDValue Const = DAG.getConstant(j, PtrOff.getValueType()); 4843 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 4844 if (GPR_idx != NumGPRs) { 4845 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 4846 MachinePointerInfo(), 4847 false, false, false, 0); 4848 MemOpChains.push_back(Load.getValue(1)); 4849 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 4850 ArgOffset += PtrByteSize; 4851 } else { 4852 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 4853 break; 4854 } 4855 } 4856 continue; 4857 } 4858 4859 switch (Arg.getSimpleValueType().SimpleTy) { 4860 default: llvm_unreachable("Unexpected ValueType for argument!"); 4861 case MVT::i1: 4862 case MVT::i32: 4863 case MVT::i64: 4864 // These can be scalar arguments or elements of an integer array type 4865 // passed directly. Clang may use those instead of "byval" aggregate 4866 // types to avoid forcing arguments to memory unnecessarily. 4867 if (GPR_idx != NumGPRs) { 4868 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 4869 } else { 4870 if (CallConv == CallingConv::Fast) 4871 ComputePtrOff(); 4872 4873 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4874 true, isTailCall, false, MemOpChains, 4875 TailCallArguments, dl); 4876 if (CallConv == CallingConv::Fast) 4877 ArgOffset += PtrByteSize; 4878 } 4879 if (CallConv != CallingConv::Fast) 4880 ArgOffset += PtrByteSize; 4881 break; 4882 case MVT::f32: 4883 case MVT::f64: { 4884 // These can be scalar arguments or elements of a float array type 4885 // passed directly. The latter are used to implement ELFv2 homogenous 4886 // float aggregates. 4887 4888 // Named arguments go into FPRs first, and once they overflow, the 4889 // remaining arguments go into GPRs and then the parameter save area. 4890 // Unnamed arguments for vararg functions always go to GPRs and 4891 // then the parameter save area. For now, put all arguments to vararg 4892 // routines always in both locations (FPR *and* GPR or stack slot). 4893 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 4894 bool NeededLoad = false; 4895 4896 // First load the argument into the next available FPR. 4897 if (FPR_idx != NumFPRs) 4898 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 4899 4900 // Next, load the argument into GPR or stack slot if needed. 4901 if (!NeedGPROrStack) 4902 ; 4903 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 4904 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4905 // once we support fp <-> gpr moves. 4906 4907 // In the non-vararg case, this can only ever happen in the 4908 // presence of f32 array types, since otherwise we never run 4909 // out of FPRs before running out of GPRs. 4910 SDValue ArgVal; 4911 4912 // Double values are always passed in a single GPR. 4913 if (Arg.getValueType() != MVT::f32) { 4914 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 4915 4916 // Non-array float values are extended and passed in a GPR. 4917 } else if (!Flags.isInConsecutiveRegs()) { 4918 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 4919 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 4920 4921 // If we have an array of floats, we collect every odd element 4922 // together with its predecessor into one GPR. 4923 } else if (ArgOffset % PtrByteSize != 0) { 4924 SDValue Lo, Hi; 4925 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 4926 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 4927 if (!isLittleEndian) 4928 std::swap(Lo, Hi); 4929 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 4930 4931 // The final element, if even, goes into the first half of a GPR. 4932 } else if (Flags.isInConsecutiveRegsLast()) { 4933 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 4934 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 4935 if (!isLittleEndian) 4936 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 4937 DAG.getConstant(32, MVT::i32)); 4938 4939 // Non-final even elements are skipped; they will be handled 4940 // together the with subsequent argument on the next go-around. 4941 } else 4942 ArgVal = SDValue(); 4943 4944 if (ArgVal.getNode()) 4945 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 4946 } else { 4947 if (CallConv == CallingConv::Fast) 4948 ComputePtrOff(); 4949 4950 // Single-precision floating-point values are mapped to the 4951 // second (rightmost) word of the stack doubleword. 4952 if (Arg.getValueType() == MVT::f32 && 4953 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 4954 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType()); 4955 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 4956 } 4957 4958 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 4959 true, isTailCall, false, MemOpChains, 4960 TailCallArguments, dl); 4961 4962 NeededLoad = true; 4963 } 4964 // When passing an array of floats, the array occupies consecutive 4965 // space in the argument area; only round up to the next doubleword 4966 // at the end of the array. Otherwise, each float takes 8 bytes. 4967 if (CallConv != CallingConv::Fast || NeededLoad) { 4968 ArgOffset += (Arg.getValueType() == MVT::f32 && 4969 Flags.isInConsecutiveRegs()) ? 4 : 8; 4970 if (Flags.isInConsecutiveRegsLast()) 4971 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4972 } 4973 break; 4974 } 4975 case MVT::v4f32: 4976 case MVT::v4i32: 4977 case MVT::v8i16: 4978 case MVT::v16i8: 4979 case MVT::v2f64: 4980 case MVT::v2i64: 4981 if (!Subtarget.hasQPX()) { 4982 // These can be scalar arguments or elements of a vector array type 4983 // passed directly. The latter are used to implement ELFv2 homogenous 4984 // vector aggregates. 4985 4986 // For a varargs call, named arguments go into VRs or on the stack as 4987 // usual; unnamed arguments always go to the stack or the corresponding 4988 // GPRs when within range. For now, we always put the value in both 4989 // locations (or even all three). 4990 if (isVarArg) { 4991 // We could elide this store in the case where the object fits 4992 // entirely in R registers. Maybe later. 4993 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, 4994 MachinePointerInfo(), false, false, 0); 4995 MemOpChains.push_back(Store); 4996 if (VR_idx != NumVRs) { 4997 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, 4998 MachinePointerInfo(), 4999 false, false, false, 0); 5000 MemOpChains.push_back(Load.getValue(1)); 5001 5002 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 || 5003 Arg.getSimpleValueType() == MVT::v2i64) ? 5004 VSRH[VR_idx] : VR[VR_idx]; 5005 ++VR_idx; 5006 5007 RegsToPass.push_back(std::make_pair(VReg, Load)); 5008 } 5009 ArgOffset += 16; 5010 for (unsigned i=0; i<16; i+=PtrByteSize) { 5011 if (GPR_idx == NumGPRs) 5012 break; 5013 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5014 DAG.getConstant(i, PtrVT)); 5015 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(), 5016 false, false, false, 0); 5017 MemOpChains.push_back(Load.getValue(1)); 5018 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5019 } 5020 break; 5021 } 5022 5023 // Non-varargs Altivec params go into VRs or on the stack. 5024 if (VR_idx != NumVRs) { 5025 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 || 5026 Arg.getSimpleValueType() == MVT::v2i64) ? 5027 VSRH[VR_idx] : VR[VR_idx]; 5028 ++VR_idx; 5029 5030 RegsToPass.push_back(std::make_pair(VReg, Arg)); 5031 } else { 5032 if (CallConv == CallingConv::Fast) 5033 ComputePtrOff(); 5034 5035 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5036 true, isTailCall, true, MemOpChains, 5037 TailCallArguments, dl); 5038 if (CallConv == CallingConv::Fast) 5039 ArgOffset += 16; 5040 } 5041 5042 if (CallConv != CallingConv::Fast) 5043 ArgOffset += 16; 5044 break; 5045 } // not QPX 5046 5047 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 5048 "Invalid QPX parameter type"); 5049 5050 /* fall through */ 5051 case MVT::v4f64: 5052 case MVT::v4i1: { 5053 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 5054 if (isVarArg) { 5055 // We could elide this store in the case where the object fits 5056 // entirely in R registers. Maybe later. 5057 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, 5058 MachinePointerInfo(), false, false, 0); 5059 MemOpChains.push_back(Store); 5060 if (QFPR_idx != NumQFPRs) { 5061 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, 5062 Store, PtrOff, MachinePointerInfo(), 5063 false, false, false, 0); 5064 MemOpChains.push_back(Load.getValue(1)); 5065 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 5066 } 5067 ArgOffset += (IsF32 ? 16 : 32); 5068 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 5069 if (GPR_idx == NumGPRs) 5070 break; 5071 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5072 DAG.getConstant(i, PtrVT)); 5073 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(), 5074 false, false, false, 0); 5075 MemOpChains.push_back(Load.getValue(1)); 5076 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5077 } 5078 break; 5079 } 5080 5081 // Non-varargs QPX params go into registers or on the stack. 5082 if (QFPR_idx != NumQFPRs) { 5083 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 5084 } else { 5085 if (CallConv == CallingConv::Fast) 5086 ComputePtrOff(); 5087 5088 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5089 true, isTailCall, true, MemOpChains, 5090 TailCallArguments, dl); 5091 if (CallConv == CallingConv::Fast) 5092 ArgOffset += (IsF32 ? 16 : 32); 5093 } 5094 5095 if (CallConv != CallingConv::Fast) 5096 ArgOffset += (IsF32 ? 16 : 32); 5097 break; 5098 } 5099 } 5100 } 5101 5102 assert(NumBytesActuallyUsed == ArgOffset); 5103 (void)NumBytesActuallyUsed; 5104 5105 if (!MemOpChains.empty()) 5106 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5107 5108 // Check if this is an indirect call (MTCTR/BCTRL). 5109 // See PrepareCall() for more information about calls through function 5110 // pointers in the 64-bit SVR4 ABI. 5111 if (!isTailCall && !IsPatchPoint && 5112 !isFunctionGlobalAddress(Callee) && 5113 !isa<ExternalSymbolSDNode>(Callee)) { 5114 // Load r2 into a virtual register and store it to the TOC save area. 5115 setUsesTOCBasePtr(DAG); 5116 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 5117 // TOC save area offset. 5118 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5119 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset); 5120 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5121 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 5122 MachinePointerInfo::getStack(TOCSaveOffset), 5123 false, false, 0); 5124 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 5125 // This does not mean the MTCTR instruction must use R12; it's easier 5126 // to model this as an extra parameter, so do that. 5127 if (isELFv2ABI && !IsPatchPoint) 5128 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 5129 } 5130 5131 // Build a sequence of copy-to-reg nodes chained together with token chain 5132 // and flag operands which copy the outgoing args into the appropriate regs. 5133 SDValue InFlag; 5134 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5135 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5136 RegsToPass[i].second, InFlag); 5137 InFlag = Chain.getValue(1); 5138 } 5139 5140 if (isTailCall) 5141 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp, 5142 FPOp, true, TailCallArguments); 5143 5144 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG, 5145 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5146 NumBytes, Ins, InVals, CS); 5147 } 5148 5149 SDValue 5150 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee, 5151 CallingConv::ID CallConv, bool isVarArg, 5152 bool isTailCall, bool IsPatchPoint, 5153 const SmallVectorImpl<ISD::OutputArg> &Outs, 5154 const SmallVectorImpl<SDValue> &OutVals, 5155 const SmallVectorImpl<ISD::InputArg> &Ins, 5156 SDLoc dl, SelectionDAG &DAG, 5157 SmallVectorImpl<SDValue> &InVals, 5158 ImmutableCallSite *CS) const { 5159 5160 unsigned NumOps = Outs.size(); 5161 5162 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 5163 bool isPPC64 = PtrVT == MVT::i64; 5164 unsigned PtrByteSize = isPPC64 ? 8 : 4; 5165 5166 MachineFunction &MF = DAG.getMachineFunction(); 5167 5168 // Mark this function as potentially containing a function that contains a 5169 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5170 // and restoring the callers stack pointer in this functions epilog. This is 5171 // done because by tail calling the called function might overwrite the value 5172 // in this function's (MF) stack pointer stack slot 0(SP). 5173 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5174 CallConv == CallingConv::Fast) 5175 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5176 5177 // Count how many bytes are to be pushed on the stack, including the linkage 5178 // area, and parameter passing area. We start with 24/48 bytes, which is 5179 // prereserved space for [SP][CR][LR][3 x unused]. 5180 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5181 unsigned NumBytes = LinkageSize; 5182 5183 // Add up all the space actually used. 5184 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 5185 // they all go in registers, but we must reserve stack space for them for 5186 // possible use by the caller. In varargs or 64-bit calls, parameters are 5187 // assigned stack space in order, with padding so Altivec parameters are 5188 // 16-byte aligned. 5189 unsigned nAltivecParamsAtEnd = 0; 5190 for (unsigned i = 0; i != NumOps; ++i) { 5191 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5192 EVT ArgVT = Outs[i].VT; 5193 // Varargs Altivec parameters are padded to a 16 byte boundary. 5194 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 5195 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 5196 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 5197 if (!isVarArg && !isPPC64) { 5198 // Non-varargs Altivec parameters go after all the non-Altivec 5199 // parameters; handle those later so we know how much padding we need. 5200 nAltivecParamsAtEnd++; 5201 continue; 5202 } 5203 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 5204 NumBytes = ((NumBytes+15)/16)*16; 5205 } 5206 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5207 } 5208 5209 // Allow for Altivec parameters at the end, if needed. 5210 if (nAltivecParamsAtEnd) { 5211 NumBytes = ((NumBytes+15)/16)*16; 5212 NumBytes += 16*nAltivecParamsAtEnd; 5213 } 5214 5215 // The prolog code of the callee may store up to 8 GPR argument registers to 5216 // the stack, allowing va_start to index over them in memory if its varargs. 5217 // Because we cannot tell if this is needed on the caller side, we have to 5218 // conservatively assume that it is needed. As such, make sure we have at 5219 // least enough stack space for the caller to store the 8 GPRs. 5220 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5221 5222 // Tail call needs the stack to be aligned. 5223 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5224 CallConv == CallingConv::Fast) 5225 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5226 5227 // Calculate by how many bytes the stack has to be adjusted in case of tail 5228 // call optimization. 5229 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5230 5231 // To protect arguments on the stack from being clobbered in a tail call, 5232 // force all the loads to happen before doing any other lowering. 5233 if (isTailCall) 5234 Chain = DAG.getStackArgumentTokenFactor(Chain); 5235 5236 // Adjust the stack pointer for the new arguments... 5237 // These operations are automatically eliminated by the prolog/epilog pass 5238 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), 5239 dl); 5240 SDValue CallSeqStart = Chain; 5241 5242 // Load the return address and frame pointer so it can be move somewhere else 5243 // later. 5244 SDValue LROp, FPOp; 5245 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true, 5246 dl); 5247 5248 // Set up a copy of the stack pointer for use loading and storing any 5249 // arguments that may not fit in the registers available for argument 5250 // passing. 5251 SDValue StackPtr; 5252 if (isPPC64) 5253 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5254 else 5255 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5256 5257 // Figure out which arguments are going to go in registers, and which in 5258 // memory. Also, if this is a vararg function, floating point operations 5259 // must be stored to our stack, and loaded into integer regs as well, if 5260 // any integer regs are available for argument passing. 5261 unsigned ArgOffset = LinkageSize; 5262 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5263 5264 static const MCPhysReg GPR_32[] = { // 32-bit registers. 5265 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 5266 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 5267 }; 5268 static const MCPhysReg GPR_64[] = { // 64-bit registers. 5269 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5270 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5271 }; 5272 static const MCPhysReg VR[] = { 5273 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5274 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5275 }; 5276 const unsigned NumGPRs = array_lengthof(GPR_32); 5277 const unsigned NumFPRs = 13; 5278 const unsigned NumVRs = array_lengthof(VR); 5279 5280 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 5281 5282 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5283 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5284 5285 SmallVector<SDValue, 8> MemOpChains; 5286 for (unsigned i = 0; i != NumOps; ++i) { 5287 SDValue Arg = OutVals[i]; 5288 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5289 5290 // PtrOff will be used to store the current argument to the stack if a 5291 // register cannot be found for it. 5292 SDValue PtrOff; 5293 5294 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType()); 5295 5296 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5297 5298 // On PPC64, promote integers to 64-bit values. 5299 if (isPPC64 && Arg.getValueType() == MVT::i32) { 5300 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5301 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5302 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5303 } 5304 5305 // FIXME memcpy is used way more than necessary. Correctness first. 5306 // Note: "by value" is code for passing a structure by value, not 5307 // basic types. 5308 if (Flags.isByVal()) { 5309 unsigned Size = Flags.getByValSize(); 5310 // Very small objects are passed right-justified. Everything else is 5311 // passed left-justified. 5312 if (Size==1 || Size==2) { 5313 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 5314 if (GPR_idx != NumGPRs) { 5315 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5316 MachinePointerInfo(), VT, 5317 false, false, false, 0); 5318 MemOpChains.push_back(Load.getValue(1)); 5319 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5320 5321 ArgOffset += PtrByteSize; 5322 } else { 5323 SDValue Const = DAG.getConstant(PtrByteSize - Size, 5324 PtrOff.getValueType()); 5325 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5326 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5327 CallSeqStart, 5328 Flags, DAG, dl); 5329 ArgOffset += PtrByteSize; 5330 } 5331 continue; 5332 } 5333 // Copy entire object into memory. There are cases where gcc-generated 5334 // code assumes it is there, even if it could be put entirely into 5335 // registers. (This is not what the doc says.) 5336 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5337 CallSeqStart, 5338 Flags, DAG, dl); 5339 5340 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 5341 // copy the pieces of the object that fit into registers from the 5342 // parameter save area. 5343 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5344 SDValue Const = DAG.getConstant(j, PtrOff.getValueType()); 5345 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5346 if (GPR_idx != NumGPRs) { 5347 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 5348 MachinePointerInfo(), 5349 false, false, false, 0); 5350 MemOpChains.push_back(Load.getValue(1)); 5351 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5352 ArgOffset += PtrByteSize; 5353 } else { 5354 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5355 break; 5356 } 5357 } 5358 continue; 5359 } 5360 5361 switch (Arg.getSimpleValueType().SimpleTy) { 5362 default: llvm_unreachable("Unexpected ValueType for argument!"); 5363 case MVT::i1: 5364 case MVT::i32: 5365 case MVT::i64: 5366 if (GPR_idx != NumGPRs) { 5367 if (Arg.getValueType() == MVT::i1) 5368 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 5369 5370 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5371 } else { 5372 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5373 isPPC64, isTailCall, false, MemOpChains, 5374 TailCallArguments, dl); 5375 } 5376 ArgOffset += PtrByteSize; 5377 break; 5378 case MVT::f32: 5379 case MVT::f64: 5380 if (FPR_idx != NumFPRs) { 5381 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5382 5383 if (isVarArg) { 5384 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, 5385 MachinePointerInfo(), false, false, 0); 5386 MemOpChains.push_back(Store); 5387 5388 // Float varargs are always shadowed in available integer registers 5389 if (GPR_idx != NumGPRs) { 5390 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, 5391 MachinePointerInfo(), false, false, 5392 false, 0); 5393 MemOpChains.push_back(Load.getValue(1)); 5394 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5395 } 5396 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 5397 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType()); 5398 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5399 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, 5400 MachinePointerInfo(), 5401 false, false, false, 0); 5402 MemOpChains.push_back(Load.getValue(1)); 5403 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5404 } 5405 } else { 5406 // If we have any FPRs remaining, we may also have GPRs remaining. 5407 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 5408 // GPRs. 5409 if (GPR_idx != NumGPRs) 5410 ++GPR_idx; 5411 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 5412 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 5413 ++GPR_idx; 5414 } 5415 } else 5416 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5417 isPPC64, isTailCall, false, MemOpChains, 5418 TailCallArguments, dl); 5419 if (isPPC64) 5420 ArgOffset += 8; 5421 else 5422 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 5423 break; 5424 case MVT::v4f32: 5425 case MVT::v4i32: 5426 case MVT::v8i16: 5427 case MVT::v16i8: 5428 if (isVarArg) { 5429 // These go aligned on the stack, or in the corresponding R registers 5430 // when within range. The Darwin PPC ABI doc claims they also go in 5431 // V registers; in fact gcc does this only for arguments that are 5432 // prototyped, not for those that match the ... We do it for all 5433 // arguments, seems to work. 5434 while (ArgOffset % 16 !=0) { 5435 ArgOffset += PtrByteSize; 5436 if (GPR_idx != NumGPRs) 5437 GPR_idx++; 5438 } 5439 // We could elide this store in the case where the object fits 5440 // entirely in R registers. Maybe later. 5441 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5442 DAG.getConstant(ArgOffset, PtrVT)); 5443 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, 5444 MachinePointerInfo(), false, false, 0); 5445 MemOpChains.push_back(Store); 5446 if (VR_idx != NumVRs) { 5447 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, 5448 MachinePointerInfo(), 5449 false, false, false, 0); 5450 MemOpChains.push_back(Load.getValue(1)); 5451 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 5452 } 5453 ArgOffset += 16; 5454 for (unsigned i=0; i<16; i+=PtrByteSize) { 5455 if (GPR_idx == NumGPRs) 5456 break; 5457 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5458 DAG.getConstant(i, PtrVT)); 5459 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(), 5460 false, false, false, 0); 5461 MemOpChains.push_back(Load.getValue(1)); 5462 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5463 } 5464 break; 5465 } 5466 5467 // Non-varargs Altivec params generally go in registers, but have 5468 // stack space allocated at the end. 5469 if (VR_idx != NumVRs) { 5470 // Doesn't have GPR space allocated. 5471 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 5472 } else if (nAltivecParamsAtEnd==0) { 5473 // We are emitting Altivec params in order. 5474 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5475 isPPC64, isTailCall, true, MemOpChains, 5476 TailCallArguments, dl); 5477 ArgOffset += 16; 5478 } 5479 break; 5480 } 5481 } 5482 // If all Altivec parameters fit in registers, as they usually do, 5483 // they get stack space following the non-Altivec parameters. We 5484 // don't track this here because nobody below needs it. 5485 // If there are more Altivec parameters than fit in registers emit 5486 // the stores here. 5487 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 5488 unsigned j = 0; 5489 // Offset is aligned; skip 1st 12 params which go in V registers. 5490 ArgOffset = ((ArgOffset+15)/16)*16; 5491 ArgOffset += 12*16; 5492 for (unsigned i = 0; i != NumOps; ++i) { 5493 SDValue Arg = OutVals[i]; 5494 EVT ArgType = Outs[i].VT; 5495 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 5496 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 5497 if (++j > NumVRs) { 5498 SDValue PtrOff; 5499 // We are emitting Altivec params in order. 5500 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5501 isPPC64, isTailCall, true, MemOpChains, 5502 TailCallArguments, dl); 5503 ArgOffset += 16; 5504 } 5505 } 5506 } 5507 } 5508 5509 if (!MemOpChains.empty()) 5510 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5511 5512 // On Darwin, R12 must contain the address of an indirect callee. This does 5513 // not mean the MTCTR instruction must use R12; it's easier to model this as 5514 // an extra parameter, so do that. 5515 if (!isTailCall && 5516 !isFunctionGlobalAddress(Callee) && 5517 !isa<ExternalSymbolSDNode>(Callee) && 5518 !isBLACompatibleAddress(Callee, DAG)) 5519 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 5520 PPC::R12), Callee)); 5521 5522 // Build a sequence of copy-to-reg nodes chained together with token chain 5523 // and flag operands which copy the outgoing args into the appropriate regs. 5524 SDValue InFlag; 5525 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5526 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5527 RegsToPass[i].second, InFlag); 5528 InFlag = Chain.getValue(1); 5529 } 5530 5531 if (isTailCall) 5532 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp, 5533 FPOp, true, TailCallArguments); 5534 5535 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG, 5536 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5537 NumBytes, Ins, InVals, CS); 5538 } 5539 5540 bool 5541 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 5542 MachineFunction &MF, bool isVarArg, 5543 const SmallVectorImpl<ISD::OutputArg> &Outs, 5544 LLVMContext &Context) const { 5545 SmallVector<CCValAssign, 16> RVLocs; 5546 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 5547 return CCInfo.CheckReturn(Outs, RetCC_PPC); 5548 } 5549 5550 SDValue 5551 PPCTargetLowering::LowerReturn(SDValue Chain, 5552 CallingConv::ID CallConv, bool isVarArg, 5553 const SmallVectorImpl<ISD::OutputArg> &Outs, 5554 const SmallVectorImpl<SDValue> &OutVals, 5555 SDLoc dl, SelectionDAG &DAG) const { 5556 5557 SmallVector<CCValAssign, 16> RVLocs; 5558 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5559 *DAG.getContext()); 5560 CCInfo.AnalyzeReturn(Outs, RetCC_PPC); 5561 5562 SDValue Flag; 5563 SmallVector<SDValue, 4> RetOps(1, Chain); 5564 5565 // Copy the result values into the output registers. 5566 for (unsigned i = 0; i != RVLocs.size(); ++i) { 5567 CCValAssign &VA = RVLocs[i]; 5568 assert(VA.isRegLoc() && "Can only return in registers!"); 5569 5570 SDValue Arg = OutVals[i]; 5571 5572 switch (VA.getLocInfo()) { 5573 default: llvm_unreachable("Unknown loc info!"); 5574 case CCValAssign::Full: break; 5575 case CCValAssign::AExt: 5576 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 5577 break; 5578 case CCValAssign::ZExt: 5579 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 5580 break; 5581 case CCValAssign::SExt: 5582 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 5583 break; 5584 } 5585 5586 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 5587 Flag = Chain.getValue(1); 5588 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 5589 } 5590 5591 RetOps[0] = Chain; // Update chain. 5592 5593 // Add the flag if we have it. 5594 if (Flag.getNode()) 5595 RetOps.push_back(Flag); 5596 5597 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 5598 } 5599 5600 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG, 5601 const PPCSubtarget &Subtarget) const { 5602 // When we pop the dynamic allocation we need to restore the SP link. 5603 SDLoc dl(Op); 5604 5605 // Get the corect type for pointers. 5606 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 5607 5608 // Construct the stack pointer operand. 5609 bool isPPC64 = Subtarget.isPPC64(); 5610 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 5611 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 5612 5613 // Get the operands for the STACKRESTORE. 5614 SDValue Chain = Op.getOperand(0); 5615 SDValue SaveSP = Op.getOperand(1); 5616 5617 // Load the old link SP. 5618 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr, 5619 MachinePointerInfo(), 5620 false, false, false, 0); 5621 5622 // Restore the stack pointer. 5623 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 5624 5625 // Store the old link SP. 5626 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(), 5627 false, false, 0); 5628 } 5629 5630 5631 5632 SDValue 5633 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const { 5634 MachineFunction &MF = DAG.getMachineFunction(); 5635 bool isPPC64 = Subtarget.isPPC64(); 5636 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 5637 5638 // Get current frame pointer save index. The users of this index will be 5639 // primarily DYNALLOC instructions. 5640 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 5641 int RASI = FI->getReturnAddrSaveIndex(); 5642 5643 // If the frame pointer save index hasn't been defined yet. 5644 if (!RASI) { 5645 // Find out what the fix offset of the frame pointer save area. 5646 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 5647 // Allocate the frame index for frame pointer save area. 5648 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 5649 // Save the result. 5650 FI->setReturnAddrSaveIndex(RASI); 5651 } 5652 return DAG.getFrameIndex(RASI, PtrVT); 5653 } 5654 5655 SDValue 5656 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 5657 MachineFunction &MF = DAG.getMachineFunction(); 5658 bool isPPC64 = Subtarget.isPPC64(); 5659 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 5660 5661 // Get current frame pointer save index. The users of this index will be 5662 // primarily DYNALLOC instructions. 5663 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 5664 int FPSI = FI->getFramePointerSaveIndex(); 5665 5666 // If the frame pointer save index hasn't been defined yet. 5667 if (!FPSI) { 5668 // Find out what the fix offset of the frame pointer save area. 5669 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 5670 // Allocate the frame index for frame pointer save area. 5671 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 5672 // Save the result. 5673 FI->setFramePointerSaveIndex(FPSI); 5674 } 5675 return DAG.getFrameIndex(FPSI, PtrVT); 5676 } 5677 5678 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 5679 SelectionDAG &DAG, 5680 const PPCSubtarget &Subtarget) const { 5681 // Get the inputs. 5682 SDValue Chain = Op.getOperand(0); 5683 SDValue Size = Op.getOperand(1); 5684 SDLoc dl(Op); 5685 5686 // Get the corect type for pointers. 5687 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 5688 // Negate the size. 5689 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 5690 DAG.getConstant(0, PtrVT), Size); 5691 // Construct a node for the frame pointer save index. 5692 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 5693 // Build a DYNALLOC node. 5694 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 5695 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 5696 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 5697 } 5698 5699 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 5700 SelectionDAG &DAG) const { 5701 SDLoc DL(Op); 5702 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 5703 DAG.getVTList(MVT::i32, MVT::Other), 5704 Op.getOperand(0), Op.getOperand(1)); 5705 } 5706 5707 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 5708 SelectionDAG &DAG) const { 5709 SDLoc DL(Op); 5710 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 5711 Op.getOperand(0), Op.getOperand(1)); 5712 } 5713 5714 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 5715 if (Op.getValueType().isVector()) 5716 return LowerVectorLoad(Op, DAG); 5717 5718 assert(Op.getValueType() == MVT::i1 && 5719 "Custom lowering only for i1 loads"); 5720 5721 // First, load 8 bits into 32 bits, then truncate to 1 bit. 5722 5723 SDLoc dl(Op); 5724 LoadSDNode *LD = cast<LoadSDNode>(Op); 5725 5726 SDValue Chain = LD->getChain(); 5727 SDValue BasePtr = LD->getBasePtr(); 5728 MachineMemOperand *MMO = LD->getMemOperand(); 5729 5730 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain, 5731 BasePtr, MVT::i8, MMO); 5732 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 5733 5734 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 5735 return DAG.getMergeValues(Ops, dl); 5736 } 5737 5738 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 5739 if (Op.getOperand(1).getValueType().isVector()) 5740 return LowerVectorStore(Op, DAG); 5741 5742 assert(Op.getOperand(1).getValueType() == MVT::i1 && 5743 "Custom lowering only for i1 stores"); 5744 5745 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 5746 5747 SDLoc dl(Op); 5748 StoreSDNode *ST = cast<StoreSDNode>(Op); 5749 5750 SDValue Chain = ST->getChain(); 5751 SDValue BasePtr = ST->getBasePtr(); 5752 SDValue Value = ST->getValue(); 5753 MachineMemOperand *MMO = ST->getMemOperand(); 5754 5755 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value); 5756 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 5757 } 5758 5759 // FIXME: Remove this once the ANDI glue bug is fixed: 5760 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 5761 assert(Op.getValueType() == MVT::i1 && 5762 "Custom lowering only for i1 results"); 5763 5764 SDLoc DL(Op); 5765 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 5766 Op.getOperand(0)); 5767 } 5768 5769 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 5770 /// possible. 5771 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 5772 // Not FP? Not a fsel. 5773 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 5774 !Op.getOperand(2).getValueType().isFloatingPoint()) 5775 return Op; 5776 5777 // We might be able to do better than this under some circumstances, but in 5778 // general, fsel-based lowering of select is a finite-math-only optimization. 5779 // For more information, see section F.3 of the 2.06 ISA specification. 5780 if (!DAG.getTarget().Options.NoInfsFPMath || 5781 !DAG.getTarget().Options.NoNaNsFPMath) 5782 return Op; 5783 5784 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5785 5786 EVT ResVT = Op.getValueType(); 5787 EVT CmpVT = Op.getOperand(0).getValueType(); 5788 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 5789 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 5790 SDLoc dl(Op); 5791 5792 // If the RHS of the comparison is a 0.0, we don't need to do the 5793 // subtraction at all. 5794 SDValue Sel1; 5795 if (isFloatingPointZero(RHS)) 5796 switch (CC) { 5797 default: break; // SETUO etc aren't handled by fsel. 5798 case ISD::SETNE: 5799 std::swap(TV, FV); 5800 case ISD::SETEQ: 5801 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 5802 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 5803 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 5804 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 5805 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 5806 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 5807 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 5808 case ISD::SETULT: 5809 case ISD::SETLT: 5810 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 5811 case ISD::SETOGE: 5812 case ISD::SETGE: 5813 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 5814 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 5815 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 5816 case ISD::SETUGT: 5817 case ISD::SETGT: 5818 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 5819 case ISD::SETOLE: 5820 case ISD::SETLE: 5821 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 5822 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 5823 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 5824 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 5825 } 5826 5827 SDValue Cmp; 5828 switch (CC) { 5829 default: break; // SETUO etc aren't handled by fsel. 5830 case ISD::SETNE: 5831 std::swap(TV, FV); 5832 case ISD::SETEQ: 5833 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS); 5834 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 5835 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 5836 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 5837 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 5838 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 5839 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 5840 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 5841 case ISD::SETULT: 5842 case ISD::SETLT: 5843 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS); 5844 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 5845 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 5846 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 5847 case ISD::SETOGE: 5848 case ISD::SETGE: 5849 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS); 5850 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 5851 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 5852 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 5853 case ISD::SETUGT: 5854 case ISD::SETGT: 5855 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS); 5856 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 5857 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 5858 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 5859 case ISD::SETOLE: 5860 case ISD::SETLE: 5861 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS); 5862 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 5863 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 5864 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 5865 } 5866 return Op; 5867 } 5868 5869 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 5870 SelectionDAG &DAG, 5871 SDLoc dl) const { 5872 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 5873 SDValue Src = Op.getOperand(0); 5874 if (Src.getValueType() == MVT::f32) 5875 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 5876 5877 SDValue Tmp; 5878 switch (Op.getSimpleValueType().SimpleTy) { 5879 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 5880 case MVT::i32: 5881 Tmp = DAG.getNode( 5882 Op.getOpcode() == ISD::FP_TO_SINT 5883 ? PPCISD::FCTIWZ 5884 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 5885 dl, MVT::f64, Src); 5886 break; 5887 case MVT::i64: 5888 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 5889 "i64 FP_TO_UINT is supported only with FPCVT"); 5890 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 5891 PPCISD::FCTIDUZ, 5892 dl, MVT::f64, Src); 5893 break; 5894 } 5895 5896 // Convert the FP value to an int value through memory. 5897 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 5898 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 5899 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 5900 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 5901 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI); 5902 5903 // Emit a store to the stack slot. 5904 SDValue Chain; 5905 if (i32Stack) { 5906 MachineFunction &MF = DAG.getMachineFunction(); 5907 MachineMemOperand *MMO = 5908 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 5909 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 5910 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 5911 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 5912 } else 5913 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, 5914 MPI, false, false, 0); 5915 5916 // Result is a load from the stack slot. If loading 4 bytes, make sure to 5917 // add in a bias. 5918 if (Op.getValueType() == MVT::i32 && !i32Stack) { 5919 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 5920 DAG.getConstant(4, FIPtr.getValueType())); 5921 MPI = MPI.getWithOffset(4); 5922 } 5923 5924 RLI.Chain = Chain; 5925 RLI.Ptr = FIPtr; 5926 RLI.MPI = MPI; 5927 } 5928 5929 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 5930 SDLoc dl) const { 5931 ReuseLoadInfo RLI; 5932 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 5933 5934 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false, 5935 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo, 5936 RLI.Ranges); 5937 } 5938 5939 // We're trying to insert a regular store, S, and then a load, L. If the 5940 // incoming value, O, is a load, we might just be able to have our load use the 5941 // address used by O. However, we don't know if anything else will store to 5942 // that address before we can load from it. To prevent this situation, we need 5943 // to insert our load, L, into the chain as a peer of O. To do this, we give L 5944 // the same chain operand as O, we create a token factor from the chain results 5945 // of O and L, and we replace all uses of O's chain result with that token 5946 // factor (see spliceIntoChain below for this last part). 5947 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 5948 ReuseLoadInfo &RLI, 5949 SelectionDAG &DAG, 5950 ISD::LoadExtType ET) const { 5951 SDLoc dl(Op); 5952 if (ET == ISD::NON_EXTLOAD && 5953 (Op.getOpcode() == ISD::FP_TO_UINT || 5954 Op.getOpcode() == ISD::FP_TO_SINT) && 5955 isOperationLegalOrCustom(Op.getOpcode(), 5956 Op.getOperand(0).getValueType())) { 5957 5958 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 5959 return true; 5960 } 5961 5962 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 5963 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 5964 LD->isNonTemporal()) 5965 return false; 5966 if (LD->getMemoryVT() != MemVT) 5967 return false; 5968 5969 RLI.Ptr = LD->getBasePtr(); 5970 if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) { 5971 assert(LD->getAddressingMode() == ISD::PRE_INC && 5972 "Non-pre-inc AM on PPC?"); 5973 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 5974 LD->getOffset()); 5975 } 5976 5977 RLI.Chain = LD->getChain(); 5978 RLI.MPI = LD->getPointerInfo(); 5979 RLI.IsInvariant = LD->isInvariant(); 5980 RLI.Alignment = LD->getAlignment(); 5981 RLI.AAInfo = LD->getAAInfo(); 5982 RLI.Ranges = LD->getRanges(); 5983 5984 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 5985 return true; 5986 } 5987 5988 // Given the head of the old chain, ResChain, insert a token factor containing 5989 // it and NewResChain, and make users of ResChain now be users of that token 5990 // factor. 5991 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 5992 SDValue NewResChain, 5993 SelectionDAG &DAG) const { 5994 if (!ResChain) 5995 return; 5996 5997 SDLoc dl(NewResChain); 5998 5999 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6000 NewResChain, DAG.getUNDEF(MVT::Other)); 6001 assert(TF.getNode() != NewResChain.getNode() && 6002 "A new TF really is required here"); 6003 6004 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 6005 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 6006 } 6007 6008 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 6009 SelectionDAG &DAG) const { 6010 SDLoc dl(Op); 6011 6012 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 6013 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 6014 return SDValue(); 6015 6016 SDValue Value = Op.getOperand(0); 6017 // The values are now known to be -1 (false) or 1 (true). To convert this 6018 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 6019 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 6020 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 6021 6022 SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64); 6023 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64, 6024 FPHalfs, FPHalfs, FPHalfs, FPHalfs); 6025 6026 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 6027 6028 if (Op.getValueType() != MVT::v4f64) 6029 Value = DAG.getNode(ISD::FP_ROUND, dl, 6030 Op.getValueType(), Value, DAG.getIntPtrConstant(1)); 6031 return Value; 6032 } 6033 6034 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 6035 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 6036 return SDValue(); 6037 6038 if (Op.getOperand(0).getValueType() == MVT::i1) 6039 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 6040 DAG.getConstantFP(1.0, Op.getValueType()), 6041 DAG.getConstantFP(0.0, Op.getValueType())); 6042 6043 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 6044 "UINT_TO_FP is supported only with FPCVT"); 6045 6046 // If we have FCFIDS, then use it when converting to single-precision. 6047 // Otherwise, convert to double-precision and then round. 6048 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 6049 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 6050 : PPCISD::FCFIDS) 6051 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 6052 : PPCISD::FCFID); 6053 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 6054 ? MVT::f32 6055 : MVT::f64; 6056 6057 if (Op.getOperand(0).getValueType() == MVT::i64) { 6058 SDValue SINT = Op.getOperand(0); 6059 // When converting to single-precision, we actually need to convert 6060 // to double-precision first and then round to single-precision. 6061 // To avoid double-rounding effects during that operation, we have 6062 // to prepare the input operand. Bits that might be truncated when 6063 // converting to double-precision are replaced by a bit that won't 6064 // be lost at this stage, but is below the single-precision rounding 6065 // position. 6066 // 6067 // However, if -enable-unsafe-fp-math is in effect, accept double 6068 // rounding to avoid the extra overhead. 6069 if (Op.getValueType() == MVT::f32 && 6070 !Subtarget.hasFPCVT() && 6071 !DAG.getTarget().Options.UnsafeFPMath) { 6072 6073 // Twiddle input to make sure the low 11 bits are zero. (If this 6074 // is the case, we are guaranteed the value will fit into the 53 bit 6075 // mantissa of an IEEE double-precision value without rounding.) 6076 // If any of those low 11 bits were not zero originally, make sure 6077 // bit 12 (value 2048) is set instead, so that the final rounding 6078 // to single-precision gets the correct result. 6079 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 6080 SINT, DAG.getConstant(2047, MVT::i64)); 6081 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 6082 Round, DAG.getConstant(2047, MVT::i64)); 6083 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 6084 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 6085 Round, DAG.getConstant(-2048, MVT::i64)); 6086 6087 // However, we cannot use that value unconditionally: if the magnitude 6088 // of the input value is small, the bit-twiddling we did above might 6089 // end up visibly changing the output. Fortunately, in that case, we 6090 // don't need to twiddle bits since the original input will convert 6091 // exactly to double-precision floating-point already. Therefore, 6092 // construct a conditional to use the original value if the top 11 6093 // bits are all sign-bit copies, and use the rounded value computed 6094 // above otherwise. 6095 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 6096 SINT, DAG.getConstant(53, MVT::i32)); 6097 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 6098 Cond, DAG.getConstant(1, MVT::i64)); 6099 Cond = DAG.getSetCC(dl, MVT::i32, 6100 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT); 6101 6102 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 6103 } 6104 6105 ReuseLoadInfo RLI; 6106 SDValue Bits; 6107 6108 MachineFunction &MF = DAG.getMachineFunction(); 6109 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 6110 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false, 6111 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo, 6112 RLI.Ranges); 6113 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 6114 } else if (Subtarget.hasLFIWAX() && 6115 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 6116 MachineMemOperand *MMO = 6117 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 6118 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 6119 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 6120 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 6121 DAG.getVTList(MVT::f64, MVT::Other), 6122 Ops, MVT::i32, MMO); 6123 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 6124 } else if (Subtarget.hasFPCVT() && 6125 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 6126 MachineMemOperand *MMO = 6127 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 6128 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 6129 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 6130 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 6131 DAG.getVTList(MVT::f64, MVT::Other), 6132 Ops, MVT::i32, MMO); 6133 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 6134 } else if (((Subtarget.hasLFIWAX() && 6135 SINT.getOpcode() == ISD::SIGN_EXTEND) || 6136 (Subtarget.hasFPCVT() && 6137 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 6138 SINT.getOperand(0).getValueType() == MVT::i32) { 6139 MachineFrameInfo *FrameInfo = MF.getFrameInfo(); 6140 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 6141 6142 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false); 6143 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 6144 6145 SDValue Store = 6146 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 6147 MachinePointerInfo::getFixedStack(FrameIdx), 6148 false, false, 0); 6149 6150 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 6151 "Expected an i32 store"); 6152 6153 RLI.Ptr = FIdx; 6154 RLI.Chain = Store; 6155 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx); 6156 RLI.Alignment = 4; 6157 6158 MachineMemOperand *MMO = 6159 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 6160 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 6161 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 6162 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 6163 PPCISD::LFIWZX : PPCISD::LFIWAX, 6164 dl, DAG.getVTList(MVT::f64, MVT::Other), 6165 Ops, MVT::i32, MMO); 6166 } else 6167 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 6168 6169 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 6170 6171 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 6172 FP = DAG.getNode(ISD::FP_ROUND, dl, 6173 MVT::f32, FP, DAG.getIntPtrConstant(0)); 6174 return FP; 6175 } 6176 6177 assert(Op.getOperand(0).getValueType() == MVT::i32 && 6178 "Unhandled INT_TO_FP type in custom expander!"); 6179 // Since we only generate this in 64-bit mode, we can take advantage of 6180 // 64-bit registers. In particular, sign extend the input value into the 6181 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 6182 // then lfd it and fcfid it. 6183 MachineFunction &MF = DAG.getMachineFunction(); 6184 MachineFrameInfo *FrameInfo = MF.getFrameInfo(); 6185 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 6186 6187 SDValue Ld; 6188 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 6189 ReuseLoadInfo RLI; 6190 bool ReusingLoad; 6191 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 6192 DAG))) { 6193 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false); 6194 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 6195 6196 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 6197 MachinePointerInfo::getFixedStack(FrameIdx), 6198 false, false, 0); 6199 6200 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 6201 "Expected an i32 store"); 6202 6203 RLI.Ptr = FIdx; 6204 RLI.Chain = Store; 6205 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx); 6206 RLI.Alignment = 4; 6207 } 6208 6209 MachineMemOperand *MMO = 6210 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 6211 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 6212 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 6213 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 6214 PPCISD::LFIWZX : PPCISD::LFIWAX, 6215 dl, DAG.getVTList(MVT::f64, MVT::Other), 6216 Ops, MVT::i32, MMO); 6217 if (ReusingLoad) 6218 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 6219 } else { 6220 assert(Subtarget.isPPC64() && 6221 "i32->FP without LFIWAX supported only on PPC64"); 6222 6223 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false); 6224 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 6225 6226 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 6227 Op.getOperand(0)); 6228 6229 // STD the extended value into the stack slot. 6230 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx, 6231 MachinePointerInfo::getFixedStack(FrameIdx), 6232 false, false, 0); 6233 6234 // Load the value as a double. 6235 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, 6236 MachinePointerInfo::getFixedStack(FrameIdx), 6237 false, false, false, 0); 6238 } 6239 6240 // FCFID it and return it. 6241 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 6242 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 6243 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0)); 6244 return FP; 6245 } 6246 6247 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 6248 SelectionDAG &DAG) const { 6249 SDLoc dl(Op); 6250 /* 6251 The rounding mode is in bits 30:31 of FPSR, and has the following 6252 settings: 6253 00 Round to nearest 6254 01 Round to 0 6255 10 Round to +inf 6256 11 Round to -inf 6257 6258 FLT_ROUNDS, on the other hand, expects the following: 6259 -1 Undefined 6260 0 Round to 0 6261 1 Round to nearest 6262 2 Round to +inf 6263 3 Round to -inf 6264 6265 To perform the conversion, we do: 6266 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 6267 */ 6268 6269 MachineFunction &MF = DAG.getMachineFunction(); 6270 EVT VT = Op.getValueType(); 6271 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 6272 6273 // Save FP Control Word to register 6274 EVT NodeTys[] = { 6275 MVT::f64, // return register 6276 MVT::Glue // unused in this context 6277 }; 6278 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 6279 6280 // Save FP register to stack slot 6281 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false); 6282 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 6283 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, 6284 StackSlot, MachinePointerInfo(), false, false,0); 6285 6286 // Load FP Control Word from low 32 bits of stack slot. 6287 SDValue Four = DAG.getConstant(4, PtrVT); 6288 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 6289 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(), 6290 false, false, false, 0); 6291 6292 // Transform as necessary 6293 SDValue CWD1 = 6294 DAG.getNode(ISD::AND, dl, MVT::i32, 6295 CWD, DAG.getConstant(3, MVT::i32)); 6296 SDValue CWD2 = 6297 DAG.getNode(ISD::SRL, dl, MVT::i32, 6298 DAG.getNode(ISD::AND, dl, MVT::i32, 6299 DAG.getNode(ISD::XOR, dl, MVT::i32, 6300 CWD, DAG.getConstant(3, MVT::i32)), 6301 DAG.getConstant(3, MVT::i32)), 6302 DAG.getConstant(1, MVT::i32)); 6303 6304 SDValue RetVal = 6305 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 6306 6307 return DAG.getNode((VT.getSizeInBits() < 16 ? 6308 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 6309 } 6310 6311 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 6312 EVT VT = Op.getValueType(); 6313 unsigned BitWidth = VT.getSizeInBits(); 6314 SDLoc dl(Op); 6315 assert(Op.getNumOperands() == 3 && 6316 VT == Op.getOperand(1).getValueType() && 6317 "Unexpected SHL!"); 6318 6319 // Expand into a bunch of logical ops. Note that these ops 6320 // depend on the PPC behavior for oversized shift amounts. 6321 SDValue Lo = Op.getOperand(0); 6322 SDValue Hi = Op.getOperand(1); 6323 SDValue Amt = Op.getOperand(2); 6324 EVT AmtVT = Amt.getValueType(); 6325 6326 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 6327 DAG.getConstant(BitWidth, AmtVT), Amt); 6328 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 6329 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 6330 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 6331 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 6332 DAG.getConstant(-BitWidth, AmtVT)); 6333 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 6334 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 6335 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 6336 SDValue OutOps[] = { OutLo, OutHi }; 6337 return DAG.getMergeValues(OutOps, dl); 6338 } 6339 6340 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 6341 EVT VT = Op.getValueType(); 6342 SDLoc dl(Op); 6343 unsigned BitWidth = VT.getSizeInBits(); 6344 assert(Op.getNumOperands() == 3 && 6345 VT == Op.getOperand(1).getValueType() && 6346 "Unexpected SRL!"); 6347 6348 // Expand into a bunch of logical ops. Note that these ops 6349 // depend on the PPC behavior for oversized shift amounts. 6350 SDValue Lo = Op.getOperand(0); 6351 SDValue Hi = Op.getOperand(1); 6352 SDValue Amt = Op.getOperand(2); 6353 EVT AmtVT = Amt.getValueType(); 6354 6355 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 6356 DAG.getConstant(BitWidth, AmtVT), Amt); 6357 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 6358 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 6359 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 6360 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 6361 DAG.getConstant(-BitWidth, AmtVT)); 6362 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 6363 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 6364 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 6365 SDValue OutOps[] = { OutLo, OutHi }; 6366 return DAG.getMergeValues(OutOps, dl); 6367 } 6368 6369 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 6370 SDLoc dl(Op); 6371 EVT VT = Op.getValueType(); 6372 unsigned BitWidth = VT.getSizeInBits(); 6373 assert(Op.getNumOperands() == 3 && 6374 VT == Op.getOperand(1).getValueType() && 6375 "Unexpected SRA!"); 6376 6377 // Expand into a bunch of logical ops, followed by a select_cc. 6378 SDValue Lo = Op.getOperand(0); 6379 SDValue Hi = Op.getOperand(1); 6380 SDValue Amt = Op.getOperand(2); 6381 EVT AmtVT = Amt.getValueType(); 6382 6383 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 6384 DAG.getConstant(BitWidth, AmtVT), Amt); 6385 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 6386 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 6387 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 6388 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 6389 DAG.getConstant(-BitWidth, AmtVT)); 6390 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 6391 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 6392 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT), 6393 Tmp4, Tmp6, ISD::SETLE); 6394 SDValue OutOps[] = { OutLo, OutHi }; 6395 return DAG.getMergeValues(OutOps, dl); 6396 } 6397 6398 //===----------------------------------------------------------------------===// 6399 // Vector related lowering. 6400 // 6401 6402 /// BuildSplatI - Build a canonical splati of Val with an element size of 6403 /// SplatSize. Cast the result to VT. 6404 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 6405 SelectionDAG &DAG, SDLoc dl) { 6406 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 6407 6408 static const MVT VTys[] = { // canonical VT to use for each size. 6409 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 6410 }; 6411 6412 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 6413 6414 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 6415 if (Val == -1) 6416 SplatSize = 1; 6417 6418 EVT CanonicalVT = VTys[SplatSize-1]; 6419 6420 // Build a canonical splat for this value. 6421 SDValue Elt = DAG.getConstant(Val, MVT::i32); 6422 SmallVector<SDValue, 8> Ops; 6423 Ops.assign(CanonicalVT.getVectorNumElements(), Elt); 6424 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops); 6425 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res); 6426 } 6427 6428 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 6429 /// specified intrinsic ID. 6430 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, 6431 SelectionDAG &DAG, SDLoc dl, 6432 EVT DestVT = MVT::Other) { 6433 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 6434 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 6435 DAG.getConstant(IID, MVT::i32), Op); 6436 } 6437 6438 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 6439 /// specified intrinsic ID. 6440 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 6441 SelectionDAG &DAG, SDLoc dl, 6442 EVT DestVT = MVT::Other) { 6443 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 6444 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 6445 DAG.getConstant(IID, MVT::i32), LHS, RHS); 6446 } 6447 6448 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 6449 /// specified intrinsic ID. 6450 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 6451 SDValue Op2, SelectionDAG &DAG, 6452 SDLoc dl, EVT DestVT = MVT::Other) { 6453 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 6454 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 6455 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2); 6456 } 6457 6458 6459 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 6460 /// amount. The result has the specified value type. 6461 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, 6462 EVT VT, SelectionDAG &DAG, SDLoc dl) { 6463 // Force LHS/RHS to be the right type. 6464 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 6465 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 6466 6467 int Ops[16]; 6468 for (unsigned i = 0; i != 16; ++i) 6469 Ops[i] = i + Amt; 6470 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 6471 return DAG.getNode(ISD::BITCAST, dl, VT, T); 6472 } 6473 6474 // If this is a case we can't handle, return null and let the default 6475 // expansion code take care of it. If we CAN select this case, and if it 6476 // selects to a single instruction, return Op. Otherwise, if we can codegen 6477 // this case more efficiently than a constant pool load, lower it to the 6478 // sequence of ops that should be used. 6479 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 6480 SelectionDAG &DAG) const { 6481 SDLoc dl(Op); 6482 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6483 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 6484 6485 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 6486 // We first build an i32 vector, load it into a QPX register, 6487 // then convert it to a floating-point vector and compare it 6488 // to a zero vector to get the boolean result. 6489 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 6490 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false); 6491 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx); 6492 EVT PtrVT = getPointerTy(); 6493 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 6494 6495 assert(BVN->getNumOperands() == 4 && 6496 "BUILD_VECTOR for v4i1 does not have 4 operands"); 6497 6498 bool IsConst = true; 6499 for (unsigned i = 0; i < 4; ++i) { 6500 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue; 6501 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 6502 IsConst = false; 6503 break; 6504 } 6505 } 6506 6507 if (IsConst) { 6508 Constant *One = 6509 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 6510 Constant *NegOne = 6511 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 6512 6513 SmallVector<Constant*, 4> CV(4, NegOne); 6514 for (unsigned i = 0; i < 4; ++i) { 6515 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) 6516 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 6517 else if (cast<ConstantSDNode>(BVN->getOperand(i))-> 6518 getConstantIntValue()->isZero()) 6519 continue; 6520 else 6521 CV[i] = One; 6522 } 6523 6524 Constant *CP = ConstantVector::get(CV); 6525 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(), 6526 16 /* alignment */); 6527 6528 SmallVector<SDValue, 2> Ops; 6529 Ops.push_back(DAG.getEntryNode()); 6530 Ops.push_back(CPIdx); 6531 6532 SmallVector<EVT, 2> ValueVTs; 6533 ValueVTs.push_back(MVT::v4i1); 6534 ValueVTs.push_back(MVT::Other); // chain 6535 SDVTList VTs = DAG.getVTList(ValueVTs); 6536 6537 return DAG.getMemIntrinsicNode(PPCISD::QVLFSb, 6538 dl, VTs, Ops, MVT::v4f32, 6539 MachinePointerInfo::getConstantPool()); 6540 } 6541 6542 SmallVector<SDValue, 4> Stores; 6543 for (unsigned i = 0; i < 4; ++i) { 6544 if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue; 6545 6546 unsigned Offset = 4*i; 6547 SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType()); 6548 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 6549 6550 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 6551 if (StoreSize > 4) { 6552 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl, 6553 BVN->getOperand(i), Idx, 6554 PtrInfo.getWithOffset(Offset), 6555 MVT::i32, false, false, 0)); 6556 } else { 6557 SDValue StoreValue = BVN->getOperand(i); 6558 if (StoreSize < 4) 6559 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 6560 6561 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, 6562 StoreValue, Idx, 6563 PtrInfo.getWithOffset(Offset), 6564 false, false, 0)); 6565 } 6566 } 6567 6568 SDValue StoreChain; 6569 if (!Stores.empty()) 6570 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 6571 else 6572 StoreChain = DAG.getEntryNode(); 6573 6574 // Now load from v4i32 into the QPX register; this will extend it to 6575 // v4i64 but not yet convert it to a floating point. Nevertheless, this 6576 // is typed as v4f64 because the QPX register integer states are not 6577 // explicitly represented. 6578 6579 SmallVector<SDValue, 2> Ops; 6580 Ops.push_back(StoreChain); 6581 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, MVT::i32)); 6582 Ops.push_back(FIdx); 6583 6584 SmallVector<EVT, 2> ValueVTs; 6585 ValueVTs.push_back(MVT::v4f64); 6586 ValueVTs.push_back(MVT::Other); // chain 6587 SDVTList VTs = DAG.getVTList(ValueVTs); 6588 6589 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 6590 dl, VTs, Ops, MVT::v4i32, PtrInfo); 6591 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 6592 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, MVT::i32), 6593 LoadedVect); 6594 6595 SDValue FPZeros = DAG.getConstantFP(0.0, MVT::f64); 6596 FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64, 6597 FPZeros, FPZeros, FPZeros, FPZeros); 6598 6599 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 6600 } 6601 6602 // All other QPX vectors are handled by generic code. 6603 if (Subtarget.hasQPX()) 6604 return SDValue(); 6605 6606 // Check if this is a splat of a constant value. 6607 APInt APSplatBits, APSplatUndef; 6608 unsigned SplatBitSize; 6609 bool HasAnyUndefs; 6610 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 6611 HasAnyUndefs, 0, true) || SplatBitSize > 32) 6612 return SDValue(); 6613 6614 unsigned SplatBits = APSplatBits.getZExtValue(); 6615 unsigned SplatUndef = APSplatUndef.getZExtValue(); 6616 unsigned SplatSize = SplatBitSize / 8; 6617 6618 // First, handle single instruction cases. 6619 6620 // All zeros? 6621 if (SplatBits == 0) { 6622 // Canonicalize all zero vectors to be v4i32. 6623 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 6624 SDValue Z = DAG.getConstant(0, MVT::i32); 6625 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z); 6626 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 6627 } 6628 return Op; 6629 } 6630 6631 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 6632 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 6633 (32-SplatBitSize)); 6634 if (SextVal >= -16 && SextVal <= 15) 6635 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 6636 6637 6638 // Two instruction sequences. 6639 6640 // If this value is in the range [-32,30] and is even, use: 6641 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 6642 // If this value is in the range [17,31] and is odd, use: 6643 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 6644 // If this value is in the range [-31,-17] and is odd, use: 6645 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 6646 // Note the last two are three-instruction sequences. 6647 if (SextVal >= -32 && SextVal <= 31) { 6648 // To avoid having these optimizations undone by constant folding, 6649 // we convert to a pseudo that will be expanded later into one of 6650 // the above forms. 6651 SDValue Elt = DAG.getConstant(SextVal, MVT::i32); 6652 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 6653 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 6654 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32); 6655 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 6656 if (VT == Op.getValueType()) 6657 return RetVal; 6658 else 6659 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 6660 } 6661 6662 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 6663 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 6664 // for fneg/fabs. 6665 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 6666 // Make -1 and vspltisw -1: 6667 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 6668 6669 // Make the VSLW intrinsic, computing 0x8000_0000. 6670 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 6671 OnesV, DAG, dl); 6672 6673 // xor by OnesV to invert it. 6674 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 6675 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 6676 } 6677 6678 // The remaining cases assume either big endian element order or 6679 // a splat-size that equates to the element size of the vector 6680 // to be built. An example that doesn't work for little endian is 6681 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits 6682 // and a vector element size of 16 bits. The code below will 6683 // produce the vector in big endian element order, which for little 6684 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}. 6685 6686 // For now, just avoid these optimizations in that case. 6687 // FIXME: Develop correct optimizations for LE with mismatched 6688 // splat and element sizes. 6689 6690 if (Subtarget.isLittleEndian() && 6691 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits()) 6692 return SDValue(); 6693 6694 // Check to see if this is a wide variety of vsplti*, binop self cases. 6695 static const signed char SplatCsts[] = { 6696 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 6697 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 6698 }; 6699 6700 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 6701 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 6702 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 6703 int i = SplatCsts[idx]; 6704 6705 // Figure out what shift amount will be used by altivec if shifted by i in 6706 // this splat size. 6707 unsigned TypeShiftAmt = i & (SplatBitSize-1); 6708 6709 // vsplti + shl self. 6710 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 6711 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 6712 static const unsigned IIDs[] = { // Intrinsic to use for each size. 6713 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 6714 Intrinsic::ppc_altivec_vslw 6715 }; 6716 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 6717 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 6718 } 6719 6720 // vsplti + srl self. 6721 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 6722 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 6723 static const unsigned IIDs[] = { // Intrinsic to use for each size. 6724 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 6725 Intrinsic::ppc_altivec_vsrw 6726 }; 6727 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 6728 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 6729 } 6730 6731 // vsplti + sra self. 6732 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 6733 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 6734 static const unsigned IIDs[] = { // Intrinsic to use for each size. 6735 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 6736 Intrinsic::ppc_altivec_vsraw 6737 }; 6738 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 6739 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 6740 } 6741 6742 // vsplti + rol self. 6743 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 6744 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 6745 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 6746 static const unsigned IIDs[] = { // Intrinsic to use for each size. 6747 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 6748 Intrinsic::ppc_altivec_vrlw 6749 }; 6750 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 6751 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 6752 } 6753 6754 // t = vsplti c, result = vsldoi t, t, 1 6755 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 6756 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 6757 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl); 6758 } 6759 // t = vsplti c, result = vsldoi t, t, 2 6760 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 6761 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 6762 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl); 6763 } 6764 // t = vsplti c, result = vsldoi t, t, 3 6765 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 6766 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 6767 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl); 6768 } 6769 } 6770 6771 return SDValue(); 6772 } 6773 6774 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6775 /// the specified operations to build the shuffle. 6776 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6777 SDValue RHS, SelectionDAG &DAG, 6778 SDLoc dl) { 6779 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6780 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6781 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6782 6783 enum { 6784 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6785 OP_VMRGHW, 6786 OP_VMRGLW, 6787 OP_VSPLTISW0, 6788 OP_VSPLTISW1, 6789 OP_VSPLTISW2, 6790 OP_VSPLTISW3, 6791 OP_VSLDOI4, 6792 OP_VSLDOI8, 6793 OP_VSLDOI12 6794 }; 6795 6796 if (OpNum == OP_COPY) { 6797 if (LHSID == (1*9+2)*9+3) return LHS; 6798 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6799 return RHS; 6800 } 6801 6802 SDValue OpLHS, OpRHS; 6803 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6804 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6805 6806 int ShufIdxs[16]; 6807 switch (OpNum) { 6808 default: llvm_unreachable("Unknown i32 permute!"); 6809 case OP_VMRGHW: 6810 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 6811 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 6812 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 6813 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 6814 break; 6815 case OP_VMRGLW: 6816 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 6817 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 6818 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 6819 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 6820 break; 6821 case OP_VSPLTISW0: 6822 for (unsigned i = 0; i != 16; ++i) 6823 ShufIdxs[i] = (i&3)+0; 6824 break; 6825 case OP_VSPLTISW1: 6826 for (unsigned i = 0; i != 16; ++i) 6827 ShufIdxs[i] = (i&3)+4; 6828 break; 6829 case OP_VSPLTISW2: 6830 for (unsigned i = 0; i != 16; ++i) 6831 ShufIdxs[i] = (i&3)+8; 6832 break; 6833 case OP_VSPLTISW3: 6834 for (unsigned i = 0; i != 16; ++i) 6835 ShufIdxs[i] = (i&3)+12; 6836 break; 6837 case OP_VSLDOI4: 6838 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 6839 case OP_VSLDOI8: 6840 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 6841 case OP_VSLDOI12: 6842 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 6843 } 6844 EVT VT = OpLHS.getValueType(); 6845 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 6846 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 6847 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 6848 return DAG.getNode(ISD::BITCAST, dl, VT, T); 6849 } 6850 6851 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 6852 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 6853 /// return the code it can be lowered into. Worst case, it can always be 6854 /// lowered into a vperm. 6855 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 6856 SelectionDAG &DAG) const { 6857 SDLoc dl(Op); 6858 SDValue V1 = Op.getOperand(0); 6859 SDValue V2 = Op.getOperand(1); 6860 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6861 EVT VT = Op.getValueType(); 6862 bool isLittleEndian = Subtarget.isLittleEndian(); 6863 6864 if (Subtarget.hasQPX()) { 6865 if (VT.getVectorNumElements() != 4) 6866 return SDValue(); 6867 6868 if (V2.getOpcode() == ISD::UNDEF) V2 = V1; 6869 6870 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 6871 if (AlignIdx != -1) { 6872 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 6873 DAG.getConstant(AlignIdx, MVT::i32)); 6874 } else if (SVOp->isSplat()) { 6875 int SplatIdx = SVOp->getSplatIndex(); 6876 if (SplatIdx >= 4) { 6877 std::swap(V1, V2); 6878 SplatIdx -= 4; 6879 } 6880 6881 // FIXME: If SplatIdx == 0 and the input came from a load, then there is 6882 // nothing to do. 6883 6884 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 6885 DAG.getConstant(SplatIdx, MVT::i32)); 6886 } 6887 6888 // Lower this into a qvgpci/qvfperm pair. 6889 6890 // Compute the qvgpci literal 6891 unsigned idx = 0; 6892 for (unsigned i = 0; i < 4; ++i) { 6893 int m = SVOp->getMaskElt(i); 6894 unsigned mm = m >= 0 ? (unsigned) m : i; 6895 idx |= mm << (3-i)*3; 6896 } 6897 6898 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 6899 DAG.getConstant(idx, MVT::i32)); 6900 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 6901 } 6902 6903 // Cases that are handled by instructions that take permute immediates 6904 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 6905 // selected by the instruction selector. 6906 if (V2.getOpcode() == ISD::UNDEF) { 6907 if (PPC::isSplatShuffleMask(SVOp, 1) || 6908 PPC::isSplatShuffleMask(SVOp, 2) || 6909 PPC::isSplatShuffleMask(SVOp, 4) || 6910 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 6911 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 6912 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 6913 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 6914 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 6915 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 6916 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 6917 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 6918 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) { 6919 return Op; 6920 } 6921 } 6922 6923 // Altivec has a variety of "shuffle immediates" that take two vector inputs 6924 // and produce a fixed permutation. If any of these match, do not lower to 6925 // VPERM. 6926 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 6927 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 6928 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 6929 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 6930 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 6931 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 6932 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 6933 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 6934 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 6935 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG)) 6936 return Op; 6937 6938 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 6939 // perfect shuffle table to emit an optimal matching sequence. 6940 ArrayRef<int> PermMask = SVOp->getMask(); 6941 6942 unsigned PFIndexes[4]; 6943 bool isFourElementShuffle = true; 6944 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 6945 unsigned EltNo = 8; // Start out undef. 6946 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 6947 if (PermMask[i*4+j] < 0) 6948 continue; // Undef, ignore it. 6949 6950 unsigned ByteSource = PermMask[i*4+j]; 6951 if ((ByteSource & 3) != j) { 6952 isFourElementShuffle = false; 6953 break; 6954 } 6955 6956 if (EltNo == 8) { 6957 EltNo = ByteSource/4; 6958 } else if (EltNo != ByteSource/4) { 6959 isFourElementShuffle = false; 6960 break; 6961 } 6962 } 6963 PFIndexes[i] = EltNo; 6964 } 6965 6966 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 6967 // perfect shuffle vector to determine if it is cost effective to do this as 6968 // discrete instructions, or whether we should use a vperm. 6969 // For now, we skip this for little endian until such time as we have a 6970 // little-endian perfect shuffle table. 6971 if (isFourElementShuffle && !isLittleEndian) { 6972 // Compute the index in the perfect shuffle table. 6973 unsigned PFTableIndex = 6974 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6975 6976 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6977 unsigned Cost = (PFEntry >> 30); 6978 6979 // Determining when to avoid vperm is tricky. Many things affect the cost 6980 // of vperm, particularly how many times the perm mask needs to be computed. 6981 // For example, if the perm mask can be hoisted out of a loop or is already 6982 // used (perhaps because there are multiple permutes with the same shuffle 6983 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 6984 // the loop requires an extra register. 6985 // 6986 // As a compromise, we only emit discrete instructions if the shuffle can be 6987 // generated in 3 or fewer operations. When we have loop information 6988 // available, if this block is within a loop, we should avoid using vperm 6989 // for 3-operation perms and use a constant pool load instead. 6990 if (Cost < 3) 6991 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6992 } 6993 6994 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 6995 // vector that will get spilled to the constant pool. 6996 if (V2.getOpcode() == ISD::UNDEF) V2 = V1; 6997 6998 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 6999 // that it is in input element units, not in bytes. Convert now. 7000 7001 // For little endian, the order of the input vectors is reversed, and 7002 // the permutation mask is complemented with respect to 31. This is 7003 // necessary to produce proper semantics with the big-endian-biased vperm 7004 // instruction. 7005 EVT EltVT = V1.getValueType().getVectorElementType(); 7006 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 7007 7008 SmallVector<SDValue, 16> ResultMask; 7009 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 7010 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 7011 7012 for (unsigned j = 0; j != BytesPerElement; ++j) 7013 if (isLittleEndian) 7014 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j), 7015 MVT::i32)); 7016 else 7017 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j, 7018 MVT::i32)); 7019 } 7020 7021 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8, 7022 ResultMask); 7023 if (isLittleEndian) 7024 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 7025 V2, V1, VPermMask); 7026 else 7027 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 7028 V1, V2, VPermMask); 7029 } 7030 7031 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an 7032 /// altivec comparison. If it is, return true and fill in Opc/isDot with 7033 /// information about the intrinsic. 7034 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc, 7035 bool &isDot, const PPCSubtarget &Subtarget) { 7036 unsigned IntrinsicID = 7037 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 7038 CompareOpc = -1; 7039 isDot = false; 7040 switch (IntrinsicID) { 7041 default: return false; 7042 // Comparison predicates. 7043 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break; 7044 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break; 7045 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break; 7046 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break; 7047 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break; 7048 case Intrinsic::ppc_altivec_vcmpequd_p: 7049 if (Subtarget.hasP8Altivec()) { 7050 CompareOpc = 199; 7051 isDot = 1; 7052 } 7053 else 7054 return false; 7055 7056 break; 7057 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break; 7058 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break; 7059 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break; 7060 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break; 7061 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break; 7062 case Intrinsic::ppc_altivec_vcmpgtsd_p: 7063 if (Subtarget.hasP8Altivec()) { 7064 CompareOpc = 967; 7065 isDot = 1; 7066 } 7067 else 7068 return false; 7069 7070 break; 7071 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break; 7072 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break; 7073 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break; 7074 case Intrinsic::ppc_altivec_vcmpgtud_p: 7075 if (Subtarget.hasP8Altivec()) { 7076 CompareOpc = 711; 7077 isDot = 1; 7078 } 7079 else 7080 return false; 7081 7082 break; 7083 7084 // Normal Comparisons. 7085 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break; 7086 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break; 7087 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break; 7088 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break; 7089 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break; 7090 case Intrinsic::ppc_altivec_vcmpequd: 7091 if (Subtarget.hasP8Altivec()) { 7092 CompareOpc = 199; 7093 isDot = 0; 7094 } 7095 else 7096 return false; 7097 7098 break; 7099 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break; 7100 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break; 7101 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break; 7102 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break; 7103 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break; 7104 case Intrinsic::ppc_altivec_vcmpgtsd: 7105 if (Subtarget.hasP8Altivec()) { 7106 CompareOpc = 967; 7107 isDot = 0; 7108 } 7109 else 7110 return false; 7111 7112 break; 7113 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break; 7114 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break; 7115 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break; 7116 case Intrinsic::ppc_altivec_vcmpgtud: 7117 if (Subtarget.hasP8Altivec()) { 7118 CompareOpc = 711; 7119 isDot = 0; 7120 } 7121 else 7122 return false; 7123 7124 break; 7125 } 7126 return true; 7127 } 7128 7129 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 7130 /// lower, do it, otherwise return null. 7131 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 7132 SelectionDAG &DAG) const { 7133 // If this is a lowered altivec predicate compare, CompareOpc is set to the 7134 // opcode number of the comparison. 7135 SDLoc dl(Op); 7136 int CompareOpc; 7137 bool isDot; 7138 if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget)) 7139 return SDValue(); // Don't custom lower most intrinsics. 7140 7141 // If this is a non-dot comparison, make the VCMP node and we are done. 7142 if (!isDot) { 7143 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 7144 Op.getOperand(1), Op.getOperand(2), 7145 DAG.getConstant(CompareOpc, MVT::i32)); 7146 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 7147 } 7148 7149 // Create the PPCISD altivec 'dot' comparison node. 7150 SDValue Ops[] = { 7151 Op.getOperand(2), // LHS 7152 Op.getOperand(3), // RHS 7153 DAG.getConstant(CompareOpc, MVT::i32) 7154 }; 7155 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 7156 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 7157 7158 // Now that we have the comparison, emit a copy from the CR to a GPR. 7159 // This is flagged to the above dot comparison. 7160 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 7161 DAG.getRegister(PPC::CR6, MVT::i32), 7162 CompNode.getValue(1)); 7163 7164 // Unpack the result based on how the target uses it. 7165 unsigned BitNo; // Bit # of CR6. 7166 bool InvertBit; // Invert result? 7167 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 7168 default: // Can't happen, don't crash on invalid number though. 7169 case 0: // Return the value of the EQ bit of CR6. 7170 BitNo = 0; InvertBit = false; 7171 break; 7172 case 1: // Return the inverted value of the EQ bit of CR6. 7173 BitNo = 0; InvertBit = true; 7174 break; 7175 case 2: // Return the value of the LT bit of CR6. 7176 BitNo = 2; InvertBit = false; 7177 break; 7178 case 3: // Return the inverted value of the LT bit of CR6. 7179 BitNo = 2; InvertBit = true; 7180 break; 7181 } 7182 7183 // Shift the bit into the low position. 7184 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 7185 DAG.getConstant(8-(3-BitNo), MVT::i32)); 7186 // Isolate the bit. 7187 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 7188 DAG.getConstant(1, MVT::i32)); 7189 7190 // If we are supposed to, toggle the bit. 7191 if (InvertBit) 7192 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 7193 DAG.getConstant(1, MVT::i32)); 7194 return Flags; 7195 } 7196 7197 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 7198 SelectionDAG &DAG) const { 7199 SDLoc dl(Op); 7200 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int 7201 // instructions), but for smaller types, we need to first extend up to v2i32 7202 // before doing going farther. 7203 if (Op.getValueType() == MVT::v2i64) { 7204 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 7205 if (ExtVT != MVT::v2i32) { 7206 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)); 7207 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op, 7208 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(), 7209 ExtVT.getVectorElementType(), 4))); 7210 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op); 7211 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op, 7212 DAG.getValueType(MVT::v2i32)); 7213 } 7214 7215 return Op; 7216 } 7217 7218 return SDValue(); 7219 } 7220 7221 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 7222 SelectionDAG &DAG) const { 7223 SDLoc dl(Op); 7224 // Create a stack slot that is 16-byte aligned. 7225 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 7226 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false); 7227 EVT PtrVT = getPointerTy(); 7228 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7229 7230 // Store the input value into Value#0 of the stack slot. 7231 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, 7232 Op.getOperand(0), FIdx, MachinePointerInfo(), 7233 false, false, 0); 7234 // Load it out. 7235 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(), 7236 false, false, false, 0); 7237 } 7238 7239 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 7240 SelectionDAG &DAG) const { 7241 SDLoc dl(Op); 7242 SDNode *N = Op.getNode(); 7243 7244 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 7245 "Unknown extract_vector_elt type"); 7246 7247 SDValue Value = N->getOperand(0); 7248 7249 // The first part of this is like the store lowering except that we don't 7250 // need to track the chain. 7251 7252 // The values are now known to be -1 (false) or 1 (true). To convert this 7253 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7254 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7255 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7256 7257 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 7258 // understand how to form the extending load. 7259 SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64); 7260 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64, 7261 FPHalfs, FPHalfs, FPHalfs, FPHalfs); 7262 7263 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7264 7265 // Now convert to an integer and store. 7266 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7267 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32), 7268 Value); 7269 7270 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 7271 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false); 7272 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx); 7273 EVT PtrVT = getPointerTy(); 7274 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7275 7276 SDValue StoreChain = DAG.getEntryNode(); 7277 SmallVector<SDValue, 2> Ops; 7278 Ops.push_back(StoreChain); 7279 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32)); 7280 Ops.push_back(Value); 7281 Ops.push_back(FIdx); 7282 7283 SmallVector<EVT, 2> ValueVTs; 7284 ValueVTs.push_back(MVT::Other); // chain 7285 SDVTList VTs = DAG.getVTList(ValueVTs); 7286 7287 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 7288 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7289 7290 // Extract the value requested. 7291 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 7292 SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType()); 7293 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7294 7295 SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 7296 PtrInfo.getWithOffset(Offset), 7297 false, false, false, 0); 7298 7299 if (!Subtarget.useCRBits()) 7300 return IntVal; 7301 7302 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 7303 } 7304 7305 /// Lowering for QPX v4i1 loads 7306 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 7307 SelectionDAG &DAG) const { 7308 SDLoc dl(Op); 7309 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 7310 SDValue LoadChain = LN->getChain(); 7311 SDValue BasePtr = LN->getBasePtr(); 7312 7313 if (Op.getValueType() == MVT::v4f64 || 7314 Op.getValueType() == MVT::v4f32) { 7315 EVT MemVT = LN->getMemoryVT(); 7316 unsigned Alignment = LN->getAlignment(); 7317 7318 // If this load is properly aligned, then it is legal. 7319 if (Alignment >= MemVT.getStoreSize()) 7320 return Op; 7321 7322 EVT ScalarVT = Op.getValueType().getScalarType(), 7323 ScalarMemVT = MemVT.getScalarType(); 7324 unsigned Stride = ScalarMemVT.getStoreSize(); 7325 7326 SmallVector<SDValue, 8> Vals, LoadChains; 7327 for (unsigned Idx = 0; Idx < 4; ++Idx) { 7328 SDValue Load; 7329 if (ScalarVT != ScalarMemVT) 7330 Load = 7331 DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 7332 BasePtr, 7333 LN->getPointerInfo().getWithOffset(Idx*Stride), 7334 ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(), 7335 LN->isInvariant(), MinAlign(Alignment, Idx*Stride), 7336 LN->getAAInfo()); 7337 else 7338 Load = 7339 DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 7340 LN->getPointerInfo().getWithOffset(Idx*Stride), 7341 LN->isVolatile(), LN->isNonTemporal(), 7342 LN->isInvariant(), MinAlign(Alignment, Idx*Stride), 7343 LN->getAAInfo()); 7344 7345 if (Idx == 0 && LN->isIndexed()) { 7346 assert(LN->getAddressingMode() == ISD::PRE_INC && 7347 "Unknown addressing mode on vector load"); 7348 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 7349 LN->getAddressingMode()); 7350 } 7351 7352 Vals.push_back(Load); 7353 LoadChains.push_back(Load.getValue(1)); 7354 7355 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 7356 DAG.getConstant(Stride, BasePtr.getValueType())); 7357 } 7358 7359 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 7360 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, 7361 Op.getValueType(), Vals); 7362 7363 if (LN->isIndexed()) { 7364 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 7365 return DAG.getMergeValues(RetOps, dl); 7366 } 7367 7368 SDValue RetOps[] = { Value, TF }; 7369 return DAG.getMergeValues(RetOps, dl); 7370 } 7371 7372 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 7373 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 7374 7375 // To lower v4i1 from a byte array, we load the byte elements of the 7376 // vector and then reuse the BUILD_VECTOR logic. 7377 7378 SmallVector<SDValue, 4> VectElmts, VectElmtChains; 7379 for (unsigned i = 0; i < 4; ++i) { 7380 SDValue Idx = DAG.getConstant(i, BasePtr.getValueType()); 7381 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 7382 7383 VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD, 7384 dl, MVT::i32, LoadChain, Idx, 7385 LN->getPointerInfo().getWithOffset(i), 7386 MVT::i8 /* memory type */, 7387 LN->isVolatile(), LN->isNonTemporal(), 7388 LN->isInvariant(), 7389 1 /* alignment */, LN->getAAInfo())); 7390 VectElmtChains.push_back(VectElmts[i].getValue(1)); 7391 } 7392 7393 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 7394 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts); 7395 7396 SDValue RVals[] = { Value, LoadChain }; 7397 return DAG.getMergeValues(RVals, dl); 7398 } 7399 7400 /// Lowering for QPX v4i1 stores 7401 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 7402 SelectionDAG &DAG) const { 7403 SDLoc dl(Op); 7404 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 7405 SDValue StoreChain = SN->getChain(); 7406 SDValue BasePtr = SN->getBasePtr(); 7407 SDValue Value = SN->getValue(); 7408 7409 if (Value.getValueType() == MVT::v4f64 || 7410 Value.getValueType() == MVT::v4f32) { 7411 EVT MemVT = SN->getMemoryVT(); 7412 unsigned Alignment = SN->getAlignment(); 7413 7414 // If this store is properly aligned, then it is legal. 7415 if (Alignment >= MemVT.getStoreSize()) 7416 return Op; 7417 7418 EVT ScalarVT = Value.getValueType().getScalarType(), 7419 ScalarMemVT = MemVT.getScalarType(); 7420 unsigned Stride = ScalarMemVT.getStoreSize(); 7421 7422 SmallVector<SDValue, 8> Stores; 7423 for (unsigned Idx = 0; Idx < 4; ++Idx) { 7424 SDValue Ex = 7425 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 7426 DAG.getConstant(Idx, getVectorIdxTy())); 7427 SDValue Store; 7428 if (ScalarVT != ScalarMemVT) 7429 Store = 7430 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 7431 SN->getPointerInfo().getWithOffset(Idx*Stride), 7432 ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(), 7433 MinAlign(Alignment, Idx*Stride), SN->getAAInfo()); 7434 else 7435 Store = 7436 DAG.getStore(StoreChain, dl, Ex, BasePtr, 7437 SN->getPointerInfo().getWithOffset(Idx*Stride), 7438 SN->isVolatile(), SN->isNonTemporal(), 7439 MinAlign(Alignment, Idx*Stride), SN->getAAInfo()); 7440 7441 if (Idx == 0 && SN->isIndexed()) { 7442 assert(SN->getAddressingMode() == ISD::PRE_INC && 7443 "Unknown addressing mode on vector store"); 7444 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 7445 SN->getAddressingMode()); 7446 } 7447 7448 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 7449 DAG.getConstant(Stride, BasePtr.getValueType())); 7450 Stores.push_back(Store); 7451 } 7452 7453 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7454 7455 if (SN->isIndexed()) { 7456 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 7457 return DAG.getMergeValues(RetOps, dl); 7458 } 7459 7460 return TF; 7461 } 7462 7463 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 7464 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 7465 7466 // The values are now known to be -1 (false) or 1 (true). To convert this 7467 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7468 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7469 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7470 7471 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 7472 // understand how to form the extending load. 7473 SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64); 7474 FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64, 7475 FPHalfs, FPHalfs, FPHalfs, FPHalfs); 7476 7477 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7478 7479 // Now convert to an integer and store. 7480 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7481 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32), 7482 Value); 7483 7484 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 7485 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false); 7486 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx); 7487 EVT PtrVT = getPointerTy(); 7488 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7489 7490 SmallVector<SDValue, 2> Ops; 7491 Ops.push_back(StoreChain); 7492 Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32)); 7493 Ops.push_back(Value); 7494 Ops.push_back(FIdx); 7495 7496 SmallVector<EVT, 2> ValueVTs; 7497 ValueVTs.push_back(MVT::Other); // chain 7498 SDVTList VTs = DAG.getVTList(ValueVTs); 7499 7500 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 7501 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7502 7503 // Move data into the byte array. 7504 SmallVector<SDValue, 4> Loads, LoadChains; 7505 for (unsigned i = 0; i < 4; ++i) { 7506 unsigned Offset = 4*i; 7507 SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType()); 7508 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7509 7510 Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 7511 PtrInfo.getWithOffset(Offset), 7512 false, false, false, 0)); 7513 LoadChains.push_back(Loads[i].getValue(1)); 7514 } 7515 7516 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 7517 7518 SmallVector<SDValue, 4> Stores; 7519 for (unsigned i = 0; i < 4; ++i) { 7520 SDValue Idx = DAG.getConstant(i, BasePtr.getValueType()); 7521 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 7522 7523 Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx, 7524 SN->getPointerInfo().getWithOffset(i), 7525 MVT::i8 /* memory type */, 7526 SN->isNonTemporal(), SN->isVolatile(), 7527 1 /* alignment */, SN->getAAInfo())); 7528 } 7529 7530 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7531 7532 return StoreChain; 7533 } 7534 7535 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 7536 SDLoc dl(Op); 7537 if (Op.getValueType() == MVT::v4i32) { 7538 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7539 7540 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 7541 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 7542 7543 SDValue RHSSwap = // = vrlw RHS, 16 7544 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 7545 7546 // Shrinkify inputs to v8i16. 7547 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 7548 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 7549 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 7550 7551 // Low parts multiplied together, generating 32-bit results (we ignore the 7552 // top parts). 7553 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 7554 LHS, RHS, DAG, dl, MVT::v4i32); 7555 7556 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 7557 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 7558 // Shift the high parts up 16 bits. 7559 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 7560 Neg16, DAG, dl); 7561 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 7562 } else if (Op.getValueType() == MVT::v8i16) { 7563 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7564 7565 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 7566 7567 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 7568 LHS, RHS, Zero, DAG, dl); 7569 } else if (Op.getValueType() == MVT::v16i8) { 7570 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7571 bool isLittleEndian = Subtarget.isLittleEndian(); 7572 7573 // Multiply the even 8-bit parts, producing 16-bit sums. 7574 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 7575 LHS, RHS, DAG, dl, MVT::v8i16); 7576 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 7577 7578 // Multiply the odd 8-bit parts, producing 16-bit sums. 7579 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 7580 LHS, RHS, DAG, dl, MVT::v8i16); 7581 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 7582 7583 // Merge the results together. Because vmuleub and vmuloub are 7584 // instructions with a big-endian bias, we must reverse the 7585 // element numbering and reverse the meaning of "odd" and "even" 7586 // when generating little endian code. 7587 int Ops[16]; 7588 for (unsigned i = 0; i != 8; ++i) { 7589 if (isLittleEndian) { 7590 Ops[i*2 ] = 2*i; 7591 Ops[i*2+1] = 2*i+16; 7592 } else { 7593 Ops[i*2 ] = 2*i+1; 7594 Ops[i*2+1] = 2*i+1+16; 7595 } 7596 } 7597 if (isLittleEndian) 7598 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 7599 else 7600 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 7601 } else { 7602 llvm_unreachable("Unknown mul to lower!"); 7603 } 7604 } 7605 7606 /// LowerOperation - Provide custom lowering hooks for some operations. 7607 /// 7608 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7609 switch (Op.getOpcode()) { 7610 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 7611 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 7612 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7613 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 7614 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7615 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 7616 case ISD::SETCC: return LowerSETCC(Op, DAG); 7617 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 7618 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 7619 case ISD::VASTART: 7620 return LowerVASTART(Op, DAG, Subtarget); 7621 7622 case ISD::VAARG: 7623 return LowerVAARG(Op, DAG, Subtarget); 7624 7625 case ISD::VACOPY: 7626 return LowerVACOPY(Op, DAG, Subtarget); 7627 7628 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget); 7629 case ISD::DYNAMIC_STACKALLOC: 7630 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget); 7631 7632 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 7633 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 7634 7635 case ISD::LOAD: return LowerLOAD(Op, DAG); 7636 case ISD::STORE: return LowerSTORE(Op, DAG); 7637 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 7638 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7639 case ISD::FP_TO_UINT: 7640 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, 7641 SDLoc(Op)); 7642 case ISD::UINT_TO_FP: 7643 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7644 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7645 7646 // Lower 64-bit shifts. 7647 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 7648 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 7649 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 7650 7651 // Vector-related lowering. 7652 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 7653 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7654 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 7655 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 7656 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG); 7657 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7658 case ISD::MUL: return LowerMUL(Op, DAG); 7659 7660 // For counter-based loop handling. 7661 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 7662 7663 // Frame & Return address. 7664 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7665 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7666 } 7667 } 7668 7669 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 7670 SmallVectorImpl<SDValue>&Results, 7671 SelectionDAG &DAG) const { 7672 SDLoc dl(N); 7673 switch (N->getOpcode()) { 7674 default: 7675 llvm_unreachable("Do not know how to custom type legalize this operation!"); 7676 case ISD::READCYCLECOUNTER: { 7677 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 7678 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 7679 7680 Results.push_back(RTB); 7681 Results.push_back(RTB.getValue(1)); 7682 Results.push_back(RTB.getValue(2)); 7683 break; 7684 } 7685 case ISD::INTRINSIC_W_CHAIN: { 7686 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 7687 Intrinsic::ppc_is_decremented_ctr_nonzero) 7688 break; 7689 7690 assert(N->getValueType(0) == MVT::i1 && 7691 "Unexpected result type for CTR decrement intrinsic"); 7692 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0)); 7693 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 7694 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 7695 N->getOperand(1)); 7696 7697 Results.push_back(NewInt); 7698 Results.push_back(NewInt.getValue(1)); 7699 break; 7700 } 7701 case ISD::VAARG: { 7702 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 7703 return; 7704 7705 EVT VT = N->getValueType(0); 7706 7707 if (VT == MVT::i64) { 7708 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget); 7709 7710 Results.push_back(NewNode); 7711 Results.push_back(NewNode.getValue(1)); 7712 } 7713 return; 7714 } 7715 case ISD::FP_ROUND_INREG: { 7716 assert(N->getValueType(0) == MVT::ppcf128); 7717 assert(N->getOperand(0).getValueType() == MVT::ppcf128); 7718 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7719 MVT::f64, N->getOperand(0), 7720 DAG.getIntPtrConstant(0)); 7721 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7722 MVT::f64, N->getOperand(0), 7723 DAG.getIntPtrConstant(1)); 7724 7725 // Add the two halves of the long double in round-to-zero mode. 7726 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7727 7728 // We know the low half is about to be thrown away, so just use something 7729 // convenient. 7730 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 7731 FPreg, FPreg)); 7732 return; 7733 } 7734 case ISD::FP_TO_SINT: 7735 // LowerFP_TO_INT() can only handle f32 and f64. 7736 if (N->getOperand(0).getValueType() == MVT::ppcf128) 7737 return; 7738 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 7739 return; 7740 } 7741 } 7742 7743 7744 //===----------------------------------------------------------------------===// 7745 // Other Lowering Code 7746 //===----------------------------------------------------------------------===// 7747 7748 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 7749 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 7750 Function *Func = Intrinsic::getDeclaration(M, Id); 7751 return Builder.CreateCall(Func); 7752 } 7753 7754 // The mappings for emitLeading/TrailingFence is taken from 7755 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 7756 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 7757 AtomicOrdering Ord, bool IsStore, 7758 bool IsLoad) const { 7759 if (Ord == SequentiallyConsistent) 7760 return callIntrinsic(Builder, Intrinsic::ppc_sync); 7761 else if (isAtLeastRelease(Ord)) 7762 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 7763 else 7764 return nullptr; 7765 } 7766 7767 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 7768 AtomicOrdering Ord, bool IsStore, 7769 bool IsLoad) const { 7770 if (IsLoad && isAtLeastAcquire(Ord)) 7771 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 7772 // FIXME: this is too conservative, a dependent branch + isync is enough. 7773 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 7774 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 7775 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 7776 else 7777 return nullptr; 7778 } 7779 7780 MachineBasicBlock * 7781 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB, 7782 bool is64bit, unsigned BinOpcode) const { 7783 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 7784 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 7785 7786 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7787 MachineFunction *F = BB->getParent(); 7788 MachineFunction::iterator It = BB; 7789 ++It; 7790 7791 unsigned dest = MI->getOperand(0).getReg(); 7792 unsigned ptrA = MI->getOperand(1).getReg(); 7793 unsigned ptrB = MI->getOperand(2).getReg(); 7794 unsigned incr = MI->getOperand(3).getReg(); 7795 DebugLoc dl = MI->getDebugLoc(); 7796 7797 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 7798 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 7799 F->insert(It, loopMBB); 7800 F->insert(It, exitMBB); 7801 exitMBB->splice(exitMBB->begin(), BB, 7802 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7803 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 7804 7805 MachineRegisterInfo &RegInfo = F->getRegInfo(); 7806 unsigned TmpReg = (!BinOpcode) ? incr : 7807 RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass 7808 : &PPC::GPRCRegClass); 7809 7810 // thisMBB: 7811 // ... 7812 // fallthrough --> loopMBB 7813 BB->addSuccessor(loopMBB); 7814 7815 // loopMBB: 7816 // l[wd]arx dest, ptr 7817 // add r0, dest, incr 7818 // st[wd]cx. r0, ptr 7819 // bne- loopMBB 7820 // fallthrough --> exitMBB 7821 BB = loopMBB; 7822 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest) 7823 .addReg(ptrA).addReg(ptrB); 7824 if (BinOpcode) 7825 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 7826 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX)) 7827 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 7828 BuildMI(BB, dl, TII->get(PPC::BCC)) 7829 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 7830 BB->addSuccessor(loopMBB); 7831 BB->addSuccessor(exitMBB); 7832 7833 // exitMBB: 7834 // ... 7835 BB = exitMBB; 7836 return BB; 7837 } 7838 7839 MachineBasicBlock * 7840 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI, 7841 MachineBasicBlock *BB, 7842 bool is8bit, // operation 7843 unsigned BinOpcode) const { 7844 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 7845 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 7846 // In 64 bit mode we have to use 64 bits for addresses, even though the 7847 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 7848 // registers without caring whether they're 32 or 64, but here we're 7849 // doing actual arithmetic on the addresses. 7850 bool is64bit = Subtarget.isPPC64(); 7851 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 7852 7853 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7854 MachineFunction *F = BB->getParent(); 7855 MachineFunction::iterator It = BB; 7856 ++It; 7857 7858 unsigned dest = MI->getOperand(0).getReg(); 7859 unsigned ptrA = MI->getOperand(1).getReg(); 7860 unsigned ptrB = MI->getOperand(2).getReg(); 7861 unsigned incr = MI->getOperand(3).getReg(); 7862 DebugLoc dl = MI->getDebugLoc(); 7863 7864 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 7865 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 7866 F->insert(It, loopMBB); 7867 F->insert(It, exitMBB); 7868 exitMBB->splice(exitMBB->begin(), BB, 7869 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7870 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 7871 7872 MachineRegisterInfo &RegInfo = F->getRegInfo(); 7873 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 7874 : &PPC::GPRCRegClass; 7875 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 7876 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 7877 unsigned ShiftReg = RegInfo.createVirtualRegister(RC); 7878 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 7879 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 7880 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 7881 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 7882 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 7883 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 7884 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 7885 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 7886 unsigned Ptr1Reg; 7887 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 7888 7889 // thisMBB: 7890 // ... 7891 // fallthrough --> loopMBB 7892 BB->addSuccessor(loopMBB); 7893 7894 // The 4-byte load must be aligned, while a char or short may be 7895 // anywhere in the word. Hence all this nasty bookkeeping code. 7896 // add ptr1, ptrA, ptrB [copy if ptrA==0] 7897 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 7898 // xori shift, shift1, 24 [16] 7899 // rlwinm ptr, ptr1, 0, 0, 29 7900 // slw incr2, incr, shift 7901 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 7902 // slw mask, mask2, shift 7903 // loopMBB: 7904 // lwarx tmpDest, ptr 7905 // add tmp, tmpDest, incr2 7906 // andc tmp2, tmpDest, mask 7907 // and tmp3, tmp, mask 7908 // or tmp4, tmp3, tmp2 7909 // stwcx. tmp4, ptr 7910 // bne- loopMBB 7911 // fallthrough --> exitMBB 7912 // srw dest, tmpDest, shift 7913 if (ptrA != ZeroReg) { 7914 Ptr1Reg = RegInfo.createVirtualRegister(RC); 7915 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 7916 .addReg(ptrA).addReg(ptrB); 7917 } else { 7918 Ptr1Reg = ptrB; 7919 } 7920 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 7921 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 7922 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 7923 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 7924 if (is64bit) 7925 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 7926 .addReg(Ptr1Reg).addImm(0).addImm(61); 7927 else 7928 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 7929 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 7930 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 7931 .addReg(incr).addReg(ShiftReg); 7932 if (is8bit) 7933 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 7934 else { 7935 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 7936 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 7937 } 7938 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 7939 .addReg(Mask2Reg).addReg(ShiftReg); 7940 7941 BB = loopMBB; 7942 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 7943 .addReg(ZeroReg).addReg(PtrReg); 7944 if (BinOpcode) 7945 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 7946 .addReg(Incr2Reg).addReg(TmpDestReg); 7947 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 7948 .addReg(TmpDestReg).addReg(MaskReg); 7949 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 7950 .addReg(TmpReg).addReg(MaskReg); 7951 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 7952 .addReg(Tmp3Reg).addReg(Tmp2Reg); 7953 BuildMI(BB, dl, TII->get(PPC::STWCX)) 7954 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 7955 BuildMI(BB, dl, TII->get(PPC::BCC)) 7956 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 7957 BB->addSuccessor(loopMBB); 7958 BB->addSuccessor(exitMBB); 7959 7960 // exitMBB: 7961 // ... 7962 BB = exitMBB; 7963 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 7964 .addReg(ShiftReg); 7965 return BB; 7966 } 7967 7968 llvm::MachineBasicBlock* 7969 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI, 7970 MachineBasicBlock *MBB) const { 7971 DebugLoc DL = MI->getDebugLoc(); 7972 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 7973 7974 MachineFunction *MF = MBB->getParent(); 7975 MachineRegisterInfo &MRI = MF->getRegInfo(); 7976 7977 const BasicBlock *BB = MBB->getBasicBlock(); 7978 MachineFunction::iterator I = MBB; 7979 ++I; 7980 7981 // Memory Reference 7982 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 7983 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 7984 7985 unsigned DstReg = MI->getOperand(0).getReg(); 7986 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 7987 assert(RC->hasType(MVT::i32) && "Invalid destination!"); 7988 unsigned mainDstReg = MRI.createVirtualRegister(RC); 7989 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 7990 7991 MVT PVT = getPointerTy(); 7992 assert((PVT == MVT::i64 || PVT == MVT::i32) && 7993 "Invalid Pointer Size!"); 7994 // For v = setjmp(buf), we generate 7995 // 7996 // thisMBB: 7997 // SjLjSetup mainMBB 7998 // bl mainMBB 7999 // v_restore = 1 8000 // b sinkMBB 8001 // 8002 // mainMBB: 8003 // buf[LabelOffset] = LR 8004 // v_main = 0 8005 // 8006 // sinkMBB: 8007 // v = phi(main, restore) 8008 // 8009 8010 MachineBasicBlock *thisMBB = MBB; 8011 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 8012 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 8013 MF->insert(I, mainMBB); 8014 MF->insert(I, sinkMBB); 8015 8016 MachineInstrBuilder MIB; 8017 8018 // Transfer the remainder of BB and its successor edges to sinkMBB. 8019 sinkMBB->splice(sinkMBB->begin(), MBB, 8020 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8021 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 8022 8023 // Note that the structure of the jmp_buf used here is not compatible 8024 // with that used by libc, and is not designed to be. Specifically, it 8025 // stores only those 'reserved' registers that LLVM does not otherwise 8026 // understand how to spill. Also, by convention, by the time this 8027 // intrinsic is called, Clang has already stored the frame address in the 8028 // first slot of the buffer and stack address in the third. Following the 8029 // X86 target code, we'll store the jump address in the second slot. We also 8030 // need to save the TOC pointer (R2) to handle jumps between shared 8031 // libraries, and that will be stored in the fourth slot. The thread 8032 // identifier (R13) is not affected. 8033 8034 // thisMBB: 8035 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 8036 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 8037 const int64_t BPOffset = 4 * PVT.getStoreSize(); 8038 8039 // Prepare IP either in reg. 8040 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 8041 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 8042 unsigned BufReg = MI->getOperand(1).getReg(); 8043 8044 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 8045 setUsesTOCBasePtr(*MBB->getParent()); 8046 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 8047 .addReg(PPC::X2) 8048 .addImm(TOCOffset) 8049 .addReg(BufReg); 8050 MIB.setMemRefs(MMOBegin, MMOEnd); 8051 } 8052 8053 // Naked functions never have a base pointer, and so we use r1. For all 8054 // other functions, this decision must be delayed until during PEI. 8055 unsigned BaseReg; 8056 if (MF->getFunction()->hasFnAttribute(Attribute::Naked)) 8057 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 8058 else 8059 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 8060 8061 MIB = BuildMI(*thisMBB, MI, DL, 8062 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 8063 .addReg(BaseReg) 8064 .addImm(BPOffset) 8065 .addReg(BufReg); 8066 MIB.setMemRefs(MMOBegin, MMOEnd); 8067 8068 // Setup 8069 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 8070 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 8071 MIB.addRegMask(TRI->getNoPreservedMask()); 8072 8073 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 8074 8075 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 8076 .addMBB(mainMBB); 8077 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 8078 8079 thisMBB->addSuccessor(mainMBB, /* weight */ 0); 8080 thisMBB->addSuccessor(sinkMBB, /* weight */ 1); 8081 8082 // mainMBB: 8083 // mainDstReg = 0 8084 MIB = 8085 BuildMI(mainMBB, DL, 8086 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 8087 8088 // Store IP 8089 if (Subtarget.isPPC64()) { 8090 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 8091 .addReg(LabelReg) 8092 .addImm(LabelOffset) 8093 .addReg(BufReg); 8094 } else { 8095 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 8096 .addReg(LabelReg) 8097 .addImm(LabelOffset) 8098 .addReg(BufReg); 8099 } 8100 8101 MIB.setMemRefs(MMOBegin, MMOEnd); 8102 8103 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 8104 mainMBB->addSuccessor(sinkMBB); 8105 8106 // sinkMBB: 8107 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 8108 TII->get(PPC::PHI), DstReg) 8109 .addReg(mainDstReg).addMBB(mainMBB) 8110 .addReg(restoreDstReg).addMBB(thisMBB); 8111 8112 MI->eraseFromParent(); 8113 return sinkMBB; 8114 } 8115 8116 MachineBasicBlock * 8117 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI, 8118 MachineBasicBlock *MBB) const { 8119 DebugLoc DL = MI->getDebugLoc(); 8120 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 8121 8122 MachineFunction *MF = MBB->getParent(); 8123 MachineRegisterInfo &MRI = MF->getRegInfo(); 8124 8125 // Memory Reference 8126 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 8127 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 8128 8129 MVT PVT = getPointerTy(); 8130 assert((PVT == MVT::i64 || PVT == MVT::i32) && 8131 "Invalid Pointer Size!"); 8132 8133 const TargetRegisterClass *RC = 8134 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 8135 unsigned Tmp = MRI.createVirtualRegister(RC); 8136 // Since FP is only updated here but NOT referenced, it's treated as GPR. 8137 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 8138 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 8139 unsigned BP = 8140 (PVT == MVT::i64) 8141 ? PPC::X30 8142 : (Subtarget.isSVR4ABI() && 8143 MF->getTarget().getRelocationModel() == Reloc::PIC_ 8144 ? PPC::R29 8145 : PPC::R30); 8146 8147 MachineInstrBuilder MIB; 8148 8149 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 8150 const int64_t SPOffset = 2 * PVT.getStoreSize(); 8151 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 8152 const int64_t BPOffset = 4 * PVT.getStoreSize(); 8153 8154 unsigned BufReg = MI->getOperand(0).getReg(); 8155 8156 // Reload FP (the jumped-to function may not have had a 8157 // frame pointer, and if so, then its r31 will be restored 8158 // as necessary). 8159 if (PVT == MVT::i64) { 8160 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 8161 .addImm(0) 8162 .addReg(BufReg); 8163 } else { 8164 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 8165 .addImm(0) 8166 .addReg(BufReg); 8167 } 8168 MIB.setMemRefs(MMOBegin, MMOEnd); 8169 8170 // Reload IP 8171 if (PVT == MVT::i64) { 8172 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 8173 .addImm(LabelOffset) 8174 .addReg(BufReg); 8175 } else { 8176 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 8177 .addImm(LabelOffset) 8178 .addReg(BufReg); 8179 } 8180 MIB.setMemRefs(MMOBegin, MMOEnd); 8181 8182 // Reload SP 8183 if (PVT == MVT::i64) { 8184 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 8185 .addImm(SPOffset) 8186 .addReg(BufReg); 8187 } else { 8188 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 8189 .addImm(SPOffset) 8190 .addReg(BufReg); 8191 } 8192 MIB.setMemRefs(MMOBegin, MMOEnd); 8193 8194 // Reload BP 8195 if (PVT == MVT::i64) { 8196 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 8197 .addImm(BPOffset) 8198 .addReg(BufReg); 8199 } else { 8200 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 8201 .addImm(BPOffset) 8202 .addReg(BufReg); 8203 } 8204 MIB.setMemRefs(MMOBegin, MMOEnd); 8205 8206 // Reload TOC 8207 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 8208 setUsesTOCBasePtr(*MBB->getParent()); 8209 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 8210 .addImm(TOCOffset) 8211 .addReg(BufReg); 8212 8213 MIB.setMemRefs(MMOBegin, MMOEnd); 8214 } 8215 8216 // Jump 8217 BuildMI(*MBB, MI, DL, 8218 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 8219 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 8220 8221 MI->eraseFromParent(); 8222 return MBB; 8223 } 8224 8225 MachineBasicBlock * 8226 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 8227 MachineBasicBlock *BB) const { 8228 if (MI->getOpcode() == TargetOpcode::STACKMAP || 8229 MI->getOpcode() == TargetOpcode::PATCHPOINT) { 8230 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 8231 MI->getOpcode() == TargetOpcode::PATCHPOINT) { 8232 // Call lowering should have added an r2 operand to indicate a dependence 8233 // on the TOC base pointer value. It can't however, because there is no 8234 // way to mark the dependence as implicit there, and so the stackmap code 8235 // will confuse it with a regular operand. Instead, add the dependence 8236 // here. 8237 setUsesTOCBasePtr(*BB->getParent()); 8238 MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 8239 } 8240 8241 return emitPatchPoint(MI, BB); 8242 } 8243 8244 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 || 8245 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) { 8246 return emitEHSjLjSetJmp(MI, BB); 8247 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 || 8248 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) { 8249 return emitEHSjLjLongJmp(MI, BB); 8250 } 8251 8252 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 8253 8254 // To "insert" these instructions we actually have to insert their 8255 // control-flow patterns. 8256 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8257 MachineFunction::iterator It = BB; 8258 ++It; 8259 8260 MachineFunction *F = BB->getParent(); 8261 8262 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 || 8263 MI->getOpcode() == PPC::SELECT_CC_I8 || 8264 MI->getOpcode() == PPC::SELECT_I4 || 8265 MI->getOpcode() == PPC::SELECT_I8)) { 8266 SmallVector<MachineOperand, 2> Cond; 8267 if (MI->getOpcode() == PPC::SELECT_CC_I4 || 8268 MI->getOpcode() == PPC::SELECT_CC_I8) 8269 Cond.push_back(MI->getOperand(4)); 8270 else 8271 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 8272 Cond.push_back(MI->getOperand(1)); 8273 8274 DebugLoc dl = MI->getDebugLoc(); 8275 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(), 8276 Cond, MI->getOperand(2).getReg(), 8277 MI->getOperand(3).getReg()); 8278 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 || 8279 MI->getOpcode() == PPC::SELECT_CC_I8 || 8280 MI->getOpcode() == PPC::SELECT_CC_F4 || 8281 MI->getOpcode() == PPC::SELECT_CC_F8 || 8282 MI->getOpcode() == PPC::SELECT_CC_QFRC || 8283 MI->getOpcode() == PPC::SELECT_CC_QSRC || 8284 MI->getOpcode() == PPC::SELECT_CC_QBRC || 8285 MI->getOpcode() == PPC::SELECT_CC_VRRC || 8286 MI->getOpcode() == PPC::SELECT_CC_VSFRC || 8287 MI->getOpcode() == PPC::SELECT_CC_VSRC || 8288 MI->getOpcode() == PPC::SELECT_I4 || 8289 MI->getOpcode() == PPC::SELECT_I8 || 8290 MI->getOpcode() == PPC::SELECT_F4 || 8291 MI->getOpcode() == PPC::SELECT_F8 || 8292 MI->getOpcode() == PPC::SELECT_QFRC || 8293 MI->getOpcode() == PPC::SELECT_QSRC || 8294 MI->getOpcode() == PPC::SELECT_QBRC || 8295 MI->getOpcode() == PPC::SELECT_VRRC || 8296 MI->getOpcode() == PPC::SELECT_VSFRC || 8297 MI->getOpcode() == PPC::SELECT_VSRC) { 8298 // The incoming instruction knows the destination vreg to set, the 8299 // condition code register to branch on, the true/false values to 8300 // select between, and a branch opcode to use. 8301 8302 // thisMBB: 8303 // ... 8304 // TrueVal = ... 8305 // cmpTY ccX, r1, r2 8306 // bCC copy1MBB 8307 // fallthrough --> copy0MBB 8308 MachineBasicBlock *thisMBB = BB; 8309 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8310 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8311 DebugLoc dl = MI->getDebugLoc(); 8312 F->insert(It, copy0MBB); 8313 F->insert(It, sinkMBB); 8314 8315 // Transfer the remainder of BB and its successor edges to sinkMBB. 8316 sinkMBB->splice(sinkMBB->begin(), BB, 8317 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8318 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8319 8320 // Next, add the true and fallthrough blocks as its successors. 8321 BB->addSuccessor(copy0MBB); 8322 BB->addSuccessor(sinkMBB); 8323 8324 if (MI->getOpcode() == PPC::SELECT_I4 || 8325 MI->getOpcode() == PPC::SELECT_I8 || 8326 MI->getOpcode() == PPC::SELECT_F4 || 8327 MI->getOpcode() == PPC::SELECT_F8 || 8328 MI->getOpcode() == PPC::SELECT_QFRC || 8329 MI->getOpcode() == PPC::SELECT_QSRC || 8330 MI->getOpcode() == PPC::SELECT_QBRC || 8331 MI->getOpcode() == PPC::SELECT_VRRC || 8332 MI->getOpcode() == PPC::SELECT_VSFRC || 8333 MI->getOpcode() == PPC::SELECT_VSRC) { 8334 BuildMI(BB, dl, TII->get(PPC::BC)) 8335 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB); 8336 } else { 8337 unsigned SelectPred = MI->getOperand(4).getImm(); 8338 BuildMI(BB, dl, TII->get(PPC::BCC)) 8339 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB); 8340 } 8341 8342 // copy0MBB: 8343 // %FalseValue = ... 8344 // # fallthrough to sinkMBB 8345 BB = copy0MBB; 8346 8347 // Update machine-CFG edges 8348 BB->addSuccessor(sinkMBB); 8349 8350 // sinkMBB: 8351 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8352 // ... 8353 BB = sinkMBB; 8354 BuildMI(*BB, BB->begin(), dl, 8355 TII->get(PPC::PHI), MI->getOperand(0).getReg()) 8356 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB) 8357 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 8358 } else if (MI->getOpcode() == PPC::ReadTB) { 8359 // To read the 64-bit time-base register on a 32-bit target, we read the 8360 // two halves. Should the counter have wrapped while it was being read, we 8361 // need to try again. 8362 // ... 8363 // readLoop: 8364 // mfspr Rx,TBU # load from TBU 8365 // mfspr Ry,TB # load from TB 8366 // mfspr Rz,TBU # load from TBU 8367 // cmpw crX,Rx,Rz # check if ‘old’=’new’ 8368 // bne readLoop # branch if they're not equal 8369 // ... 8370 8371 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 8372 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8373 DebugLoc dl = MI->getDebugLoc(); 8374 F->insert(It, readMBB); 8375 F->insert(It, sinkMBB); 8376 8377 // Transfer the remainder of BB and its successor edges to sinkMBB. 8378 sinkMBB->splice(sinkMBB->begin(), BB, 8379 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8380 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8381 8382 BB->addSuccessor(readMBB); 8383 BB = readMBB; 8384 8385 MachineRegisterInfo &RegInfo = F->getRegInfo(); 8386 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 8387 unsigned LoReg = MI->getOperand(0).getReg(); 8388 unsigned HiReg = MI->getOperand(1).getReg(); 8389 8390 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 8391 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 8392 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 8393 8394 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 8395 8396 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 8397 .addReg(HiReg).addReg(ReadAgainReg); 8398 BuildMI(BB, dl, TII->get(PPC::BCC)) 8399 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB); 8400 8401 BB->addSuccessor(readMBB); 8402 BB->addSuccessor(sinkMBB); 8403 } 8404 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 8405 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 8406 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 8407 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 8408 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 8409 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4); 8410 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 8411 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8); 8412 8413 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 8414 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 8415 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 8416 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 8417 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 8418 BB = EmitAtomicBinary(MI, BB, false, PPC::AND); 8419 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 8420 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8); 8421 8422 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 8423 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 8424 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 8425 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 8426 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 8427 BB = EmitAtomicBinary(MI, BB, false, PPC::OR); 8428 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 8429 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8); 8430 8431 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 8432 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 8433 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 8434 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 8435 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 8436 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR); 8437 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 8438 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8); 8439 8440 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 8441 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 8442 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 8443 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 8444 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 8445 BB = EmitAtomicBinary(MI, BB, false, PPC::NAND); 8446 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 8447 BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8); 8448 8449 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 8450 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 8451 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 8452 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 8453 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 8454 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF); 8455 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 8456 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8); 8457 8458 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8) 8459 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 8460 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16) 8461 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 8462 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32) 8463 BB = EmitAtomicBinary(MI, BB, false, 0); 8464 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64) 8465 BB = EmitAtomicBinary(MI, BB, true, 0); 8466 8467 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 8468 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) { 8469 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 8470 8471 unsigned dest = MI->getOperand(0).getReg(); 8472 unsigned ptrA = MI->getOperand(1).getReg(); 8473 unsigned ptrB = MI->getOperand(2).getReg(); 8474 unsigned oldval = MI->getOperand(3).getReg(); 8475 unsigned newval = MI->getOperand(4).getReg(); 8476 DebugLoc dl = MI->getDebugLoc(); 8477 8478 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 8479 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 8480 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 8481 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 8482 F->insert(It, loop1MBB); 8483 F->insert(It, loop2MBB); 8484 F->insert(It, midMBB); 8485 F->insert(It, exitMBB); 8486 exitMBB->splice(exitMBB->begin(), BB, 8487 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8488 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8489 8490 // thisMBB: 8491 // ... 8492 // fallthrough --> loopMBB 8493 BB->addSuccessor(loop1MBB); 8494 8495 // loop1MBB: 8496 // l[wd]arx dest, ptr 8497 // cmp[wd] dest, oldval 8498 // bne- midMBB 8499 // loop2MBB: 8500 // st[wd]cx. newval, ptr 8501 // bne- loopMBB 8502 // b exitBB 8503 // midMBB: 8504 // st[wd]cx. dest, ptr 8505 // exitBB: 8506 BB = loop1MBB; 8507 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest) 8508 .addReg(ptrA).addReg(ptrB); 8509 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 8510 .addReg(oldval).addReg(dest); 8511 BuildMI(BB, dl, TII->get(PPC::BCC)) 8512 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 8513 BB->addSuccessor(loop2MBB); 8514 BB->addSuccessor(midMBB); 8515 8516 BB = loop2MBB; 8517 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX)) 8518 .addReg(newval).addReg(ptrA).addReg(ptrB); 8519 BuildMI(BB, dl, TII->get(PPC::BCC)) 8520 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 8521 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 8522 BB->addSuccessor(loop1MBB); 8523 BB->addSuccessor(exitMBB); 8524 8525 BB = midMBB; 8526 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX)) 8527 .addReg(dest).addReg(ptrA).addReg(ptrB); 8528 BB->addSuccessor(exitMBB); 8529 8530 // exitMBB: 8531 // ... 8532 BB = exitMBB; 8533 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 8534 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 8535 // We must use 64-bit registers for addresses when targeting 64-bit, 8536 // since we're actually doing arithmetic on them. Other registers 8537 // can be 32-bit. 8538 bool is64bit = Subtarget.isPPC64(); 8539 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 8540 8541 unsigned dest = MI->getOperand(0).getReg(); 8542 unsigned ptrA = MI->getOperand(1).getReg(); 8543 unsigned ptrB = MI->getOperand(2).getReg(); 8544 unsigned oldval = MI->getOperand(3).getReg(); 8545 unsigned newval = MI->getOperand(4).getReg(); 8546 DebugLoc dl = MI->getDebugLoc(); 8547 8548 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 8549 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 8550 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 8551 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 8552 F->insert(It, loop1MBB); 8553 F->insert(It, loop2MBB); 8554 F->insert(It, midMBB); 8555 F->insert(It, exitMBB); 8556 exitMBB->splice(exitMBB->begin(), BB, 8557 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8558 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8559 8560 MachineRegisterInfo &RegInfo = F->getRegInfo(); 8561 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 8562 : &PPC::GPRCRegClass; 8563 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 8564 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 8565 unsigned ShiftReg = RegInfo.createVirtualRegister(RC); 8566 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 8567 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 8568 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 8569 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 8570 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 8571 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 8572 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 8573 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 8574 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 8575 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 8576 unsigned Ptr1Reg; 8577 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 8578 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 8579 // thisMBB: 8580 // ... 8581 // fallthrough --> loopMBB 8582 BB->addSuccessor(loop1MBB); 8583 8584 // The 4-byte load must be aligned, while a char or short may be 8585 // anywhere in the word. Hence all this nasty bookkeeping code. 8586 // add ptr1, ptrA, ptrB [copy if ptrA==0] 8587 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 8588 // xori shift, shift1, 24 [16] 8589 // rlwinm ptr, ptr1, 0, 0, 29 8590 // slw newval2, newval, shift 8591 // slw oldval2, oldval,shift 8592 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 8593 // slw mask, mask2, shift 8594 // and newval3, newval2, mask 8595 // and oldval3, oldval2, mask 8596 // loop1MBB: 8597 // lwarx tmpDest, ptr 8598 // and tmp, tmpDest, mask 8599 // cmpw tmp, oldval3 8600 // bne- midMBB 8601 // loop2MBB: 8602 // andc tmp2, tmpDest, mask 8603 // or tmp4, tmp2, newval3 8604 // stwcx. tmp4, ptr 8605 // bne- loop1MBB 8606 // b exitBB 8607 // midMBB: 8608 // stwcx. tmpDest, ptr 8609 // exitBB: 8610 // srw dest, tmpDest, shift 8611 if (ptrA != ZeroReg) { 8612 Ptr1Reg = RegInfo.createVirtualRegister(RC); 8613 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 8614 .addReg(ptrA).addReg(ptrB); 8615 } else { 8616 Ptr1Reg = ptrB; 8617 } 8618 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 8619 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 8620 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 8621 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 8622 if (is64bit) 8623 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 8624 .addReg(Ptr1Reg).addImm(0).addImm(61); 8625 else 8626 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 8627 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 8628 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 8629 .addReg(newval).addReg(ShiftReg); 8630 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 8631 .addReg(oldval).addReg(ShiftReg); 8632 if (is8bit) 8633 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 8634 else { 8635 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 8636 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 8637 .addReg(Mask3Reg).addImm(65535); 8638 } 8639 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 8640 .addReg(Mask2Reg).addReg(ShiftReg); 8641 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 8642 .addReg(NewVal2Reg).addReg(MaskReg); 8643 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 8644 .addReg(OldVal2Reg).addReg(MaskReg); 8645 8646 BB = loop1MBB; 8647 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 8648 .addReg(ZeroReg).addReg(PtrReg); 8649 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 8650 .addReg(TmpDestReg).addReg(MaskReg); 8651 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 8652 .addReg(TmpReg).addReg(OldVal3Reg); 8653 BuildMI(BB, dl, TII->get(PPC::BCC)) 8654 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 8655 BB->addSuccessor(loop2MBB); 8656 BB->addSuccessor(midMBB); 8657 8658 BB = loop2MBB; 8659 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 8660 .addReg(TmpDestReg).addReg(MaskReg); 8661 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 8662 .addReg(Tmp2Reg).addReg(NewVal3Reg); 8663 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 8664 .addReg(ZeroReg).addReg(PtrReg); 8665 BuildMI(BB, dl, TII->get(PPC::BCC)) 8666 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 8667 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 8668 BB->addSuccessor(loop1MBB); 8669 BB->addSuccessor(exitMBB); 8670 8671 BB = midMBB; 8672 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 8673 .addReg(ZeroReg).addReg(PtrReg); 8674 BB->addSuccessor(exitMBB); 8675 8676 // exitMBB: 8677 // ... 8678 BB = exitMBB; 8679 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 8680 .addReg(ShiftReg); 8681 } else if (MI->getOpcode() == PPC::FADDrtz) { 8682 // This pseudo performs an FADD with rounding mode temporarily forced 8683 // to round-to-zero. We emit this via custom inserter since the FPSCR 8684 // is not modeled at the SelectionDAG level. 8685 unsigned Dest = MI->getOperand(0).getReg(); 8686 unsigned Src1 = MI->getOperand(1).getReg(); 8687 unsigned Src2 = MI->getOperand(2).getReg(); 8688 DebugLoc dl = MI->getDebugLoc(); 8689 8690 MachineRegisterInfo &RegInfo = F->getRegInfo(); 8691 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 8692 8693 // Save FPSCR value. 8694 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 8695 8696 // Set rounding mode to round-to-zero. 8697 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 8698 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 8699 8700 // Perform addition. 8701 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 8702 8703 // Restore FPSCR value. 8704 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 8705 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT || 8706 MI->getOpcode() == PPC::ANDIo_1_GT_BIT || 8707 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 8708 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) { 8709 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 8710 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ? 8711 PPC::ANDIo8 : PPC::ANDIo; 8712 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT || 8713 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8); 8714 8715 MachineRegisterInfo &RegInfo = F->getRegInfo(); 8716 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? 8717 &PPC::GPRCRegClass : 8718 &PPC::G8RCRegClass); 8719 8720 DebugLoc dl = MI->getDebugLoc(); 8721 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 8722 .addReg(MI->getOperand(1).getReg()).addImm(1); 8723 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 8724 MI->getOperand(0).getReg()) 8725 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 8726 } else { 8727 llvm_unreachable("Unexpected instr type to insert"); 8728 } 8729 8730 MI->eraseFromParent(); // The pseudo instruction is gone now. 8731 return BB; 8732 } 8733 8734 //===----------------------------------------------------------------------===// 8735 // Target Optimization Hooks 8736 //===----------------------------------------------------------------------===// 8737 8738 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand, 8739 DAGCombinerInfo &DCI, 8740 unsigned &RefinementSteps, 8741 bool &UseOneConstNR) const { 8742 EVT VT = Operand.getValueType(); 8743 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 8744 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 8745 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 8746 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 8747 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 8748 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 8749 // Convergence is quadratic, so we essentially double the number of digits 8750 // correct after every iteration. For both FRE and FRSQRTE, the minimum 8751 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is 8752 // 2^-14. IEEE float has 23 digits and double has 52 digits. 8753 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 8754 if (VT.getScalarType() == MVT::f64) 8755 ++RefinementSteps; 8756 UseOneConstNR = true; 8757 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 8758 } 8759 return SDValue(); 8760 } 8761 8762 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, 8763 DAGCombinerInfo &DCI, 8764 unsigned &RefinementSteps) const { 8765 EVT VT = Operand.getValueType(); 8766 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 8767 (VT == MVT::f64 && Subtarget.hasFRE()) || 8768 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 8769 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 8770 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 8771 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 8772 // Convergence is quadratic, so we essentially double the number of digits 8773 // correct after every iteration. For both FRE and FRSQRTE, the minimum 8774 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is 8775 // 2^-14. IEEE float has 23 digits and double has 52 digits. 8776 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 8777 if (VT.getScalarType() == MVT::f64) 8778 ++RefinementSteps; 8779 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 8780 } 8781 return SDValue(); 8782 } 8783 8784 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const { 8785 // Note: This functionality is used only when unsafe-fp-math is enabled, and 8786 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 8787 // enabled for division), this functionality is redundant with the default 8788 // combiner logic (once the division -> reciprocal/multiply transformation 8789 // has taken place). As a result, this matters more for older cores than for 8790 // newer ones. 8791 8792 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8793 // reciprocal if there are two or more FDIVs (for embedded cores with only 8794 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 8795 switch (Subtarget.getDarwinDirective()) { 8796 default: 8797 return NumUsers > 2; 8798 case PPC::DIR_440: 8799 case PPC::DIR_A2: 8800 case PPC::DIR_E500mc: 8801 case PPC::DIR_E5500: 8802 return NumUsers > 1; 8803 } 8804 } 8805 8806 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 8807 unsigned Bytes, int Dist, 8808 SelectionDAG &DAG) { 8809 if (VT.getSizeInBits() / 8 != Bytes) 8810 return false; 8811 8812 SDValue BaseLoc = Base->getBasePtr(); 8813 if (Loc.getOpcode() == ISD::FrameIndex) { 8814 if (BaseLoc.getOpcode() != ISD::FrameIndex) 8815 return false; 8816 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 8817 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 8818 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 8819 int FS = MFI->getObjectSize(FI); 8820 int BFS = MFI->getObjectSize(BFI); 8821 if (FS != BFS || FS != (int)Bytes) return false; 8822 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes); 8823 } 8824 8825 // Handle X+C 8826 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc && 8827 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes) 8828 return true; 8829 8830 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8831 const GlobalValue *GV1 = nullptr; 8832 const GlobalValue *GV2 = nullptr; 8833 int64_t Offset1 = 0; 8834 int64_t Offset2 = 0; 8835 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 8836 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 8837 if (isGA1 && isGA2 && GV1 == GV2) 8838 return Offset1 == (Offset2 + Dist*Bytes); 8839 return false; 8840 } 8841 8842 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 8843 // not enforce equality of the chain operands. 8844 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 8845 unsigned Bytes, int Dist, 8846 SelectionDAG &DAG) { 8847 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 8848 EVT VT = LS->getMemoryVT(); 8849 SDValue Loc = LS->getBasePtr(); 8850 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 8851 } 8852 8853 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 8854 EVT VT; 8855 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 8856 default: return false; 8857 case Intrinsic::ppc_qpx_qvlfd: 8858 case Intrinsic::ppc_qpx_qvlfda: 8859 VT = MVT::v4f64; 8860 break; 8861 case Intrinsic::ppc_qpx_qvlfs: 8862 case Intrinsic::ppc_qpx_qvlfsa: 8863 VT = MVT::v4f32; 8864 break; 8865 case Intrinsic::ppc_qpx_qvlfcd: 8866 case Intrinsic::ppc_qpx_qvlfcda: 8867 VT = MVT::v2f64; 8868 break; 8869 case Intrinsic::ppc_qpx_qvlfcs: 8870 case Intrinsic::ppc_qpx_qvlfcsa: 8871 VT = MVT::v2f32; 8872 break; 8873 case Intrinsic::ppc_qpx_qvlfiwa: 8874 case Intrinsic::ppc_qpx_qvlfiwz: 8875 case Intrinsic::ppc_altivec_lvx: 8876 case Intrinsic::ppc_altivec_lvxl: 8877 case Intrinsic::ppc_vsx_lxvw4x: 8878 VT = MVT::v4i32; 8879 break; 8880 case Intrinsic::ppc_vsx_lxvd2x: 8881 VT = MVT::v2f64; 8882 break; 8883 case Intrinsic::ppc_altivec_lvebx: 8884 VT = MVT::i8; 8885 break; 8886 case Intrinsic::ppc_altivec_lvehx: 8887 VT = MVT::i16; 8888 break; 8889 case Intrinsic::ppc_altivec_lvewx: 8890 VT = MVT::i32; 8891 break; 8892 } 8893 8894 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 8895 } 8896 8897 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 8898 EVT VT; 8899 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 8900 default: return false; 8901 case Intrinsic::ppc_qpx_qvstfd: 8902 case Intrinsic::ppc_qpx_qvstfda: 8903 VT = MVT::v4f64; 8904 break; 8905 case Intrinsic::ppc_qpx_qvstfs: 8906 case Intrinsic::ppc_qpx_qvstfsa: 8907 VT = MVT::v4f32; 8908 break; 8909 case Intrinsic::ppc_qpx_qvstfcd: 8910 case Intrinsic::ppc_qpx_qvstfcda: 8911 VT = MVT::v2f64; 8912 break; 8913 case Intrinsic::ppc_qpx_qvstfcs: 8914 case Intrinsic::ppc_qpx_qvstfcsa: 8915 VT = MVT::v2f32; 8916 break; 8917 case Intrinsic::ppc_qpx_qvstfiw: 8918 case Intrinsic::ppc_qpx_qvstfiwa: 8919 case Intrinsic::ppc_altivec_stvx: 8920 case Intrinsic::ppc_altivec_stvxl: 8921 case Intrinsic::ppc_vsx_stxvw4x: 8922 VT = MVT::v4i32; 8923 break; 8924 case Intrinsic::ppc_vsx_stxvd2x: 8925 VT = MVT::v2f64; 8926 break; 8927 case Intrinsic::ppc_altivec_stvebx: 8928 VT = MVT::i8; 8929 break; 8930 case Intrinsic::ppc_altivec_stvehx: 8931 VT = MVT::i16; 8932 break; 8933 case Intrinsic::ppc_altivec_stvewx: 8934 VT = MVT::i32; 8935 break; 8936 } 8937 8938 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 8939 } 8940 8941 return false; 8942 } 8943 8944 // Return true is there is a nearyby consecutive load to the one provided 8945 // (regardless of alignment). We search up and down the chain, looking though 8946 // token factors and other loads (but nothing else). As a result, a true result 8947 // indicates that it is safe to create a new consecutive load adjacent to the 8948 // load provided. 8949 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 8950 SDValue Chain = LD->getChain(); 8951 EVT VT = LD->getMemoryVT(); 8952 8953 SmallSet<SDNode *, 16> LoadRoots; 8954 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 8955 SmallSet<SDNode *, 16> Visited; 8956 8957 // First, search up the chain, branching to follow all token-factor operands. 8958 // If we find a consecutive load, then we're done, otherwise, record all 8959 // nodes just above the top-level loads and token factors. 8960 while (!Queue.empty()) { 8961 SDNode *ChainNext = Queue.pop_back_val(); 8962 if (!Visited.insert(ChainNext).second) 8963 continue; 8964 8965 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 8966 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 8967 return true; 8968 8969 if (!Visited.count(ChainLD->getChain().getNode())) 8970 Queue.push_back(ChainLD->getChain().getNode()); 8971 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 8972 for (const SDUse &O : ChainNext->ops()) 8973 if (!Visited.count(O.getNode())) 8974 Queue.push_back(O.getNode()); 8975 } else 8976 LoadRoots.insert(ChainNext); 8977 } 8978 8979 // Second, search down the chain, starting from the top-level nodes recorded 8980 // in the first phase. These top-level nodes are the nodes just above all 8981 // loads and token factors. Starting with their uses, recursively look though 8982 // all loads (just the chain uses) and token factors to find a consecutive 8983 // load. 8984 Visited.clear(); 8985 Queue.clear(); 8986 8987 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 8988 IE = LoadRoots.end(); I != IE; ++I) { 8989 Queue.push_back(*I); 8990 8991 while (!Queue.empty()) { 8992 SDNode *LoadRoot = Queue.pop_back_val(); 8993 if (!Visited.insert(LoadRoot).second) 8994 continue; 8995 8996 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 8997 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 8998 return true; 8999 9000 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 9001 UE = LoadRoot->use_end(); UI != UE; ++UI) 9002 if (((isa<MemSDNode>(*UI) && 9003 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 9004 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 9005 Queue.push_back(*UI); 9006 } 9007 } 9008 9009 return false; 9010 } 9011 9012 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 9013 DAGCombinerInfo &DCI) const { 9014 SelectionDAG &DAG = DCI.DAG; 9015 SDLoc dl(N); 9016 9017 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 9018 // If we're tracking CR bits, we need to be careful that we don't have: 9019 // trunc(binary-ops(zext(x), zext(y))) 9020 // or 9021 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 9022 // such that we're unnecessarily moving things into GPRs when it would be 9023 // better to keep them in CR bits. 9024 9025 // Note that trunc here can be an actual i1 trunc, or can be the effective 9026 // truncation that comes from a setcc or select_cc. 9027 if (N->getOpcode() == ISD::TRUNCATE && 9028 N->getValueType(0) != MVT::i1) 9029 return SDValue(); 9030 9031 if (N->getOperand(0).getValueType() != MVT::i32 && 9032 N->getOperand(0).getValueType() != MVT::i64) 9033 return SDValue(); 9034 9035 if (N->getOpcode() == ISD::SETCC || 9036 N->getOpcode() == ISD::SELECT_CC) { 9037 // If we're looking at a comparison, then we need to make sure that the 9038 // high bits (all except for the first) don't matter the result. 9039 ISD::CondCode CC = 9040 cast<CondCodeSDNode>(N->getOperand( 9041 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 9042 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 9043 9044 if (ISD::isSignedIntSetCC(CC)) { 9045 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 9046 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 9047 return SDValue(); 9048 } else if (ISD::isUnsignedIntSetCC(CC)) { 9049 if (!DAG.MaskedValueIsZero(N->getOperand(0), 9050 APInt::getHighBitsSet(OpBits, OpBits-1)) || 9051 !DAG.MaskedValueIsZero(N->getOperand(1), 9052 APInt::getHighBitsSet(OpBits, OpBits-1))) 9053 return SDValue(); 9054 } else { 9055 // This is neither a signed nor an unsigned comparison, just make sure 9056 // that the high bits are equal. 9057 APInt Op1Zero, Op1One; 9058 APInt Op2Zero, Op2One; 9059 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One); 9060 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One); 9061 9062 // We don't really care about what is known about the first bit (if 9063 // anything), so clear it in all masks prior to comparing them. 9064 Op1Zero.clearBit(0); Op1One.clearBit(0); 9065 Op2Zero.clearBit(0); Op2One.clearBit(0); 9066 9067 if (Op1Zero != Op2Zero || Op1One != Op2One) 9068 return SDValue(); 9069 } 9070 } 9071 9072 // We now know that the higher-order bits are irrelevant, we just need to 9073 // make sure that all of the intermediate operations are bit operations, and 9074 // all inputs are extensions. 9075 if (N->getOperand(0).getOpcode() != ISD::AND && 9076 N->getOperand(0).getOpcode() != ISD::OR && 9077 N->getOperand(0).getOpcode() != ISD::XOR && 9078 N->getOperand(0).getOpcode() != ISD::SELECT && 9079 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 9080 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 9081 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 9082 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 9083 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 9084 return SDValue(); 9085 9086 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 9087 N->getOperand(1).getOpcode() != ISD::AND && 9088 N->getOperand(1).getOpcode() != ISD::OR && 9089 N->getOperand(1).getOpcode() != ISD::XOR && 9090 N->getOperand(1).getOpcode() != ISD::SELECT && 9091 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 9092 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 9093 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 9094 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 9095 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 9096 return SDValue(); 9097 9098 SmallVector<SDValue, 4> Inputs; 9099 SmallVector<SDValue, 8> BinOps, PromOps; 9100 SmallPtrSet<SDNode *, 16> Visited; 9101 9102 for (unsigned i = 0; i < 2; ++i) { 9103 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 9104 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 9105 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 9106 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 9107 isa<ConstantSDNode>(N->getOperand(i))) 9108 Inputs.push_back(N->getOperand(i)); 9109 else 9110 BinOps.push_back(N->getOperand(i)); 9111 9112 if (N->getOpcode() == ISD::TRUNCATE) 9113 break; 9114 } 9115 9116 // Visit all inputs, collect all binary operations (and, or, xor and 9117 // select) that are all fed by extensions. 9118 while (!BinOps.empty()) { 9119 SDValue BinOp = BinOps.back(); 9120 BinOps.pop_back(); 9121 9122 if (!Visited.insert(BinOp.getNode()).second) 9123 continue; 9124 9125 PromOps.push_back(BinOp); 9126 9127 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 9128 // The condition of the select is not promoted. 9129 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 9130 continue; 9131 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 9132 continue; 9133 9134 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 9135 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 9136 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 9137 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 9138 isa<ConstantSDNode>(BinOp.getOperand(i))) { 9139 Inputs.push_back(BinOp.getOperand(i)); 9140 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 9141 BinOp.getOperand(i).getOpcode() == ISD::OR || 9142 BinOp.getOperand(i).getOpcode() == ISD::XOR || 9143 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 9144 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 9145 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 9146 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 9147 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 9148 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 9149 BinOps.push_back(BinOp.getOperand(i)); 9150 } else { 9151 // We have an input that is not an extension or another binary 9152 // operation; we'll abort this transformation. 9153 return SDValue(); 9154 } 9155 } 9156 } 9157 9158 // Make sure that this is a self-contained cluster of operations (which 9159 // is not quite the same thing as saying that everything has only one 9160 // use). 9161 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 9162 if (isa<ConstantSDNode>(Inputs[i])) 9163 continue; 9164 9165 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 9166 UE = Inputs[i].getNode()->use_end(); 9167 UI != UE; ++UI) { 9168 SDNode *User = *UI; 9169 if (User != N && !Visited.count(User)) 9170 return SDValue(); 9171 9172 // Make sure that we're not going to promote the non-output-value 9173 // operand(s) or SELECT or SELECT_CC. 9174 // FIXME: Although we could sometimes handle this, and it does occur in 9175 // practice that one of the condition inputs to the select is also one of 9176 // the outputs, we currently can't deal with this. 9177 if (User->getOpcode() == ISD::SELECT) { 9178 if (User->getOperand(0) == Inputs[i]) 9179 return SDValue(); 9180 } else if (User->getOpcode() == ISD::SELECT_CC) { 9181 if (User->getOperand(0) == Inputs[i] || 9182 User->getOperand(1) == Inputs[i]) 9183 return SDValue(); 9184 } 9185 } 9186 } 9187 9188 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 9189 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 9190 UE = PromOps[i].getNode()->use_end(); 9191 UI != UE; ++UI) { 9192 SDNode *User = *UI; 9193 if (User != N && !Visited.count(User)) 9194 return SDValue(); 9195 9196 // Make sure that we're not going to promote the non-output-value 9197 // operand(s) or SELECT or SELECT_CC. 9198 // FIXME: Although we could sometimes handle this, and it does occur in 9199 // practice that one of the condition inputs to the select is also one of 9200 // the outputs, we currently can't deal with this. 9201 if (User->getOpcode() == ISD::SELECT) { 9202 if (User->getOperand(0) == PromOps[i]) 9203 return SDValue(); 9204 } else if (User->getOpcode() == ISD::SELECT_CC) { 9205 if (User->getOperand(0) == PromOps[i] || 9206 User->getOperand(1) == PromOps[i]) 9207 return SDValue(); 9208 } 9209 } 9210 } 9211 9212 // Replace all inputs with the extension operand. 9213 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 9214 // Constants may have users outside the cluster of to-be-promoted nodes, 9215 // and so we need to replace those as we do the promotions. 9216 if (isa<ConstantSDNode>(Inputs[i])) 9217 continue; 9218 else 9219 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 9220 } 9221 9222 // Replace all operations (these are all the same, but have a different 9223 // (i1) return type). DAG.getNode will validate that the types of 9224 // a binary operator match, so go through the list in reverse so that 9225 // we've likely promoted both operands first. Any intermediate truncations or 9226 // extensions disappear. 9227 while (!PromOps.empty()) { 9228 SDValue PromOp = PromOps.back(); 9229 PromOps.pop_back(); 9230 9231 if (PromOp.getOpcode() == ISD::TRUNCATE || 9232 PromOp.getOpcode() == ISD::SIGN_EXTEND || 9233 PromOp.getOpcode() == ISD::ZERO_EXTEND || 9234 PromOp.getOpcode() == ISD::ANY_EXTEND) { 9235 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 9236 PromOp.getOperand(0).getValueType() != MVT::i1) { 9237 // The operand is not yet ready (see comment below). 9238 PromOps.insert(PromOps.begin(), PromOp); 9239 continue; 9240 } 9241 9242 SDValue RepValue = PromOp.getOperand(0); 9243 if (isa<ConstantSDNode>(RepValue)) 9244 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 9245 9246 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 9247 continue; 9248 } 9249 9250 unsigned C; 9251 switch (PromOp.getOpcode()) { 9252 default: C = 0; break; 9253 case ISD::SELECT: C = 1; break; 9254 case ISD::SELECT_CC: C = 2; break; 9255 } 9256 9257 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 9258 PromOp.getOperand(C).getValueType() != MVT::i1) || 9259 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 9260 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 9261 // The to-be-promoted operands of this node have not yet been 9262 // promoted (this should be rare because we're going through the 9263 // list backward, but if one of the operands has several users in 9264 // this cluster of to-be-promoted nodes, it is possible). 9265 PromOps.insert(PromOps.begin(), PromOp); 9266 continue; 9267 } 9268 9269 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 9270 PromOp.getNode()->op_end()); 9271 9272 // If there are any constant inputs, make sure they're replaced now. 9273 for (unsigned i = 0; i < 2; ++i) 9274 if (isa<ConstantSDNode>(Ops[C+i])) 9275 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 9276 9277 DAG.ReplaceAllUsesOfValueWith(PromOp, 9278 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 9279 } 9280 9281 // Now we're left with the initial truncation itself. 9282 if (N->getOpcode() == ISD::TRUNCATE) 9283 return N->getOperand(0); 9284 9285 // Otherwise, this is a comparison. The operands to be compared have just 9286 // changed type (to i1), but everything else is the same. 9287 return SDValue(N, 0); 9288 } 9289 9290 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 9291 DAGCombinerInfo &DCI) const { 9292 SelectionDAG &DAG = DCI.DAG; 9293 SDLoc dl(N); 9294 9295 // If we're tracking CR bits, we need to be careful that we don't have: 9296 // zext(binary-ops(trunc(x), trunc(y))) 9297 // or 9298 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 9299 // such that we're unnecessarily moving things into CR bits that can more 9300 // efficiently stay in GPRs. Note that if we're not certain that the high 9301 // bits are set as required by the final extension, we still may need to do 9302 // some masking to get the proper behavior. 9303 9304 // This same functionality is important on PPC64 when dealing with 9305 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 9306 // the return values of functions. Because it is so similar, it is handled 9307 // here as well. 9308 9309 if (N->getValueType(0) != MVT::i32 && 9310 N->getValueType(0) != MVT::i64) 9311 return SDValue(); 9312 9313 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 9314 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 9315 return SDValue(); 9316 9317 if (N->getOperand(0).getOpcode() != ISD::AND && 9318 N->getOperand(0).getOpcode() != ISD::OR && 9319 N->getOperand(0).getOpcode() != ISD::XOR && 9320 N->getOperand(0).getOpcode() != ISD::SELECT && 9321 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 9322 return SDValue(); 9323 9324 SmallVector<SDValue, 4> Inputs; 9325 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 9326 SmallPtrSet<SDNode *, 16> Visited; 9327 9328 // Visit all inputs, collect all binary operations (and, or, xor and 9329 // select) that are all fed by truncations. 9330 while (!BinOps.empty()) { 9331 SDValue BinOp = BinOps.back(); 9332 BinOps.pop_back(); 9333 9334 if (!Visited.insert(BinOp.getNode()).second) 9335 continue; 9336 9337 PromOps.push_back(BinOp); 9338 9339 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 9340 // The condition of the select is not promoted. 9341 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 9342 continue; 9343 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 9344 continue; 9345 9346 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 9347 isa<ConstantSDNode>(BinOp.getOperand(i))) { 9348 Inputs.push_back(BinOp.getOperand(i)); 9349 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 9350 BinOp.getOperand(i).getOpcode() == ISD::OR || 9351 BinOp.getOperand(i).getOpcode() == ISD::XOR || 9352 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 9353 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 9354 BinOps.push_back(BinOp.getOperand(i)); 9355 } else { 9356 // We have an input that is not a truncation or another binary 9357 // operation; we'll abort this transformation. 9358 return SDValue(); 9359 } 9360 } 9361 } 9362 9363 // The operands of a select that must be truncated when the select is 9364 // promoted because the operand is actually part of the to-be-promoted set. 9365 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 9366 9367 // Make sure that this is a self-contained cluster of operations (which 9368 // is not quite the same thing as saying that everything has only one 9369 // use). 9370 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 9371 if (isa<ConstantSDNode>(Inputs[i])) 9372 continue; 9373 9374 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 9375 UE = Inputs[i].getNode()->use_end(); 9376 UI != UE; ++UI) { 9377 SDNode *User = *UI; 9378 if (User != N && !Visited.count(User)) 9379 return SDValue(); 9380 9381 // If we're going to promote the non-output-value operand(s) or SELECT or 9382 // SELECT_CC, record them for truncation. 9383 if (User->getOpcode() == ISD::SELECT) { 9384 if (User->getOperand(0) == Inputs[i]) 9385 SelectTruncOp[0].insert(std::make_pair(User, 9386 User->getOperand(0).getValueType())); 9387 } else if (User->getOpcode() == ISD::SELECT_CC) { 9388 if (User->getOperand(0) == Inputs[i]) 9389 SelectTruncOp[0].insert(std::make_pair(User, 9390 User->getOperand(0).getValueType())); 9391 if (User->getOperand(1) == Inputs[i]) 9392 SelectTruncOp[1].insert(std::make_pair(User, 9393 User->getOperand(1).getValueType())); 9394 } 9395 } 9396 } 9397 9398 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 9399 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 9400 UE = PromOps[i].getNode()->use_end(); 9401 UI != UE; ++UI) { 9402 SDNode *User = *UI; 9403 if (User != N && !Visited.count(User)) 9404 return SDValue(); 9405 9406 // If we're going to promote the non-output-value operand(s) or SELECT or 9407 // SELECT_CC, record them for truncation. 9408 if (User->getOpcode() == ISD::SELECT) { 9409 if (User->getOperand(0) == PromOps[i]) 9410 SelectTruncOp[0].insert(std::make_pair(User, 9411 User->getOperand(0).getValueType())); 9412 } else if (User->getOpcode() == ISD::SELECT_CC) { 9413 if (User->getOperand(0) == PromOps[i]) 9414 SelectTruncOp[0].insert(std::make_pair(User, 9415 User->getOperand(0).getValueType())); 9416 if (User->getOperand(1) == PromOps[i]) 9417 SelectTruncOp[1].insert(std::make_pair(User, 9418 User->getOperand(1).getValueType())); 9419 } 9420 } 9421 } 9422 9423 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 9424 bool ReallyNeedsExt = false; 9425 if (N->getOpcode() != ISD::ANY_EXTEND) { 9426 // If all of the inputs are not already sign/zero extended, then 9427 // we'll still need to do that at the end. 9428 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 9429 if (isa<ConstantSDNode>(Inputs[i])) 9430 continue; 9431 9432 unsigned OpBits = 9433 Inputs[i].getOperand(0).getValueSizeInBits(); 9434 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 9435 9436 if ((N->getOpcode() == ISD::ZERO_EXTEND && 9437 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 9438 APInt::getHighBitsSet(OpBits, 9439 OpBits-PromBits))) || 9440 (N->getOpcode() == ISD::SIGN_EXTEND && 9441 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 9442 (OpBits-(PromBits-1)))) { 9443 ReallyNeedsExt = true; 9444 break; 9445 } 9446 } 9447 } 9448 9449 // Replace all inputs, either with the truncation operand, or a 9450 // truncation or extension to the final output type. 9451 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 9452 // Constant inputs need to be replaced with the to-be-promoted nodes that 9453 // use them because they might have users outside of the cluster of 9454 // promoted nodes. 9455 if (isa<ConstantSDNode>(Inputs[i])) 9456 continue; 9457 9458 SDValue InSrc = Inputs[i].getOperand(0); 9459 if (Inputs[i].getValueType() == N->getValueType(0)) 9460 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 9461 else if (N->getOpcode() == ISD::SIGN_EXTEND) 9462 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 9463 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 9464 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9465 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 9466 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 9467 else 9468 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 9469 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 9470 } 9471 9472 // Replace all operations (these are all the same, but have a different 9473 // (promoted) return type). DAG.getNode will validate that the types of 9474 // a binary operator match, so go through the list in reverse so that 9475 // we've likely promoted both operands first. 9476 while (!PromOps.empty()) { 9477 SDValue PromOp = PromOps.back(); 9478 PromOps.pop_back(); 9479 9480 unsigned C; 9481 switch (PromOp.getOpcode()) { 9482 default: C = 0; break; 9483 case ISD::SELECT: C = 1; break; 9484 case ISD::SELECT_CC: C = 2; break; 9485 } 9486 9487 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 9488 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 9489 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 9490 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 9491 // The to-be-promoted operands of this node have not yet been 9492 // promoted (this should be rare because we're going through the 9493 // list backward, but if one of the operands has several users in 9494 // this cluster of to-be-promoted nodes, it is possible). 9495 PromOps.insert(PromOps.begin(), PromOp); 9496 continue; 9497 } 9498 9499 // For SELECT and SELECT_CC nodes, we do a similar check for any 9500 // to-be-promoted comparison inputs. 9501 if (PromOp.getOpcode() == ISD::SELECT || 9502 PromOp.getOpcode() == ISD::SELECT_CC) { 9503 if ((SelectTruncOp[0].count(PromOp.getNode()) && 9504 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 9505 (SelectTruncOp[1].count(PromOp.getNode()) && 9506 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 9507 PromOps.insert(PromOps.begin(), PromOp); 9508 continue; 9509 } 9510 } 9511 9512 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 9513 PromOp.getNode()->op_end()); 9514 9515 // If this node has constant inputs, then they'll need to be promoted here. 9516 for (unsigned i = 0; i < 2; ++i) { 9517 if (!isa<ConstantSDNode>(Ops[C+i])) 9518 continue; 9519 if (Ops[C+i].getValueType() == N->getValueType(0)) 9520 continue; 9521 9522 if (N->getOpcode() == ISD::SIGN_EXTEND) 9523 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 9524 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9525 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 9526 else 9527 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 9528 } 9529 9530 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 9531 // truncate them again to the original value type. 9532 if (PromOp.getOpcode() == ISD::SELECT || 9533 PromOp.getOpcode() == ISD::SELECT_CC) { 9534 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 9535 if (SI0 != SelectTruncOp[0].end()) 9536 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 9537 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 9538 if (SI1 != SelectTruncOp[1].end()) 9539 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 9540 } 9541 9542 DAG.ReplaceAllUsesOfValueWith(PromOp, 9543 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 9544 } 9545 9546 // Now we're left with the initial extension itself. 9547 if (!ReallyNeedsExt) 9548 return N->getOperand(0); 9549 9550 // To zero extend, just mask off everything except for the first bit (in the 9551 // i1 case). 9552 if (N->getOpcode() == ISD::ZERO_EXTEND) 9553 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 9554 DAG.getConstant(APInt::getLowBitsSet( 9555 N->getValueSizeInBits(0), PromBits), 9556 N->getValueType(0))); 9557 9558 assert(N->getOpcode() == ISD::SIGN_EXTEND && 9559 "Invalid extension type"); 9560 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0)); 9561 SDValue ShiftCst = 9562 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy); 9563 return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 9564 DAG.getNode(ISD::SHL, dl, N->getValueType(0), 9565 N->getOperand(0), ShiftCst), ShiftCst); 9566 } 9567 9568 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 9569 DAGCombinerInfo &DCI) const { 9570 assert((N->getOpcode() == ISD::SINT_TO_FP || 9571 N->getOpcode() == ISD::UINT_TO_FP) && 9572 "Need an int -> FP conversion node here"); 9573 9574 if (!Subtarget.has64BitSupport()) 9575 return SDValue(); 9576 9577 SelectionDAG &DAG = DCI.DAG; 9578 SDLoc dl(N); 9579 SDValue Op(N, 0); 9580 9581 // Don't handle ppc_fp128 here or i1 conversions. 9582 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 9583 return SDValue(); 9584 if (Op.getOperand(0).getValueType() == MVT::i1) 9585 return SDValue(); 9586 9587 // For i32 intermediate values, unfortunately, the conversion functions 9588 // leave the upper 32 bits of the value are undefined. Within the set of 9589 // scalar instructions, we have no method for zero- or sign-extending the 9590 // value. Thus, we cannot handle i32 intermediate values here. 9591 if (Op.getOperand(0).getValueType() == MVT::i32) 9592 return SDValue(); 9593 9594 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 9595 "UINT_TO_FP is supported only with FPCVT"); 9596 9597 // If we have FCFIDS, then use it when converting to single-precision. 9598 // Otherwise, convert to double-precision and then round. 9599 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 9600 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 9601 : PPCISD::FCFIDS) 9602 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 9603 : PPCISD::FCFID); 9604 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 9605 ? MVT::f32 9606 : MVT::f64; 9607 9608 // If we're converting from a float, to an int, and back to a float again, 9609 // then we don't need the store/load pair at all. 9610 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 9611 Subtarget.hasFPCVT()) || 9612 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 9613 SDValue Src = Op.getOperand(0).getOperand(0); 9614 if (Src.getValueType() == MVT::f32) { 9615 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 9616 DCI.AddToWorklist(Src.getNode()); 9617 } 9618 9619 unsigned FCTOp = 9620 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 9621 PPCISD::FCTIDUZ; 9622 9623 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 9624 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 9625 9626 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 9627 FP = DAG.getNode(ISD::FP_ROUND, dl, 9628 MVT::f32, FP, DAG.getIntPtrConstant(0)); 9629 DCI.AddToWorklist(FP.getNode()); 9630 } 9631 9632 return FP; 9633 } 9634 9635 return SDValue(); 9636 } 9637 9638 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 9639 // builtins) into loads with swaps. 9640 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 9641 DAGCombinerInfo &DCI) const { 9642 SelectionDAG &DAG = DCI.DAG; 9643 SDLoc dl(N); 9644 SDValue Chain; 9645 SDValue Base; 9646 MachineMemOperand *MMO; 9647 9648 switch (N->getOpcode()) { 9649 default: 9650 llvm_unreachable("Unexpected opcode for little endian VSX load"); 9651 case ISD::LOAD: { 9652 LoadSDNode *LD = cast<LoadSDNode>(N); 9653 Chain = LD->getChain(); 9654 Base = LD->getBasePtr(); 9655 MMO = LD->getMemOperand(); 9656 // If the MMO suggests this isn't a load of a full vector, leave 9657 // things alone. For a built-in, we have to make the change for 9658 // correctness, so if there is a size problem that will be a bug. 9659 if (MMO->getSize() < 16) 9660 return SDValue(); 9661 break; 9662 } 9663 case ISD::INTRINSIC_W_CHAIN: { 9664 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 9665 Chain = Intrin->getChain(); 9666 Base = Intrin->getBasePtr(); 9667 MMO = Intrin->getMemOperand(); 9668 break; 9669 } 9670 } 9671 9672 MVT VecTy = N->getValueType(0).getSimpleVT(); 9673 SDValue LoadOps[] = { Chain, Base }; 9674 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 9675 DAG.getVTList(VecTy, MVT::Other), 9676 LoadOps, VecTy, MMO); 9677 DCI.AddToWorklist(Load.getNode()); 9678 Chain = Load.getValue(1); 9679 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 9680 DAG.getVTList(VecTy, MVT::Other), Chain, Load); 9681 DCI.AddToWorklist(Swap.getNode()); 9682 return Swap; 9683 } 9684 9685 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 9686 // builtins) into stores with swaps. 9687 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 9688 DAGCombinerInfo &DCI) const { 9689 SelectionDAG &DAG = DCI.DAG; 9690 SDLoc dl(N); 9691 SDValue Chain; 9692 SDValue Base; 9693 unsigned SrcOpnd; 9694 MachineMemOperand *MMO; 9695 9696 switch (N->getOpcode()) { 9697 default: 9698 llvm_unreachable("Unexpected opcode for little endian VSX store"); 9699 case ISD::STORE: { 9700 StoreSDNode *ST = cast<StoreSDNode>(N); 9701 Chain = ST->getChain(); 9702 Base = ST->getBasePtr(); 9703 MMO = ST->getMemOperand(); 9704 SrcOpnd = 1; 9705 // If the MMO suggests this isn't a store of a full vector, leave 9706 // things alone. For a built-in, we have to make the change for 9707 // correctness, so if there is a size problem that will be a bug. 9708 if (MMO->getSize() < 16) 9709 return SDValue(); 9710 break; 9711 } 9712 case ISD::INTRINSIC_VOID: { 9713 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 9714 Chain = Intrin->getChain(); 9715 // Intrin->getBasePtr() oddly does not get what we want. 9716 Base = Intrin->getOperand(3); 9717 MMO = Intrin->getMemOperand(); 9718 SrcOpnd = 2; 9719 break; 9720 } 9721 } 9722 9723 SDValue Src = N->getOperand(SrcOpnd); 9724 MVT VecTy = Src.getValueType().getSimpleVT(); 9725 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 9726 DAG.getVTList(VecTy, MVT::Other), Chain, Src); 9727 DCI.AddToWorklist(Swap.getNode()); 9728 Chain = Swap.getValue(1); 9729 SDValue StoreOps[] = { Chain, Swap, Base }; 9730 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 9731 DAG.getVTList(MVT::Other), 9732 StoreOps, VecTy, MMO); 9733 DCI.AddToWorklist(Store.getNode()); 9734 return Store; 9735 } 9736 9737 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 9738 DAGCombinerInfo &DCI) const { 9739 SelectionDAG &DAG = DCI.DAG; 9740 SDLoc dl(N); 9741 switch (N->getOpcode()) { 9742 default: break; 9743 case PPCISD::SHL: 9744 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 9745 if (C->isNullValue()) // 0 << V -> 0. 9746 return N->getOperand(0); 9747 } 9748 break; 9749 case PPCISD::SRL: 9750 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 9751 if (C->isNullValue()) // 0 >>u V -> 0. 9752 return N->getOperand(0); 9753 } 9754 break; 9755 case PPCISD::SRA: 9756 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 9757 if (C->isNullValue() || // 0 >>s V -> 0. 9758 C->isAllOnesValue()) // -1 >>s V -> -1. 9759 return N->getOperand(0); 9760 } 9761 break; 9762 case ISD::SIGN_EXTEND: 9763 case ISD::ZERO_EXTEND: 9764 case ISD::ANY_EXTEND: 9765 return DAGCombineExtBoolTrunc(N, DCI); 9766 case ISD::TRUNCATE: 9767 case ISD::SETCC: 9768 case ISD::SELECT_CC: 9769 return DAGCombineTruncBoolExt(N, DCI); 9770 case ISD::SINT_TO_FP: 9771 case ISD::UINT_TO_FP: 9772 return combineFPToIntToFP(N, DCI); 9773 case ISD::STORE: { 9774 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)). 9775 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() && 9776 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT && 9777 N->getOperand(1).getValueType() == MVT::i32 && 9778 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) { 9779 SDValue Val = N->getOperand(1).getOperand(0); 9780 if (Val.getValueType() == MVT::f32) { 9781 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 9782 DCI.AddToWorklist(Val.getNode()); 9783 } 9784 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val); 9785 DCI.AddToWorklist(Val.getNode()); 9786 9787 SDValue Ops[] = { 9788 N->getOperand(0), Val, N->getOperand(2), 9789 DAG.getValueType(N->getOperand(1).getValueType()) 9790 }; 9791 9792 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 9793 DAG.getVTList(MVT::Other), Ops, 9794 cast<StoreSDNode>(N)->getMemoryVT(), 9795 cast<StoreSDNode>(N)->getMemOperand()); 9796 DCI.AddToWorklist(Val.getNode()); 9797 return Val; 9798 } 9799 9800 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 9801 if (cast<StoreSDNode>(N)->isUnindexed() && 9802 N->getOperand(1).getOpcode() == ISD::BSWAP && 9803 N->getOperand(1).getNode()->hasOneUse() && 9804 (N->getOperand(1).getValueType() == MVT::i32 || 9805 N->getOperand(1).getValueType() == MVT::i16 || 9806 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 9807 N->getOperand(1).getValueType() == MVT::i64))) { 9808 SDValue BSwapOp = N->getOperand(1).getOperand(0); 9809 // Do an any-extend to 32-bits if this is a half-word input. 9810 if (BSwapOp.getValueType() == MVT::i16) 9811 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 9812 9813 SDValue Ops[] = { 9814 N->getOperand(0), BSwapOp, N->getOperand(2), 9815 DAG.getValueType(N->getOperand(1).getValueType()) 9816 }; 9817 return 9818 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 9819 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 9820 cast<StoreSDNode>(N)->getMemOperand()); 9821 } 9822 9823 // For little endian, VSX stores require generating xxswapd/lxvd2x. 9824 EVT VT = N->getOperand(1).getValueType(); 9825 if (VT.isSimple()) { 9826 MVT StoreVT = VT.getSimpleVT(); 9827 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() && 9828 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 9829 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 9830 return expandVSXStoreForLE(N, DCI); 9831 } 9832 break; 9833 } 9834 case ISD::LOAD: { 9835 LoadSDNode *LD = cast<LoadSDNode>(N); 9836 EVT VT = LD->getValueType(0); 9837 9838 // For little endian, VSX loads require generating lxvd2x/xxswapd. 9839 if (VT.isSimple()) { 9840 MVT LoadVT = VT.getSimpleVT(); 9841 if (Subtarget.hasVSX() && Subtarget.isLittleEndian() && 9842 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 9843 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 9844 return expandVSXLoadForLE(N, DCI); 9845 } 9846 9847 EVT MemVT = LD->getMemoryVT(); 9848 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 9849 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty); 9850 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 9851 unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy); 9852 if (LD->isUnindexed() && VT.isVector() && 9853 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 9854 // P8 and later hardware should just use LOAD. 9855 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 9856 VT == MVT::v4i32 || VT == MVT::v4f32)) || 9857 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 9858 LD->getAlignment() >= ScalarABIAlignment)) && 9859 LD->getAlignment() < ABIAlignment) { 9860 // This is a type-legal unaligned Altivec or QPX load. 9861 SDValue Chain = LD->getChain(); 9862 SDValue Ptr = LD->getBasePtr(); 9863 bool isLittleEndian = Subtarget.isLittleEndian(); 9864 9865 // This implements the loading of unaligned vectors as described in 9866 // the venerable Apple Velocity Engine overview. Specifically: 9867 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 9868 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 9869 // 9870 // The general idea is to expand a sequence of one or more unaligned 9871 // loads into an alignment-based permutation-control instruction (lvsl 9872 // or lvsr), a series of regular vector loads (which always truncate 9873 // their input address to an aligned address), and a series of 9874 // permutations. The results of these permutations are the requested 9875 // loaded values. The trick is that the last "extra" load is not taken 9876 // from the address you might suspect (sizeof(vector) bytes after the 9877 // last requested load), but rather sizeof(vector) - 1 bytes after the 9878 // last requested vector. The point of this is to avoid a page fault if 9879 // the base address happened to be aligned. This works because if the 9880 // base address is aligned, then adding less than a full vector length 9881 // will cause the last vector in the sequence to be (re)loaded. 9882 // Otherwise, the next vector will be fetched as you might suspect was 9883 // necessary. 9884 9885 // We might be able to reuse the permutation generation from 9886 // a different base address offset from this one by an aligned amount. 9887 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 9888 // optimization later. 9889 Intrinsic::ID Intr, IntrLD, IntrPerm; 9890 MVT PermCntlTy, PermTy, LDTy; 9891 if (Subtarget.hasAltivec()) { 9892 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 9893 Intrinsic::ppc_altivec_lvsl; 9894 IntrLD = Intrinsic::ppc_altivec_lvx; 9895 IntrPerm = Intrinsic::ppc_altivec_vperm; 9896 PermCntlTy = MVT::v16i8; 9897 PermTy = MVT::v4i32; 9898 LDTy = MVT::v4i32; 9899 } else { 9900 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 9901 Intrinsic::ppc_qpx_qvlpcls; 9902 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 9903 Intrinsic::ppc_qpx_qvlfs; 9904 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 9905 PermCntlTy = MVT::v4f64; 9906 PermTy = MVT::v4f64; 9907 LDTy = MemVT.getSimpleVT(); 9908 } 9909 9910 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 9911 9912 // Create the new MMO for the new base load. It is like the original MMO, 9913 // but represents an area in memory almost twice the vector size centered 9914 // on the original address. If the address is unaligned, we might start 9915 // reading up to (sizeof(vector)-1) bytes below the address of the 9916 // original unaligned load. 9917 MachineFunction &MF = DAG.getMachineFunction(); 9918 MachineMemOperand *BaseMMO = 9919 MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1, 9920 2*MemVT.getStoreSize()-1); 9921 9922 // Create the new base load. 9923 SDValue LDXIntID = DAG.getTargetConstant(IntrLD, getPointerTy()); 9924 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 9925 SDValue BaseLoad = 9926 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 9927 DAG.getVTList(PermTy, MVT::Other), 9928 BaseLoadOps, LDTy, BaseMMO); 9929 9930 // Note that the value of IncOffset (which is provided to the next 9931 // load's pointer info offset value, and thus used to calculate the 9932 // alignment), and the value of IncValue (which is actually used to 9933 // increment the pointer value) are different! This is because we 9934 // require the next load to appear to be aligned, even though it 9935 // is actually offset from the base pointer by a lesser amount. 9936 int IncOffset = VT.getSizeInBits() / 8; 9937 int IncValue = IncOffset; 9938 9939 // Walk (both up and down) the chain looking for another load at the real 9940 // (aligned) offset (the alignment of the other load does not matter in 9941 // this case). If found, then do not use the offset reduction trick, as 9942 // that will prevent the loads from being later combined (as they would 9943 // otherwise be duplicates). 9944 if (!findConsecutiveLoad(LD, DAG)) 9945 --IncValue; 9946 9947 SDValue Increment = DAG.getConstant(IncValue, getPointerTy()); 9948 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 9949 9950 MachineMemOperand *ExtraMMO = 9951 MF.getMachineMemOperand(LD->getMemOperand(), 9952 1, 2*MemVT.getStoreSize()-1); 9953 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 9954 SDValue ExtraLoad = 9955 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 9956 DAG.getVTList(PermTy, MVT::Other), 9957 ExtraLoadOps, LDTy, ExtraMMO); 9958 9959 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 9960 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 9961 9962 // Because vperm has a big-endian bias, we must reverse the order 9963 // of the input vectors and complement the permute control vector 9964 // when generating little endian code. We have already handled the 9965 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 9966 // and ExtraLoad here. 9967 SDValue Perm; 9968 if (isLittleEndian) 9969 Perm = BuildIntrinsicOp(IntrPerm, 9970 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 9971 else 9972 Perm = BuildIntrinsicOp(IntrPerm, 9973 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 9974 9975 if (VT != PermTy) 9976 Perm = Subtarget.hasAltivec() ? 9977 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 9978 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 9979 DAG.getTargetConstant(1, MVT::i64)); 9980 // second argument is 1 because this rounding 9981 // is always exact. 9982 9983 // The output of the permutation is our loaded result, the TokenFactor is 9984 // our new chain. 9985 DCI.CombineTo(N, Perm, TF); 9986 return SDValue(N, 0); 9987 } 9988 } 9989 break; 9990 case ISD::INTRINSIC_WO_CHAIN: { 9991 bool isLittleEndian = Subtarget.isLittleEndian(); 9992 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9993 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 9994 : Intrinsic::ppc_altivec_lvsl); 9995 if ((IID == Intr || 9996 IID == Intrinsic::ppc_qpx_qvlpcld || 9997 IID == Intrinsic::ppc_qpx_qvlpcls) && 9998 N->getOperand(1)->getOpcode() == ISD::ADD) { 9999 SDValue Add = N->getOperand(1); 10000 10001 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 10002 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 10003 10004 if (DAG.MaskedValueIsZero( 10005 Add->getOperand(1), 10006 APInt::getAllOnesValue(Bits /* alignment */) 10007 .zext( 10008 Add.getValueType().getScalarType().getSizeInBits()))) { 10009 SDNode *BasePtr = Add->getOperand(0).getNode(); 10010 for (SDNode::use_iterator UI = BasePtr->use_begin(), 10011 UE = BasePtr->use_end(); 10012 UI != UE; ++UI) { 10013 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 10014 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 10015 // We've found another LVSL/LVSR, and this address is an aligned 10016 // multiple of that one. The results will be the same, so use the 10017 // one we've just found instead. 10018 10019 return SDValue(*UI, 0); 10020 } 10021 } 10022 } 10023 10024 if (isa<ConstantSDNode>(Add->getOperand(1))) { 10025 SDNode *BasePtr = Add->getOperand(0).getNode(); 10026 for (SDNode::use_iterator UI = BasePtr->use_begin(), 10027 UE = BasePtr->use_end(); UI != UE; ++UI) { 10028 if (UI->getOpcode() == ISD::ADD && 10029 isa<ConstantSDNode>(UI->getOperand(1)) && 10030 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 10031 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 10032 (1ULL << Bits) == 0) { 10033 SDNode *OtherAdd = *UI; 10034 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 10035 VE = OtherAdd->use_end(); VI != VE; ++VI) { 10036 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 10037 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 10038 return SDValue(*VI, 0); 10039 } 10040 } 10041 } 10042 } 10043 } 10044 } 10045 } 10046 10047 break; 10048 case ISD::INTRINSIC_W_CHAIN: { 10049 // For little endian, VSX loads require generating lxvd2x/xxswapd. 10050 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) { 10051 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10052 default: 10053 break; 10054 case Intrinsic::ppc_vsx_lxvw4x: 10055 case Intrinsic::ppc_vsx_lxvd2x: 10056 return expandVSXLoadForLE(N, DCI); 10057 } 10058 } 10059 break; 10060 } 10061 case ISD::INTRINSIC_VOID: { 10062 // For little endian, VSX stores require generating xxswapd/stxvd2x. 10063 if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) { 10064 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10065 default: 10066 break; 10067 case Intrinsic::ppc_vsx_stxvw4x: 10068 case Intrinsic::ppc_vsx_stxvd2x: 10069 return expandVSXStoreForLE(N, DCI); 10070 } 10071 } 10072 break; 10073 } 10074 case ISD::BSWAP: 10075 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 10076 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 10077 N->getOperand(0).hasOneUse() && 10078 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 10079 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 10080 N->getValueType(0) == MVT::i64))) { 10081 SDValue Load = N->getOperand(0); 10082 LoadSDNode *LD = cast<LoadSDNode>(Load); 10083 // Create the byte-swapping load. 10084 SDValue Ops[] = { 10085 LD->getChain(), // Chain 10086 LD->getBasePtr(), // Ptr 10087 DAG.getValueType(N->getValueType(0)) // VT 10088 }; 10089 SDValue BSLoad = 10090 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 10091 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 10092 MVT::i64 : MVT::i32, MVT::Other), 10093 Ops, LD->getMemoryVT(), LD->getMemOperand()); 10094 10095 // If this is an i16 load, insert the truncate. 10096 SDValue ResVal = BSLoad; 10097 if (N->getValueType(0) == MVT::i16) 10098 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 10099 10100 // First, combine the bswap away. This makes the value produced by the 10101 // load dead. 10102 DCI.CombineTo(N, ResVal); 10103 10104 // Next, combine the load away, we give it a bogus result value but a real 10105 // chain result. The result value is dead because the bswap is dead. 10106 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 10107 10108 // Return N so it doesn't get rechecked! 10109 return SDValue(N, 0); 10110 } 10111 10112 break; 10113 case PPCISD::VCMP: { 10114 // If a VCMPo node already exists with exactly the same operands as this 10115 // node, use its result instead of this node (VCMPo computes both a CR6 and 10116 // a normal output). 10117 // 10118 if (!N->getOperand(0).hasOneUse() && 10119 !N->getOperand(1).hasOneUse() && 10120 !N->getOperand(2).hasOneUse()) { 10121 10122 // Scan all of the users of the LHS, looking for VCMPo's that match. 10123 SDNode *VCMPoNode = nullptr; 10124 10125 SDNode *LHSN = N->getOperand(0).getNode(); 10126 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 10127 UI != E; ++UI) 10128 if (UI->getOpcode() == PPCISD::VCMPo && 10129 UI->getOperand(1) == N->getOperand(1) && 10130 UI->getOperand(2) == N->getOperand(2) && 10131 UI->getOperand(0) == N->getOperand(0)) { 10132 VCMPoNode = *UI; 10133 break; 10134 } 10135 10136 // If there is no VCMPo node, or if the flag value has a single use, don't 10137 // transform this. 10138 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 10139 break; 10140 10141 // Look at the (necessarily single) use of the flag value. If it has a 10142 // chain, this transformation is more complex. Note that multiple things 10143 // could use the value result, which we should ignore. 10144 SDNode *FlagUser = nullptr; 10145 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 10146 FlagUser == nullptr; ++UI) { 10147 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 10148 SDNode *User = *UI; 10149 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 10150 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 10151 FlagUser = User; 10152 break; 10153 } 10154 } 10155 } 10156 10157 // If the user is a MFOCRF instruction, we know this is safe. 10158 // Otherwise we give up for right now. 10159 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 10160 return SDValue(VCMPoNode, 0); 10161 } 10162 break; 10163 } 10164 case ISD::BRCOND: { 10165 SDValue Cond = N->getOperand(1); 10166 SDValue Target = N->getOperand(2); 10167 10168 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 10169 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 10170 Intrinsic::ppc_is_decremented_ctr_nonzero) { 10171 10172 // We now need to make the intrinsic dead (it cannot be instruction 10173 // selected). 10174 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 10175 assert(Cond.getNode()->hasOneUse() && 10176 "Counter decrement has more than one use"); 10177 10178 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 10179 N->getOperand(0), Target); 10180 } 10181 } 10182 break; 10183 case ISD::BR_CC: { 10184 // If this is a branch on an altivec predicate comparison, lower this so 10185 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 10186 // lowering is done pre-legalize, because the legalizer lowers the predicate 10187 // compare down to code that is difficult to reassemble. 10188 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 10189 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 10190 10191 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 10192 // value. If so, pass-through the AND to get to the intrinsic. 10193 if (LHS.getOpcode() == ISD::AND && 10194 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 10195 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 10196 Intrinsic::ppc_is_decremented_ctr_nonzero && 10197 isa<ConstantSDNode>(LHS.getOperand(1)) && 10198 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()-> 10199 isZero()) 10200 LHS = LHS.getOperand(0); 10201 10202 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 10203 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 10204 Intrinsic::ppc_is_decremented_ctr_nonzero && 10205 isa<ConstantSDNode>(RHS)) { 10206 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 10207 "Counter decrement comparison is not EQ or NE"); 10208 10209 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 10210 bool isBDNZ = (CC == ISD::SETEQ && Val) || 10211 (CC == ISD::SETNE && !Val); 10212 10213 // We now need to make the intrinsic dead (it cannot be instruction 10214 // selected). 10215 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 10216 assert(LHS.getNode()->hasOneUse() && 10217 "Counter decrement has more than one use"); 10218 10219 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 10220 N->getOperand(0), N->getOperand(4)); 10221 } 10222 10223 int CompareOpc; 10224 bool isDot; 10225 10226 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 10227 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 10228 getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 10229 assert(isDot && "Can't compare against a vector result!"); 10230 10231 // If this is a comparison against something other than 0/1, then we know 10232 // that the condition is never/always true. 10233 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 10234 if (Val != 0 && Val != 1) { 10235 if (CC == ISD::SETEQ) // Cond never true, remove branch. 10236 return N->getOperand(0); 10237 // Always !=, turn it into an unconditional branch. 10238 return DAG.getNode(ISD::BR, dl, MVT::Other, 10239 N->getOperand(0), N->getOperand(4)); 10240 } 10241 10242 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 10243 10244 // Create the PPCISD altivec 'dot' comparison node. 10245 SDValue Ops[] = { 10246 LHS.getOperand(2), // LHS of compare 10247 LHS.getOperand(3), // RHS of compare 10248 DAG.getConstant(CompareOpc, MVT::i32) 10249 }; 10250 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 10251 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10252 10253 // Unpack the result based on how the target uses it. 10254 PPC::Predicate CompOpc; 10255 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 10256 default: // Can't happen, don't crash on invalid number though. 10257 case 0: // Branch on the value of the EQ bit of CR6. 10258 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 10259 break; 10260 case 1: // Branch on the inverted value of the EQ bit of CR6. 10261 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 10262 break; 10263 case 2: // Branch on the value of the LT bit of CR6. 10264 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 10265 break; 10266 case 3: // Branch on the inverted value of the LT bit of CR6. 10267 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 10268 break; 10269 } 10270 10271 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 10272 DAG.getConstant(CompOpc, MVT::i32), 10273 DAG.getRegister(PPC::CR6, MVT::i32), 10274 N->getOperand(4), CompNode.getValue(1)); 10275 } 10276 break; 10277 } 10278 } 10279 10280 return SDValue(); 10281 } 10282 10283 SDValue 10284 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 10285 SelectionDAG &DAG, 10286 std::vector<SDNode *> *Created) const { 10287 // fold (sdiv X, pow2) 10288 EVT VT = N->getValueType(0); 10289 if (VT == MVT::i64 && !Subtarget.isPPC64()) 10290 return SDValue(); 10291 if ((VT != MVT::i32 && VT != MVT::i64) || 10292 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 10293 return SDValue(); 10294 10295 SDLoc DL(N); 10296 SDValue N0 = N->getOperand(0); 10297 10298 bool IsNegPow2 = (-Divisor).isPowerOf2(); 10299 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 10300 SDValue ShiftAmt = DAG.getConstant(Lg2, VT); 10301 10302 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 10303 if (Created) 10304 Created->push_back(Op.getNode()); 10305 10306 if (IsNegPow2) { 10307 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op); 10308 if (Created) 10309 Created->push_back(Op.getNode()); 10310 } 10311 10312 return Op; 10313 } 10314 10315 //===----------------------------------------------------------------------===// 10316 // Inline Assembly Support 10317 //===----------------------------------------------------------------------===// 10318 10319 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 10320 APInt &KnownZero, 10321 APInt &KnownOne, 10322 const SelectionDAG &DAG, 10323 unsigned Depth) const { 10324 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0); 10325 switch (Op.getOpcode()) { 10326 default: break; 10327 case PPCISD::LBRX: { 10328 // lhbrx is known to have the top bits cleared out. 10329 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 10330 KnownZero = 0xFFFF0000; 10331 break; 10332 } 10333 case ISD::INTRINSIC_WO_CHAIN: { 10334 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 10335 default: break; 10336 case Intrinsic::ppc_altivec_vcmpbfp_p: 10337 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10338 case Intrinsic::ppc_altivec_vcmpequb_p: 10339 case Intrinsic::ppc_altivec_vcmpequh_p: 10340 case Intrinsic::ppc_altivec_vcmpequw_p: 10341 case Intrinsic::ppc_altivec_vcmpequd_p: 10342 case Intrinsic::ppc_altivec_vcmpgefp_p: 10343 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10344 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10345 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10346 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10347 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10348 case Intrinsic::ppc_altivec_vcmpgtub_p: 10349 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10350 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10351 case Intrinsic::ppc_altivec_vcmpgtud_p: 10352 KnownZero = ~1U; // All bits but the low one are known to be zero. 10353 break; 10354 } 10355 } 10356 } 10357 } 10358 10359 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10360 switch (Subtarget.getDarwinDirective()) { 10361 default: break; 10362 case PPC::DIR_970: 10363 case PPC::DIR_PWR4: 10364 case PPC::DIR_PWR5: 10365 case PPC::DIR_PWR5X: 10366 case PPC::DIR_PWR6: 10367 case PPC::DIR_PWR6X: 10368 case PPC::DIR_PWR7: 10369 case PPC::DIR_PWR8: { 10370 if (!ML) 10371 break; 10372 10373 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 10374 10375 // For small loops (between 5 and 8 instructions), align to a 32-byte 10376 // boundary so that the entire loop fits in one instruction-cache line. 10377 uint64_t LoopSize = 0; 10378 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 10379 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) 10380 LoopSize += TII->GetInstSizeInBytes(J); 10381 10382 if (LoopSize > 16 && LoopSize <= 32) 10383 return 5; 10384 10385 break; 10386 } 10387 } 10388 10389 return TargetLowering::getPrefLoopAlignment(ML); 10390 } 10391 10392 /// getConstraintType - Given a constraint, return the type of 10393 /// constraint it is for this target. 10394 PPCTargetLowering::ConstraintType 10395 PPCTargetLowering::getConstraintType(const std::string &Constraint) const { 10396 if (Constraint.size() == 1) { 10397 switch (Constraint[0]) { 10398 default: break; 10399 case 'b': 10400 case 'r': 10401 case 'f': 10402 case 'v': 10403 case 'y': 10404 return C_RegisterClass; 10405 case 'Z': 10406 // FIXME: While Z does indicate a memory constraint, it specifically 10407 // indicates an r+r address (used in conjunction with the 'y' modifier 10408 // in the replacement string). Currently, we're forcing the base 10409 // register to be r0 in the asm printer (which is interpreted as zero) 10410 // and forming the complete address in the second register. This is 10411 // suboptimal. 10412 return C_Memory; 10413 } 10414 } else if (Constraint == "wc") { // individual CR bits. 10415 return C_RegisterClass; 10416 } else if (Constraint == "wa" || Constraint == "wd" || 10417 Constraint == "wf" || Constraint == "ws") { 10418 return C_RegisterClass; // VSX registers. 10419 } 10420 return TargetLowering::getConstraintType(Constraint); 10421 } 10422 10423 /// Examine constraint type and operand type and determine a weight value. 10424 /// This object must already have been set up with the operand type 10425 /// and the current alternative constraint selected. 10426 TargetLowering::ConstraintWeight 10427 PPCTargetLowering::getSingleConstraintMatchWeight( 10428 AsmOperandInfo &info, const char *constraint) const { 10429 ConstraintWeight weight = CW_Invalid; 10430 Value *CallOperandVal = info.CallOperandVal; 10431 // If we don't have a value, we can't do a match, 10432 // but allow it at the lowest weight. 10433 if (!CallOperandVal) 10434 return CW_Default; 10435 Type *type = CallOperandVal->getType(); 10436 10437 // Look at the constraint type. 10438 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 10439 return CW_Register; // an individual CR bit. 10440 else if ((StringRef(constraint) == "wa" || 10441 StringRef(constraint) == "wd" || 10442 StringRef(constraint) == "wf") && 10443 type->isVectorTy()) 10444 return CW_Register; 10445 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 10446 return CW_Register; 10447 10448 switch (*constraint) { 10449 default: 10450 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 10451 break; 10452 case 'b': 10453 if (type->isIntegerTy()) 10454 weight = CW_Register; 10455 break; 10456 case 'f': 10457 if (type->isFloatTy()) 10458 weight = CW_Register; 10459 break; 10460 case 'd': 10461 if (type->isDoubleTy()) 10462 weight = CW_Register; 10463 break; 10464 case 'v': 10465 if (type->isVectorTy()) 10466 weight = CW_Register; 10467 break; 10468 case 'y': 10469 weight = CW_Register; 10470 break; 10471 case 'Z': 10472 weight = CW_Memory; 10473 break; 10474 } 10475 return weight; 10476 } 10477 10478 std::pair<unsigned, const TargetRegisterClass *> 10479 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10480 const std::string &Constraint, 10481 MVT VT) const { 10482 if (Constraint.size() == 1) { 10483 // GCC RS6000 Constraint Letters 10484 switch (Constraint[0]) { 10485 case 'b': // R1-R31 10486 if (VT == MVT::i64 && Subtarget.isPPC64()) 10487 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 10488 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 10489 case 'r': // R0-R31 10490 if (VT == MVT::i64 && Subtarget.isPPC64()) 10491 return std::make_pair(0U, &PPC::G8RCRegClass); 10492 return std::make_pair(0U, &PPC::GPRCRegClass); 10493 case 'f': 10494 if (VT == MVT::f32 || VT == MVT::i32) 10495 return std::make_pair(0U, &PPC::F4RCRegClass); 10496 if (VT == MVT::f64 || VT == MVT::i64) 10497 return std::make_pair(0U, &PPC::F8RCRegClass); 10498 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 10499 return std::make_pair(0U, &PPC::QFRCRegClass); 10500 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 10501 return std::make_pair(0U, &PPC::QSRCRegClass); 10502 break; 10503 case 'v': 10504 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 10505 return std::make_pair(0U, &PPC::QFRCRegClass); 10506 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 10507 return std::make_pair(0U, &PPC::QSRCRegClass); 10508 return std::make_pair(0U, &PPC::VRRCRegClass); 10509 case 'y': // crrc 10510 return std::make_pair(0U, &PPC::CRRCRegClass); 10511 } 10512 } else if (Constraint == "wc") { // an individual CR bit. 10513 return std::make_pair(0U, &PPC::CRBITRCRegClass); 10514 } else if (Constraint == "wa" || Constraint == "wd" || 10515 Constraint == "wf") { 10516 return std::make_pair(0U, &PPC::VSRCRegClass); 10517 } else if (Constraint == "ws") { 10518 return std::make_pair(0U, &PPC::VSFRCRegClass); 10519 } 10520 10521 std::pair<unsigned, const TargetRegisterClass *> R = 10522 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10523 10524 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 10525 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 10526 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 10527 // register. 10528 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 10529 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 10530 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 10531 PPC::GPRCRegClass.contains(R.first)) 10532 return std::make_pair(TRI->getMatchingSuperReg(R.first, 10533 PPC::sub_32, &PPC::G8RCRegClass), 10534 &PPC::G8RCRegClass); 10535 10536 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 10537 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 10538 R.first = PPC::CR0; 10539 R.second = &PPC::CRRCRegClass; 10540 } 10541 10542 return R; 10543 } 10544 10545 10546 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 10547 /// vector. If it is invalid, don't add anything to Ops. 10548 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 10549 std::string &Constraint, 10550 std::vector<SDValue>&Ops, 10551 SelectionDAG &DAG) const { 10552 SDValue Result; 10553 10554 // Only support length 1 constraints. 10555 if (Constraint.length() > 1) return; 10556 10557 char Letter = Constraint[0]; 10558 switch (Letter) { 10559 default: break; 10560 case 'I': 10561 case 'J': 10562 case 'K': 10563 case 'L': 10564 case 'M': 10565 case 'N': 10566 case 'O': 10567 case 'P': { 10568 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 10569 if (!CST) return; // Must be an immediate to match. 10570 int64_t Value = CST->getSExtValue(); 10571 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 10572 // numbers are printed as such. 10573 switch (Letter) { 10574 default: llvm_unreachable("Unknown constraint letter!"); 10575 case 'I': // "I" is a signed 16-bit constant. 10576 if (isInt<16>(Value)) 10577 Result = DAG.getTargetConstant(Value, TCVT); 10578 break; 10579 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 10580 if (isShiftedUInt<16, 16>(Value)) 10581 Result = DAG.getTargetConstant(Value, TCVT); 10582 break; 10583 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 10584 if (isShiftedInt<16, 16>(Value)) 10585 Result = DAG.getTargetConstant(Value, TCVT); 10586 break; 10587 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 10588 if (isUInt<16>(Value)) 10589 Result = DAG.getTargetConstant(Value, TCVT); 10590 break; 10591 case 'M': // "M" is a constant that is greater than 31. 10592 if (Value > 31) 10593 Result = DAG.getTargetConstant(Value, TCVT); 10594 break; 10595 case 'N': // "N" is a positive constant that is an exact power of two. 10596 if (Value > 0 && isPowerOf2_64(Value)) 10597 Result = DAG.getTargetConstant(Value, TCVT); 10598 break; 10599 case 'O': // "O" is the constant zero. 10600 if (Value == 0) 10601 Result = DAG.getTargetConstant(Value, TCVT); 10602 break; 10603 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 10604 if (isInt<16>(-Value)) 10605 Result = DAG.getTargetConstant(Value, TCVT); 10606 break; 10607 } 10608 break; 10609 } 10610 } 10611 10612 if (Result.getNode()) { 10613 Ops.push_back(Result); 10614 return; 10615 } 10616 10617 // Handle standard constraint letters. 10618 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10619 } 10620 10621 // isLegalAddressingMode - Return true if the addressing mode represented 10622 // by AM is legal for this target, for a load/store of the specified type. 10623 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM, 10624 Type *Ty) const { 10625 // PPC does not allow r+i addressing modes for vectors! 10626 if (Ty->isVectorTy() && AM.BaseOffs != 0) 10627 return false; 10628 10629 // PPC allows a sign-extended 16-bit immediate field. 10630 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 10631 return false; 10632 10633 // No global is ever allowed as a base. 10634 if (AM.BaseGV) 10635 return false; 10636 10637 // PPC only support r+r, 10638 switch (AM.Scale) { 10639 case 0: // "r+i" or just "i", depending on HasBaseReg. 10640 break; 10641 case 1: 10642 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 10643 return false; 10644 // Otherwise we have r+r or r+i. 10645 break; 10646 case 2: 10647 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 10648 return false; 10649 // Allow 2*r as r+r. 10650 break; 10651 default: 10652 // No other scales are supported. 10653 return false; 10654 } 10655 10656 return true; 10657 } 10658 10659 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 10660 SelectionDAG &DAG) const { 10661 MachineFunction &MF = DAG.getMachineFunction(); 10662 MachineFrameInfo *MFI = MF.getFrameInfo(); 10663 MFI->setReturnAddressIsTaken(true); 10664 10665 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 10666 return SDValue(); 10667 10668 SDLoc dl(Op); 10669 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10670 10671 // Make sure the function does not optimize away the store of the RA to 10672 // the stack. 10673 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 10674 FuncInfo->setLRStoreRequired(); 10675 bool isPPC64 = Subtarget.isPPC64(); 10676 10677 if (Depth > 0) { 10678 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 10679 SDValue Offset = 10680 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), 10681 isPPC64 ? MVT::i64 : MVT::i32); 10682 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 10683 DAG.getNode(ISD::ADD, dl, getPointerTy(), 10684 FrameAddr, Offset), 10685 MachinePointerInfo(), false, false, false, 0); 10686 } 10687 10688 // Just load the return address off the stack. 10689 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 10690 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 10691 RetAddrFI, MachinePointerInfo(), false, false, false, 0); 10692 } 10693 10694 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 10695 SelectionDAG &DAG) const { 10696 SDLoc dl(Op); 10697 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10698 10699 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 10700 bool isPPC64 = PtrVT == MVT::i64; 10701 10702 MachineFunction &MF = DAG.getMachineFunction(); 10703 MachineFrameInfo *MFI = MF.getFrameInfo(); 10704 MFI->setFrameAddressIsTaken(true); 10705 10706 // Naked functions never have a frame pointer, and so we use r1. For all 10707 // other functions, this decision must be delayed until during PEI. 10708 unsigned FrameReg; 10709 if (MF.getFunction()->hasFnAttribute(Attribute::Naked)) 10710 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 10711 else 10712 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 10713 10714 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 10715 PtrVT); 10716 while (Depth--) 10717 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 10718 FrameAddr, MachinePointerInfo(), false, false, 10719 false, 0); 10720 return FrameAddr; 10721 } 10722 10723 // FIXME? Maybe this could be a TableGen attribute on some registers and 10724 // this table could be generated automatically from RegInfo. 10725 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, 10726 EVT VT) const { 10727 bool isPPC64 = Subtarget.isPPC64(); 10728 bool isDarwinABI = Subtarget.isDarwinABI(); 10729 10730 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 10731 (!isPPC64 && VT != MVT::i32)) 10732 report_fatal_error("Invalid register global variable type"); 10733 10734 bool is64Bit = isPPC64 && VT == MVT::i64; 10735 unsigned Reg = StringSwitch<unsigned>(RegName) 10736 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 10737 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 10738 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 10739 (is64Bit ? PPC::X13 : PPC::R13)) 10740 .Default(0); 10741 10742 if (Reg) 10743 return Reg; 10744 report_fatal_error("Invalid register name global variable"); 10745 } 10746 10747 bool 10748 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 10749 // The PowerPC target isn't yet aware of offsets. 10750 return false; 10751 } 10752 10753 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 10754 const CallInst &I, 10755 unsigned Intrinsic) const { 10756 10757 switch (Intrinsic) { 10758 case Intrinsic::ppc_qpx_qvlfd: 10759 case Intrinsic::ppc_qpx_qvlfs: 10760 case Intrinsic::ppc_qpx_qvlfcd: 10761 case Intrinsic::ppc_qpx_qvlfcs: 10762 case Intrinsic::ppc_qpx_qvlfiwa: 10763 case Intrinsic::ppc_qpx_qvlfiwz: 10764 case Intrinsic::ppc_altivec_lvx: 10765 case Intrinsic::ppc_altivec_lvxl: 10766 case Intrinsic::ppc_altivec_lvebx: 10767 case Intrinsic::ppc_altivec_lvehx: 10768 case Intrinsic::ppc_altivec_lvewx: 10769 case Intrinsic::ppc_vsx_lxvd2x: 10770 case Intrinsic::ppc_vsx_lxvw4x: { 10771 EVT VT; 10772 switch (Intrinsic) { 10773 case Intrinsic::ppc_altivec_lvebx: 10774 VT = MVT::i8; 10775 break; 10776 case Intrinsic::ppc_altivec_lvehx: 10777 VT = MVT::i16; 10778 break; 10779 case Intrinsic::ppc_altivec_lvewx: 10780 VT = MVT::i32; 10781 break; 10782 case Intrinsic::ppc_vsx_lxvd2x: 10783 VT = MVT::v2f64; 10784 break; 10785 case Intrinsic::ppc_qpx_qvlfd: 10786 VT = MVT::v4f64; 10787 break; 10788 case Intrinsic::ppc_qpx_qvlfs: 10789 VT = MVT::v4f32; 10790 break; 10791 case Intrinsic::ppc_qpx_qvlfcd: 10792 VT = MVT::v2f64; 10793 break; 10794 case Intrinsic::ppc_qpx_qvlfcs: 10795 VT = MVT::v2f32; 10796 break; 10797 default: 10798 VT = MVT::v4i32; 10799 break; 10800 } 10801 10802 Info.opc = ISD::INTRINSIC_W_CHAIN; 10803 Info.memVT = VT; 10804 Info.ptrVal = I.getArgOperand(0); 10805 Info.offset = -VT.getStoreSize()+1; 10806 Info.size = 2*VT.getStoreSize()-1; 10807 Info.align = 1; 10808 Info.vol = false; 10809 Info.readMem = true; 10810 Info.writeMem = false; 10811 return true; 10812 } 10813 case Intrinsic::ppc_qpx_qvlfda: 10814 case Intrinsic::ppc_qpx_qvlfsa: 10815 case Intrinsic::ppc_qpx_qvlfcda: 10816 case Intrinsic::ppc_qpx_qvlfcsa: 10817 case Intrinsic::ppc_qpx_qvlfiwaa: 10818 case Intrinsic::ppc_qpx_qvlfiwza: { 10819 EVT VT; 10820 switch (Intrinsic) { 10821 case Intrinsic::ppc_qpx_qvlfda: 10822 VT = MVT::v4f64; 10823 break; 10824 case Intrinsic::ppc_qpx_qvlfsa: 10825 VT = MVT::v4f32; 10826 break; 10827 case Intrinsic::ppc_qpx_qvlfcda: 10828 VT = MVT::v2f64; 10829 break; 10830 case Intrinsic::ppc_qpx_qvlfcsa: 10831 VT = MVT::v2f32; 10832 break; 10833 default: 10834 VT = MVT::v4i32; 10835 break; 10836 } 10837 10838 Info.opc = ISD::INTRINSIC_W_CHAIN; 10839 Info.memVT = VT; 10840 Info.ptrVal = I.getArgOperand(0); 10841 Info.offset = 0; 10842 Info.size = VT.getStoreSize(); 10843 Info.align = 1; 10844 Info.vol = false; 10845 Info.readMem = true; 10846 Info.writeMem = false; 10847 return true; 10848 } 10849 case Intrinsic::ppc_qpx_qvstfd: 10850 case Intrinsic::ppc_qpx_qvstfs: 10851 case Intrinsic::ppc_qpx_qvstfcd: 10852 case Intrinsic::ppc_qpx_qvstfcs: 10853 case Intrinsic::ppc_qpx_qvstfiw: 10854 case Intrinsic::ppc_altivec_stvx: 10855 case Intrinsic::ppc_altivec_stvxl: 10856 case Intrinsic::ppc_altivec_stvebx: 10857 case Intrinsic::ppc_altivec_stvehx: 10858 case Intrinsic::ppc_altivec_stvewx: 10859 case Intrinsic::ppc_vsx_stxvd2x: 10860 case Intrinsic::ppc_vsx_stxvw4x: { 10861 EVT VT; 10862 switch (Intrinsic) { 10863 case Intrinsic::ppc_altivec_stvebx: 10864 VT = MVT::i8; 10865 break; 10866 case Intrinsic::ppc_altivec_stvehx: 10867 VT = MVT::i16; 10868 break; 10869 case Intrinsic::ppc_altivec_stvewx: 10870 VT = MVT::i32; 10871 break; 10872 case Intrinsic::ppc_vsx_stxvd2x: 10873 VT = MVT::v2f64; 10874 break; 10875 case Intrinsic::ppc_qpx_qvstfd: 10876 VT = MVT::v4f64; 10877 break; 10878 case Intrinsic::ppc_qpx_qvstfs: 10879 VT = MVT::v4f32; 10880 break; 10881 case Intrinsic::ppc_qpx_qvstfcd: 10882 VT = MVT::v2f64; 10883 break; 10884 case Intrinsic::ppc_qpx_qvstfcs: 10885 VT = MVT::v2f32; 10886 break; 10887 default: 10888 VT = MVT::v4i32; 10889 break; 10890 } 10891 10892 Info.opc = ISD::INTRINSIC_VOID; 10893 Info.memVT = VT; 10894 Info.ptrVal = I.getArgOperand(1); 10895 Info.offset = -VT.getStoreSize()+1; 10896 Info.size = 2*VT.getStoreSize()-1; 10897 Info.align = 1; 10898 Info.vol = false; 10899 Info.readMem = false; 10900 Info.writeMem = true; 10901 return true; 10902 } 10903 case Intrinsic::ppc_qpx_qvstfda: 10904 case Intrinsic::ppc_qpx_qvstfsa: 10905 case Intrinsic::ppc_qpx_qvstfcda: 10906 case Intrinsic::ppc_qpx_qvstfcsa: 10907 case Intrinsic::ppc_qpx_qvstfiwa: { 10908 EVT VT; 10909 switch (Intrinsic) { 10910 case Intrinsic::ppc_qpx_qvstfda: 10911 VT = MVT::v4f64; 10912 break; 10913 case Intrinsic::ppc_qpx_qvstfsa: 10914 VT = MVT::v4f32; 10915 break; 10916 case Intrinsic::ppc_qpx_qvstfcda: 10917 VT = MVT::v2f64; 10918 break; 10919 case Intrinsic::ppc_qpx_qvstfcsa: 10920 VT = MVT::v2f32; 10921 break; 10922 default: 10923 VT = MVT::v4i32; 10924 break; 10925 } 10926 10927 Info.opc = ISD::INTRINSIC_VOID; 10928 Info.memVT = VT; 10929 Info.ptrVal = I.getArgOperand(1); 10930 Info.offset = 0; 10931 Info.size = VT.getStoreSize(); 10932 Info.align = 1; 10933 Info.vol = false; 10934 Info.readMem = false; 10935 Info.writeMem = true; 10936 return true; 10937 } 10938 default: 10939 break; 10940 } 10941 10942 return false; 10943 } 10944 10945 /// getOptimalMemOpType - Returns the target specific optimal type for load 10946 /// and store operations as a result of memset, memcpy, and memmove 10947 /// lowering. If DstAlign is zero that means it's safe to destination 10948 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 10949 /// means there isn't a need to check it against alignment requirement, 10950 /// probably because the source does not need to be loaded. If 'IsMemset' is 10951 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 10952 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 10953 /// source is constant so it does not need to be loaded. 10954 /// It returns EVT::Other if the type should be determined using generic 10955 /// target-independent logic. 10956 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 10957 unsigned DstAlign, unsigned SrcAlign, 10958 bool IsMemset, bool ZeroMemset, 10959 bool MemcpyStrSrc, 10960 MachineFunction &MF) const { 10961 const Function *F = MF.getFunction(); 10962 // When expanding a memset, require at least two QPX instructions to cover 10963 // the cost of loading the value to be stored from the constant pool. 10964 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 10965 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 10966 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 10967 return MVT::v4f64; 10968 } 10969 10970 // We should use Altivec/VSX loads and stores when available. For unaligned 10971 // addresses, unaligned VSX loads are only fast starting with the P8. 10972 if (Subtarget.hasAltivec() && Size >= 16 && 10973 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 10974 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 10975 return MVT::v4i32; 10976 10977 if (Subtarget.isPPC64()) { 10978 return MVT::i64; 10979 } 10980 10981 return MVT::i32; 10982 } 10983 10984 /// \brief Returns true if it is beneficial to convert a load of a constant 10985 /// to just the constant itself. 10986 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 10987 Type *Ty) const { 10988 assert(Ty->isIntegerTy()); 10989 10990 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 10991 if (BitSize == 0 || BitSize > 64) 10992 return false; 10993 return true; 10994 } 10995 10996 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 10997 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10998 return false; 10999 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 11000 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 11001 return NumBits1 == 64 && NumBits2 == 32; 11002 } 11003 11004 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 11005 if (!VT1.isInteger() || !VT2.isInteger()) 11006 return false; 11007 unsigned NumBits1 = VT1.getSizeInBits(); 11008 unsigned NumBits2 = VT2.getSizeInBits(); 11009 return NumBits1 == 64 && NumBits2 == 32; 11010 } 11011 11012 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 11013 // Generally speaking, zexts are not free, but they are free when they can be 11014 // folded with other operations. 11015 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 11016 EVT MemVT = LD->getMemoryVT(); 11017 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 11018 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 11019 (LD->getExtensionType() == ISD::NON_EXTLOAD || 11020 LD->getExtensionType() == ISD::ZEXTLOAD)) 11021 return true; 11022 } 11023 11024 // FIXME: Add other cases... 11025 // - 32-bit shifts with a zext to i64 11026 // - zext after ctlz, bswap, etc. 11027 // - zext after and by a constant mask 11028 11029 return TargetLowering::isZExtFree(Val, VT2); 11030 } 11031 11032 bool PPCTargetLowering::isFPExtFree(EVT VT) const { 11033 assert(VT.isFloatingPoint()); 11034 return true; 11035 } 11036 11037 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 11038 return isInt<16>(Imm) || isUInt<16>(Imm); 11039 } 11040 11041 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 11042 return isInt<16>(Imm) || isUInt<16>(Imm); 11043 } 11044 11045 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 11046 unsigned, 11047 unsigned, 11048 bool *Fast) const { 11049 if (DisablePPCUnaligned) 11050 return false; 11051 11052 // PowerPC supports unaligned memory access for simple non-vector types. 11053 // Although accessing unaligned addresses is not as efficient as accessing 11054 // aligned addresses, it is generally more efficient than manual expansion, 11055 // and generally only traps for software emulation when crossing page 11056 // boundaries. 11057 11058 if (!VT.isSimple()) 11059 return false; 11060 11061 if (VT.getSimpleVT().isVector()) { 11062 if (Subtarget.hasVSX()) { 11063 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 11064 VT != MVT::v4f32 && VT != MVT::v4i32) 11065 return false; 11066 } else { 11067 return false; 11068 } 11069 } 11070 11071 if (VT == MVT::ppcf128) 11072 return false; 11073 11074 if (Fast) 11075 *Fast = true; 11076 11077 return true; 11078 } 11079 11080 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 11081 VT = VT.getScalarType(); 11082 11083 if (!VT.isSimple()) 11084 return false; 11085 11086 switch (VT.getSimpleVT().SimpleTy) { 11087 case MVT::f32: 11088 case MVT::f64: 11089 return true; 11090 default: 11091 break; 11092 } 11093 11094 return false; 11095 } 11096 11097 const MCPhysReg * 11098 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 11099 // LR is a callee-save register, but we must treat it as clobbered by any call 11100 // site. Hence we include LR in the scratch registers, which are in turn added 11101 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 11102 // to CTR, which is used by any indirect call. 11103 static const MCPhysReg ScratchRegs[] = { 11104 PPC::X12, PPC::LR8, PPC::CTR8, 0 11105 }; 11106 11107 return ScratchRegs; 11108 } 11109 11110 bool 11111 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 11112 EVT VT , unsigned DefinedValues) const { 11113 if (VT == MVT::v2i64) 11114 return false; 11115 11116 if (Subtarget.hasQPX()) { 11117 if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1) 11118 return true; 11119 } 11120 11121 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 11122 } 11123 11124 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 11125 if (DisableILPPref || Subtarget.enableMachineScheduler()) 11126 return TargetLowering::getSchedulingPreference(N); 11127 11128 return Sched::ILP; 11129 } 11130 11131 // Create a fast isel object. 11132 FastISel * 11133 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 11134 const TargetLibraryInfo *LibInfo) const { 11135 return PPC::createFastISel(FuncInfo, LibInfo); 11136 } 11137