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 "PPCMachineFunctionInfo.h" 16 #include "PPCPerfectShuffle.h" 17 #include "PPCTargetMachine.h" 18 #include "MCTargetDesc/PPCPredicates.h" 19 #include "llvm/CallingConv.h" 20 #include "llvm/Constants.h" 21 #include "llvm/DerivedTypes.h" 22 #include "llvm/Function.h" 23 #include "llvm/Intrinsics.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/CodeGen/CallingConvLower.h" 26 #include "llvm/CodeGen/MachineFrameInfo.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineInstrBuilder.h" 29 #include "llvm/CodeGen/MachineRegisterInfo.h" 30 #include "llvm/CodeGen/SelectionDAG.h" 31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetOptions.h" 37 using namespace llvm; 38 39 static bool CC_PPC_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 40 CCValAssign::LocInfo &LocInfo, 41 ISD::ArgFlagsTy &ArgFlags, 42 CCState &State); 43 static bool CC_PPC_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 44 MVT &LocVT, 45 CCValAssign::LocInfo &LocInfo, 46 ISD::ArgFlagsTy &ArgFlags, 47 CCState &State); 48 static bool CC_PPC_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 49 MVT &LocVT, 50 CCValAssign::LocInfo &LocInfo, 51 ISD::ArgFlagsTy &ArgFlags, 52 CCState &State); 53 54 static cl::opt<bool> EnablePPCPreinc("enable-ppc-preinc", 55 cl::desc("enable preincrement load/store generation on PPC (experimental)"), 56 cl::Hidden); 57 58 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) { 59 if (TM.getSubtargetImpl()->isDarwin()) 60 return new TargetLoweringObjectFileMachO(); 61 62 return new TargetLoweringObjectFileELF(); 63 } 64 65 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM) 66 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) { 67 68 setPow2DivIsCheap(); 69 70 // Use _setjmp/_longjmp instead of setjmp/longjmp. 71 setUseUnderscoreSetJmp(true); 72 setUseUnderscoreLongJmp(true); 73 74 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 75 // arguments are at least 4/8 bytes aligned. 76 setMinStackArgumentAlignment(TM.getSubtarget<PPCSubtarget>().isPPC64() ? 8:4); 77 78 // Set up the register classes. 79 addRegisterClass(MVT::i32, PPC::GPRCRegisterClass); 80 addRegisterClass(MVT::f32, PPC::F4RCRegisterClass); 81 addRegisterClass(MVT::f64, PPC::F8RCRegisterClass); 82 83 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD 84 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 85 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand); 86 87 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 88 89 // PowerPC has pre-inc load and store's. 90 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 91 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 92 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 93 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 94 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 95 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 96 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 97 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 98 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 99 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 100 101 // This is used in the ppcf128->int sequence. Note it has different semantics 102 // from FP_ROUND: that rounds to nearest, this rounds to zero. 103 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom); 104 105 // We do not currently implment this libm ops for PowerPC. 106 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 107 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 108 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 109 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 110 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 111 112 // PowerPC has no SREM/UREM instructions 113 setOperationAction(ISD::SREM, MVT::i32, Expand); 114 setOperationAction(ISD::UREM, MVT::i32, Expand); 115 setOperationAction(ISD::SREM, MVT::i64, Expand); 116 setOperationAction(ISD::UREM, MVT::i64, Expand); 117 118 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 119 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 120 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 121 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 122 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 123 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 124 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 125 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 126 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 127 128 // We don't support sin/cos/sqrt/fmod/pow 129 setOperationAction(ISD::FSIN , MVT::f64, Expand); 130 setOperationAction(ISD::FCOS , MVT::f64, Expand); 131 setOperationAction(ISD::FREM , MVT::f64, Expand); 132 setOperationAction(ISD::FPOW , MVT::f64, Expand); 133 setOperationAction(ISD::FMA , MVT::f64, Expand); 134 setOperationAction(ISD::FSIN , MVT::f32, Expand); 135 setOperationAction(ISD::FCOS , MVT::f32, Expand); 136 setOperationAction(ISD::FREM , MVT::f32, Expand); 137 setOperationAction(ISD::FPOW , MVT::f32, Expand); 138 setOperationAction(ISD::FMA , MVT::f32, Expand); 139 140 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 141 142 // If we're enabling GP optimizations, use hardware square root 143 if (!TM.getSubtarget<PPCSubtarget>().hasFSQRT()) { 144 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 145 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 146 } 147 148 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 149 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 150 151 // PowerPC does not have BSWAP, CTPOP or CTTZ 152 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 153 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 154 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 155 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand); 156 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand); 157 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 158 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 159 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 160 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand); 161 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand); 162 163 // PowerPC does not have ROTR 164 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 165 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 166 167 // PowerPC does not have Select 168 setOperationAction(ISD::SELECT, MVT::i32, Expand); 169 setOperationAction(ISD::SELECT, MVT::i64, Expand); 170 setOperationAction(ISD::SELECT, MVT::f32, Expand); 171 setOperationAction(ISD::SELECT, MVT::f64, Expand); 172 173 // PowerPC wants to turn select_cc of FP into fsel when possible. 174 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 175 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 176 177 // PowerPC wants to optimize integer setcc a bit 178 setOperationAction(ISD::SETCC, MVT::i32, Custom); 179 180 // PowerPC does not have BRCOND which requires SetCC 181 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 182 183 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 184 185 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 186 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 187 188 // PowerPC does not have [U|S]INT_TO_FP 189 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 190 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 191 192 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 193 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 194 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 195 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 196 197 // We cannot sextinreg(i1). Expand to shifts. 198 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 199 200 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand); 201 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand); 202 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand); 203 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand); 204 205 206 // We want to legalize GlobalAddress and ConstantPool nodes into the 207 // appropriate instructions to materialize the address. 208 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 209 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 210 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 211 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 212 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 213 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 214 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 215 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 216 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 217 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 218 219 // TRAP is legal. 220 setOperationAction(ISD::TRAP, MVT::Other, Legal); 221 222 // TRAMPOLINE is custom lowered. 223 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 224 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 225 226 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 227 setOperationAction(ISD::VASTART , MVT::Other, Custom); 228 229 if (TM.getSubtarget<PPCSubtarget>().isSVR4ABI()) { 230 if (TM.getSubtarget<PPCSubtarget>().isPPC64()) { 231 // VAARG always uses double-word chunks, so promote anything smaller. 232 setOperationAction(ISD::VAARG, MVT::i1, Promote); 233 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 234 setOperationAction(ISD::VAARG, MVT::i8, Promote); 235 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 236 setOperationAction(ISD::VAARG, MVT::i16, Promote); 237 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 238 setOperationAction(ISD::VAARG, MVT::i32, Promote); 239 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 240 setOperationAction(ISD::VAARG, MVT::Other, Expand); 241 } else { 242 // VAARG is custom lowered with the 32-bit SVR4 ABI. 243 setOperationAction(ISD::VAARG, MVT::Other, Custom); 244 setOperationAction(ISD::VAARG, MVT::i64, Custom); 245 } 246 } else 247 setOperationAction(ISD::VAARG, MVT::Other, Expand); 248 249 // Use the default implementation. 250 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 251 setOperationAction(ISD::VAEND , MVT::Other, Expand); 252 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 253 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 254 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 255 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 256 257 // We want to custom lower some of our intrinsics. 258 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 259 260 // Comparisons that require checking two conditions. 261 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 262 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 263 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 264 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 265 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 266 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 267 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 268 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 269 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 270 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 271 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 272 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 273 274 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) { 275 // They also have instructions for converting between i64 and fp. 276 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 277 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 278 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 279 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 280 // This is just the low 32 bits of a (signed) fp->i64 conversion. 281 // We cannot do this with Promote because i64 is not a legal type. 282 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 283 284 // FIXME: disable this lowered code. This generates 64-bit register values, 285 // and we don't model the fact that the top part is clobbered by calls. We 286 // need to flag these together so that the value isn't live across a call. 287 //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 288 } else { 289 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 290 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 291 } 292 293 if (TM.getSubtarget<PPCSubtarget>().use64BitRegs()) { 294 // 64-bit PowerPC implementations can support i64 types directly 295 addRegisterClass(MVT::i64, PPC::G8RCRegisterClass); 296 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 297 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 298 // 64-bit PowerPC wants to expand i128 shifts itself. 299 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 300 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 301 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 302 } else { 303 // 32-bit PowerPC wants to expand i64 shifts itself. 304 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 305 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 306 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 307 } 308 309 if (TM.getSubtarget<PPCSubtarget>().hasAltivec()) { 310 // First set operation action for all vector types to expand. Then we 311 // will selectively turn on ones that can be effectively codegen'd. 312 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 313 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) { 314 MVT::SimpleValueType VT = (MVT::SimpleValueType)i; 315 316 // add/sub are legal for all supported vector VT's. 317 setOperationAction(ISD::ADD , VT, Legal); 318 setOperationAction(ISD::SUB , VT, Legal); 319 320 // We promote all shuffles to v16i8. 321 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 322 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 323 324 // We promote all non-typed operations to v4i32. 325 setOperationAction(ISD::AND , VT, Promote); 326 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 327 setOperationAction(ISD::OR , VT, Promote); 328 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 329 setOperationAction(ISD::XOR , VT, Promote); 330 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 331 setOperationAction(ISD::LOAD , VT, Promote); 332 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 333 setOperationAction(ISD::SELECT, VT, Promote); 334 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 335 setOperationAction(ISD::STORE, VT, Promote); 336 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 337 338 // No other operations are legal. 339 setOperationAction(ISD::MUL , VT, Expand); 340 setOperationAction(ISD::SDIV, VT, Expand); 341 setOperationAction(ISD::SREM, VT, Expand); 342 setOperationAction(ISD::UDIV, VT, Expand); 343 setOperationAction(ISD::UREM, VT, Expand); 344 setOperationAction(ISD::FDIV, VT, Expand); 345 setOperationAction(ISD::FNEG, VT, Expand); 346 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 347 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 348 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 349 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 350 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 351 setOperationAction(ISD::UDIVREM, VT, Expand); 352 setOperationAction(ISD::SDIVREM, VT, Expand); 353 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 354 setOperationAction(ISD::FPOW, VT, Expand); 355 setOperationAction(ISD::CTPOP, VT, Expand); 356 setOperationAction(ISD::CTLZ, VT, Expand); 357 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand); 358 setOperationAction(ISD::CTTZ, VT, Expand); 359 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand); 360 } 361 362 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 363 // with merges, splats, etc. 364 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 365 366 setOperationAction(ISD::AND , MVT::v4i32, Legal); 367 setOperationAction(ISD::OR , MVT::v4i32, Legal); 368 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 369 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 370 setOperationAction(ISD::SELECT, MVT::v4i32, Expand); 371 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 372 373 addRegisterClass(MVT::v4f32, PPC::VRRCRegisterClass); 374 addRegisterClass(MVT::v4i32, PPC::VRRCRegisterClass); 375 addRegisterClass(MVT::v8i16, PPC::VRRCRegisterClass); 376 addRegisterClass(MVT::v16i8, PPC::VRRCRegisterClass); 377 378 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 379 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 380 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 381 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 382 383 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 384 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 385 386 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 387 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 388 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 389 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 390 } 391 392 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand); 393 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand); 394 395 setBooleanContents(ZeroOrOneBooleanContent); 396 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct? 397 398 if (TM.getSubtarget<PPCSubtarget>().isPPC64()) { 399 setStackPointerRegisterToSaveRestore(PPC::X1); 400 setExceptionPointerRegister(PPC::X3); 401 setExceptionSelectorRegister(PPC::X4); 402 } else { 403 setStackPointerRegisterToSaveRestore(PPC::R1); 404 setExceptionPointerRegister(PPC::R3); 405 setExceptionSelectorRegister(PPC::R4); 406 } 407 408 // We have target-specific dag combine patterns for the following nodes: 409 setTargetDAGCombine(ISD::SINT_TO_FP); 410 setTargetDAGCombine(ISD::STORE); 411 setTargetDAGCombine(ISD::BR_CC); 412 setTargetDAGCombine(ISD::BSWAP); 413 414 // Darwin long double math library functions have $LDBL128 appended. 415 if (TM.getSubtarget<PPCSubtarget>().isDarwin()) { 416 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 417 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 418 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 419 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 420 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 421 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 422 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 423 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 424 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 425 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 426 } 427 428 setMinFunctionAlignment(2); 429 if (PPCSubTarget.isDarwin()) 430 setPrefFunctionAlignment(4); 431 432 setInsertFencesForAtomic(true); 433 434 setSchedulingPreference(Sched::Hybrid); 435 436 computeRegisterProperties(); 437 } 438 439 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 440 /// function arguments in the caller parameter area. 441 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const { 442 const TargetMachine &TM = getTargetMachine(); 443 // Darwin passes everything on 4 byte boundary. 444 if (TM.getSubtarget<PPCSubtarget>().isDarwin()) 445 return 4; 446 // FIXME SVR4 TBD 447 return 4; 448 } 449 450 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 451 switch (Opcode) { 452 default: return 0; 453 case PPCISD::FSEL: return "PPCISD::FSEL"; 454 case PPCISD::FCFID: return "PPCISD::FCFID"; 455 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 456 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 457 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 458 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 459 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 460 case PPCISD::VPERM: return "PPCISD::VPERM"; 461 case PPCISD::Hi: return "PPCISD::Hi"; 462 case PPCISD::Lo: return "PPCISD::Lo"; 463 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 464 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE"; 465 case PPCISD::LOAD: return "PPCISD::LOAD"; 466 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC"; 467 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 468 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 469 case PPCISD::SRL: return "PPCISD::SRL"; 470 case PPCISD::SRA: return "PPCISD::SRA"; 471 case PPCISD::SHL: return "PPCISD::SHL"; 472 case PPCISD::EXTSW_32: return "PPCISD::EXTSW_32"; 473 case PPCISD::STD_32: return "PPCISD::STD_32"; 474 case PPCISD::CALL_SVR4: return "PPCISD::CALL_SVR4"; 475 case PPCISD::CALL_Darwin: return "PPCISD::CALL_Darwin"; 476 case PPCISD::NOP: return "PPCISD::NOP"; 477 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 478 case PPCISD::BCTRL_Darwin: return "PPCISD::BCTRL_Darwin"; 479 case PPCISD::BCTRL_SVR4: return "PPCISD::BCTRL_SVR4"; 480 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 481 case PPCISD::MFCR: return "PPCISD::MFCR"; 482 case PPCISD::VCMP: return "PPCISD::VCMP"; 483 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 484 case PPCISD::LBRX: return "PPCISD::LBRX"; 485 case PPCISD::STBRX: return "PPCISD::STBRX"; 486 case PPCISD::LARX: return "PPCISD::LARX"; 487 case PPCISD::STCX: return "PPCISD::STCX"; 488 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 489 case PPCISD::MFFS: return "PPCISD::MFFS"; 490 case PPCISD::MTFSB0: return "PPCISD::MTFSB0"; 491 case PPCISD::MTFSB1: return "PPCISD::MTFSB1"; 492 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 493 case PPCISD::MTFSF: return "PPCISD::MTFSF"; 494 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 495 } 496 } 497 498 EVT PPCTargetLowering::getSetCCResultType(EVT VT) const { 499 return MVT::i32; 500 } 501 502 //===----------------------------------------------------------------------===// 503 // Node matching predicates, for use by the tblgen matching code. 504 //===----------------------------------------------------------------------===// 505 506 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 507 static bool isFloatingPointZero(SDValue Op) { 508 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 509 return CFP->getValueAPF().isZero(); 510 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 511 // Maybe this has already been legalized into the constant pool? 512 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 513 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 514 return CFP->getValueAPF().isZero(); 515 } 516 return false; 517 } 518 519 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 520 /// true if Op is undef or if it matches the specified value. 521 static bool isConstantOrUndef(int Op, int Val) { 522 return Op < 0 || Op == Val; 523 } 524 525 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 526 /// VPKUHUM instruction. 527 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) { 528 if (!isUnary) { 529 for (unsigned i = 0; i != 16; ++i) 530 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 531 return false; 532 } else { 533 for (unsigned i = 0; i != 8; ++i) 534 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) || 535 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1)) 536 return false; 537 } 538 return true; 539 } 540 541 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 542 /// VPKUWUM instruction. 543 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) { 544 if (!isUnary) { 545 for (unsigned i = 0; i != 16; i += 2) 546 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 547 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 548 return false; 549 } else { 550 for (unsigned i = 0; i != 8; i += 2) 551 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 552 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) || 553 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) || 554 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3)) 555 return false; 556 } 557 return true; 558 } 559 560 /// isVMerge - Common function, used to match vmrg* shuffles. 561 /// 562 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 563 unsigned LHSStart, unsigned RHSStart) { 564 assert(N->getValueType(0) == MVT::v16i8 && 565 "PPC only supports shuffles by bytes!"); 566 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 567 "Unsupported merge size!"); 568 569 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 570 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 571 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 572 LHSStart+j+i*UnitSize) || 573 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 574 RHSStart+j+i*UnitSize)) 575 return false; 576 } 577 return true; 578 } 579 580 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 581 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes). 582 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 583 bool isUnary) { 584 if (!isUnary) 585 return isVMerge(N, UnitSize, 8, 24); 586 return isVMerge(N, UnitSize, 8, 8); 587 } 588 589 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 590 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes). 591 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 592 bool isUnary) { 593 if (!isUnary) 594 return isVMerge(N, UnitSize, 0, 16); 595 return isVMerge(N, UnitSize, 0, 0); 596 } 597 598 599 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 600 /// amount, otherwise return -1. 601 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) { 602 assert(N->getValueType(0) == MVT::v16i8 && 603 "PPC only supports shuffles by bytes!"); 604 605 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 606 607 // Find the first non-undef value in the shuffle mask. 608 unsigned i; 609 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 610 /*search*/; 611 612 if (i == 16) return -1; // all undef. 613 614 // Otherwise, check to see if the rest of the elements are consecutively 615 // numbered from this value. 616 unsigned ShiftAmt = SVOp->getMaskElt(i); 617 if (ShiftAmt < i) return -1; 618 ShiftAmt -= i; 619 620 if (!isUnary) { 621 // Check the rest of the elements to see if they are consecutive. 622 for (++i; i != 16; ++i) 623 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 624 return -1; 625 } else { 626 // Check the rest of the elements to see if they are consecutive. 627 for (++i; i != 16; ++i) 628 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 629 return -1; 630 } 631 return ShiftAmt; 632 } 633 634 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 635 /// specifies a splat of a single element that is suitable for input to 636 /// VSPLTB/VSPLTH/VSPLTW. 637 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 638 assert(N->getValueType(0) == MVT::v16i8 && 639 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 640 641 // This is a splat operation if each element of the permute is the same, and 642 // if the value doesn't reference the second vector. 643 unsigned ElementBase = N->getMaskElt(0); 644 645 // FIXME: Handle UNDEF elements too! 646 if (ElementBase >= 16) 647 return false; 648 649 // Check that the indices are consecutive, in the case of a multi-byte element 650 // splatted with a v16i8 mask. 651 for (unsigned i = 1; i != EltSize; ++i) 652 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 653 return false; 654 655 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 656 if (N->getMaskElt(i) < 0) continue; 657 for (unsigned j = 0; j != EltSize; ++j) 658 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 659 return false; 660 } 661 return true; 662 } 663 664 /// isAllNegativeZeroVector - Returns true if all elements of build_vector 665 /// are -0.0. 666 bool PPC::isAllNegativeZeroVector(SDNode *N) { 667 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N); 668 669 APInt APVal, APUndef; 670 unsigned BitSize; 671 bool HasAnyUndefs; 672 673 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true)) 674 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 675 return CFP->getValueAPF().isNegZero(); 676 677 return false; 678 } 679 680 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 681 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 682 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) { 683 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 684 assert(isSplatShuffleMask(SVOp, EltSize)); 685 return SVOp->getMaskElt(0) / EltSize; 686 } 687 688 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 689 /// by using a vspltis[bhw] instruction of the specified element size, return 690 /// the constant being splatted. The ByteSize field indicates the number of 691 /// bytes of each element [124] -> [bhw]. 692 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 693 SDValue OpVal(0, 0); 694 695 // If ByteSize of the splat is bigger than the element size of the 696 // build_vector, then we have a case where we are checking for a splat where 697 // multiple elements of the buildvector are folded together into a single 698 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 699 unsigned EltSize = 16/N->getNumOperands(); 700 if (EltSize < ByteSize) { 701 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 702 SDValue UniquedVals[4]; 703 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 704 705 // See if all of the elements in the buildvector agree across. 706 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 707 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 708 // If the element isn't a constant, bail fully out. 709 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 710 711 712 if (UniquedVals[i&(Multiple-1)].getNode() == 0) 713 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 714 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 715 return SDValue(); // no match. 716 } 717 718 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 719 // either constant or undef values that are identical for each chunk. See 720 // if these chunks can form into a larger vspltis*. 721 722 // Check to see if all of the leading entries are either 0 or -1. If 723 // neither, then this won't fit into the immediate field. 724 bool LeadingZero = true; 725 bool LeadingOnes = true; 726 for (unsigned i = 0; i != Multiple-1; ++i) { 727 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs. 728 729 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue(); 730 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue(); 731 } 732 // Finally, check the least significant entry. 733 if (LeadingZero) { 734 if (UniquedVals[Multiple-1].getNode() == 0) 735 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef 736 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 737 if (Val < 16) 738 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4) 739 } 740 if (LeadingOnes) { 741 if (UniquedVals[Multiple-1].getNode() == 0) 742 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef 743 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 744 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 745 return DAG.getTargetConstant(Val, MVT::i32); 746 } 747 748 return SDValue(); 749 } 750 751 // Check to see if this buildvec has a single non-undef value in its elements. 752 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 753 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; 754 if (OpVal.getNode() == 0) 755 OpVal = N->getOperand(i); 756 else if (OpVal != N->getOperand(i)) 757 return SDValue(); 758 } 759 760 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def. 761 762 unsigned ValSizeInBytes = EltSize; 763 uint64_t Value = 0; 764 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 765 Value = CN->getZExtValue(); 766 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 767 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 768 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 769 } 770 771 // If the splat value is larger than the element value, then we can never do 772 // this splat. The only case that we could fit the replicated bits into our 773 // immediate field for would be zero, and we prefer to use vxor for it. 774 if (ValSizeInBytes < ByteSize) return SDValue(); 775 776 // If the element value is larger than the splat value, cut it in half and 777 // check to see if the two halves are equal. Continue doing this until we 778 // get to ByteSize. This allows us to handle 0x01010101 as 0x01. 779 while (ValSizeInBytes > ByteSize) { 780 ValSizeInBytes >>= 1; 781 782 // If the top half equals the bottom half, we're still ok. 783 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) != 784 (Value & ((1 << (8*ValSizeInBytes))-1))) 785 return SDValue(); 786 } 787 788 // Properly sign extend the value. 789 int ShAmt = (4-ByteSize)*8; 790 int MaskVal = ((int)Value << ShAmt) >> ShAmt; 791 792 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 793 if (MaskVal == 0) return SDValue(); 794 795 // Finally, if this value fits in a 5 bit sext field, return it 796 if (((MaskVal << (32-5)) >> (32-5)) == MaskVal) 797 return DAG.getTargetConstant(MaskVal, MVT::i32); 798 return SDValue(); 799 } 800 801 //===----------------------------------------------------------------------===// 802 // Addressing Mode Selection 803 //===----------------------------------------------------------------------===// 804 805 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 806 /// or 64-bit immediate, and if the value can be accurately represented as a 807 /// sign extension from a 16-bit value. If so, this returns true and the 808 /// immediate. 809 static bool isIntS16Immediate(SDNode *N, short &Imm) { 810 if (N->getOpcode() != ISD::Constant) 811 return false; 812 813 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue(); 814 if (N->getValueType(0) == MVT::i32) 815 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 816 else 817 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 818 } 819 static bool isIntS16Immediate(SDValue Op, short &Imm) { 820 return isIntS16Immediate(Op.getNode(), Imm); 821 } 822 823 824 /// SelectAddressRegReg - Given the specified addressed, check to see if it 825 /// can be represented as an indexed [r+r] operation. Returns false if it 826 /// can be more efficiently represented with [r+imm]. 827 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 828 SDValue &Index, 829 SelectionDAG &DAG) const { 830 short imm = 0; 831 if (N.getOpcode() == ISD::ADD) { 832 if (isIntS16Immediate(N.getOperand(1), imm)) 833 return false; // r+i 834 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 835 return false; // r+i 836 837 Base = N.getOperand(0); 838 Index = N.getOperand(1); 839 return true; 840 } else if (N.getOpcode() == ISD::OR) { 841 if (isIntS16Immediate(N.getOperand(1), imm)) 842 return false; // r+i can fold it if we can. 843 844 // If this is an or of disjoint bitfields, we can codegen this as an add 845 // (for better address arithmetic) if the LHS and RHS of the OR are provably 846 // disjoint. 847 APInt LHSKnownZero, LHSKnownOne; 848 APInt RHSKnownZero, RHSKnownOne; 849 DAG.ComputeMaskedBits(N.getOperand(0), 850 APInt::getAllOnesValue(N.getOperand(0) 851 .getValueSizeInBits()), 852 LHSKnownZero, LHSKnownOne); 853 854 if (LHSKnownZero.getBoolValue()) { 855 DAG.ComputeMaskedBits(N.getOperand(1), 856 APInt::getAllOnesValue(N.getOperand(1) 857 .getValueSizeInBits()), 858 RHSKnownZero, RHSKnownOne); 859 // If all of the bits are known zero on the LHS or RHS, the add won't 860 // carry. 861 if (~(LHSKnownZero | RHSKnownZero) == 0) { 862 Base = N.getOperand(0); 863 Index = N.getOperand(1); 864 return true; 865 } 866 } 867 } 868 869 return false; 870 } 871 872 /// Returns true if the address N can be represented by a base register plus 873 /// a signed 16-bit displacement [r+imm], and if it is not better 874 /// represented as reg+reg. 875 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 876 SDValue &Base, 877 SelectionDAG &DAG) const { 878 // FIXME dl should come from parent load or store, not from address 879 DebugLoc dl = N.getDebugLoc(); 880 // If this can be more profitably realized as r+r, fail. 881 if (SelectAddressRegReg(N, Disp, Base, DAG)) 882 return false; 883 884 if (N.getOpcode() == ISD::ADD) { 885 short imm = 0; 886 if (isIntS16Immediate(N.getOperand(1), imm)) { 887 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32); 888 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 889 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 890 } else { 891 Base = N.getOperand(0); 892 } 893 return true; // [r+i] 894 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 895 // Match LOAD (ADD (X, Lo(G))). 896 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 897 && "Cannot handle constant offsets yet!"); 898 Disp = N.getOperand(1).getOperand(0); // The global address. 899 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 900 Disp.getOpcode() == ISD::TargetConstantPool || 901 Disp.getOpcode() == ISD::TargetJumpTable); 902 Base = N.getOperand(0); 903 return true; // [&g+r] 904 } 905 } else if (N.getOpcode() == ISD::OR) { 906 short imm = 0; 907 if (isIntS16Immediate(N.getOperand(1), imm)) { 908 // If this is an or of disjoint bitfields, we can codegen this as an add 909 // (for better address arithmetic) if the LHS and RHS of the OR are 910 // provably disjoint. 911 APInt LHSKnownZero, LHSKnownOne; 912 DAG.ComputeMaskedBits(N.getOperand(0), 913 APInt::getAllOnesValue(N.getOperand(0) 914 .getValueSizeInBits()), 915 LHSKnownZero, LHSKnownOne); 916 917 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 918 // If all of the bits are known zero on the LHS or RHS, the add won't 919 // carry. 920 Base = N.getOperand(0); 921 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32); 922 return true; 923 } 924 } 925 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 926 // Loading from a constant address. 927 928 // If this address fits entirely in a 16-bit sext immediate field, codegen 929 // this as "d, 0" 930 short Imm; 931 if (isIntS16Immediate(CN, Imm)) { 932 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0)); 933 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0, 934 CN->getValueType(0)); 935 return true; 936 } 937 938 // Handle 32-bit sext immediates with LIS + addr mode. 939 if (CN->getValueType(0) == MVT::i32 || 940 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) { 941 int Addr = (int)CN->getZExtValue(); 942 943 // Otherwise, break this down into an LIS + disp. 944 Disp = DAG.getTargetConstant((short)Addr, MVT::i32); 945 946 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32); 947 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 948 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 949 return true; 950 } 951 } 952 953 Disp = DAG.getTargetConstant(0, getPointerTy()); 954 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) 955 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 956 else 957 Base = N; 958 return true; // [r+0] 959 } 960 961 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 962 /// represented as an indexed [r+r] operation. 963 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 964 SDValue &Index, 965 SelectionDAG &DAG) const { 966 // Check to see if we can easily represent this as an [r+r] address. This 967 // will fail if it thinks that the address is more profitably represented as 968 // reg+imm, e.g. where imm = 0. 969 if (SelectAddressRegReg(N, Base, Index, DAG)) 970 return true; 971 972 // If the operand is an addition, always emit this as [r+r], since this is 973 // better (for code size, and execution, as the memop does the add for free) 974 // than emitting an explicit add. 975 if (N.getOpcode() == ISD::ADD) { 976 Base = N.getOperand(0); 977 Index = N.getOperand(1); 978 return true; 979 } 980 981 // Otherwise, do it the hard way, using R0 as the base register. 982 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0, 983 N.getValueType()); 984 Index = N; 985 return true; 986 } 987 988 /// SelectAddressRegImmShift - Returns true if the address N can be 989 /// represented by a base register plus a signed 14-bit displacement 990 /// [r+imm*4]. Suitable for use by STD and friends. 991 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp, 992 SDValue &Base, 993 SelectionDAG &DAG) const { 994 // FIXME dl should come from the parent load or store, not the address 995 DebugLoc dl = N.getDebugLoc(); 996 // If this can be more profitably realized as r+r, fail. 997 if (SelectAddressRegReg(N, Disp, Base, DAG)) 998 return false; 999 1000 if (N.getOpcode() == ISD::ADD) { 1001 short imm = 0; 1002 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) { 1003 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32); 1004 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 1005 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1006 } else { 1007 Base = N.getOperand(0); 1008 } 1009 return true; // [r+i] 1010 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 1011 // Match LOAD (ADD (X, Lo(G))). 1012 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 1013 && "Cannot handle constant offsets yet!"); 1014 Disp = N.getOperand(1).getOperand(0); // The global address. 1015 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 1016 Disp.getOpcode() == ISD::TargetConstantPool || 1017 Disp.getOpcode() == ISD::TargetJumpTable); 1018 Base = N.getOperand(0); 1019 return true; // [&g+r] 1020 } 1021 } else if (N.getOpcode() == ISD::OR) { 1022 short imm = 0; 1023 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) { 1024 // If this is an or of disjoint bitfields, we can codegen this as an add 1025 // (for better address arithmetic) if the LHS and RHS of the OR are 1026 // provably disjoint. 1027 APInt LHSKnownZero, LHSKnownOne; 1028 DAG.ComputeMaskedBits(N.getOperand(0), 1029 APInt::getAllOnesValue(N.getOperand(0) 1030 .getValueSizeInBits()), 1031 LHSKnownZero, LHSKnownOne); 1032 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 1033 // If all of the bits are known zero on the LHS or RHS, the add won't 1034 // carry. 1035 Base = N.getOperand(0); 1036 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32); 1037 return true; 1038 } 1039 } 1040 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 1041 // Loading from a constant address. Verify low two bits are clear. 1042 if ((CN->getZExtValue() & 3) == 0) { 1043 // If this address fits entirely in a 14-bit sext immediate field, codegen 1044 // this as "d, 0" 1045 short Imm; 1046 if (isIntS16Immediate(CN, Imm)) { 1047 Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy()); 1048 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0, 1049 CN->getValueType(0)); 1050 return true; 1051 } 1052 1053 // Fold the low-part of 32-bit absolute addresses into addr mode. 1054 if (CN->getValueType(0) == MVT::i32 || 1055 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) { 1056 int Addr = (int)CN->getZExtValue(); 1057 1058 // Otherwise, break this down into an LIS + disp. 1059 Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32); 1060 Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32); 1061 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 1062 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base),0); 1063 return true; 1064 } 1065 } 1066 } 1067 1068 Disp = DAG.getTargetConstant(0, getPointerTy()); 1069 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) 1070 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 1071 else 1072 Base = N; 1073 return true; // [r+0] 1074 } 1075 1076 1077 /// getPreIndexedAddressParts - returns true by value, base pointer and 1078 /// offset pointer and addressing mode by reference if the node's address 1079 /// can be legally represented as pre-indexed load / store address. 1080 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 1081 SDValue &Offset, 1082 ISD::MemIndexedMode &AM, 1083 SelectionDAG &DAG) const { 1084 // Disabled by default for now. 1085 if (!EnablePPCPreinc) return false; 1086 1087 SDValue Ptr; 1088 EVT VT; 1089 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 1090 Ptr = LD->getBasePtr(); 1091 VT = LD->getMemoryVT(); 1092 1093 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 1094 Ptr = ST->getBasePtr(); 1095 VT = ST->getMemoryVT(); 1096 } else 1097 return false; 1098 1099 // PowerPC doesn't have preinc load/store instructions for vectors. 1100 if (VT.isVector()) 1101 return false; 1102 1103 // TODO: Check reg+reg first. 1104 1105 // LDU/STU use reg+imm*4, others use reg+imm. 1106 if (VT != MVT::i64) { 1107 // reg + imm 1108 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG)) 1109 return false; 1110 } else { 1111 // reg + imm * 4. 1112 if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG)) 1113 return false; 1114 } 1115 1116 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 1117 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 1118 // sext i32 to i64 when addr mode is r+i. 1119 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 1120 LD->getExtensionType() == ISD::SEXTLOAD && 1121 isa<ConstantSDNode>(Offset)) 1122 return false; 1123 } 1124 1125 AM = ISD::PRE_INC; 1126 return true; 1127 } 1128 1129 //===----------------------------------------------------------------------===// 1130 // LowerOperation implementation 1131 //===----------------------------------------------------------------------===// 1132 1133 /// GetLabelAccessInfo - Return true if we should reference labels using a 1134 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags. 1135 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags, 1136 unsigned &LoOpFlags, const GlobalValue *GV = 0) { 1137 HiOpFlags = PPCII::MO_HA16; 1138 LoOpFlags = PPCII::MO_LO16; 1139 1140 // Don't use the pic base if not in PIC relocation model. Or if we are on a 1141 // non-darwin platform. We don't support PIC on other platforms yet. 1142 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ && 1143 TM.getSubtarget<PPCSubtarget>().isDarwin(); 1144 if (isPIC) { 1145 HiOpFlags |= PPCII::MO_PIC_FLAG; 1146 LoOpFlags |= PPCII::MO_PIC_FLAG; 1147 } 1148 1149 // If this is a reference to a global value that requires a non-lazy-ptr, make 1150 // sure that instruction lowering adds it. 1151 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) { 1152 HiOpFlags |= PPCII::MO_NLP_FLAG; 1153 LoOpFlags |= PPCII::MO_NLP_FLAG; 1154 1155 if (GV->hasHiddenVisibility()) { 1156 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 1157 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 1158 } 1159 } 1160 1161 return isPIC; 1162 } 1163 1164 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 1165 SelectionDAG &DAG) { 1166 EVT PtrVT = HiPart.getValueType(); 1167 SDValue Zero = DAG.getConstant(0, PtrVT); 1168 DebugLoc DL = HiPart.getDebugLoc(); 1169 1170 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 1171 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 1172 1173 // With PIC, the first instruction is actually "GR+hi(&G)". 1174 if (isPIC) 1175 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 1176 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 1177 1178 // Generate non-pic code that has direct accesses to the constant pool. 1179 // The address of the global is just (hi(&g)+lo(&g)). 1180 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 1181 } 1182 1183 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 1184 SelectionDAG &DAG) const { 1185 EVT PtrVT = Op.getValueType(); 1186 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 1187 const Constant *C = CP->getConstVal(); 1188 1189 unsigned MOHiFlag, MOLoFlag; 1190 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag); 1191 SDValue CPIHi = 1192 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 1193 SDValue CPILo = 1194 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 1195 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG); 1196 } 1197 1198 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 1199 EVT PtrVT = Op.getValueType(); 1200 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 1201 1202 unsigned MOHiFlag, MOLoFlag; 1203 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag); 1204 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 1205 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 1206 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG); 1207 } 1208 1209 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 1210 SelectionDAG &DAG) const { 1211 EVT PtrVT = Op.getValueType(); 1212 1213 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 1214 1215 unsigned MOHiFlag, MOLoFlag; 1216 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag); 1217 SDValue TgtBAHi = DAG.getBlockAddress(BA, PtrVT, /*isTarget=*/true, MOHiFlag); 1218 SDValue TgtBALo = DAG.getBlockAddress(BA, PtrVT, /*isTarget=*/true, MOLoFlag); 1219 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG); 1220 } 1221 1222 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 1223 SelectionDAG &DAG) const { 1224 EVT PtrVT = Op.getValueType(); 1225 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 1226 DebugLoc DL = GSDN->getDebugLoc(); 1227 const GlobalValue *GV = GSDN->getGlobal(); 1228 1229 // 64-bit SVR4 ABI code is always position-independent. 1230 // The actual address of the GlobalValue is stored in the TOC. 1231 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) { 1232 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 1233 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA, 1234 DAG.getRegister(PPC::X2, MVT::i64)); 1235 } 1236 1237 unsigned MOHiFlag, MOLoFlag; 1238 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV); 1239 1240 SDValue GAHi = 1241 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 1242 SDValue GALo = 1243 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 1244 1245 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG); 1246 1247 // If the global reference is actually to a non-lazy-pointer, we have to do an 1248 // extra load to get the address of the global. 1249 if (MOHiFlag & PPCII::MO_NLP_FLAG) 1250 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(), 1251 false, false, false, 0); 1252 return Ptr; 1253 } 1254 1255 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 1256 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1257 DebugLoc dl = Op.getDebugLoc(); 1258 1259 // If we're comparing for equality to zero, expose the fact that this is 1260 // implented as a ctlz/srl pair on ppc, so that the dag combiner can 1261 // fold the new nodes. 1262 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1263 if (C->isNullValue() && CC == ISD::SETEQ) { 1264 EVT VT = Op.getOperand(0).getValueType(); 1265 SDValue Zext = Op.getOperand(0); 1266 if (VT.bitsLT(MVT::i32)) { 1267 VT = MVT::i32; 1268 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 1269 } 1270 unsigned Log2b = Log2_32(VT.getSizeInBits()); 1271 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 1272 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 1273 DAG.getConstant(Log2b, MVT::i32)); 1274 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 1275 } 1276 // Leave comparisons against 0 and -1 alone for now, since they're usually 1277 // optimized. FIXME: revisit this when we can custom lower all setcc 1278 // optimizations. 1279 if (C->isAllOnesValue() || C->isNullValue()) 1280 return SDValue(); 1281 } 1282 1283 // If we have an integer seteq/setne, turn it into a compare against zero 1284 // by xor'ing the rhs with the lhs, which is faster than setting a 1285 // condition register, reading it back out, and masking the correct bit. The 1286 // normal approach here uses sub to do this instead of xor. Using xor exposes 1287 // the result to other bit-twiddling opportunities. 1288 EVT LHSVT = Op.getOperand(0).getValueType(); 1289 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1290 EVT VT = Op.getValueType(); 1291 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 1292 Op.getOperand(1)); 1293 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC); 1294 } 1295 return SDValue(); 1296 } 1297 1298 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG, 1299 const PPCSubtarget &Subtarget) const { 1300 SDNode *Node = Op.getNode(); 1301 EVT VT = Node->getValueType(0); 1302 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1303 SDValue InChain = Node->getOperand(0); 1304 SDValue VAListPtr = Node->getOperand(1); 1305 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 1306 DebugLoc dl = Node->getDebugLoc(); 1307 1308 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 1309 1310 // gpr_index 1311 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 1312 VAListPtr, MachinePointerInfo(SV), MVT::i8, 1313 false, false, 0); 1314 InChain = GprIndex.getValue(1); 1315 1316 if (VT == MVT::i64) { 1317 // Check if GprIndex is even 1318 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 1319 DAG.getConstant(1, MVT::i32)); 1320 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 1321 DAG.getConstant(0, MVT::i32), ISD::SETNE); 1322 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 1323 DAG.getConstant(1, MVT::i32)); 1324 // Align GprIndex to be even if it isn't 1325 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 1326 GprIndex); 1327 } 1328 1329 // fpr index is 1 byte after gpr 1330 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 1331 DAG.getConstant(1, MVT::i32)); 1332 1333 // fpr 1334 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 1335 FprPtr, MachinePointerInfo(SV), MVT::i8, 1336 false, false, 0); 1337 InChain = FprIndex.getValue(1); 1338 1339 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 1340 DAG.getConstant(8, MVT::i32)); 1341 1342 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 1343 DAG.getConstant(4, MVT::i32)); 1344 1345 // areas 1346 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, 1347 MachinePointerInfo(), false, false, 1348 false, 0); 1349 InChain = OverflowArea.getValue(1); 1350 1351 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, 1352 MachinePointerInfo(), false, false, 1353 false, 0); 1354 InChain = RegSaveArea.getValue(1); 1355 1356 // select overflow_area if index > 8 1357 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 1358 DAG.getConstant(8, MVT::i32), ISD::SETLT); 1359 1360 // adjustment constant gpr_index * 4/8 1361 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 1362 VT.isInteger() ? GprIndex : FprIndex, 1363 DAG.getConstant(VT.isInteger() ? 4 : 8, 1364 MVT::i32)); 1365 1366 // OurReg = RegSaveArea + RegConstant 1367 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 1368 RegConstant); 1369 1370 // Floating types are 32 bytes into RegSaveArea 1371 if (VT.isFloatingPoint()) 1372 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 1373 DAG.getConstant(32, MVT::i32)); 1374 1375 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 1376 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 1377 VT.isInteger() ? GprIndex : FprIndex, 1378 DAG.getConstant(VT == MVT::i64 ? 2 : 1, 1379 MVT::i32)); 1380 1381 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 1382 VT.isInteger() ? VAListPtr : FprPtr, 1383 MachinePointerInfo(SV), 1384 MVT::i8, false, false, 0); 1385 1386 // determine if we should load from reg_save_area or overflow_area 1387 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 1388 1389 // increase overflow_area by 4/8 if gpr/fpr > 8 1390 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 1391 DAG.getConstant(VT.isInteger() ? 4 : 8, 1392 MVT::i32)); 1393 1394 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 1395 OverflowAreaPlusN); 1396 1397 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, 1398 OverflowAreaPtr, 1399 MachinePointerInfo(), 1400 MVT::i32, false, false, 0); 1401 1402 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(), 1403 false, false, false, 0); 1404 } 1405 1406 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 1407 SelectionDAG &DAG) const { 1408 return Op.getOperand(0); 1409 } 1410 1411 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 1412 SelectionDAG &DAG) const { 1413 SDValue Chain = Op.getOperand(0); 1414 SDValue Trmp = Op.getOperand(1); // trampoline 1415 SDValue FPtr = Op.getOperand(2); // nested function 1416 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 1417 DebugLoc dl = Op.getDebugLoc(); 1418 1419 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1420 bool isPPC64 = (PtrVT == MVT::i64); 1421 Type *IntPtrTy = 1422 DAG.getTargetLoweringInfo().getTargetData()->getIntPtrType( 1423 *DAG.getContext()); 1424 1425 TargetLowering::ArgListTy Args; 1426 TargetLowering::ArgListEntry Entry; 1427 1428 Entry.Ty = IntPtrTy; 1429 Entry.Node = Trmp; Args.push_back(Entry); 1430 1431 // TrampSize == (isPPC64 ? 48 : 40); 1432 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, 1433 isPPC64 ? MVT::i64 : MVT::i32); 1434 Args.push_back(Entry); 1435 1436 Entry.Node = FPtr; Args.push_back(Entry); 1437 Entry.Node = Nest; Args.push_back(Entry); 1438 1439 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 1440 std::pair<SDValue, SDValue> CallResult = 1441 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), 1442 false, false, false, false, 0, CallingConv::C, 1443 /*isTailCall=*/false, 1444 /*doesNotRet=*/false, /*isReturnValueUsed=*/true, 1445 DAG.getExternalSymbol("__trampoline_setup", PtrVT), 1446 Args, DAG, dl); 1447 1448 return CallResult.second; 1449 } 1450 1451 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG, 1452 const PPCSubtarget &Subtarget) const { 1453 MachineFunction &MF = DAG.getMachineFunction(); 1454 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1455 1456 DebugLoc dl = Op.getDebugLoc(); 1457 1458 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 1459 // vastart just stores the address of the VarArgsFrameIndex slot into the 1460 // memory location argument. 1461 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1462 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 1463 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 1464 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 1465 MachinePointerInfo(SV), 1466 false, false, 0); 1467 } 1468 1469 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 1470 // We suppose the given va_list is already allocated. 1471 // 1472 // typedef struct { 1473 // char gpr; /* index into the array of 8 GPRs 1474 // * stored in the register save area 1475 // * gpr=0 corresponds to r3, 1476 // * gpr=1 to r4, etc. 1477 // */ 1478 // char fpr; /* index into the array of 8 FPRs 1479 // * stored in the register save area 1480 // * fpr=0 corresponds to f1, 1481 // * fpr=1 to f2, etc. 1482 // */ 1483 // char *overflow_arg_area; 1484 // /* location on stack that holds 1485 // * the next overflow argument 1486 // */ 1487 // char *reg_save_area; 1488 // /* where r3:r10 and f1:f8 (if saved) 1489 // * are stored 1490 // */ 1491 // } va_list[1]; 1492 1493 1494 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32); 1495 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32); 1496 1497 1498 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1499 1500 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 1501 PtrVT); 1502 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 1503 PtrVT); 1504 1505 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 1506 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT); 1507 1508 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 1509 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT); 1510 1511 uint64_t FPROffset = 1; 1512 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT); 1513 1514 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 1515 1516 // Store first byte : number of int regs 1517 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, 1518 Op.getOperand(1), 1519 MachinePointerInfo(SV), 1520 MVT::i8, false, false, 0); 1521 uint64_t nextOffset = FPROffset; 1522 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 1523 ConstFPROffset); 1524 1525 // Store second byte : number of float regs 1526 SDValue secondStore = 1527 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 1528 MachinePointerInfo(SV, nextOffset), MVT::i8, 1529 false, false, 0); 1530 nextOffset += StackOffset; 1531 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 1532 1533 // Store second word : arguments given on stack 1534 SDValue thirdStore = 1535 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 1536 MachinePointerInfo(SV, nextOffset), 1537 false, false, 0); 1538 nextOffset += FrameOffset; 1539 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 1540 1541 // Store third word : arguments given in registers 1542 return DAG.getStore(thirdStore, dl, FR, nextPtr, 1543 MachinePointerInfo(SV, nextOffset), 1544 false, false, 0); 1545 1546 } 1547 1548 #include "PPCGenCallingConv.inc" 1549 1550 static bool CC_PPC_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 1551 CCValAssign::LocInfo &LocInfo, 1552 ISD::ArgFlagsTy &ArgFlags, 1553 CCState &State) { 1554 return true; 1555 } 1556 1557 static bool CC_PPC_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 1558 MVT &LocVT, 1559 CCValAssign::LocInfo &LocInfo, 1560 ISD::ArgFlagsTy &ArgFlags, 1561 CCState &State) { 1562 static const uint16_t ArgRegs[] = { 1563 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 1564 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 1565 }; 1566 const unsigned NumArgRegs = array_lengthof(ArgRegs); 1567 1568 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs); 1569 1570 // Skip one register if the first unallocated register has an even register 1571 // number and there are still argument registers available which have not been 1572 // allocated yet. RegNum is actually an index into ArgRegs, which means we 1573 // need to skip a register if RegNum is odd. 1574 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 1575 State.AllocateReg(ArgRegs[RegNum]); 1576 } 1577 1578 // Always return false here, as this function only makes sure that the first 1579 // unallocated register has an odd register number and does not actually 1580 // allocate a register for the current argument. 1581 return false; 1582 } 1583 1584 static bool CC_PPC_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 1585 MVT &LocVT, 1586 CCValAssign::LocInfo &LocInfo, 1587 ISD::ArgFlagsTy &ArgFlags, 1588 CCState &State) { 1589 static const uint16_t ArgRegs[] = { 1590 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 1591 PPC::F8 1592 }; 1593 1594 const unsigned NumArgRegs = array_lengthof(ArgRegs); 1595 1596 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs); 1597 1598 // If there is only one Floating-point register left we need to put both f64 1599 // values of a split ppc_fp128 value on the stack. 1600 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 1601 State.AllocateReg(ArgRegs[RegNum]); 1602 } 1603 1604 // Always return false here, as this function only makes sure that the two f64 1605 // values a ppc_fp128 value is split into are both passed in registers or both 1606 // passed on the stack and does not actually allocate a register for the 1607 // current argument. 1608 return false; 1609 } 1610 1611 /// GetFPR - Get the set of FP registers that should be allocated for arguments, 1612 /// on Darwin. 1613 static const uint16_t *GetFPR() { 1614 static const uint16_t FPR[] = { 1615 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 1616 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13 1617 }; 1618 1619 return FPR; 1620 } 1621 1622 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 1623 /// the stack. 1624 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 1625 unsigned PtrByteSize) { 1626 unsigned ArgSize = ArgVT.getSizeInBits()/8; 1627 if (Flags.isByVal()) 1628 ArgSize = Flags.getByValSize(); 1629 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 1630 1631 return ArgSize; 1632 } 1633 1634 SDValue 1635 PPCTargetLowering::LowerFormalArguments(SDValue Chain, 1636 CallingConv::ID CallConv, bool isVarArg, 1637 const SmallVectorImpl<ISD::InputArg> 1638 &Ins, 1639 DebugLoc dl, SelectionDAG &DAG, 1640 SmallVectorImpl<SDValue> &InVals) 1641 const { 1642 if (PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64()) { 1643 return LowerFormalArguments_SVR4(Chain, CallConv, isVarArg, Ins, 1644 dl, DAG, InVals); 1645 } else { 1646 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 1647 dl, DAG, InVals); 1648 } 1649 } 1650 1651 SDValue 1652 PPCTargetLowering::LowerFormalArguments_SVR4( 1653 SDValue Chain, 1654 CallingConv::ID CallConv, bool isVarArg, 1655 const SmallVectorImpl<ISD::InputArg> 1656 &Ins, 1657 DebugLoc dl, SelectionDAG &DAG, 1658 SmallVectorImpl<SDValue> &InVals) const { 1659 1660 // 32-bit SVR4 ABI Stack Frame Layout: 1661 // +-----------------------------------+ 1662 // +--> | Back chain | 1663 // | +-----------------------------------+ 1664 // | | Floating-point register save area | 1665 // | +-----------------------------------+ 1666 // | | General register save area | 1667 // | +-----------------------------------+ 1668 // | | CR save word | 1669 // | +-----------------------------------+ 1670 // | | VRSAVE save word | 1671 // | +-----------------------------------+ 1672 // | | Alignment padding | 1673 // | +-----------------------------------+ 1674 // | | Vector register save area | 1675 // | +-----------------------------------+ 1676 // | | Local variable space | 1677 // | +-----------------------------------+ 1678 // | | Parameter list area | 1679 // | +-----------------------------------+ 1680 // | | LR save word | 1681 // | +-----------------------------------+ 1682 // SP--> +--- | Back chain | 1683 // +-----------------------------------+ 1684 // 1685 // Specifications: 1686 // System V Application Binary Interface PowerPC Processor Supplement 1687 // AltiVec Technology Programming Interface Manual 1688 1689 MachineFunction &MF = DAG.getMachineFunction(); 1690 MachineFrameInfo *MFI = MF.getFrameInfo(); 1691 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1692 1693 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1694 // Potential tail calls could cause overwriting of argument stack slots. 1695 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 1696 (CallConv == CallingConv::Fast)); 1697 unsigned PtrByteSize = 4; 1698 1699 // Assign locations to all of the incoming arguments. 1700 SmallVector<CCValAssign, 16> ArgLocs; 1701 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 1702 getTargetMachine(), ArgLocs, *DAG.getContext()); 1703 1704 // Reserve space for the linkage area on the stack. 1705 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize); 1706 1707 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC_SVR4); 1708 1709 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 1710 CCValAssign &VA = ArgLocs[i]; 1711 1712 // Arguments stored in registers. 1713 if (VA.isRegLoc()) { 1714 const TargetRegisterClass *RC; 1715 EVT ValVT = VA.getValVT(); 1716 1717 switch (ValVT.getSimpleVT().SimpleTy) { 1718 default: 1719 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 1720 case MVT::i32: 1721 RC = PPC::GPRCRegisterClass; 1722 break; 1723 case MVT::f32: 1724 RC = PPC::F4RCRegisterClass; 1725 break; 1726 case MVT::f64: 1727 RC = PPC::F8RCRegisterClass; 1728 break; 1729 case MVT::v16i8: 1730 case MVT::v8i16: 1731 case MVT::v4i32: 1732 case MVT::v4f32: 1733 RC = PPC::VRRCRegisterClass; 1734 break; 1735 } 1736 1737 // Transform the arguments stored in physical registers into virtual ones. 1738 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 1739 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT); 1740 1741 InVals.push_back(ArgValue); 1742 } else { 1743 // Argument stored in memory. 1744 assert(VA.isMemLoc()); 1745 1746 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8; 1747 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(), 1748 isImmutable); 1749 1750 // Create load nodes to retrieve arguments from the stack. 1751 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 1752 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 1753 MachinePointerInfo(), 1754 false, false, false, 0)); 1755 } 1756 } 1757 1758 // Assign locations to all of the incoming aggregate by value arguments. 1759 // Aggregates passed by value are stored in the local variable space of the 1760 // caller's stack frame, right above the parameter list area. 1761 SmallVector<CCValAssign, 16> ByValArgLocs; 1762 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 1763 getTargetMachine(), ByValArgLocs, *DAG.getContext()); 1764 1765 // Reserve stack space for the allocations in CCInfo. 1766 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 1767 1768 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC_SVR4_ByVal); 1769 1770 // Area that is at least reserved in the caller of this function. 1771 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 1772 1773 // Set the size that is at least reserved in caller of this function. Tail 1774 // call optimized function's reserved stack space needs to be aligned so that 1775 // taking the difference between two stack areas will result in an aligned 1776 // stack. 1777 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 1778 1779 MinReservedArea = 1780 std::max(MinReservedArea, 1781 PPCFrameLowering::getMinCallFrameSize(false, false)); 1782 1783 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()-> 1784 getStackAlignment(); 1785 unsigned AlignMask = TargetAlign-1; 1786 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask; 1787 1788 FI->setMinReservedArea(MinReservedArea); 1789 1790 SmallVector<SDValue, 8> MemOps; 1791 1792 // If the function takes variable number of arguments, make a frame index for 1793 // the start of the first vararg value... for expansion of llvm.va_start. 1794 if (isVarArg) { 1795 static const uint16_t GPArgRegs[] = { 1796 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 1797 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 1798 }; 1799 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 1800 1801 static const uint16_t FPArgRegs[] = { 1802 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 1803 PPC::F8 1804 }; 1805 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 1806 1807 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs, 1808 NumGPArgRegs)); 1809 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs, 1810 NumFPArgRegs)); 1811 1812 // Make room for NumGPArgRegs and NumFPArgRegs. 1813 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 1814 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8; 1815 1816 FuncInfo->setVarArgsStackOffset( 1817 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8, 1818 CCInfo.getNextStackOffset(), true)); 1819 1820 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false)); 1821 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 1822 1823 // The fixed integer arguments of a variadic function are stored to the 1824 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing 1825 // the result of va_next. 1826 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 1827 // Get an existing live-in vreg, or add a new one. 1828 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 1829 if (!VReg) 1830 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 1831 1832 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 1833 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 1834 MachinePointerInfo(), false, false, 0); 1835 MemOps.push_back(Store); 1836 // Increment the address by four for the next argument to store 1837 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT); 1838 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 1839 } 1840 1841 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 1842 // is set. 1843 // The double arguments are stored to the VarArgsFrameIndex 1844 // on the stack. 1845 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 1846 // Get an existing live-in vreg, or add a new one. 1847 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 1848 if (!VReg) 1849 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 1850 1851 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 1852 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 1853 MachinePointerInfo(), false, false, 0); 1854 MemOps.push_back(Store); 1855 // Increment the address by eight for the next argument to store 1856 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8, 1857 PtrVT); 1858 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 1859 } 1860 } 1861 1862 if (!MemOps.empty()) 1863 Chain = DAG.getNode(ISD::TokenFactor, dl, 1864 MVT::Other, &MemOps[0], MemOps.size()); 1865 1866 return Chain; 1867 } 1868 1869 SDValue 1870 PPCTargetLowering::LowerFormalArguments_Darwin( 1871 SDValue Chain, 1872 CallingConv::ID CallConv, bool isVarArg, 1873 const SmallVectorImpl<ISD::InputArg> 1874 &Ins, 1875 DebugLoc dl, SelectionDAG &DAG, 1876 SmallVectorImpl<SDValue> &InVals) const { 1877 // TODO: add description of PPC stack frame format, or at least some docs. 1878 // 1879 MachineFunction &MF = DAG.getMachineFunction(); 1880 MachineFrameInfo *MFI = MF.getFrameInfo(); 1881 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1882 1883 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1884 bool isPPC64 = PtrVT == MVT::i64; 1885 // Potential tail calls could cause overwriting of argument stack slots. 1886 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 1887 (CallConv == CallingConv::Fast)); 1888 unsigned PtrByteSize = isPPC64 ? 8 : 4; 1889 1890 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true); 1891 // Area that is at least reserved in caller of this function. 1892 unsigned MinReservedArea = ArgOffset; 1893 1894 static const uint16_t GPR_32[] = { // 32-bit registers. 1895 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 1896 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 1897 }; 1898 static const uint16_t GPR_64[] = { // 64-bit registers. 1899 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 1900 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 1901 }; 1902 1903 static const uint16_t *FPR = GetFPR(); 1904 1905 static const uint16_t VR[] = { 1906 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 1907 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 1908 }; 1909 1910 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 1911 const unsigned Num_FPR_Regs = 13; 1912 const unsigned Num_VR_Regs = array_lengthof( VR); 1913 1914 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 1915 1916 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32; 1917 1918 // In 32-bit non-varargs functions, the stack space for vectors is after the 1919 // stack space for non-vectors. We do not use this space unless we have 1920 // too many vectors to fit in registers, something that only occurs in 1921 // constructed examples:), but we have to walk the arglist to figure 1922 // that out...for the pathological case, compute VecArgOffset as the 1923 // start of the vector parameter area. Computing VecArgOffset is the 1924 // entire point of the following loop. 1925 unsigned VecArgOffset = ArgOffset; 1926 if (!isVarArg && !isPPC64) { 1927 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 1928 ++ArgNo) { 1929 EVT ObjectVT = Ins[ArgNo].VT; 1930 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 1931 1932 if (Flags.isByVal()) { 1933 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 1934 unsigned ObjSize = Flags.getByValSize(); 1935 unsigned ArgSize = 1936 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 1937 VecArgOffset += ArgSize; 1938 continue; 1939 } 1940 1941 switch(ObjectVT.getSimpleVT().SimpleTy) { 1942 default: llvm_unreachable("Unhandled argument type!"); 1943 case MVT::i32: 1944 case MVT::f32: 1945 VecArgOffset += isPPC64 ? 8 : 4; 1946 break; 1947 case MVT::i64: // PPC64 1948 case MVT::f64: 1949 VecArgOffset += 8; 1950 break; 1951 case MVT::v4f32: 1952 case MVT::v4i32: 1953 case MVT::v8i16: 1954 case MVT::v16i8: 1955 // Nothing to do, we're only looking at Nonvector args here. 1956 break; 1957 } 1958 } 1959 } 1960 // We've found where the vector parameter area in memory is. Skip the 1961 // first 12 parameters; these don't use that memory. 1962 VecArgOffset = ((VecArgOffset+15)/16)*16; 1963 VecArgOffset += 12*16; 1964 1965 // Add DAG nodes to load the arguments or copy them out of registers. On 1966 // entry to a function on PPC, the arguments start after the linkage area, 1967 // although the first ones are often in registers. 1968 1969 SmallVector<SDValue, 8> MemOps; 1970 unsigned nAltivecParamsAtEnd = 0; 1971 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 1972 SDValue ArgVal; 1973 bool needsLoad = false; 1974 EVT ObjectVT = Ins[ArgNo].VT; 1975 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 1976 unsigned ArgSize = ObjSize; 1977 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 1978 1979 unsigned CurArgOffset = ArgOffset; 1980 1981 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 1982 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 1983 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 1984 if (isVarArg || isPPC64) { 1985 MinReservedArea = ((MinReservedArea+15)/16)*16; 1986 MinReservedArea += CalculateStackSlotSize(ObjectVT, 1987 Flags, 1988 PtrByteSize); 1989 } else nAltivecParamsAtEnd++; 1990 } else 1991 // Calculate min reserved area. 1992 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 1993 Flags, 1994 PtrByteSize); 1995 1996 // FIXME the codegen can be much improved in some cases. 1997 // We do not have to keep everything in memory. 1998 if (Flags.isByVal()) { 1999 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 2000 ObjSize = Flags.getByValSize(); 2001 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 2002 // Objects of size 1 and 2 are right justified, everything else is 2003 // left justified. This means the memory address is adjusted forwards. 2004 if (ObjSize==1 || ObjSize==2) { 2005 CurArgOffset = CurArgOffset + (4 - ObjSize); 2006 } 2007 // The value of the object is its address. 2008 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true); 2009 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2010 InVals.push_back(FIN); 2011 if (ObjSize==1 || ObjSize==2) { 2012 if (GPR_idx != Num_GPR_Regs) { 2013 unsigned VReg; 2014 if (isPPC64) 2015 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2016 else 2017 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 2018 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2019 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 2020 MachinePointerInfo(), 2021 ObjSize==1 ? MVT::i8 : MVT::i16, 2022 false, false, 0); 2023 MemOps.push_back(Store); 2024 ++GPR_idx; 2025 } 2026 2027 ArgOffset += PtrByteSize; 2028 2029 continue; 2030 } 2031 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 2032 // Store whatever pieces of the object are in registers 2033 // to memory. ArgVal will be address of the beginning of 2034 // the object. 2035 if (GPR_idx != Num_GPR_Regs) { 2036 unsigned VReg; 2037 if (isPPC64) 2038 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2039 else 2040 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 2041 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true); 2042 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2043 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2044 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2045 MachinePointerInfo(), 2046 false, false, 0); 2047 MemOps.push_back(Store); 2048 ++GPR_idx; 2049 ArgOffset += PtrByteSize; 2050 } else { 2051 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 2052 break; 2053 } 2054 } 2055 continue; 2056 } 2057 2058 switch (ObjectVT.getSimpleVT().SimpleTy) { 2059 default: llvm_unreachable("Unhandled argument type!"); 2060 case MVT::i32: 2061 if (!isPPC64) { 2062 if (GPR_idx != Num_GPR_Regs) { 2063 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 2064 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 2065 ++GPR_idx; 2066 } else { 2067 needsLoad = true; 2068 ArgSize = PtrByteSize; 2069 } 2070 // All int arguments reserve stack space in the Darwin ABI. 2071 ArgOffset += PtrByteSize; 2072 break; 2073 } 2074 // FALLTHROUGH 2075 case MVT::i64: // PPC64 2076 if (GPR_idx != Num_GPR_Regs) { 2077 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2078 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 2079 2080 if (ObjectVT == MVT::i32) { 2081 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 2082 // value to MVT::i64 and then truncate to the correct register size. 2083 if (Flags.isSExt()) 2084 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 2085 DAG.getValueType(ObjectVT)); 2086 else if (Flags.isZExt()) 2087 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 2088 DAG.getValueType(ObjectVT)); 2089 2090 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 2091 } 2092 2093 ++GPR_idx; 2094 } else { 2095 needsLoad = true; 2096 ArgSize = PtrByteSize; 2097 } 2098 // All int arguments reserve stack space in the Darwin ABI. 2099 ArgOffset += 8; 2100 break; 2101 2102 case MVT::f32: 2103 case MVT::f64: 2104 // Every 4 bytes of argument space consumes one of the GPRs available for 2105 // argument passing. 2106 if (GPR_idx != Num_GPR_Regs) { 2107 ++GPR_idx; 2108 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 2109 ++GPR_idx; 2110 } 2111 if (FPR_idx != Num_FPR_Regs) { 2112 unsigned VReg; 2113 2114 if (ObjectVT == MVT::f32) 2115 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 2116 else 2117 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 2118 2119 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 2120 ++FPR_idx; 2121 } else { 2122 needsLoad = true; 2123 } 2124 2125 // All FP arguments reserve stack space in the Darwin ABI. 2126 ArgOffset += isPPC64 ? 8 : ObjSize; 2127 break; 2128 case MVT::v4f32: 2129 case MVT::v4i32: 2130 case MVT::v8i16: 2131 case MVT::v16i8: 2132 // Note that vector arguments in registers don't reserve stack space, 2133 // except in varargs functions. 2134 if (VR_idx != Num_VR_Regs) { 2135 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 2136 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 2137 if (isVarArg) { 2138 while ((ArgOffset % 16) != 0) { 2139 ArgOffset += PtrByteSize; 2140 if (GPR_idx != Num_GPR_Regs) 2141 GPR_idx++; 2142 } 2143 ArgOffset += 16; 2144 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 2145 } 2146 ++VR_idx; 2147 } else { 2148 if (!isVarArg && !isPPC64) { 2149 // Vectors go after all the nonvectors. 2150 CurArgOffset = VecArgOffset; 2151 VecArgOffset += 16; 2152 } else { 2153 // Vectors are aligned. 2154 ArgOffset = ((ArgOffset+15)/16)*16; 2155 CurArgOffset = ArgOffset; 2156 ArgOffset += 16; 2157 } 2158 needsLoad = true; 2159 } 2160 break; 2161 } 2162 2163 // We need to load the argument to a virtual register if we determined above 2164 // that we ran out of physical registers of the appropriate type. 2165 if (needsLoad) { 2166 int FI = MFI->CreateFixedObject(ObjSize, 2167 CurArgOffset + (ArgSize - ObjSize), 2168 isImmutable); 2169 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 2170 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(), 2171 false, false, false, 0); 2172 } 2173 2174 InVals.push_back(ArgVal); 2175 } 2176 2177 // Set the size that is at least reserved in caller of this function. Tail 2178 // call optimized function's reserved stack space needs to be aligned so that 2179 // taking the difference between two stack areas will result in an aligned 2180 // stack. 2181 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 2182 // Add the Altivec parameters at the end, if needed. 2183 if (nAltivecParamsAtEnd) { 2184 MinReservedArea = ((MinReservedArea+15)/16)*16; 2185 MinReservedArea += 16*nAltivecParamsAtEnd; 2186 } 2187 MinReservedArea = 2188 std::max(MinReservedArea, 2189 PPCFrameLowering::getMinCallFrameSize(isPPC64, true)); 2190 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()-> 2191 getStackAlignment(); 2192 unsigned AlignMask = TargetAlign-1; 2193 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask; 2194 FI->setMinReservedArea(MinReservedArea); 2195 2196 // If the function takes variable number of arguments, make a frame index for 2197 // the start of the first vararg value... for expansion of llvm.va_start. 2198 if (isVarArg) { 2199 int Depth = ArgOffset; 2200 2201 FuncInfo->setVarArgsFrameIndex( 2202 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8, 2203 Depth, true)); 2204 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2205 2206 // If this function is vararg, store any remaining integer argument regs 2207 // to their spots on the stack so that they may be loaded by deferencing the 2208 // result of va_next. 2209 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 2210 unsigned VReg; 2211 2212 if (isPPC64) 2213 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 2214 else 2215 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 2216 2217 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 2218 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 2219 MachinePointerInfo(), false, false, 0); 2220 MemOps.push_back(Store); 2221 // Increment the address by four for the next argument to store 2222 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT); 2223 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 2224 } 2225 } 2226 2227 if (!MemOps.empty()) 2228 Chain = DAG.getNode(ISD::TokenFactor, dl, 2229 MVT::Other, &MemOps[0], MemOps.size()); 2230 2231 return Chain; 2232 } 2233 2234 /// CalculateParameterAndLinkageAreaSize - Get the size of the paramter plus 2235 /// linkage area for the Darwin ABI. 2236 static unsigned 2237 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG, 2238 bool isPPC64, 2239 bool isVarArg, 2240 unsigned CC, 2241 const SmallVectorImpl<ISD::OutputArg> 2242 &Outs, 2243 const SmallVectorImpl<SDValue> &OutVals, 2244 unsigned &nAltivecParamsAtEnd) { 2245 // Count how many bytes are to be pushed on the stack, including the linkage 2246 // area, and parameter passing area. We start with 24/48 bytes, which is 2247 // prereserved space for [SP][CR][LR][3 x unused]. 2248 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true); 2249 unsigned NumOps = Outs.size(); 2250 unsigned PtrByteSize = isPPC64 ? 8 : 4; 2251 2252 // Add up all the space actually used. 2253 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 2254 // they all go in registers, but we must reserve stack space for them for 2255 // possible use by the caller. In varargs or 64-bit calls, parameters are 2256 // assigned stack space in order, with padding so Altivec parameters are 2257 // 16-byte aligned. 2258 nAltivecParamsAtEnd = 0; 2259 for (unsigned i = 0; i != NumOps; ++i) { 2260 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2261 EVT ArgVT = Outs[i].VT; 2262 // Varargs Altivec parameters are padded to a 16 byte boundary. 2263 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 || 2264 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) { 2265 if (!isVarArg && !isPPC64) { 2266 // Non-varargs Altivec parameters go after all the non-Altivec 2267 // parameters; handle those later so we know how much padding we need. 2268 nAltivecParamsAtEnd++; 2269 continue; 2270 } 2271 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 2272 NumBytes = ((NumBytes+15)/16)*16; 2273 } 2274 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 2275 } 2276 2277 // Allow for Altivec parameters at the end, if needed. 2278 if (nAltivecParamsAtEnd) { 2279 NumBytes = ((NumBytes+15)/16)*16; 2280 NumBytes += 16*nAltivecParamsAtEnd; 2281 } 2282 2283 // The prolog code of the callee may store up to 8 GPR argument registers to 2284 // the stack, allowing va_start to index over them in memory if its varargs. 2285 // Because we cannot tell if this is needed on the caller side, we have to 2286 // conservatively assume that it is needed. As such, make sure we have at 2287 // least enough stack space for the caller to store the 8 GPRs. 2288 NumBytes = std::max(NumBytes, 2289 PPCFrameLowering::getMinCallFrameSize(isPPC64, true)); 2290 2291 // Tail call needs the stack to be aligned. 2292 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){ 2293 unsigned TargetAlign = DAG.getMachineFunction().getTarget(). 2294 getFrameLowering()->getStackAlignment(); 2295 unsigned AlignMask = TargetAlign-1; 2296 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 2297 } 2298 2299 return NumBytes; 2300 } 2301 2302 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 2303 /// adjusted to accommodate the arguments for the tailcall. 2304 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 2305 unsigned ParamSize) { 2306 2307 if (!isTailCall) return 0; 2308 2309 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 2310 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 2311 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 2312 // Remember only if the new adjustement is bigger. 2313 if (SPDiff < FI->getTailCallSPDelta()) 2314 FI->setTailCallSPDelta(SPDiff); 2315 2316 return SPDiff; 2317 } 2318 2319 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2320 /// for tail call optimization. Targets which want to do tail call 2321 /// optimization should implement this function. 2322 bool 2323 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2324 CallingConv::ID CalleeCC, 2325 bool isVarArg, 2326 const SmallVectorImpl<ISD::InputArg> &Ins, 2327 SelectionDAG& DAG) const { 2328 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 2329 return false; 2330 2331 // Variable argument functions are not supported. 2332 if (isVarArg) 2333 return false; 2334 2335 MachineFunction &MF = DAG.getMachineFunction(); 2336 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 2337 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 2338 // Functions containing by val parameters are not supported. 2339 for (unsigned i = 0; i != Ins.size(); i++) { 2340 ISD::ArgFlagsTy Flags = Ins[i].Flags; 2341 if (Flags.isByVal()) return false; 2342 } 2343 2344 // Non PIC/GOT tail calls are supported. 2345 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 2346 return true; 2347 2348 // At the moment we can only do local tail calls (in same module, hidden 2349 // or protected) if we are generating PIC. 2350 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2351 return G->getGlobal()->hasHiddenVisibility() 2352 || G->getGlobal()->hasProtectedVisibility(); 2353 } 2354 2355 return false; 2356 } 2357 2358 /// isCallCompatibleAddress - Return the immediate to use if the specified 2359 /// 32-bit value is representable in the immediate field of a BxA instruction. 2360 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 2361 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 2362 if (!C) return 0; 2363 2364 int Addr = C->getZExtValue(); 2365 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 2366 (Addr << 6 >> 6) != Addr) 2367 return 0; // Top 6 bits have to be sext of immediate. 2368 2369 return DAG.getConstant((int)C->getZExtValue() >> 2, 2370 DAG.getTargetLoweringInfo().getPointerTy()).getNode(); 2371 } 2372 2373 namespace { 2374 2375 struct TailCallArgumentInfo { 2376 SDValue Arg; 2377 SDValue FrameIdxOp; 2378 int FrameIdx; 2379 2380 TailCallArgumentInfo() : FrameIdx(0) {} 2381 }; 2382 2383 } 2384 2385 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 2386 static void 2387 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG, 2388 SDValue Chain, 2389 const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs, 2390 SmallVector<SDValue, 8> &MemOpChains, 2391 DebugLoc dl) { 2392 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 2393 SDValue Arg = TailCallArgs[i].Arg; 2394 SDValue FIN = TailCallArgs[i].FrameIdxOp; 2395 int FI = TailCallArgs[i].FrameIdx; 2396 // Store relative to framepointer. 2397 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN, 2398 MachinePointerInfo::getFixedStack(FI), 2399 false, false, 0)); 2400 } 2401 } 2402 2403 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 2404 /// the appropriate stack slot for the tail call optimized function call. 2405 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, 2406 MachineFunction &MF, 2407 SDValue Chain, 2408 SDValue OldRetAddr, 2409 SDValue OldFP, 2410 int SPDiff, 2411 bool isPPC64, 2412 bool isDarwinABI, 2413 DebugLoc dl) { 2414 if (SPDiff) { 2415 // Calculate the new stack slot for the return address. 2416 int SlotSize = isPPC64 ? 8 : 4; 2417 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64, 2418 isDarwinABI); 2419 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize, 2420 NewRetAddrLoc, true); 2421 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 2422 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 2423 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 2424 MachinePointerInfo::getFixedStack(NewRetAddr), 2425 false, false, 0); 2426 2427 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 2428 // slot as the FP is never overwritten. 2429 if (isDarwinABI) { 2430 int NewFPLoc = 2431 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI); 2432 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc, 2433 true); 2434 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 2435 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 2436 MachinePointerInfo::getFixedStack(NewFPIdx), 2437 false, false, 0); 2438 } 2439 } 2440 return Chain; 2441 } 2442 2443 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 2444 /// the position of the argument. 2445 static void 2446 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 2447 SDValue Arg, int SPDiff, unsigned ArgOffset, 2448 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) { 2449 int Offset = ArgOffset + SPDiff; 2450 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8; 2451 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 2452 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 2453 SDValue FIN = DAG.getFrameIndex(FI, VT); 2454 TailCallArgumentInfo Info; 2455 Info.Arg = Arg; 2456 Info.FrameIdxOp = FIN; 2457 Info.FrameIdx = FI; 2458 TailCallArguments.push_back(Info); 2459 } 2460 2461 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 2462 /// stack slot. Returns the chain as result and the loaded frame pointers in 2463 /// LROpOut/FPOpout. Used when tail calling. 2464 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG, 2465 int SPDiff, 2466 SDValue Chain, 2467 SDValue &LROpOut, 2468 SDValue &FPOpOut, 2469 bool isDarwinABI, 2470 DebugLoc dl) const { 2471 if (SPDiff) { 2472 // Load the LR and FP stack slot for later adjusting. 2473 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32; 2474 LROpOut = getReturnAddrFrameIndex(DAG); 2475 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(), 2476 false, false, false, 0); 2477 Chain = SDValue(LROpOut.getNode(), 1); 2478 2479 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 2480 // slot as the FP is never overwritten. 2481 if (isDarwinABI) { 2482 FPOpOut = getFramePointerFrameIndex(DAG); 2483 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(), 2484 false, false, false, 0); 2485 Chain = SDValue(FPOpOut.getNode(), 1); 2486 } 2487 } 2488 return Chain; 2489 } 2490 2491 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 2492 /// by "Src" to address "Dst" of size "Size". Alignment information is 2493 /// specified by the specific parameter attribute. The copy will be passed as 2494 /// a byval function parameter. 2495 /// Sometimes what we are copying is the end of a larger object, the part that 2496 /// does not fit in registers. 2497 static SDValue 2498 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 2499 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 2500 DebugLoc dl) { 2501 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 2502 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 2503 false, false, MachinePointerInfo(0), 2504 MachinePointerInfo(0)); 2505 } 2506 2507 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 2508 /// tail calls. 2509 static void 2510 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, 2511 SDValue Arg, SDValue PtrOff, int SPDiff, 2512 unsigned ArgOffset, bool isPPC64, bool isTailCall, 2513 bool isVector, SmallVector<SDValue, 8> &MemOpChains, 2514 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments, 2515 DebugLoc dl) { 2516 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2517 if (!isTailCall) { 2518 if (isVector) { 2519 SDValue StackPtr; 2520 if (isPPC64) 2521 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 2522 else 2523 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 2524 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 2525 DAG.getConstant(ArgOffset, PtrVT)); 2526 } 2527 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, 2528 MachinePointerInfo(), false, false, 0)); 2529 // Calculate and remember argument location. 2530 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 2531 TailCallArguments); 2532 } 2533 2534 static 2535 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 2536 DebugLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes, 2537 SDValue LROp, SDValue FPOp, bool isDarwinABI, 2538 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments) { 2539 MachineFunction &MF = DAG.getMachineFunction(); 2540 2541 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 2542 // might overwrite each other in case of tail call optimization. 2543 SmallVector<SDValue, 8> MemOpChains2; 2544 // Do not flag preceding copytoreg stuff together with the following stuff. 2545 InFlag = SDValue(); 2546 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 2547 MemOpChains2, dl); 2548 if (!MemOpChains2.empty()) 2549 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2550 &MemOpChains2[0], MemOpChains2.size()); 2551 2552 // Store the return address to the appropriate stack slot. 2553 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff, 2554 isPPC64, isDarwinABI, dl); 2555 2556 // Emit callseq_end just before tailcall node. 2557 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 2558 DAG.getIntPtrConstant(0, true), InFlag); 2559 InFlag = Chain.getValue(1); 2560 } 2561 2562 static 2563 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, 2564 SDValue &Chain, DebugLoc dl, int SPDiff, bool isTailCall, 2565 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 2566 SmallVector<SDValue, 8> &Ops, std::vector<EVT> &NodeTys, 2567 const PPCSubtarget &PPCSubTarget) { 2568 2569 bool isPPC64 = PPCSubTarget.isPPC64(); 2570 bool isSVR4ABI = PPCSubTarget.isSVR4ABI(); 2571 2572 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2573 NodeTys.push_back(MVT::Other); // Returns a chain 2574 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 2575 2576 unsigned CallOpc = isSVR4ABI ? PPCISD::CALL_SVR4 : PPCISD::CALL_Darwin; 2577 2578 bool needIndirectCall = true; 2579 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 2580 // If this is an absolute destination address, use the munged value. 2581 Callee = SDValue(Dest, 0); 2582 needIndirectCall = false; 2583 } 2584 2585 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2586 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201 2587 // Use indirect calls for ALL functions calls in JIT mode, since the 2588 // far-call stubs may be outside relocation limits for a BL instruction. 2589 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) { 2590 unsigned OpFlags = 0; 2591 if (DAG.getTarget().getRelocationModel() != Reloc::Static && 2592 (PPCSubTarget.getTargetTriple().isMacOSX() && 2593 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) && 2594 (G->getGlobal()->isDeclaration() || 2595 G->getGlobal()->isWeakForLinker())) { 2596 // PC-relative references to external symbols should go through $stub, 2597 // unless we're building with the leopard linker or later, which 2598 // automatically synthesizes these stubs. 2599 OpFlags = PPCII::MO_DARWIN_STUB; 2600 } 2601 2602 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 2603 // every direct call is) turn it into a TargetGlobalAddress / 2604 // TargetExternalSymbol node so that legalize doesn't hack it. 2605 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 2606 Callee.getValueType(), 2607 0, OpFlags); 2608 needIndirectCall = false; 2609 } 2610 } 2611 2612 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2613 unsigned char OpFlags = 0; 2614 2615 if (DAG.getTarget().getRelocationModel() != Reloc::Static && 2616 (PPCSubTarget.getTargetTriple().isMacOSX() && 2617 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) { 2618 // PC-relative references to external symbols should go through $stub, 2619 // unless we're building with the leopard linker or later, which 2620 // automatically synthesizes these stubs. 2621 OpFlags = PPCII::MO_DARWIN_STUB; 2622 } 2623 2624 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 2625 OpFlags); 2626 needIndirectCall = false; 2627 } 2628 2629 if (needIndirectCall) { 2630 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 2631 // to do the call, we can't use PPCISD::CALL. 2632 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 2633 2634 if (isSVR4ABI && isPPC64) { 2635 // Function pointers in the 64-bit SVR4 ABI do not point to the function 2636 // entry point, but to the function descriptor (the function entry point 2637 // address is part of the function descriptor though). 2638 // The function descriptor is a three doubleword structure with the 2639 // following fields: function entry point, TOC base address and 2640 // environment pointer. 2641 // Thus for a call through a function pointer, the following actions need 2642 // to be performed: 2643 // 1. Save the TOC of the caller in the TOC save area of its stack 2644 // frame (this is done in LowerCall_Darwin()). 2645 // 2. Load the address of the function entry point from the function 2646 // descriptor. 2647 // 3. Load the TOC of the callee from the function descriptor into r2. 2648 // 4. Load the environment pointer from the function descriptor into 2649 // r11. 2650 // 5. Branch to the function entry point address. 2651 // 6. On return of the callee, the TOC of the caller needs to be 2652 // restored (this is done in FinishCall()). 2653 // 2654 // All those operations are flagged together to ensure that no other 2655 // operations can be scheduled in between. E.g. without flagging the 2656 // operations together, a TOC access in the caller could be scheduled 2657 // between the load of the callee TOC and the branch to the callee, which 2658 // results in the TOC access going through the TOC of the callee instead 2659 // of going through the TOC of the caller, which leads to incorrect code. 2660 2661 // Load the address of the function entry point from the function 2662 // descriptor. 2663 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue); 2664 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps, 2665 InFlag.getNode() ? 3 : 2); 2666 Chain = LoadFuncPtr.getValue(1); 2667 InFlag = LoadFuncPtr.getValue(2); 2668 2669 // Load environment pointer into r11. 2670 // Offset of the environment pointer within the function descriptor. 2671 SDValue PtrOff = DAG.getIntPtrConstant(16); 2672 2673 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 2674 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr, 2675 InFlag); 2676 Chain = LoadEnvPtr.getValue(1); 2677 InFlag = LoadEnvPtr.getValue(2); 2678 2679 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 2680 InFlag); 2681 Chain = EnvVal.getValue(0); 2682 InFlag = EnvVal.getValue(1); 2683 2684 // Load TOC of the callee into r2. We are using a target-specific load 2685 // with r2 hard coded, because the result of a target-independent load 2686 // would never go directly into r2, since r2 is a reserved register (which 2687 // prevents the register allocator from allocating it), resulting in an 2688 // additional register being allocated and an unnecessary move instruction 2689 // being generated. 2690 VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2691 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, 2692 Callee, InFlag); 2693 Chain = LoadTOCPtr.getValue(0); 2694 InFlag = LoadTOCPtr.getValue(1); 2695 2696 MTCTROps[0] = Chain; 2697 MTCTROps[1] = LoadFuncPtr; 2698 MTCTROps[2] = InFlag; 2699 } 2700 2701 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps, 2702 2 + (InFlag.getNode() != 0)); 2703 InFlag = Chain.getValue(1); 2704 2705 NodeTys.clear(); 2706 NodeTys.push_back(MVT::Other); 2707 NodeTys.push_back(MVT::Glue); 2708 Ops.push_back(Chain); 2709 CallOpc = isSVR4ABI ? PPCISD::BCTRL_SVR4 : PPCISD::BCTRL_Darwin; 2710 Callee.setNode(0); 2711 // Add CTR register as callee so a bctr can be emitted later. 2712 if (isTailCall) 2713 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 2714 } 2715 2716 // If this is a direct call, pass the chain and the callee. 2717 if (Callee.getNode()) { 2718 Ops.push_back(Chain); 2719 Ops.push_back(Callee); 2720 } 2721 // If this is a tail call add stack pointer delta. 2722 if (isTailCall) 2723 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32)); 2724 2725 // Add argument registers to the end of the list so that they are known live 2726 // into the call. 2727 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2728 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2729 RegsToPass[i].second.getValueType())); 2730 2731 return CallOpc; 2732 } 2733 2734 SDValue 2735 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 2736 CallingConv::ID CallConv, bool isVarArg, 2737 const SmallVectorImpl<ISD::InputArg> &Ins, 2738 DebugLoc dl, SelectionDAG &DAG, 2739 SmallVectorImpl<SDValue> &InVals) const { 2740 2741 SmallVector<CCValAssign, 16> RVLocs; 2742 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), 2743 getTargetMachine(), RVLocs, *DAG.getContext()); 2744 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC); 2745 2746 // Copy all of the result registers out of their specified physreg. 2747 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 2748 CCValAssign &VA = RVLocs[i]; 2749 EVT VT = VA.getValVT(); 2750 assert(VA.isRegLoc() && "Can only return in registers!"); 2751 Chain = DAG.getCopyFromReg(Chain, dl, 2752 VA.getLocReg(), VT, InFlag).getValue(1); 2753 InVals.push_back(Chain.getValue(0)); 2754 InFlag = Chain.getValue(2); 2755 } 2756 2757 return Chain; 2758 } 2759 2760 SDValue 2761 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, DebugLoc dl, 2762 bool isTailCall, bool isVarArg, 2763 SelectionDAG &DAG, 2764 SmallVector<std::pair<unsigned, SDValue>, 8> 2765 &RegsToPass, 2766 SDValue InFlag, SDValue Chain, 2767 SDValue &Callee, 2768 int SPDiff, unsigned NumBytes, 2769 const SmallVectorImpl<ISD::InputArg> &Ins, 2770 SmallVectorImpl<SDValue> &InVals) const { 2771 std::vector<EVT> NodeTys; 2772 SmallVector<SDValue, 8> Ops; 2773 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff, 2774 isTailCall, RegsToPass, Ops, NodeTys, 2775 PPCSubTarget); 2776 2777 // When performing tail call optimization the callee pops its arguments off 2778 // the stack. Account for this here so these bytes can be pushed back on in 2779 // PPCRegisterInfo::eliminateCallFramePseudoInstr. 2780 int BytesCalleePops = 2781 (CallConv == CallingConv::Fast && 2782 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 2783 2784 // Add a register mask operand representing the call-preserved registers. 2785 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo(); 2786 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv); 2787 assert(Mask && "Missing call preserved mask for calling convention"); 2788 Ops.push_back(DAG.getRegisterMask(Mask)); 2789 2790 if (InFlag.getNode()) 2791 Ops.push_back(InFlag); 2792 2793 // Emit tail call. 2794 if (isTailCall) { 2795 // If this is the first return lowered for this function, add the regs 2796 // to the liveout set for the function. 2797 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) { 2798 SmallVector<CCValAssign, 16> RVLocs; 2799 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 2800 getTargetMachine(), RVLocs, *DAG.getContext()); 2801 CCInfo.AnalyzeCallResult(Ins, RetCC_PPC); 2802 for (unsigned i = 0; i != RVLocs.size(); ++i) 2803 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg()); 2804 } 2805 2806 assert(((Callee.getOpcode() == ISD::Register && 2807 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 2808 Callee.getOpcode() == ISD::TargetExternalSymbol || 2809 Callee.getOpcode() == ISD::TargetGlobalAddress || 2810 isa<ConstantSDNode>(Callee)) && 2811 "Expecting an global address, external symbol, absolute value or register"); 2812 2813 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size()); 2814 } 2815 2816 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size()); 2817 InFlag = Chain.getValue(1); 2818 2819 // Add a NOP immediately after the branch instruction when using the 64-bit 2820 // SVR4 ABI. At link time, if caller and callee are in a different module and 2821 // thus have a different TOC, the call will be replaced with a call to a stub 2822 // function which saves the current TOC, loads the TOC of the callee and 2823 // branches to the callee. The NOP will be replaced with a load instruction 2824 // which restores the TOC of the caller from the TOC save slot of the current 2825 // stack frame. If caller and callee belong to the same module (and have the 2826 // same TOC), the NOP will remain unchanged. 2827 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) { 2828 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 2829 if (CallOpc == PPCISD::BCTRL_SVR4) { 2830 // This is a call through a function pointer. 2831 // Restore the caller TOC from the save area into R2. 2832 // See PrepareCall() for more information about calls through function 2833 // pointers in the 64-bit SVR4 ABI. 2834 // We are using a target-specific load with r2 hard coded, because the 2835 // result of a target-independent load would never go directly into r2, 2836 // since r2 is a reserved register (which prevents the register allocator 2837 // from allocating it), resulting in an additional register being 2838 // allocated and an unnecessary move instruction being generated. 2839 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag); 2840 InFlag = Chain.getValue(1); 2841 } else { 2842 // Otherwise insert NOP. 2843 InFlag = DAG.getNode(PPCISD::NOP, dl, MVT::Glue, InFlag); 2844 } 2845 } 2846 2847 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 2848 DAG.getIntPtrConstant(BytesCalleePops, true), 2849 InFlag); 2850 if (!Ins.empty()) 2851 InFlag = Chain.getValue(1); 2852 2853 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 2854 Ins, dl, DAG, InVals); 2855 } 2856 2857 SDValue 2858 PPCTargetLowering::LowerCall(SDValue Chain, SDValue Callee, 2859 CallingConv::ID CallConv, bool isVarArg, 2860 bool doesNotRet, bool &isTailCall, 2861 const SmallVectorImpl<ISD::OutputArg> &Outs, 2862 const SmallVectorImpl<SDValue> &OutVals, 2863 const SmallVectorImpl<ISD::InputArg> &Ins, 2864 DebugLoc dl, SelectionDAG &DAG, 2865 SmallVectorImpl<SDValue> &InVals) const { 2866 if (isTailCall) 2867 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 2868 Ins, DAG); 2869 2870 if (PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64()) 2871 return LowerCall_SVR4(Chain, Callee, CallConv, isVarArg, 2872 isTailCall, Outs, OutVals, Ins, 2873 dl, DAG, InVals); 2874 2875 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 2876 isTailCall, Outs, OutVals, Ins, 2877 dl, DAG, InVals); 2878 } 2879 2880 SDValue 2881 PPCTargetLowering::LowerCall_SVR4(SDValue Chain, SDValue Callee, 2882 CallingConv::ID CallConv, bool isVarArg, 2883 bool isTailCall, 2884 const SmallVectorImpl<ISD::OutputArg> &Outs, 2885 const SmallVectorImpl<SDValue> &OutVals, 2886 const SmallVectorImpl<ISD::InputArg> &Ins, 2887 DebugLoc dl, SelectionDAG &DAG, 2888 SmallVectorImpl<SDValue> &InVals) const { 2889 // See PPCTargetLowering::LowerFormalArguments_SVR4() for a description 2890 // of the 32-bit SVR4 ABI stack frame layout. 2891 2892 assert((CallConv == CallingConv::C || 2893 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 2894 2895 unsigned PtrByteSize = 4; 2896 2897 MachineFunction &MF = DAG.getMachineFunction(); 2898 2899 // Mark this function as potentially containing a function that contains a 2900 // tail call. As a consequence the frame pointer will be used for dynamicalloc 2901 // and restoring the callers stack pointer in this functions epilog. This is 2902 // done because by tail calling the called function might overwrite the value 2903 // in this function's (MF) stack pointer stack slot 0(SP). 2904 if (getTargetMachine().Options.GuaranteedTailCallOpt && 2905 CallConv == CallingConv::Fast) 2906 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 2907 2908 // Count how many bytes are to be pushed on the stack, including the linkage 2909 // area, parameter list area and the part of the local variable space which 2910 // contains copies of aggregates which are passed by value. 2911 2912 // Assign locations to all of the outgoing arguments. 2913 SmallVector<CCValAssign, 16> ArgLocs; 2914 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 2915 getTargetMachine(), ArgLocs, *DAG.getContext()); 2916 2917 // Reserve space for the linkage area on the stack. 2918 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize); 2919 2920 if (isVarArg) { 2921 // Handle fixed and variable vector arguments differently. 2922 // Fixed vector arguments go into registers as long as registers are 2923 // available. Variable vector arguments always go into memory. 2924 unsigned NumArgs = Outs.size(); 2925 2926 for (unsigned i = 0; i != NumArgs; ++i) { 2927 MVT ArgVT = Outs[i].VT; 2928 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 2929 bool Result; 2930 2931 if (Outs[i].IsFixed) { 2932 Result = CC_PPC_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 2933 CCInfo); 2934 } else { 2935 Result = CC_PPC_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 2936 ArgFlags, CCInfo); 2937 } 2938 2939 if (Result) { 2940 #ifndef NDEBUG 2941 errs() << "Call operand #" << i << " has unhandled type " 2942 << EVT(ArgVT).getEVTString() << "\n"; 2943 #endif 2944 llvm_unreachable(0); 2945 } 2946 } 2947 } else { 2948 // All arguments are treated the same. 2949 CCInfo.AnalyzeCallOperands(Outs, CC_PPC_SVR4); 2950 } 2951 2952 // Assign locations to all of the outgoing aggregate by value arguments. 2953 SmallVector<CCValAssign, 16> ByValArgLocs; 2954 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 2955 getTargetMachine(), ByValArgLocs, *DAG.getContext()); 2956 2957 // Reserve stack space for the allocations in CCInfo. 2958 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 2959 2960 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC_SVR4_ByVal); 2961 2962 // Size of the linkage area, parameter list area and the part of the local 2963 // space variable where copies of aggregates which are passed by value are 2964 // stored. 2965 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 2966 2967 // Calculate by how many bytes the stack has to be adjusted in case of tail 2968 // call optimization. 2969 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 2970 2971 // Adjust the stack pointer for the new arguments... 2972 // These operations are automatically eliminated by the prolog/epilog pass 2973 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true)); 2974 SDValue CallSeqStart = Chain; 2975 2976 // Load the return address and frame pointer so it can be moved somewhere else 2977 // later. 2978 SDValue LROp, FPOp; 2979 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false, 2980 dl); 2981 2982 // Set up a copy of the stack pointer for use loading and storing any 2983 // arguments that may not fit in the registers available for argument 2984 // passing. 2985 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 2986 2987 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2988 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 2989 SmallVector<SDValue, 8> MemOpChains; 2990 2991 bool seenFloatArg = false; 2992 // Walk the register/memloc assignments, inserting copies/loads. 2993 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 2994 i != e; 2995 ++i) { 2996 CCValAssign &VA = ArgLocs[i]; 2997 SDValue Arg = OutVals[i]; 2998 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2999 3000 if (Flags.isByVal()) { 3001 // Argument is an aggregate which is passed by value, thus we need to 3002 // create a copy of it in the local variable space of the current stack 3003 // frame (which is the stack frame of the caller) and pass the address of 3004 // this copy to the callee. 3005 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 3006 CCValAssign &ByValVA = ByValArgLocs[j++]; 3007 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 3008 3009 // Memory reserved in the local variable space of the callers stack frame. 3010 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 3011 3012 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 3013 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 3014 3015 // Create a copy of the argument in the local area of the current 3016 // stack frame. 3017 SDValue MemcpyCall = 3018 CreateCopyOfByValArgument(Arg, PtrOff, 3019 CallSeqStart.getNode()->getOperand(0), 3020 Flags, DAG, dl); 3021 3022 // This must go outside the CALLSEQ_START..END. 3023 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, 3024 CallSeqStart.getNode()->getOperand(1)); 3025 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 3026 NewCallSeqStart.getNode()); 3027 Chain = CallSeqStart = NewCallSeqStart; 3028 3029 // Pass the address of the aggregate copy on the stack either in a 3030 // physical register or in the parameter list area of the current stack 3031 // frame to the callee. 3032 Arg = PtrOff; 3033 } 3034 3035 if (VA.isRegLoc()) { 3036 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 3037 // Put argument in a physical register. 3038 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3039 } else { 3040 // Put argument in the parameter list area of the current stack frame. 3041 assert(VA.isMemLoc()); 3042 unsigned LocMemOffset = VA.getLocMemOffset(); 3043 3044 if (!isTailCall) { 3045 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 3046 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 3047 3048 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, 3049 MachinePointerInfo(), 3050 false, false, 0)); 3051 } else { 3052 // Calculate and remember argument location. 3053 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 3054 TailCallArguments); 3055 } 3056 } 3057 } 3058 3059 if (!MemOpChains.empty()) 3060 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3061 &MemOpChains[0], MemOpChains.size()); 3062 3063 // Set CR6 to true if this is a vararg call with floating args passed in 3064 // registers. 3065 if (isVarArg) { 3066 SDValue SetCR(DAG.getMachineNode(seenFloatArg ? PPC::CRSET : PPC::CRUNSET, 3067 dl, MVT::i32), 0); 3068 RegsToPass.push_back(std::make_pair(unsigned(PPC::CR1EQ), SetCR)); 3069 } 3070 3071 // Build a sequence of copy-to-reg nodes chained together with token chain 3072 // and flag operands which copy the outgoing args into the appropriate regs. 3073 SDValue InFlag; 3074 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 3075 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 3076 RegsToPass[i].second, InFlag); 3077 InFlag = Chain.getValue(1); 3078 } 3079 3080 if (isTailCall) 3081 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp, 3082 false, TailCallArguments); 3083 3084 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG, 3085 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes, 3086 Ins, InVals); 3087 } 3088 3089 SDValue 3090 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee, 3091 CallingConv::ID CallConv, bool isVarArg, 3092 bool isTailCall, 3093 const SmallVectorImpl<ISD::OutputArg> &Outs, 3094 const SmallVectorImpl<SDValue> &OutVals, 3095 const SmallVectorImpl<ISD::InputArg> &Ins, 3096 DebugLoc dl, SelectionDAG &DAG, 3097 SmallVectorImpl<SDValue> &InVals) const { 3098 3099 unsigned NumOps = Outs.size(); 3100 3101 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3102 bool isPPC64 = PtrVT == MVT::i64; 3103 unsigned PtrByteSize = isPPC64 ? 8 : 4; 3104 3105 MachineFunction &MF = DAG.getMachineFunction(); 3106 3107 // Mark this function as potentially containing a function that contains a 3108 // tail call. As a consequence the frame pointer will be used for dynamicalloc 3109 // and restoring the callers stack pointer in this functions epilog. This is 3110 // done because by tail calling the called function might overwrite the value 3111 // in this function's (MF) stack pointer stack slot 0(SP). 3112 if (getTargetMachine().Options.GuaranteedTailCallOpt && 3113 CallConv == CallingConv::Fast) 3114 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 3115 3116 unsigned nAltivecParamsAtEnd = 0; 3117 3118 // Count how many bytes are to be pushed on the stack, including the linkage 3119 // area, and parameter passing area. We start with 24/48 bytes, which is 3120 // prereserved space for [SP][CR][LR][3 x unused]. 3121 unsigned NumBytes = 3122 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv, 3123 Outs, OutVals, 3124 nAltivecParamsAtEnd); 3125 3126 // Calculate by how many bytes the stack has to be adjusted in case of tail 3127 // call optimization. 3128 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 3129 3130 // To protect arguments on the stack from being clobbered in a tail call, 3131 // force all the loads to happen before doing any other lowering. 3132 if (isTailCall) 3133 Chain = DAG.getStackArgumentTokenFactor(Chain); 3134 3135 // Adjust the stack pointer for the new arguments... 3136 // These operations are automatically eliminated by the prolog/epilog pass 3137 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true)); 3138 SDValue CallSeqStart = Chain; 3139 3140 // Load the return address and frame pointer so it can be move somewhere else 3141 // later. 3142 SDValue LROp, FPOp; 3143 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true, 3144 dl); 3145 3146 // Set up a copy of the stack pointer for use loading and storing any 3147 // arguments that may not fit in the registers available for argument 3148 // passing. 3149 SDValue StackPtr; 3150 if (isPPC64) 3151 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 3152 else 3153 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 3154 3155 // Figure out which arguments are going to go in registers, and which in 3156 // memory. Also, if this is a vararg function, floating point operations 3157 // must be stored to our stack, and loaded into integer regs as well, if 3158 // any integer regs are available for argument passing. 3159 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true); 3160 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3161 3162 static const uint16_t GPR_32[] = { // 32-bit registers. 3163 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3164 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3165 }; 3166 static const uint16_t GPR_64[] = { // 64-bit registers. 3167 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3168 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3169 }; 3170 static const uint16_t *FPR = GetFPR(); 3171 3172 static const uint16_t VR[] = { 3173 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3174 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3175 }; 3176 const unsigned NumGPRs = array_lengthof(GPR_32); 3177 const unsigned NumFPRs = 13; 3178 const unsigned NumVRs = array_lengthof(VR); 3179 3180 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32; 3181 3182 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3183 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 3184 3185 SmallVector<SDValue, 8> MemOpChains; 3186 for (unsigned i = 0; i != NumOps; ++i) { 3187 SDValue Arg = OutVals[i]; 3188 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3189 3190 // PtrOff will be used to store the current argument to the stack if a 3191 // register cannot be found for it. 3192 SDValue PtrOff; 3193 3194 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType()); 3195 3196 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 3197 3198 // On PPC64, promote integers to 64-bit values. 3199 if (isPPC64 && Arg.getValueType() == MVT::i32) { 3200 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 3201 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 3202 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 3203 } 3204 3205 // FIXME memcpy is used way more than necessary. Correctness first. 3206 if (Flags.isByVal()) { 3207 unsigned Size = Flags.getByValSize(); 3208 if (Size==1 || Size==2) { 3209 // Very small objects are passed right-justified. 3210 // Everything else is passed left-justified. 3211 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 3212 if (GPR_idx != NumGPRs) { 3213 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 3214 MachinePointerInfo(), VT, 3215 false, false, 0); 3216 MemOpChains.push_back(Load.getValue(1)); 3217 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 3218 3219 ArgOffset += PtrByteSize; 3220 } else { 3221 SDValue Const = DAG.getConstant(4 - Size, PtrOff.getValueType()); 3222 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 3223 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, AddPtr, 3224 CallSeqStart.getNode()->getOperand(0), 3225 Flags, DAG, dl); 3226 // This must go outside the CALLSEQ_START..END. 3227 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, 3228 CallSeqStart.getNode()->getOperand(1)); 3229 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 3230 NewCallSeqStart.getNode()); 3231 Chain = CallSeqStart = NewCallSeqStart; 3232 ArgOffset += PtrByteSize; 3233 } 3234 continue; 3235 } 3236 // Copy entire object into memory. There are cases where gcc-generated 3237 // code assumes it is there, even if it could be put entirely into 3238 // registers. (This is not what the doc says.) 3239 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 3240 CallSeqStart.getNode()->getOperand(0), 3241 Flags, DAG, dl); 3242 // This must go outside the CALLSEQ_START..END. 3243 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, 3244 CallSeqStart.getNode()->getOperand(1)); 3245 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), NewCallSeqStart.getNode()); 3246 Chain = CallSeqStart = NewCallSeqStart; 3247 // And copy the pieces of it that fit into registers. 3248 for (unsigned j=0; j<Size; j+=PtrByteSize) { 3249 SDValue Const = DAG.getConstant(j, PtrOff.getValueType()); 3250 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 3251 if (GPR_idx != NumGPRs) { 3252 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 3253 MachinePointerInfo(), 3254 false, false, false, 0); 3255 MemOpChains.push_back(Load.getValue(1)); 3256 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 3257 ArgOffset += PtrByteSize; 3258 } else { 3259 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 3260 break; 3261 } 3262 } 3263 continue; 3264 } 3265 3266 switch (Arg.getValueType().getSimpleVT().SimpleTy) { 3267 default: llvm_unreachable("Unexpected ValueType for argument!"); 3268 case MVT::i32: 3269 case MVT::i64: 3270 if (GPR_idx != NumGPRs) { 3271 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 3272 } else { 3273 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 3274 isPPC64, isTailCall, false, MemOpChains, 3275 TailCallArguments, dl); 3276 } 3277 ArgOffset += PtrByteSize; 3278 break; 3279 case MVT::f32: 3280 case MVT::f64: 3281 if (FPR_idx != NumFPRs) { 3282 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 3283 3284 if (isVarArg) { 3285 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, 3286 MachinePointerInfo(), false, false, 0); 3287 MemOpChains.push_back(Store); 3288 3289 // Float varargs are always shadowed in available integer registers 3290 if (GPR_idx != NumGPRs) { 3291 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, 3292 MachinePointerInfo(), false, false, 3293 false, 0); 3294 MemOpChains.push_back(Load.getValue(1)); 3295 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 3296 } 3297 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 3298 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType()); 3299 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 3300 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, 3301 MachinePointerInfo(), 3302 false, false, false, 0); 3303 MemOpChains.push_back(Load.getValue(1)); 3304 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 3305 } 3306 } else { 3307 // If we have any FPRs remaining, we may also have GPRs remaining. 3308 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 3309 // GPRs. 3310 if (GPR_idx != NumGPRs) 3311 ++GPR_idx; 3312 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 3313 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 3314 ++GPR_idx; 3315 } 3316 } else { 3317 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 3318 isPPC64, isTailCall, false, MemOpChains, 3319 TailCallArguments, dl); 3320 } 3321 if (isPPC64) 3322 ArgOffset += 8; 3323 else 3324 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 3325 break; 3326 case MVT::v4f32: 3327 case MVT::v4i32: 3328 case MVT::v8i16: 3329 case MVT::v16i8: 3330 if (isVarArg) { 3331 // These go aligned on the stack, or in the corresponding R registers 3332 // when within range. The Darwin PPC ABI doc claims they also go in 3333 // V registers; in fact gcc does this only for arguments that are 3334 // prototyped, not for those that match the ... We do it for all 3335 // arguments, seems to work. 3336 while (ArgOffset % 16 !=0) { 3337 ArgOffset += PtrByteSize; 3338 if (GPR_idx != NumGPRs) 3339 GPR_idx++; 3340 } 3341 // We could elide this store in the case where the object fits 3342 // entirely in R registers. Maybe later. 3343 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 3344 DAG.getConstant(ArgOffset, PtrVT)); 3345 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, 3346 MachinePointerInfo(), false, false, 0); 3347 MemOpChains.push_back(Store); 3348 if (VR_idx != NumVRs) { 3349 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, 3350 MachinePointerInfo(), 3351 false, false, false, 0); 3352 MemOpChains.push_back(Load.getValue(1)); 3353 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 3354 } 3355 ArgOffset += 16; 3356 for (unsigned i=0; i<16; i+=PtrByteSize) { 3357 if (GPR_idx == NumGPRs) 3358 break; 3359 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 3360 DAG.getConstant(i, PtrVT)); 3361 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(), 3362 false, false, false, 0); 3363 MemOpChains.push_back(Load.getValue(1)); 3364 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 3365 } 3366 break; 3367 } 3368 3369 // Non-varargs Altivec params generally go in registers, but have 3370 // stack space allocated at the end. 3371 if (VR_idx != NumVRs) { 3372 // Doesn't have GPR space allocated. 3373 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 3374 } else if (nAltivecParamsAtEnd==0) { 3375 // We are emitting Altivec params in order. 3376 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 3377 isPPC64, isTailCall, true, MemOpChains, 3378 TailCallArguments, dl); 3379 ArgOffset += 16; 3380 } 3381 break; 3382 } 3383 } 3384 // If all Altivec parameters fit in registers, as they usually do, 3385 // they get stack space following the non-Altivec parameters. We 3386 // don't track this here because nobody below needs it. 3387 // If there are more Altivec parameters than fit in registers emit 3388 // the stores here. 3389 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 3390 unsigned j = 0; 3391 // Offset is aligned; skip 1st 12 params which go in V registers. 3392 ArgOffset = ((ArgOffset+15)/16)*16; 3393 ArgOffset += 12*16; 3394 for (unsigned i = 0; i != NumOps; ++i) { 3395 SDValue Arg = OutVals[i]; 3396 EVT ArgType = Outs[i].VT; 3397 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 3398 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 3399 if (++j > NumVRs) { 3400 SDValue PtrOff; 3401 // We are emitting Altivec params in order. 3402 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 3403 isPPC64, isTailCall, true, MemOpChains, 3404 TailCallArguments, dl); 3405 ArgOffset += 16; 3406 } 3407 } 3408 } 3409 } 3410 3411 if (!MemOpChains.empty()) 3412 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3413 &MemOpChains[0], MemOpChains.size()); 3414 3415 // Check if this is an indirect call (MTCTR/BCTRL). 3416 // See PrepareCall() for more information about calls through function 3417 // pointers in the 64-bit SVR4 ABI. 3418 if (!isTailCall && isPPC64 && PPCSubTarget.isSVR4ABI() && 3419 !dyn_cast<GlobalAddressSDNode>(Callee) && 3420 !dyn_cast<ExternalSymbolSDNode>(Callee) && 3421 !isBLACompatibleAddress(Callee, DAG)) { 3422 // Load r2 into a virtual register and store it to the TOC save area. 3423 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 3424 // TOC save area offset. 3425 SDValue PtrOff = DAG.getIntPtrConstant(40); 3426 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 3427 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(), 3428 false, false, 0); 3429 } 3430 3431 // On Darwin, R12 must contain the address of an indirect callee. This does 3432 // not mean the MTCTR instruction must use R12; it's easier to model this as 3433 // an extra parameter, so do that. 3434 if (!isTailCall && 3435 !dyn_cast<GlobalAddressSDNode>(Callee) && 3436 !dyn_cast<ExternalSymbolSDNode>(Callee) && 3437 !isBLACompatibleAddress(Callee, DAG)) 3438 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 3439 PPC::R12), Callee)); 3440 3441 // Build a sequence of copy-to-reg nodes chained together with token chain 3442 // and flag operands which copy the outgoing args into the appropriate regs. 3443 SDValue InFlag; 3444 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 3445 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 3446 RegsToPass[i].second, InFlag); 3447 InFlag = Chain.getValue(1); 3448 } 3449 3450 if (isTailCall) 3451 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp, 3452 FPOp, true, TailCallArguments); 3453 3454 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG, 3455 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes, 3456 Ins, InVals); 3457 } 3458 3459 bool 3460 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 3461 MachineFunction &MF, bool isVarArg, 3462 const SmallVectorImpl<ISD::OutputArg> &Outs, 3463 LLVMContext &Context) const { 3464 SmallVector<CCValAssign, 16> RVLocs; 3465 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 3466 RVLocs, Context); 3467 return CCInfo.CheckReturn(Outs, RetCC_PPC); 3468 } 3469 3470 SDValue 3471 PPCTargetLowering::LowerReturn(SDValue Chain, 3472 CallingConv::ID CallConv, bool isVarArg, 3473 const SmallVectorImpl<ISD::OutputArg> &Outs, 3474 const SmallVectorImpl<SDValue> &OutVals, 3475 DebugLoc dl, SelectionDAG &DAG) const { 3476 3477 SmallVector<CCValAssign, 16> RVLocs; 3478 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3479 getTargetMachine(), RVLocs, *DAG.getContext()); 3480 CCInfo.AnalyzeReturn(Outs, RetCC_PPC); 3481 3482 // If this is the first return lowered for this function, add the regs to the 3483 // liveout set for the function. 3484 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) { 3485 for (unsigned i = 0; i != RVLocs.size(); ++i) 3486 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg()); 3487 } 3488 3489 SDValue Flag; 3490 3491 // Copy the result values into the output registers. 3492 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3493 CCValAssign &VA = RVLocs[i]; 3494 assert(VA.isRegLoc() && "Can only return in registers!"); 3495 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 3496 OutVals[i], Flag); 3497 Flag = Chain.getValue(1); 3498 } 3499 3500 if (Flag.getNode()) 3501 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain, Flag); 3502 else 3503 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain); 3504 } 3505 3506 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG, 3507 const PPCSubtarget &Subtarget) const { 3508 // When we pop the dynamic allocation we need to restore the SP link. 3509 DebugLoc dl = Op.getDebugLoc(); 3510 3511 // Get the corect type for pointers. 3512 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3513 3514 // Construct the stack pointer operand. 3515 bool isPPC64 = Subtarget.isPPC64(); 3516 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 3517 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 3518 3519 // Get the operands for the STACKRESTORE. 3520 SDValue Chain = Op.getOperand(0); 3521 SDValue SaveSP = Op.getOperand(1); 3522 3523 // Load the old link SP. 3524 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr, 3525 MachinePointerInfo(), 3526 false, false, false, 0); 3527 3528 // Restore the stack pointer. 3529 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 3530 3531 // Store the old link SP. 3532 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(), 3533 false, false, 0); 3534 } 3535 3536 3537 3538 SDValue 3539 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const { 3540 MachineFunction &MF = DAG.getMachineFunction(); 3541 bool isPPC64 = PPCSubTarget.isPPC64(); 3542 bool isDarwinABI = PPCSubTarget.isDarwinABI(); 3543 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3544 3545 // Get current frame pointer save index. The users of this index will be 3546 // primarily DYNALLOC instructions. 3547 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 3548 int RASI = FI->getReturnAddrSaveIndex(); 3549 3550 // If the frame pointer save index hasn't been defined yet. 3551 if (!RASI) { 3552 // Find out what the fix offset of the frame pointer save area. 3553 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI); 3554 // Allocate the frame index for frame pointer save area. 3555 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true); 3556 // Save the result. 3557 FI->setReturnAddrSaveIndex(RASI); 3558 } 3559 return DAG.getFrameIndex(RASI, PtrVT); 3560 } 3561 3562 SDValue 3563 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 3564 MachineFunction &MF = DAG.getMachineFunction(); 3565 bool isPPC64 = PPCSubTarget.isPPC64(); 3566 bool isDarwinABI = PPCSubTarget.isDarwinABI(); 3567 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3568 3569 // Get current frame pointer save index. The users of this index will be 3570 // primarily DYNALLOC instructions. 3571 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 3572 int FPSI = FI->getFramePointerSaveIndex(); 3573 3574 // If the frame pointer save index hasn't been defined yet. 3575 if (!FPSI) { 3576 // Find out what the fix offset of the frame pointer save area. 3577 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64, 3578 isDarwinABI); 3579 3580 // Allocate the frame index for frame pointer save area. 3581 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 3582 // Save the result. 3583 FI->setFramePointerSaveIndex(FPSI); 3584 } 3585 return DAG.getFrameIndex(FPSI, PtrVT); 3586 } 3587 3588 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3589 SelectionDAG &DAG, 3590 const PPCSubtarget &Subtarget) const { 3591 // Get the inputs. 3592 SDValue Chain = Op.getOperand(0); 3593 SDValue Size = Op.getOperand(1); 3594 DebugLoc dl = Op.getDebugLoc(); 3595 3596 // Get the corect type for pointers. 3597 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3598 // Negate the size. 3599 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 3600 DAG.getConstant(0, PtrVT), Size); 3601 // Construct a node for the frame pointer save index. 3602 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 3603 // Build a DYNALLOC node. 3604 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 3605 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 3606 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3); 3607 } 3608 3609 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 3610 /// possible. 3611 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 3612 // Not FP? Not a fsel. 3613 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 3614 !Op.getOperand(2).getValueType().isFloatingPoint()) 3615 return Op; 3616 3617 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3618 3619 // Cannot handle SETEQ/SETNE. 3620 if (CC == ISD::SETEQ || CC == ISD::SETNE) return Op; 3621 3622 EVT ResVT = Op.getValueType(); 3623 EVT CmpVT = Op.getOperand(0).getValueType(); 3624 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 3625 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 3626 DebugLoc dl = Op.getDebugLoc(); 3627 3628 // If the RHS of the comparison is a 0.0, we don't need to do the 3629 // subtraction at all. 3630 if (isFloatingPointZero(RHS)) 3631 switch (CC) { 3632 default: break; // SETUO etc aren't handled by fsel. 3633 case ISD::SETULT: 3634 case ISD::SETLT: 3635 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 3636 case ISD::SETOGE: 3637 case ISD::SETGE: 3638 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 3639 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 3640 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 3641 case ISD::SETUGT: 3642 case ISD::SETGT: 3643 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 3644 case ISD::SETOLE: 3645 case ISD::SETLE: 3646 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 3647 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 3648 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 3649 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 3650 } 3651 3652 SDValue Cmp; 3653 switch (CC) { 3654 default: break; // SETUO etc aren't handled by fsel. 3655 case ISD::SETULT: 3656 case ISD::SETLT: 3657 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS); 3658 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 3659 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 3660 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 3661 case ISD::SETOGE: 3662 case ISD::SETGE: 3663 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS); 3664 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 3665 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 3666 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 3667 case ISD::SETUGT: 3668 case ISD::SETGT: 3669 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS); 3670 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 3671 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 3672 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 3673 case ISD::SETOLE: 3674 case ISD::SETLE: 3675 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS); 3676 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 3677 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 3678 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 3679 } 3680 return Op; 3681 } 3682 3683 // FIXME: Split this code up when LegalizeDAGTypes lands. 3684 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 3685 DebugLoc dl) const { 3686 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 3687 SDValue Src = Op.getOperand(0); 3688 if (Src.getValueType() == MVT::f32) 3689 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 3690 3691 SDValue Tmp; 3692 switch (Op.getValueType().getSimpleVT().SimpleTy) { 3693 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 3694 case MVT::i32: 3695 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ : 3696 PPCISD::FCTIDZ, 3697 dl, MVT::f64, Src); 3698 break; 3699 case MVT::i64: 3700 Tmp = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Src); 3701 break; 3702 } 3703 3704 // Convert the FP value to an int value through memory. 3705 SDValue FIPtr = DAG.CreateStackTemporary(MVT::f64); 3706 3707 // Emit a store to the stack slot. 3708 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, 3709 MachinePointerInfo(), false, false, 0); 3710 3711 // Result is a load from the stack slot. If loading 4 bytes, make sure to 3712 // add in a bias. 3713 if (Op.getValueType() == MVT::i32) 3714 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 3715 DAG.getConstant(4, FIPtr.getValueType())); 3716 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MachinePointerInfo(), 3717 false, false, false, 0); 3718 } 3719 3720 SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op, 3721 SelectionDAG &DAG) const { 3722 DebugLoc dl = Op.getDebugLoc(); 3723 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 3724 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 3725 return SDValue(); 3726 3727 if (Op.getOperand(0).getValueType() == MVT::i64) { 3728 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op.getOperand(0)); 3729 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Bits); 3730 if (Op.getValueType() == MVT::f32) 3731 FP = DAG.getNode(ISD::FP_ROUND, dl, 3732 MVT::f32, FP, DAG.getIntPtrConstant(0)); 3733 return FP; 3734 } 3735 3736 assert(Op.getOperand(0).getValueType() == MVT::i32 && 3737 "Unhandled SINT_TO_FP type in custom expander!"); 3738 // Since we only generate this in 64-bit mode, we can take advantage of 3739 // 64-bit registers. In particular, sign extend the input value into the 3740 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 3741 // then lfd it and fcfid it. 3742 MachineFunction &MF = DAG.getMachineFunction(); 3743 MachineFrameInfo *FrameInfo = MF.getFrameInfo(); 3744 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false); 3745 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3746 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 3747 3748 SDValue Ext64 = DAG.getNode(PPCISD::EXTSW_32, dl, MVT::i32, 3749 Op.getOperand(0)); 3750 3751 // STD the extended value into the stack slot. 3752 MachineMemOperand *MMO = 3753 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx), 3754 MachineMemOperand::MOStore, 8, 8); 3755 SDValue Ops[] = { DAG.getEntryNode(), Ext64, FIdx }; 3756 SDValue Store = 3757 DAG.getMemIntrinsicNode(PPCISD::STD_32, dl, DAG.getVTList(MVT::Other), 3758 Ops, 4, MVT::i64, MMO); 3759 // Load the value as a double. 3760 SDValue Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, MachinePointerInfo(), 3761 false, false, false, 0); 3762 3763 // FCFID it and return it. 3764 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Ld); 3765 if (Op.getValueType() == MVT::f32) 3766 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0)); 3767 return FP; 3768 } 3769 3770 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 3771 SelectionDAG &DAG) const { 3772 DebugLoc dl = Op.getDebugLoc(); 3773 /* 3774 The rounding mode is in bits 30:31 of FPSR, and has the following 3775 settings: 3776 00 Round to nearest 3777 01 Round to 0 3778 10 Round to +inf 3779 11 Round to -inf 3780 3781 FLT_ROUNDS, on the other hand, expects the following: 3782 -1 Undefined 3783 0 Round to 0 3784 1 Round to nearest 3785 2 Round to +inf 3786 3 Round to -inf 3787 3788 To perform the conversion, we do: 3789 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 3790 */ 3791 3792 MachineFunction &MF = DAG.getMachineFunction(); 3793 EVT VT = Op.getValueType(); 3794 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 3795 std::vector<EVT> NodeTys; 3796 SDValue MFFSreg, InFlag; 3797 3798 // Save FP Control Word to register 3799 NodeTys.push_back(MVT::f64); // return register 3800 NodeTys.push_back(MVT::Glue); // unused in this context 3801 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0); 3802 3803 // Save FP register to stack slot 3804 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false); 3805 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 3806 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, 3807 StackSlot, MachinePointerInfo(), false, false,0); 3808 3809 // Load FP Control Word from low 32 bits of stack slot. 3810 SDValue Four = DAG.getConstant(4, PtrVT); 3811 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 3812 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(), 3813 false, false, false, 0); 3814 3815 // Transform as necessary 3816 SDValue CWD1 = 3817 DAG.getNode(ISD::AND, dl, MVT::i32, 3818 CWD, DAG.getConstant(3, MVT::i32)); 3819 SDValue CWD2 = 3820 DAG.getNode(ISD::SRL, dl, MVT::i32, 3821 DAG.getNode(ISD::AND, dl, MVT::i32, 3822 DAG.getNode(ISD::XOR, dl, MVT::i32, 3823 CWD, DAG.getConstant(3, MVT::i32)), 3824 DAG.getConstant(3, MVT::i32)), 3825 DAG.getConstant(1, MVT::i32)); 3826 3827 SDValue RetVal = 3828 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 3829 3830 return DAG.getNode((VT.getSizeInBits() < 16 ? 3831 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 3832 } 3833 3834 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 3835 EVT VT = Op.getValueType(); 3836 unsigned BitWidth = VT.getSizeInBits(); 3837 DebugLoc dl = Op.getDebugLoc(); 3838 assert(Op.getNumOperands() == 3 && 3839 VT == Op.getOperand(1).getValueType() && 3840 "Unexpected SHL!"); 3841 3842 // Expand into a bunch of logical ops. Note that these ops 3843 // depend on the PPC behavior for oversized shift amounts. 3844 SDValue Lo = Op.getOperand(0); 3845 SDValue Hi = Op.getOperand(1); 3846 SDValue Amt = Op.getOperand(2); 3847 EVT AmtVT = Amt.getValueType(); 3848 3849 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 3850 DAG.getConstant(BitWidth, AmtVT), Amt); 3851 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 3852 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 3853 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 3854 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 3855 DAG.getConstant(-BitWidth, AmtVT)); 3856 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 3857 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 3858 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 3859 SDValue OutOps[] = { OutLo, OutHi }; 3860 return DAG.getMergeValues(OutOps, 2, dl); 3861 } 3862 3863 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 3864 EVT VT = Op.getValueType(); 3865 DebugLoc dl = Op.getDebugLoc(); 3866 unsigned BitWidth = VT.getSizeInBits(); 3867 assert(Op.getNumOperands() == 3 && 3868 VT == Op.getOperand(1).getValueType() && 3869 "Unexpected SRL!"); 3870 3871 // Expand into a bunch of logical ops. Note that these ops 3872 // depend on the PPC behavior for oversized shift amounts. 3873 SDValue Lo = Op.getOperand(0); 3874 SDValue Hi = Op.getOperand(1); 3875 SDValue Amt = Op.getOperand(2); 3876 EVT AmtVT = Amt.getValueType(); 3877 3878 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 3879 DAG.getConstant(BitWidth, AmtVT), Amt); 3880 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 3881 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 3882 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 3883 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 3884 DAG.getConstant(-BitWidth, AmtVT)); 3885 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 3886 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 3887 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 3888 SDValue OutOps[] = { OutLo, OutHi }; 3889 return DAG.getMergeValues(OutOps, 2, dl); 3890 } 3891 3892 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 3893 DebugLoc dl = Op.getDebugLoc(); 3894 EVT VT = Op.getValueType(); 3895 unsigned BitWidth = VT.getSizeInBits(); 3896 assert(Op.getNumOperands() == 3 && 3897 VT == Op.getOperand(1).getValueType() && 3898 "Unexpected SRA!"); 3899 3900 // Expand into a bunch of logical ops, followed by a select_cc. 3901 SDValue Lo = Op.getOperand(0); 3902 SDValue Hi = Op.getOperand(1); 3903 SDValue Amt = Op.getOperand(2); 3904 EVT AmtVT = Amt.getValueType(); 3905 3906 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 3907 DAG.getConstant(BitWidth, AmtVT), Amt); 3908 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 3909 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 3910 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 3911 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 3912 DAG.getConstant(-BitWidth, AmtVT)); 3913 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 3914 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 3915 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT), 3916 Tmp4, Tmp6, ISD::SETLE); 3917 SDValue OutOps[] = { OutLo, OutHi }; 3918 return DAG.getMergeValues(OutOps, 2, dl); 3919 } 3920 3921 //===----------------------------------------------------------------------===// 3922 // Vector related lowering. 3923 // 3924 3925 /// BuildSplatI - Build a canonical splati of Val with an element size of 3926 /// SplatSize. Cast the result to VT. 3927 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 3928 SelectionDAG &DAG, DebugLoc dl) { 3929 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 3930 3931 static const EVT VTys[] = { // canonical VT to use for each size. 3932 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 3933 }; 3934 3935 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 3936 3937 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 3938 if (Val == -1) 3939 SplatSize = 1; 3940 3941 EVT CanonicalVT = VTys[SplatSize-1]; 3942 3943 // Build a canonical splat for this value. 3944 SDValue Elt = DAG.getConstant(Val, MVT::i32); 3945 SmallVector<SDValue, 8> Ops; 3946 Ops.assign(CanonicalVT.getVectorNumElements(), Elt); 3947 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, 3948 &Ops[0], Ops.size()); 3949 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res); 3950 } 3951 3952 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 3953 /// specified intrinsic ID. 3954 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 3955 SelectionDAG &DAG, DebugLoc dl, 3956 EVT DestVT = MVT::Other) { 3957 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 3958 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 3959 DAG.getConstant(IID, MVT::i32), LHS, RHS); 3960 } 3961 3962 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 3963 /// specified intrinsic ID. 3964 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 3965 SDValue Op2, SelectionDAG &DAG, 3966 DebugLoc dl, EVT DestVT = MVT::Other) { 3967 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 3968 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 3969 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2); 3970 } 3971 3972 3973 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 3974 /// amount. The result has the specified value type. 3975 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, 3976 EVT VT, SelectionDAG &DAG, DebugLoc dl) { 3977 // Force LHS/RHS to be the right type. 3978 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 3979 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 3980 3981 int Ops[16]; 3982 for (unsigned i = 0; i != 16; ++i) 3983 Ops[i] = i + Amt; 3984 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 3985 return DAG.getNode(ISD::BITCAST, dl, VT, T); 3986 } 3987 3988 // If this is a case we can't handle, return null and let the default 3989 // expansion code take care of it. If we CAN select this case, and if it 3990 // selects to a single instruction, return Op. Otherwise, if we can codegen 3991 // this case more efficiently than a constant pool load, lower it to the 3992 // sequence of ops that should be used. 3993 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 3994 SelectionDAG &DAG) const { 3995 DebugLoc dl = Op.getDebugLoc(); 3996 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 3997 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 3998 3999 // Check if this is a splat of a constant value. 4000 APInt APSplatBits, APSplatUndef; 4001 unsigned SplatBitSize; 4002 bool HasAnyUndefs; 4003 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 4004 HasAnyUndefs, 0, true) || SplatBitSize > 32) 4005 return SDValue(); 4006 4007 unsigned SplatBits = APSplatBits.getZExtValue(); 4008 unsigned SplatUndef = APSplatUndef.getZExtValue(); 4009 unsigned SplatSize = SplatBitSize / 8; 4010 4011 // First, handle single instruction cases. 4012 4013 // All zeros? 4014 if (SplatBits == 0) { 4015 // Canonicalize all zero vectors to be v4i32. 4016 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 4017 SDValue Z = DAG.getConstant(0, MVT::i32); 4018 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z); 4019 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 4020 } 4021 return Op; 4022 } 4023 4024 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 4025 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 4026 (32-SplatBitSize)); 4027 if (SextVal >= -16 && SextVal <= 15) 4028 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 4029 4030 4031 // Two instruction sequences. 4032 4033 // If this value is in the range [-32,30] and is even, use: 4034 // tmp = VSPLTI[bhw], result = add tmp, tmp 4035 if (SextVal >= -32 && SextVal <= 30 && (SextVal & 1) == 0) { 4036 SDValue Res = BuildSplatI(SextVal >> 1, SplatSize, MVT::Other, DAG, dl); 4037 Res = DAG.getNode(ISD::ADD, dl, Res.getValueType(), Res, Res); 4038 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 4039 } 4040 4041 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 4042 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 4043 // for fneg/fabs. 4044 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 4045 // Make -1 and vspltisw -1: 4046 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 4047 4048 // Make the VSLW intrinsic, computing 0x8000_0000. 4049 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 4050 OnesV, DAG, dl); 4051 4052 // xor by OnesV to invert it. 4053 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 4054 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 4055 } 4056 4057 // Check to see if this is a wide variety of vsplti*, binop self cases. 4058 static const signed char SplatCsts[] = { 4059 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 4060 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 4061 }; 4062 4063 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 4064 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 4065 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 4066 int i = SplatCsts[idx]; 4067 4068 // Figure out what shift amount will be used by altivec if shifted by i in 4069 // this splat size. 4070 unsigned TypeShiftAmt = i & (SplatBitSize-1); 4071 4072 // vsplti + shl self. 4073 if (SextVal == (i << (int)TypeShiftAmt)) { 4074 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 4075 static const unsigned IIDs[] = { // Intrinsic to use for each size. 4076 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 4077 Intrinsic::ppc_altivec_vslw 4078 }; 4079 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 4080 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 4081 } 4082 4083 // vsplti + srl self. 4084 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 4085 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 4086 static const unsigned IIDs[] = { // Intrinsic to use for each size. 4087 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 4088 Intrinsic::ppc_altivec_vsrw 4089 }; 4090 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 4091 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 4092 } 4093 4094 // vsplti + sra self. 4095 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 4096 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 4097 static const unsigned IIDs[] = { // Intrinsic to use for each size. 4098 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 4099 Intrinsic::ppc_altivec_vsraw 4100 }; 4101 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 4102 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 4103 } 4104 4105 // vsplti + rol self. 4106 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 4107 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 4108 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 4109 static const unsigned IIDs[] = { // Intrinsic to use for each size. 4110 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 4111 Intrinsic::ppc_altivec_vrlw 4112 }; 4113 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 4114 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 4115 } 4116 4117 // t = vsplti c, result = vsldoi t, t, 1 4118 if (SextVal == ((i << 8) | (i < 0 ? 0xFF : 0))) { 4119 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 4120 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl); 4121 } 4122 // t = vsplti c, result = vsldoi t, t, 2 4123 if (SextVal == ((i << 16) | (i < 0 ? 0xFFFF : 0))) { 4124 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 4125 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl); 4126 } 4127 // t = vsplti c, result = vsldoi t, t, 3 4128 if (SextVal == ((i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 4129 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 4130 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl); 4131 } 4132 } 4133 4134 // Three instruction sequences. 4135 4136 // Odd, in range [17,31]: (vsplti C)-(vsplti -16). 4137 if (SextVal >= 0 && SextVal <= 31) { 4138 SDValue LHS = BuildSplatI(SextVal-16, SplatSize, MVT::Other, DAG, dl); 4139 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl); 4140 LHS = DAG.getNode(ISD::SUB, dl, LHS.getValueType(), LHS, RHS); 4141 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), LHS); 4142 } 4143 // Odd, in range [-31,-17]: (vsplti C)+(vsplti -16). 4144 if (SextVal >= -31 && SextVal <= 0) { 4145 SDValue LHS = BuildSplatI(SextVal+16, SplatSize, MVT::Other, DAG, dl); 4146 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl); 4147 LHS = DAG.getNode(ISD::ADD, dl, LHS.getValueType(), LHS, RHS); 4148 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), LHS); 4149 } 4150 4151 return SDValue(); 4152 } 4153 4154 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 4155 /// the specified operations to build the shuffle. 4156 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 4157 SDValue RHS, SelectionDAG &DAG, 4158 DebugLoc dl) { 4159 unsigned OpNum = (PFEntry >> 26) & 0x0F; 4160 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 4161 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 4162 4163 enum { 4164 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 4165 OP_VMRGHW, 4166 OP_VMRGLW, 4167 OP_VSPLTISW0, 4168 OP_VSPLTISW1, 4169 OP_VSPLTISW2, 4170 OP_VSPLTISW3, 4171 OP_VSLDOI4, 4172 OP_VSLDOI8, 4173 OP_VSLDOI12 4174 }; 4175 4176 if (OpNum == OP_COPY) { 4177 if (LHSID == (1*9+2)*9+3) return LHS; 4178 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 4179 return RHS; 4180 } 4181 4182 SDValue OpLHS, OpRHS; 4183 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 4184 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 4185 4186 int ShufIdxs[16]; 4187 switch (OpNum) { 4188 default: llvm_unreachable("Unknown i32 permute!"); 4189 case OP_VMRGHW: 4190 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 4191 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 4192 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 4193 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 4194 break; 4195 case OP_VMRGLW: 4196 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 4197 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 4198 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 4199 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 4200 break; 4201 case OP_VSPLTISW0: 4202 for (unsigned i = 0; i != 16; ++i) 4203 ShufIdxs[i] = (i&3)+0; 4204 break; 4205 case OP_VSPLTISW1: 4206 for (unsigned i = 0; i != 16; ++i) 4207 ShufIdxs[i] = (i&3)+4; 4208 break; 4209 case OP_VSPLTISW2: 4210 for (unsigned i = 0; i != 16; ++i) 4211 ShufIdxs[i] = (i&3)+8; 4212 break; 4213 case OP_VSPLTISW3: 4214 for (unsigned i = 0; i != 16; ++i) 4215 ShufIdxs[i] = (i&3)+12; 4216 break; 4217 case OP_VSLDOI4: 4218 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 4219 case OP_VSLDOI8: 4220 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 4221 case OP_VSLDOI12: 4222 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 4223 } 4224 EVT VT = OpLHS.getValueType(); 4225 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 4226 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 4227 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 4228 return DAG.getNode(ISD::BITCAST, dl, VT, T); 4229 } 4230 4231 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 4232 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 4233 /// return the code it can be lowered into. Worst case, it can always be 4234 /// lowered into a vperm. 4235 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 4236 SelectionDAG &DAG) const { 4237 DebugLoc dl = Op.getDebugLoc(); 4238 SDValue V1 = Op.getOperand(0); 4239 SDValue V2 = Op.getOperand(1); 4240 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 4241 EVT VT = Op.getValueType(); 4242 4243 // Cases that are handled by instructions that take permute immediates 4244 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 4245 // selected by the instruction selector. 4246 if (V2.getOpcode() == ISD::UNDEF) { 4247 if (PPC::isSplatShuffleMask(SVOp, 1) || 4248 PPC::isSplatShuffleMask(SVOp, 2) || 4249 PPC::isSplatShuffleMask(SVOp, 4) || 4250 PPC::isVPKUWUMShuffleMask(SVOp, true) || 4251 PPC::isVPKUHUMShuffleMask(SVOp, true) || 4252 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 || 4253 PPC::isVMRGLShuffleMask(SVOp, 1, true) || 4254 PPC::isVMRGLShuffleMask(SVOp, 2, true) || 4255 PPC::isVMRGLShuffleMask(SVOp, 4, true) || 4256 PPC::isVMRGHShuffleMask(SVOp, 1, true) || 4257 PPC::isVMRGHShuffleMask(SVOp, 2, true) || 4258 PPC::isVMRGHShuffleMask(SVOp, 4, true)) { 4259 return Op; 4260 } 4261 } 4262 4263 // Altivec has a variety of "shuffle immediates" that take two vector inputs 4264 // and produce a fixed permutation. If any of these match, do not lower to 4265 // VPERM. 4266 if (PPC::isVPKUWUMShuffleMask(SVOp, false) || 4267 PPC::isVPKUHUMShuffleMask(SVOp, false) || 4268 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 || 4269 PPC::isVMRGLShuffleMask(SVOp, 1, false) || 4270 PPC::isVMRGLShuffleMask(SVOp, 2, false) || 4271 PPC::isVMRGLShuffleMask(SVOp, 4, false) || 4272 PPC::isVMRGHShuffleMask(SVOp, 1, false) || 4273 PPC::isVMRGHShuffleMask(SVOp, 2, false) || 4274 PPC::isVMRGHShuffleMask(SVOp, 4, false)) 4275 return Op; 4276 4277 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 4278 // perfect shuffle table to emit an optimal matching sequence. 4279 ArrayRef<int> PermMask = SVOp->getMask(); 4280 4281 unsigned PFIndexes[4]; 4282 bool isFourElementShuffle = true; 4283 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 4284 unsigned EltNo = 8; // Start out undef. 4285 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 4286 if (PermMask[i*4+j] < 0) 4287 continue; // Undef, ignore it. 4288 4289 unsigned ByteSource = PermMask[i*4+j]; 4290 if ((ByteSource & 3) != j) { 4291 isFourElementShuffle = false; 4292 break; 4293 } 4294 4295 if (EltNo == 8) { 4296 EltNo = ByteSource/4; 4297 } else if (EltNo != ByteSource/4) { 4298 isFourElementShuffle = false; 4299 break; 4300 } 4301 } 4302 PFIndexes[i] = EltNo; 4303 } 4304 4305 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 4306 // perfect shuffle vector to determine if it is cost effective to do this as 4307 // discrete instructions, or whether we should use a vperm. 4308 if (isFourElementShuffle) { 4309 // Compute the index in the perfect shuffle table. 4310 unsigned PFTableIndex = 4311 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 4312 4313 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 4314 unsigned Cost = (PFEntry >> 30); 4315 4316 // Determining when to avoid vperm is tricky. Many things affect the cost 4317 // of vperm, particularly how many times the perm mask needs to be computed. 4318 // For example, if the perm mask can be hoisted out of a loop or is already 4319 // used (perhaps because there are multiple permutes with the same shuffle 4320 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 4321 // the loop requires an extra register. 4322 // 4323 // As a compromise, we only emit discrete instructions if the shuffle can be 4324 // generated in 3 or fewer operations. When we have loop information 4325 // available, if this block is within a loop, we should avoid using vperm 4326 // for 3-operation perms and use a constant pool load instead. 4327 if (Cost < 3) 4328 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 4329 } 4330 4331 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 4332 // vector that will get spilled to the constant pool. 4333 if (V2.getOpcode() == ISD::UNDEF) V2 = V1; 4334 4335 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 4336 // that it is in input element units, not in bytes. Convert now. 4337 EVT EltVT = V1.getValueType().getVectorElementType(); 4338 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 4339 4340 SmallVector<SDValue, 16> ResultMask; 4341 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 4342 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 4343 4344 for (unsigned j = 0; j != BytesPerElement; ++j) 4345 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j, 4346 MVT::i32)); 4347 } 4348 4349 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8, 4350 &ResultMask[0], ResultMask.size()); 4351 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask); 4352 } 4353 4354 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an 4355 /// altivec comparison. If it is, return true and fill in Opc/isDot with 4356 /// information about the intrinsic. 4357 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc, 4358 bool &isDot) { 4359 unsigned IntrinsicID = 4360 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 4361 CompareOpc = -1; 4362 isDot = false; 4363 switch (IntrinsicID) { 4364 default: return false; 4365 // Comparison predicates. 4366 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break; 4367 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break; 4368 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break; 4369 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break; 4370 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break; 4371 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break; 4372 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break; 4373 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break; 4374 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break; 4375 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break; 4376 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break; 4377 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break; 4378 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break; 4379 4380 // Normal Comparisons. 4381 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break; 4382 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break; 4383 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break; 4384 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break; 4385 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break; 4386 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break; 4387 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break; 4388 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break; 4389 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break; 4390 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break; 4391 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break; 4392 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break; 4393 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break; 4394 } 4395 return true; 4396 } 4397 4398 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 4399 /// lower, do it, otherwise return null. 4400 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4401 SelectionDAG &DAG) const { 4402 // If this is a lowered altivec predicate compare, CompareOpc is set to the 4403 // opcode number of the comparison. 4404 DebugLoc dl = Op.getDebugLoc(); 4405 int CompareOpc; 4406 bool isDot; 4407 if (!getAltivecCompareInfo(Op, CompareOpc, isDot)) 4408 return SDValue(); // Don't custom lower most intrinsics. 4409 4410 // If this is a non-dot comparison, make the VCMP node and we are done. 4411 if (!isDot) { 4412 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 4413 Op.getOperand(1), Op.getOperand(2), 4414 DAG.getConstant(CompareOpc, MVT::i32)); 4415 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 4416 } 4417 4418 // Create the PPCISD altivec 'dot' comparison node. 4419 SDValue Ops[] = { 4420 Op.getOperand(2), // LHS 4421 Op.getOperand(3), // RHS 4422 DAG.getConstant(CompareOpc, MVT::i32) 4423 }; 4424 std::vector<EVT> VTs; 4425 VTs.push_back(Op.getOperand(2).getValueType()); 4426 VTs.push_back(MVT::Glue); 4427 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3); 4428 4429 // Now that we have the comparison, emit a copy from the CR to a GPR. 4430 // This is flagged to the above dot comparison. 4431 SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32, 4432 DAG.getRegister(PPC::CR6, MVT::i32), 4433 CompNode.getValue(1)); 4434 4435 // Unpack the result based on how the target uses it. 4436 unsigned BitNo; // Bit # of CR6. 4437 bool InvertBit; // Invert result? 4438 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 4439 default: // Can't happen, don't crash on invalid number though. 4440 case 0: // Return the value of the EQ bit of CR6. 4441 BitNo = 0; InvertBit = false; 4442 break; 4443 case 1: // Return the inverted value of the EQ bit of CR6. 4444 BitNo = 0; InvertBit = true; 4445 break; 4446 case 2: // Return the value of the LT bit of CR6. 4447 BitNo = 2; InvertBit = false; 4448 break; 4449 case 3: // Return the inverted value of the LT bit of CR6. 4450 BitNo = 2; InvertBit = true; 4451 break; 4452 } 4453 4454 // Shift the bit into the low position. 4455 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 4456 DAG.getConstant(8-(3-BitNo), MVT::i32)); 4457 // Isolate the bit. 4458 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 4459 DAG.getConstant(1, MVT::i32)); 4460 4461 // If we are supposed to, toggle the bit. 4462 if (InvertBit) 4463 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 4464 DAG.getConstant(1, MVT::i32)); 4465 return Flags; 4466 } 4467 4468 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 4469 SelectionDAG &DAG) const { 4470 DebugLoc dl = Op.getDebugLoc(); 4471 // Create a stack slot that is 16-byte aligned. 4472 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 4473 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false); 4474 EVT PtrVT = getPointerTy(); 4475 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 4476 4477 // Store the input value into Value#0 of the stack slot. 4478 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, 4479 Op.getOperand(0), FIdx, MachinePointerInfo(), 4480 false, false, 0); 4481 // Load it out. 4482 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(), 4483 false, false, false, 0); 4484 } 4485 4486 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 4487 DebugLoc dl = Op.getDebugLoc(); 4488 if (Op.getValueType() == MVT::v4i32) { 4489 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 4490 4491 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 4492 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 4493 4494 SDValue RHSSwap = // = vrlw RHS, 16 4495 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 4496 4497 // Shrinkify inputs to v8i16. 4498 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 4499 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 4500 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 4501 4502 // Low parts multiplied together, generating 32-bit results (we ignore the 4503 // top parts). 4504 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 4505 LHS, RHS, DAG, dl, MVT::v4i32); 4506 4507 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 4508 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 4509 // Shift the high parts up 16 bits. 4510 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 4511 Neg16, DAG, dl); 4512 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 4513 } else if (Op.getValueType() == MVT::v8i16) { 4514 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 4515 4516 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 4517 4518 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 4519 LHS, RHS, Zero, DAG, dl); 4520 } else if (Op.getValueType() == MVT::v16i8) { 4521 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 4522 4523 // Multiply the even 8-bit parts, producing 16-bit sums. 4524 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 4525 LHS, RHS, DAG, dl, MVT::v8i16); 4526 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 4527 4528 // Multiply the odd 8-bit parts, producing 16-bit sums. 4529 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 4530 LHS, RHS, DAG, dl, MVT::v8i16); 4531 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 4532 4533 // Merge the results together. 4534 int Ops[16]; 4535 for (unsigned i = 0; i != 8; ++i) { 4536 Ops[i*2 ] = 2*i+1; 4537 Ops[i*2+1] = 2*i+1+16; 4538 } 4539 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 4540 } else { 4541 llvm_unreachable("Unknown mul to lower!"); 4542 } 4543 } 4544 4545 /// LowerOperation - Provide custom lowering hooks for some operations. 4546 /// 4547 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4548 switch (Op.getOpcode()) { 4549 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 4550 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 4551 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 4552 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 4553 case ISD::GlobalTLSAddress: llvm_unreachable("TLS not implemented for PPC"); 4554 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 4555 case ISD::SETCC: return LowerSETCC(Op, DAG); 4556 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 4557 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 4558 case ISD::VASTART: 4559 return LowerVASTART(Op, DAG, PPCSubTarget); 4560 4561 case ISD::VAARG: 4562 return LowerVAARG(Op, DAG, PPCSubTarget); 4563 4564 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget); 4565 case ISD::DYNAMIC_STACKALLOC: 4566 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget); 4567 4568 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 4569 case ISD::FP_TO_UINT: 4570 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, 4571 Op.getDebugLoc()); 4572 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG); 4573 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 4574 4575 // Lower 64-bit shifts. 4576 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 4577 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 4578 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 4579 4580 // Vector-related lowering. 4581 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 4582 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 4583 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4584 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 4585 case ISD::MUL: return LowerMUL(Op, DAG); 4586 4587 // Frame & Return address. 4588 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4589 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 4590 } 4591 } 4592 4593 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 4594 SmallVectorImpl<SDValue>&Results, 4595 SelectionDAG &DAG) const { 4596 const TargetMachine &TM = getTargetMachine(); 4597 DebugLoc dl = N->getDebugLoc(); 4598 switch (N->getOpcode()) { 4599 default: 4600 llvm_unreachable("Do not know how to custom type legalize this operation!"); 4601 case ISD::VAARG: { 4602 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI() 4603 || TM.getSubtarget<PPCSubtarget>().isPPC64()) 4604 return; 4605 4606 EVT VT = N->getValueType(0); 4607 4608 if (VT == MVT::i64) { 4609 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget); 4610 4611 Results.push_back(NewNode); 4612 Results.push_back(NewNode.getValue(1)); 4613 } 4614 return; 4615 } 4616 case ISD::FP_ROUND_INREG: { 4617 assert(N->getValueType(0) == MVT::ppcf128); 4618 assert(N->getOperand(0).getValueType() == MVT::ppcf128); 4619 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 4620 MVT::f64, N->getOperand(0), 4621 DAG.getIntPtrConstant(0)); 4622 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 4623 MVT::f64, N->getOperand(0), 4624 DAG.getIntPtrConstant(1)); 4625 4626 // This sequence changes FPSCR to do round-to-zero, adds the two halves 4627 // of the long double, and puts FPSCR back the way it was. We do not 4628 // actually model FPSCR. 4629 std::vector<EVT> NodeTys; 4630 SDValue Ops[4], Result, MFFSreg, InFlag, FPreg; 4631 4632 NodeTys.push_back(MVT::f64); // Return register 4633 NodeTys.push_back(MVT::Glue); // Returns a flag for later insns 4634 Result = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0); 4635 MFFSreg = Result.getValue(0); 4636 InFlag = Result.getValue(1); 4637 4638 NodeTys.clear(); 4639 NodeTys.push_back(MVT::Glue); // Returns a flag 4640 Ops[0] = DAG.getConstant(31, MVT::i32); 4641 Ops[1] = InFlag; 4642 Result = DAG.getNode(PPCISD::MTFSB1, dl, NodeTys, Ops, 2); 4643 InFlag = Result.getValue(0); 4644 4645 NodeTys.clear(); 4646 NodeTys.push_back(MVT::Glue); // Returns a flag 4647 Ops[0] = DAG.getConstant(30, MVT::i32); 4648 Ops[1] = InFlag; 4649 Result = DAG.getNode(PPCISD::MTFSB0, dl, NodeTys, Ops, 2); 4650 InFlag = Result.getValue(0); 4651 4652 NodeTys.clear(); 4653 NodeTys.push_back(MVT::f64); // result of add 4654 NodeTys.push_back(MVT::Glue); // Returns a flag 4655 Ops[0] = Lo; 4656 Ops[1] = Hi; 4657 Ops[2] = InFlag; 4658 Result = DAG.getNode(PPCISD::FADDRTZ, dl, NodeTys, Ops, 3); 4659 FPreg = Result.getValue(0); 4660 InFlag = Result.getValue(1); 4661 4662 NodeTys.clear(); 4663 NodeTys.push_back(MVT::f64); 4664 Ops[0] = DAG.getConstant(1, MVT::i32); 4665 Ops[1] = MFFSreg; 4666 Ops[2] = FPreg; 4667 Ops[3] = InFlag; 4668 Result = DAG.getNode(PPCISD::MTFSF, dl, NodeTys, Ops, 4); 4669 FPreg = Result.getValue(0); 4670 4671 // We know the low half is about to be thrown away, so just use something 4672 // convenient. 4673 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 4674 FPreg, FPreg)); 4675 return; 4676 } 4677 case ISD::FP_TO_SINT: 4678 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 4679 return; 4680 } 4681 } 4682 4683 4684 //===----------------------------------------------------------------------===// 4685 // Other Lowering Code 4686 //===----------------------------------------------------------------------===// 4687 4688 MachineBasicBlock * 4689 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB, 4690 bool is64bit, unsigned BinOpcode) const { 4691 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 4692 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 4693 4694 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 4695 MachineFunction *F = BB->getParent(); 4696 MachineFunction::iterator It = BB; 4697 ++It; 4698 4699 unsigned dest = MI->getOperand(0).getReg(); 4700 unsigned ptrA = MI->getOperand(1).getReg(); 4701 unsigned ptrB = MI->getOperand(2).getReg(); 4702 unsigned incr = MI->getOperand(3).getReg(); 4703 DebugLoc dl = MI->getDebugLoc(); 4704 4705 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 4706 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 4707 F->insert(It, loopMBB); 4708 F->insert(It, exitMBB); 4709 exitMBB->splice(exitMBB->begin(), BB, 4710 llvm::next(MachineBasicBlock::iterator(MI)), 4711 BB->end()); 4712 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 4713 4714 MachineRegisterInfo &RegInfo = F->getRegInfo(); 4715 unsigned TmpReg = (!BinOpcode) ? incr : 4716 RegInfo.createVirtualRegister( 4717 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass : 4718 (const TargetRegisterClass *) &PPC::GPRCRegClass); 4719 4720 // thisMBB: 4721 // ... 4722 // fallthrough --> loopMBB 4723 BB->addSuccessor(loopMBB); 4724 4725 // loopMBB: 4726 // l[wd]arx dest, ptr 4727 // add r0, dest, incr 4728 // st[wd]cx. r0, ptr 4729 // bne- loopMBB 4730 // fallthrough --> exitMBB 4731 BB = loopMBB; 4732 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest) 4733 .addReg(ptrA).addReg(ptrB); 4734 if (BinOpcode) 4735 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 4736 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX)) 4737 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 4738 BuildMI(BB, dl, TII->get(PPC::BCC)) 4739 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 4740 BB->addSuccessor(loopMBB); 4741 BB->addSuccessor(exitMBB); 4742 4743 // exitMBB: 4744 // ... 4745 BB = exitMBB; 4746 return BB; 4747 } 4748 4749 MachineBasicBlock * 4750 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI, 4751 MachineBasicBlock *BB, 4752 bool is8bit, // operation 4753 unsigned BinOpcode) const { 4754 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 4755 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 4756 // In 64 bit mode we have to use 64 bits for addresses, even though the 4757 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 4758 // registers without caring whether they're 32 or 64, but here we're 4759 // doing actual arithmetic on the addresses. 4760 bool is64bit = PPCSubTarget.isPPC64(); 4761 unsigned ZeroReg = is64bit ? PPC::X0 : PPC::R0; 4762 4763 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 4764 MachineFunction *F = BB->getParent(); 4765 MachineFunction::iterator It = BB; 4766 ++It; 4767 4768 unsigned dest = MI->getOperand(0).getReg(); 4769 unsigned ptrA = MI->getOperand(1).getReg(); 4770 unsigned ptrB = MI->getOperand(2).getReg(); 4771 unsigned incr = MI->getOperand(3).getReg(); 4772 DebugLoc dl = MI->getDebugLoc(); 4773 4774 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 4775 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 4776 F->insert(It, loopMBB); 4777 F->insert(It, exitMBB); 4778 exitMBB->splice(exitMBB->begin(), BB, 4779 llvm::next(MachineBasicBlock::iterator(MI)), 4780 BB->end()); 4781 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 4782 4783 MachineRegisterInfo &RegInfo = F->getRegInfo(); 4784 const TargetRegisterClass *RC = 4785 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass : 4786 (const TargetRegisterClass *) &PPC::GPRCRegClass; 4787 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 4788 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 4789 unsigned ShiftReg = RegInfo.createVirtualRegister(RC); 4790 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 4791 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 4792 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 4793 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 4794 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 4795 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 4796 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 4797 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 4798 unsigned Ptr1Reg; 4799 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 4800 4801 // thisMBB: 4802 // ... 4803 // fallthrough --> loopMBB 4804 BB->addSuccessor(loopMBB); 4805 4806 // The 4-byte load must be aligned, while a char or short may be 4807 // anywhere in the word. Hence all this nasty bookkeeping code. 4808 // add ptr1, ptrA, ptrB [copy if ptrA==0] 4809 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 4810 // xori shift, shift1, 24 [16] 4811 // rlwinm ptr, ptr1, 0, 0, 29 4812 // slw incr2, incr, shift 4813 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 4814 // slw mask, mask2, shift 4815 // loopMBB: 4816 // lwarx tmpDest, ptr 4817 // add tmp, tmpDest, incr2 4818 // andc tmp2, tmpDest, mask 4819 // and tmp3, tmp, mask 4820 // or tmp4, tmp3, tmp2 4821 // stwcx. tmp4, ptr 4822 // bne- loopMBB 4823 // fallthrough --> exitMBB 4824 // srw dest, tmpDest, shift 4825 if (ptrA != ZeroReg) { 4826 Ptr1Reg = RegInfo.createVirtualRegister(RC); 4827 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 4828 .addReg(ptrA).addReg(ptrB); 4829 } else { 4830 Ptr1Reg = ptrB; 4831 } 4832 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 4833 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 4834 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 4835 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 4836 if (is64bit) 4837 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 4838 .addReg(Ptr1Reg).addImm(0).addImm(61); 4839 else 4840 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 4841 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 4842 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 4843 .addReg(incr).addReg(ShiftReg); 4844 if (is8bit) 4845 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 4846 else { 4847 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 4848 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 4849 } 4850 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 4851 .addReg(Mask2Reg).addReg(ShiftReg); 4852 4853 BB = loopMBB; 4854 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 4855 .addReg(ZeroReg).addReg(PtrReg); 4856 if (BinOpcode) 4857 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 4858 .addReg(Incr2Reg).addReg(TmpDestReg); 4859 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 4860 .addReg(TmpDestReg).addReg(MaskReg); 4861 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 4862 .addReg(TmpReg).addReg(MaskReg); 4863 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 4864 .addReg(Tmp3Reg).addReg(Tmp2Reg); 4865 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX)) 4866 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 4867 BuildMI(BB, dl, TII->get(PPC::BCC)) 4868 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 4869 BB->addSuccessor(loopMBB); 4870 BB->addSuccessor(exitMBB); 4871 4872 // exitMBB: 4873 // ... 4874 BB = exitMBB; 4875 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 4876 .addReg(ShiftReg); 4877 return BB; 4878 } 4879 4880 MachineBasicBlock * 4881 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 4882 MachineBasicBlock *BB) const { 4883 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 4884 4885 // To "insert" these instructions we actually have to insert their 4886 // control-flow patterns. 4887 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 4888 MachineFunction::iterator It = BB; 4889 ++It; 4890 4891 MachineFunction *F = BB->getParent(); 4892 4893 if (MI->getOpcode() == PPC::SELECT_CC_I4 || 4894 MI->getOpcode() == PPC::SELECT_CC_I8 || 4895 MI->getOpcode() == PPC::SELECT_CC_F4 || 4896 MI->getOpcode() == PPC::SELECT_CC_F8 || 4897 MI->getOpcode() == PPC::SELECT_CC_VRRC) { 4898 4899 // The incoming instruction knows the destination vreg to set, the 4900 // condition code register to branch on, the true/false values to 4901 // select between, and a branch opcode to use. 4902 4903 // thisMBB: 4904 // ... 4905 // TrueVal = ... 4906 // cmpTY ccX, r1, r2 4907 // bCC copy1MBB 4908 // fallthrough --> copy0MBB 4909 MachineBasicBlock *thisMBB = BB; 4910 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 4911 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 4912 unsigned SelectPred = MI->getOperand(4).getImm(); 4913 DebugLoc dl = MI->getDebugLoc(); 4914 F->insert(It, copy0MBB); 4915 F->insert(It, sinkMBB); 4916 4917 // Transfer the remainder of BB and its successor edges to sinkMBB. 4918 sinkMBB->splice(sinkMBB->begin(), BB, 4919 llvm::next(MachineBasicBlock::iterator(MI)), 4920 BB->end()); 4921 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 4922 4923 // Next, add the true and fallthrough blocks as its successors. 4924 BB->addSuccessor(copy0MBB); 4925 BB->addSuccessor(sinkMBB); 4926 4927 BuildMI(BB, dl, TII->get(PPC::BCC)) 4928 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB); 4929 4930 // copy0MBB: 4931 // %FalseValue = ... 4932 // # fallthrough to sinkMBB 4933 BB = copy0MBB; 4934 4935 // Update machine-CFG edges 4936 BB->addSuccessor(sinkMBB); 4937 4938 // sinkMBB: 4939 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 4940 // ... 4941 BB = sinkMBB; 4942 BuildMI(*BB, BB->begin(), dl, 4943 TII->get(PPC::PHI), MI->getOperand(0).getReg()) 4944 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB) 4945 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 4946 } 4947 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 4948 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 4949 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 4950 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 4951 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 4952 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4); 4953 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 4954 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8); 4955 4956 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 4957 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 4958 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 4959 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 4960 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 4961 BB = EmitAtomicBinary(MI, BB, false, PPC::AND); 4962 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 4963 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8); 4964 4965 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 4966 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 4967 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 4968 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 4969 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 4970 BB = EmitAtomicBinary(MI, BB, false, PPC::OR); 4971 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 4972 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8); 4973 4974 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 4975 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 4976 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 4977 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 4978 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 4979 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR); 4980 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 4981 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8); 4982 4983 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 4984 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC); 4985 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 4986 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC); 4987 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 4988 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC); 4989 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 4990 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8); 4991 4992 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 4993 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 4994 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 4995 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 4996 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 4997 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF); 4998 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 4999 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8); 5000 5001 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8) 5002 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 5003 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16) 5004 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 5005 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32) 5006 BB = EmitAtomicBinary(MI, BB, false, 0); 5007 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64) 5008 BB = EmitAtomicBinary(MI, BB, true, 0); 5009 5010 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 5011 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) { 5012 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 5013 5014 unsigned dest = MI->getOperand(0).getReg(); 5015 unsigned ptrA = MI->getOperand(1).getReg(); 5016 unsigned ptrB = MI->getOperand(2).getReg(); 5017 unsigned oldval = MI->getOperand(3).getReg(); 5018 unsigned newval = MI->getOperand(4).getReg(); 5019 DebugLoc dl = MI->getDebugLoc(); 5020 5021 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 5022 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 5023 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 5024 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 5025 F->insert(It, loop1MBB); 5026 F->insert(It, loop2MBB); 5027 F->insert(It, midMBB); 5028 F->insert(It, exitMBB); 5029 exitMBB->splice(exitMBB->begin(), BB, 5030 llvm::next(MachineBasicBlock::iterator(MI)), 5031 BB->end()); 5032 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 5033 5034 // thisMBB: 5035 // ... 5036 // fallthrough --> loopMBB 5037 BB->addSuccessor(loop1MBB); 5038 5039 // loop1MBB: 5040 // l[wd]arx dest, ptr 5041 // cmp[wd] dest, oldval 5042 // bne- midMBB 5043 // loop2MBB: 5044 // st[wd]cx. newval, ptr 5045 // bne- loopMBB 5046 // b exitBB 5047 // midMBB: 5048 // st[wd]cx. dest, ptr 5049 // exitBB: 5050 BB = loop1MBB; 5051 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest) 5052 .addReg(ptrA).addReg(ptrB); 5053 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 5054 .addReg(oldval).addReg(dest); 5055 BuildMI(BB, dl, TII->get(PPC::BCC)) 5056 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 5057 BB->addSuccessor(loop2MBB); 5058 BB->addSuccessor(midMBB); 5059 5060 BB = loop2MBB; 5061 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX)) 5062 .addReg(newval).addReg(ptrA).addReg(ptrB); 5063 BuildMI(BB, dl, TII->get(PPC::BCC)) 5064 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 5065 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 5066 BB->addSuccessor(loop1MBB); 5067 BB->addSuccessor(exitMBB); 5068 5069 BB = midMBB; 5070 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX)) 5071 .addReg(dest).addReg(ptrA).addReg(ptrB); 5072 BB->addSuccessor(exitMBB); 5073 5074 // exitMBB: 5075 // ... 5076 BB = exitMBB; 5077 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 5078 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 5079 // We must use 64-bit registers for addresses when targeting 64-bit, 5080 // since we're actually doing arithmetic on them. Other registers 5081 // can be 32-bit. 5082 bool is64bit = PPCSubTarget.isPPC64(); 5083 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 5084 5085 unsigned dest = MI->getOperand(0).getReg(); 5086 unsigned ptrA = MI->getOperand(1).getReg(); 5087 unsigned ptrB = MI->getOperand(2).getReg(); 5088 unsigned oldval = MI->getOperand(3).getReg(); 5089 unsigned newval = MI->getOperand(4).getReg(); 5090 DebugLoc dl = MI->getDebugLoc(); 5091 5092 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 5093 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 5094 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 5095 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 5096 F->insert(It, loop1MBB); 5097 F->insert(It, loop2MBB); 5098 F->insert(It, midMBB); 5099 F->insert(It, exitMBB); 5100 exitMBB->splice(exitMBB->begin(), BB, 5101 llvm::next(MachineBasicBlock::iterator(MI)), 5102 BB->end()); 5103 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 5104 5105 MachineRegisterInfo &RegInfo = F->getRegInfo(); 5106 const TargetRegisterClass *RC = 5107 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass : 5108 (const TargetRegisterClass *) &PPC::GPRCRegClass; 5109 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 5110 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 5111 unsigned ShiftReg = RegInfo.createVirtualRegister(RC); 5112 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 5113 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 5114 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 5115 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 5116 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 5117 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 5118 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 5119 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 5120 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 5121 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 5122 unsigned Ptr1Reg; 5123 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 5124 unsigned ZeroReg = is64bit ? PPC::X0 : PPC::R0; 5125 // thisMBB: 5126 // ... 5127 // fallthrough --> loopMBB 5128 BB->addSuccessor(loop1MBB); 5129 5130 // The 4-byte load must be aligned, while a char or short may be 5131 // anywhere in the word. Hence all this nasty bookkeeping code. 5132 // add ptr1, ptrA, ptrB [copy if ptrA==0] 5133 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 5134 // xori shift, shift1, 24 [16] 5135 // rlwinm ptr, ptr1, 0, 0, 29 5136 // slw newval2, newval, shift 5137 // slw oldval2, oldval,shift 5138 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 5139 // slw mask, mask2, shift 5140 // and newval3, newval2, mask 5141 // and oldval3, oldval2, mask 5142 // loop1MBB: 5143 // lwarx tmpDest, ptr 5144 // and tmp, tmpDest, mask 5145 // cmpw tmp, oldval3 5146 // bne- midMBB 5147 // loop2MBB: 5148 // andc tmp2, tmpDest, mask 5149 // or tmp4, tmp2, newval3 5150 // stwcx. tmp4, ptr 5151 // bne- loop1MBB 5152 // b exitBB 5153 // midMBB: 5154 // stwcx. tmpDest, ptr 5155 // exitBB: 5156 // srw dest, tmpDest, shift 5157 if (ptrA != ZeroReg) { 5158 Ptr1Reg = RegInfo.createVirtualRegister(RC); 5159 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 5160 .addReg(ptrA).addReg(ptrB); 5161 } else { 5162 Ptr1Reg = ptrB; 5163 } 5164 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 5165 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 5166 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 5167 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 5168 if (is64bit) 5169 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 5170 .addReg(Ptr1Reg).addImm(0).addImm(61); 5171 else 5172 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 5173 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 5174 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 5175 .addReg(newval).addReg(ShiftReg); 5176 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 5177 .addReg(oldval).addReg(ShiftReg); 5178 if (is8bit) 5179 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 5180 else { 5181 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 5182 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 5183 .addReg(Mask3Reg).addImm(65535); 5184 } 5185 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 5186 .addReg(Mask2Reg).addReg(ShiftReg); 5187 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 5188 .addReg(NewVal2Reg).addReg(MaskReg); 5189 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 5190 .addReg(OldVal2Reg).addReg(MaskReg); 5191 5192 BB = loop1MBB; 5193 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 5194 .addReg(ZeroReg).addReg(PtrReg); 5195 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 5196 .addReg(TmpDestReg).addReg(MaskReg); 5197 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 5198 .addReg(TmpReg).addReg(OldVal3Reg); 5199 BuildMI(BB, dl, TII->get(PPC::BCC)) 5200 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 5201 BB->addSuccessor(loop2MBB); 5202 BB->addSuccessor(midMBB); 5203 5204 BB = loop2MBB; 5205 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 5206 .addReg(TmpDestReg).addReg(MaskReg); 5207 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 5208 .addReg(Tmp2Reg).addReg(NewVal3Reg); 5209 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 5210 .addReg(ZeroReg).addReg(PtrReg); 5211 BuildMI(BB, dl, TII->get(PPC::BCC)) 5212 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 5213 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 5214 BB->addSuccessor(loop1MBB); 5215 BB->addSuccessor(exitMBB); 5216 5217 BB = midMBB; 5218 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 5219 .addReg(ZeroReg).addReg(PtrReg); 5220 BB->addSuccessor(exitMBB); 5221 5222 // exitMBB: 5223 // ... 5224 BB = exitMBB; 5225 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 5226 .addReg(ShiftReg); 5227 } else { 5228 llvm_unreachable("Unexpected instr type to insert"); 5229 } 5230 5231 MI->eraseFromParent(); // The pseudo instruction is gone now. 5232 return BB; 5233 } 5234 5235 //===----------------------------------------------------------------------===// 5236 // Target Optimization Hooks 5237 //===----------------------------------------------------------------------===// 5238 5239 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 5240 DAGCombinerInfo &DCI) const { 5241 const TargetMachine &TM = getTargetMachine(); 5242 SelectionDAG &DAG = DCI.DAG; 5243 DebugLoc dl = N->getDebugLoc(); 5244 switch (N->getOpcode()) { 5245 default: break; 5246 case PPCISD::SHL: 5247 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 5248 if (C->isNullValue()) // 0 << V -> 0. 5249 return N->getOperand(0); 5250 } 5251 break; 5252 case PPCISD::SRL: 5253 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 5254 if (C->isNullValue()) // 0 >>u V -> 0. 5255 return N->getOperand(0); 5256 } 5257 break; 5258 case PPCISD::SRA: 5259 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 5260 if (C->isNullValue() || // 0 >>s V -> 0. 5261 C->isAllOnesValue()) // -1 >>s V -> -1. 5262 return N->getOperand(0); 5263 } 5264 break; 5265 5266 case ISD::SINT_TO_FP: 5267 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) { 5268 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) { 5269 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores. 5270 // We allow the src/dst to be either f32/f64, but the intermediate 5271 // type must be i64. 5272 if (N->getOperand(0).getValueType() == MVT::i64 && 5273 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) { 5274 SDValue Val = N->getOperand(0).getOperand(0); 5275 if (Val.getValueType() == MVT::f32) { 5276 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 5277 DCI.AddToWorklist(Val.getNode()); 5278 } 5279 5280 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val); 5281 DCI.AddToWorklist(Val.getNode()); 5282 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val); 5283 DCI.AddToWorklist(Val.getNode()); 5284 if (N->getValueType(0) == MVT::f32) { 5285 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val, 5286 DAG.getIntPtrConstant(0)); 5287 DCI.AddToWorklist(Val.getNode()); 5288 } 5289 return Val; 5290 } else if (N->getOperand(0).getValueType() == MVT::i32) { 5291 // If the intermediate type is i32, we can avoid the load/store here 5292 // too. 5293 } 5294 } 5295 } 5296 break; 5297 case ISD::STORE: 5298 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)). 5299 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() && 5300 !cast<StoreSDNode>(N)->isTruncatingStore() && 5301 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT && 5302 N->getOperand(1).getValueType() == MVT::i32 && 5303 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) { 5304 SDValue Val = N->getOperand(1).getOperand(0); 5305 if (Val.getValueType() == MVT::f32) { 5306 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 5307 DCI.AddToWorklist(Val.getNode()); 5308 } 5309 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val); 5310 DCI.AddToWorklist(Val.getNode()); 5311 5312 Val = DAG.getNode(PPCISD::STFIWX, dl, MVT::Other, N->getOperand(0), Val, 5313 N->getOperand(2), N->getOperand(3)); 5314 DCI.AddToWorklist(Val.getNode()); 5315 return Val; 5316 } 5317 5318 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 5319 if (cast<StoreSDNode>(N)->isUnindexed() && 5320 N->getOperand(1).getOpcode() == ISD::BSWAP && 5321 N->getOperand(1).getNode()->hasOneUse() && 5322 (N->getOperand(1).getValueType() == MVT::i32 || 5323 N->getOperand(1).getValueType() == MVT::i16)) { 5324 SDValue BSwapOp = N->getOperand(1).getOperand(0); 5325 // Do an any-extend to 32-bits if this is a half-word input. 5326 if (BSwapOp.getValueType() == MVT::i16) 5327 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 5328 5329 SDValue Ops[] = { 5330 N->getOperand(0), BSwapOp, N->getOperand(2), 5331 DAG.getValueType(N->getOperand(1).getValueType()) 5332 }; 5333 return 5334 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 5335 Ops, array_lengthof(Ops), 5336 cast<StoreSDNode>(N)->getMemoryVT(), 5337 cast<StoreSDNode>(N)->getMemOperand()); 5338 } 5339 break; 5340 case ISD::BSWAP: 5341 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 5342 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 5343 N->getOperand(0).hasOneUse() && 5344 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) { 5345 SDValue Load = N->getOperand(0); 5346 LoadSDNode *LD = cast<LoadSDNode>(Load); 5347 // Create the byte-swapping load. 5348 SDValue Ops[] = { 5349 LD->getChain(), // Chain 5350 LD->getBasePtr(), // Ptr 5351 DAG.getValueType(N->getValueType(0)) // VT 5352 }; 5353 SDValue BSLoad = 5354 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 5355 DAG.getVTList(MVT::i32, MVT::Other), Ops, 3, 5356 LD->getMemoryVT(), LD->getMemOperand()); 5357 5358 // If this is an i16 load, insert the truncate. 5359 SDValue ResVal = BSLoad; 5360 if (N->getValueType(0) == MVT::i16) 5361 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 5362 5363 // First, combine the bswap away. This makes the value produced by the 5364 // load dead. 5365 DCI.CombineTo(N, ResVal); 5366 5367 // Next, combine the load away, we give it a bogus result value but a real 5368 // chain result. The result value is dead because the bswap is dead. 5369 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 5370 5371 // Return N so it doesn't get rechecked! 5372 return SDValue(N, 0); 5373 } 5374 5375 break; 5376 case PPCISD::VCMP: { 5377 // If a VCMPo node already exists with exactly the same operands as this 5378 // node, use its result instead of this node (VCMPo computes both a CR6 and 5379 // a normal output). 5380 // 5381 if (!N->getOperand(0).hasOneUse() && 5382 !N->getOperand(1).hasOneUse() && 5383 !N->getOperand(2).hasOneUse()) { 5384 5385 // Scan all of the users of the LHS, looking for VCMPo's that match. 5386 SDNode *VCMPoNode = 0; 5387 5388 SDNode *LHSN = N->getOperand(0).getNode(); 5389 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 5390 UI != E; ++UI) 5391 if (UI->getOpcode() == PPCISD::VCMPo && 5392 UI->getOperand(1) == N->getOperand(1) && 5393 UI->getOperand(2) == N->getOperand(2) && 5394 UI->getOperand(0) == N->getOperand(0)) { 5395 VCMPoNode = *UI; 5396 break; 5397 } 5398 5399 // If there is no VCMPo node, or if the flag value has a single use, don't 5400 // transform this. 5401 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 5402 break; 5403 5404 // Look at the (necessarily single) use of the flag value. If it has a 5405 // chain, this transformation is more complex. Note that multiple things 5406 // could use the value result, which we should ignore. 5407 SDNode *FlagUser = 0; 5408 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 5409 FlagUser == 0; ++UI) { 5410 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 5411 SDNode *User = *UI; 5412 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 5413 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 5414 FlagUser = User; 5415 break; 5416 } 5417 } 5418 } 5419 5420 // If the user is a MFCR instruction, we know this is safe. Otherwise we 5421 // give up for right now. 5422 if (FlagUser->getOpcode() == PPCISD::MFCR) 5423 return SDValue(VCMPoNode, 0); 5424 } 5425 break; 5426 } 5427 case ISD::BR_CC: { 5428 // If this is a branch on an altivec predicate comparison, lower this so 5429 // that we don't have to do a MFCR: instead, branch directly on CR6. This 5430 // lowering is done pre-legalize, because the legalizer lowers the predicate 5431 // compare down to code that is difficult to reassemble. 5432 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 5433 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 5434 int CompareOpc; 5435 bool isDot; 5436 5437 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 5438 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 5439 getAltivecCompareInfo(LHS, CompareOpc, isDot)) { 5440 assert(isDot && "Can't compare against a vector result!"); 5441 5442 // If this is a comparison against something other than 0/1, then we know 5443 // that the condition is never/always true. 5444 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 5445 if (Val != 0 && Val != 1) { 5446 if (CC == ISD::SETEQ) // Cond never true, remove branch. 5447 return N->getOperand(0); 5448 // Always !=, turn it into an unconditional branch. 5449 return DAG.getNode(ISD::BR, dl, MVT::Other, 5450 N->getOperand(0), N->getOperand(4)); 5451 } 5452 5453 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 5454 5455 // Create the PPCISD altivec 'dot' comparison node. 5456 std::vector<EVT> VTs; 5457 SDValue Ops[] = { 5458 LHS.getOperand(2), // LHS of compare 5459 LHS.getOperand(3), // RHS of compare 5460 DAG.getConstant(CompareOpc, MVT::i32) 5461 }; 5462 VTs.push_back(LHS.getOperand(2).getValueType()); 5463 VTs.push_back(MVT::Glue); 5464 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3); 5465 5466 // Unpack the result based on how the target uses it. 5467 PPC::Predicate CompOpc; 5468 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 5469 default: // Can't happen, don't crash on invalid number though. 5470 case 0: // Branch on the value of the EQ bit of CR6. 5471 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 5472 break; 5473 case 1: // Branch on the inverted value of the EQ bit of CR6. 5474 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 5475 break; 5476 case 2: // Branch on the value of the LT bit of CR6. 5477 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 5478 break; 5479 case 3: // Branch on the inverted value of the LT bit of CR6. 5480 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 5481 break; 5482 } 5483 5484 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 5485 DAG.getConstant(CompOpc, MVT::i32), 5486 DAG.getRegister(PPC::CR6, MVT::i32), 5487 N->getOperand(4), CompNode.getValue(1)); 5488 } 5489 break; 5490 } 5491 } 5492 5493 return SDValue(); 5494 } 5495 5496 //===----------------------------------------------------------------------===// 5497 // Inline Assembly Support 5498 //===----------------------------------------------------------------------===// 5499 5500 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 5501 const APInt &Mask, 5502 APInt &KnownZero, 5503 APInt &KnownOne, 5504 const SelectionDAG &DAG, 5505 unsigned Depth) const { 5506 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); 5507 switch (Op.getOpcode()) { 5508 default: break; 5509 case PPCISD::LBRX: { 5510 // lhbrx is known to have the top bits cleared out. 5511 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 5512 KnownZero = 0xFFFF0000; 5513 break; 5514 } 5515 case ISD::INTRINSIC_WO_CHAIN: { 5516 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 5517 default: break; 5518 case Intrinsic::ppc_altivec_vcmpbfp_p: 5519 case Intrinsic::ppc_altivec_vcmpeqfp_p: 5520 case Intrinsic::ppc_altivec_vcmpequb_p: 5521 case Intrinsic::ppc_altivec_vcmpequh_p: 5522 case Intrinsic::ppc_altivec_vcmpequw_p: 5523 case Intrinsic::ppc_altivec_vcmpgefp_p: 5524 case Intrinsic::ppc_altivec_vcmpgtfp_p: 5525 case Intrinsic::ppc_altivec_vcmpgtsb_p: 5526 case Intrinsic::ppc_altivec_vcmpgtsh_p: 5527 case Intrinsic::ppc_altivec_vcmpgtsw_p: 5528 case Intrinsic::ppc_altivec_vcmpgtub_p: 5529 case Intrinsic::ppc_altivec_vcmpgtuh_p: 5530 case Intrinsic::ppc_altivec_vcmpgtuw_p: 5531 KnownZero = ~1U; // All bits but the low one are known to be zero. 5532 break; 5533 } 5534 } 5535 } 5536 } 5537 5538 5539 /// getConstraintType - Given a constraint, return the type of 5540 /// constraint it is for this target. 5541 PPCTargetLowering::ConstraintType 5542 PPCTargetLowering::getConstraintType(const std::string &Constraint) const { 5543 if (Constraint.size() == 1) { 5544 switch (Constraint[0]) { 5545 default: break; 5546 case 'b': 5547 case 'r': 5548 case 'f': 5549 case 'v': 5550 case 'y': 5551 return C_RegisterClass; 5552 } 5553 } 5554 return TargetLowering::getConstraintType(Constraint); 5555 } 5556 5557 /// Examine constraint type and operand type and determine a weight value. 5558 /// This object must already have been set up with the operand type 5559 /// and the current alternative constraint selected. 5560 TargetLowering::ConstraintWeight 5561 PPCTargetLowering::getSingleConstraintMatchWeight( 5562 AsmOperandInfo &info, const char *constraint) const { 5563 ConstraintWeight weight = CW_Invalid; 5564 Value *CallOperandVal = info.CallOperandVal; 5565 // If we don't have a value, we can't do a match, 5566 // but allow it at the lowest weight. 5567 if (CallOperandVal == NULL) 5568 return CW_Default; 5569 Type *type = CallOperandVal->getType(); 5570 // Look at the constraint type. 5571 switch (*constraint) { 5572 default: 5573 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 5574 break; 5575 case 'b': 5576 if (type->isIntegerTy()) 5577 weight = CW_Register; 5578 break; 5579 case 'f': 5580 if (type->isFloatTy()) 5581 weight = CW_Register; 5582 break; 5583 case 'd': 5584 if (type->isDoubleTy()) 5585 weight = CW_Register; 5586 break; 5587 case 'v': 5588 if (type->isVectorTy()) 5589 weight = CW_Register; 5590 break; 5591 case 'y': 5592 weight = CW_Register; 5593 break; 5594 } 5595 return weight; 5596 } 5597 5598 std::pair<unsigned, const TargetRegisterClass*> 5599 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 5600 EVT VT) const { 5601 if (Constraint.size() == 1) { 5602 // GCC RS6000 Constraint Letters 5603 switch (Constraint[0]) { 5604 case 'b': // R1-R31 5605 case 'r': // R0-R31 5606 if (VT == MVT::i64 && PPCSubTarget.isPPC64()) 5607 return std::make_pair(0U, PPC::G8RCRegisterClass); 5608 return std::make_pair(0U, PPC::GPRCRegisterClass); 5609 case 'f': 5610 if (VT == MVT::f32) 5611 return std::make_pair(0U, PPC::F4RCRegisterClass); 5612 else if (VT == MVT::f64) 5613 return std::make_pair(0U, PPC::F8RCRegisterClass); 5614 break; 5615 case 'v': 5616 return std::make_pair(0U, PPC::VRRCRegisterClass); 5617 case 'y': // crrc 5618 return std::make_pair(0U, PPC::CRRCRegisterClass); 5619 } 5620 } 5621 5622 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 5623 } 5624 5625 5626 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 5627 /// vector. If it is invalid, don't add anything to Ops. 5628 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 5629 std::string &Constraint, 5630 std::vector<SDValue>&Ops, 5631 SelectionDAG &DAG) const { 5632 SDValue Result(0,0); 5633 5634 // Only support length 1 constraints. 5635 if (Constraint.length() > 1) return; 5636 5637 char Letter = Constraint[0]; 5638 switch (Letter) { 5639 default: break; 5640 case 'I': 5641 case 'J': 5642 case 'K': 5643 case 'L': 5644 case 'M': 5645 case 'N': 5646 case 'O': 5647 case 'P': { 5648 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 5649 if (!CST) return; // Must be an immediate to match. 5650 unsigned Value = CST->getZExtValue(); 5651 switch (Letter) { 5652 default: llvm_unreachable("Unknown constraint letter!"); 5653 case 'I': // "I" is a signed 16-bit constant. 5654 if ((short)Value == (int)Value) 5655 Result = DAG.getTargetConstant(Value, Op.getValueType()); 5656 break; 5657 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 5658 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 5659 if ((short)Value == 0) 5660 Result = DAG.getTargetConstant(Value, Op.getValueType()); 5661 break; 5662 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 5663 if ((Value >> 16) == 0) 5664 Result = DAG.getTargetConstant(Value, Op.getValueType()); 5665 break; 5666 case 'M': // "M" is a constant that is greater than 31. 5667 if (Value > 31) 5668 Result = DAG.getTargetConstant(Value, Op.getValueType()); 5669 break; 5670 case 'N': // "N" is a positive constant that is an exact power of two. 5671 if ((int)Value > 0 && isPowerOf2_32(Value)) 5672 Result = DAG.getTargetConstant(Value, Op.getValueType()); 5673 break; 5674 case 'O': // "O" is the constant zero. 5675 if (Value == 0) 5676 Result = DAG.getTargetConstant(Value, Op.getValueType()); 5677 break; 5678 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 5679 if ((short)-Value == (int)-Value) 5680 Result = DAG.getTargetConstant(Value, Op.getValueType()); 5681 break; 5682 } 5683 break; 5684 } 5685 } 5686 5687 if (Result.getNode()) { 5688 Ops.push_back(Result); 5689 return; 5690 } 5691 5692 // Handle standard constraint letters. 5693 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 5694 } 5695 5696 // isLegalAddressingMode - Return true if the addressing mode represented 5697 // by AM is legal for this target, for a load/store of the specified type. 5698 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM, 5699 Type *Ty) const { 5700 // FIXME: PPC does not allow r+i addressing modes for vectors! 5701 5702 // PPC allows a sign-extended 16-bit immediate field. 5703 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 5704 return false; 5705 5706 // No global is ever allowed as a base. 5707 if (AM.BaseGV) 5708 return false; 5709 5710 // PPC only support r+r, 5711 switch (AM.Scale) { 5712 case 0: // "r+i" or just "i", depending on HasBaseReg. 5713 break; 5714 case 1: 5715 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 5716 return false; 5717 // Otherwise we have r+r or r+i. 5718 break; 5719 case 2: 5720 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 5721 return false; 5722 // Allow 2*r as r+r. 5723 break; 5724 default: 5725 // No other scales are supported. 5726 return false; 5727 } 5728 5729 return true; 5730 } 5731 5732 /// isLegalAddressImmediate - Return true if the integer value can be used 5733 /// as the offset of the target addressing mode for load / store of the 5734 /// given type. 5735 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,Type *Ty) const{ 5736 // PPC allows a sign-extended 16-bit immediate field. 5737 return (V > -(1 << 16) && V < (1 << 16)-1); 5738 } 5739 5740 bool PPCTargetLowering::isLegalAddressImmediate(GlobalValue* GV) const { 5741 return false; 5742 } 5743 5744 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 5745 SelectionDAG &DAG) const { 5746 MachineFunction &MF = DAG.getMachineFunction(); 5747 MachineFrameInfo *MFI = MF.getFrameInfo(); 5748 MFI->setReturnAddressIsTaken(true); 5749 5750 DebugLoc dl = Op.getDebugLoc(); 5751 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5752 5753 // Make sure the function does not optimize away the store of the RA to 5754 // the stack. 5755 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 5756 FuncInfo->setLRStoreRequired(); 5757 bool isPPC64 = PPCSubTarget.isPPC64(); 5758 bool isDarwinABI = PPCSubTarget.isDarwinABI(); 5759 5760 if (Depth > 0) { 5761 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5762 SDValue Offset = 5763 5764 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI), 5765 isPPC64? MVT::i64 : MVT::i32); 5766 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 5767 DAG.getNode(ISD::ADD, dl, getPointerTy(), 5768 FrameAddr, Offset), 5769 MachinePointerInfo(), false, false, false, 0); 5770 } 5771 5772 // Just load the return address off the stack. 5773 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 5774 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 5775 RetAddrFI, MachinePointerInfo(), false, false, false, 0); 5776 } 5777 5778 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 5779 SelectionDAG &DAG) const { 5780 DebugLoc dl = Op.getDebugLoc(); 5781 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5782 5783 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 5784 bool isPPC64 = PtrVT == MVT::i64; 5785 5786 MachineFunction &MF = DAG.getMachineFunction(); 5787 MachineFrameInfo *MFI = MF.getFrameInfo(); 5788 MFI->setFrameAddressIsTaken(true); 5789 bool is31 = (getTargetMachine().Options.DisableFramePointerElim(MF) || 5790 MFI->hasVarSizedObjects()) && 5791 MFI->getStackSize() && 5792 !MF.getFunction()->hasFnAttr(Attribute::Naked); 5793 unsigned FrameReg = isPPC64 ? (is31 ? PPC::X31 : PPC::X1) : 5794 (is31 ? PPC::R31 : PPC::R1); 5795 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 5796 PtrVT); 5797 while (Depth--) 5798 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 5799 FrameAddr, MachinePointerInfo(), false, false, 5800 false, 0); 5801 return FrameAddr; 5802 } 5803 5804 bool 5805 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5806 // The PowerPC target isn't yet aware of offsets. 5807 return false; 5808 } 5809 5810 /// getOptimalMemOpType - Returns the target specific optimal type for load 5811 /// and store operations as a result of memset, memcpy, and memmove 5812 /// lowering. If DstAlign is zero that means it's safe to destination 5813 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 5814 /// means there isn't a need to check it against alignment requirement, 5815 /// probably because the source does not need to be loaded. If 5816 /// 'IsZeroVal' is true, that means it's safe to return a 5817 /// non-scalar-integer type, e.g. empty string source, constant, or loaded 5818 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is 5819 /// constant so it does not need to be loaded. 5820 /// It returns EVT::Other if the type should be determined using generic 5821 /// target-independent logic. 5822 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 5823 unsigned DstAlign, unsigned SrcAlign, 5824 bool IsZeroVal, 5825 bool MemcpyStrSrc, 5826 MachineFunction &MF) const { 5827 if (this->PPCSubTarget.isPPC64()) { 5828 return MVT::i64; 5829 } else { 5830 return MVT::i32; 5831 } 5832 } 5833