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