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