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 "PPC.h" 17 #include "PPCCCState.h" 18 #include "PPCCallingConv.h" 19 #include "PPCFrameLowering.h" 20 #include "PPCInstrInfo.h" 21 #include "PPCMachineFunctionInfo.h" 22 #include "PPCPerfectShuffle.h" 23 #include "PPCRegisterInfo.h" 24 #include "PPCSubtarget.h" 25 #include "PPCTargetMachine.h" 26 #include "llvm/ADT/APFloat.h" 27 #include "llvm/ADT/APInt.h" 28 #include "llvm/ADT/ArrayRef.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/None.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallSet.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/CodeGen/CallingConvLower.h" 39 #include "llvm/CodeGen/ISDOpcodes.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineLoopInfo.h" 47 #include "llvm/CodeGen/MachineMemOperand.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/ValueTypes.h" 57 #include "llvm/IR/CallSite.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/Module.h" 70 #include "llvm/IR/Type.h" 71 #include "llvm/IR/Use.h" 72 #include "llvm/IR/Value.h" 73 #include "llvm/MC/MCExpr.h" 74 #include "llvm/MC/MCRegisterInfo.h" 75 #include "llvm/Support/AtomicOrdering.h" 76 #include "llvm/Support/BranchProbability.h" 77 #include "llvm/Support/Casting.h" 78 #include "llvm/Support/CodeGen.h" 79 #include "llvm/Support/CommandLine.h" 80 #include "llvm/Support/Compiler.h" 81 #include "llvm/Support/Debug.h" 82 #include "llvm/Support/ErrorHandling.h" 83 #include "llvm/Support/Format.h" 84 #include "llvm/Support/KnownBits.h" 85 #include "llvm/Support/MachineValueType.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include "llvm/Target/TargetMachine.h" 89 #include "llvm/Target/TargetOptions.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstdint> 93 #include <iterator> 94 #include <list> 95 #include <utility> 96 #include <vector> 97 98 using namespace llvm; 99 100 #define DEBUG_TYPE "ppc-lowering" 101 102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 104 105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 107 108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 110 111 static cl::opt<bool> DisableSCO("disable-ppc-sco", 112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 113 114 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 115 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 116 117 STATISTIC(NumTailCalls, "Number of tail calls"); 118 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 119 120 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 121 122 // FIXME: Remove this once the bug has been fixed! 123 extern cl::opt<bool> ANDIGlueBug; 124 125 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 126 const PPCSubtarget &STI) 127 : TargetLowering(TM), Subtarget(STI) { 128 // Use _setjmp/_longjmp instead of setjmp/longjmp. 129 setUseUnderscoreSetJmp(true); 130 setUseUnderscoreLongJmp(true); 131 132 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 133 // arguments are at least 4/8 bytes aligned. 134 bool isPPC64 = Subtarget.isPPC64(); 135 setMinStackArgumentAlignment(isPPC64 ? 8:4); 136 137 // Set up the register classes. 138 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 139 if (!useSoftFloat()) { 140 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 141 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 142 } 143 144 // Match BITREVERSE to customized fast code sequence in the td file. 145 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 146 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 147 148 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 149 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 150 151 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 152 for (MVT VT : MVT::integer_valuetypes()) { 153 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 154 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 155 } 156 157 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 158 159 // PowerPC has pre-inc load and store's. 160 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 161 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 162 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 163 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 164 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 165 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 166 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 167 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 168 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 169 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 170 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 171 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 172 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 173 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 174 175 if (Subtarget.useCRBits()) { 176 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 177 178 if (isPPC64 || Subtarget.hasFPCVT()) { 179 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 180 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 181 isPPC64 ? MVT::i64 : MVT::i32); 182 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 183 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 184 isPPC64 ? MVT::i64 : MVT::i32); 185 } else { 186 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 187 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 188 } 189 190 // PowerPC does not support direct load/store of condition registers. 191 setOperationAction(ISD::LOAD, MVT::i1, Custom); 192 setOperationAction(ISD::STORE, MVT::i1, Custom); 193 194 // FIXME: Remove this once the ANDI glue bug is fixed: 195 if (ANDIGlueBug) 196 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 197 198 for (MVT VT : MVT::integer_valuetypes()) { 199 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 200 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 201 setTruncStoreAction(VT, MVT::i1, Expand); 202 } 203 204 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 205 } 206 207 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 208 // PPC (the libcall is not available). 209 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 210 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 211 212 // We do not currently implement these libm ops for PowerPC. 213 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 214 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 215 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 216 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 217 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 218 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 219 220 // PowerPC has no SREM/UREM instructions unless we are on P9 221 // On P9 we may use a hardware instruction to compute the remainder. 222 // The instructions are not legalized directly because in the cases where the 223 // result of both the remainder and the division is required it is more 224 // efficient to compute the remainder from the result of the division rather 225 // than use the remainder instruction. 226 if (Subtarget.isISA3_0()) { 227 setOperationAction(ISD::SREM, MVT::i32, Custom); 228 setOperationAction(ISD::UREM, MVT::i32, Custom); 229 setOperationAction(ISD::SREM, MVT::i64, Custom); 230 setOperationAction(ISD::UREM, MVT::i64, Custom); 231 } else { 232 setOperationAction(ISD::SREM, MVT::i32, Expand); 233 setOperationAction(ISD::UREM, MVT::i32, Expand); 234 setOperationAction(ISD::SREM, MVT::i64, Expand); 235 setOperationAction(ISD::UREM, MVT::i64, Expand); 236 } 237 238 if (Subtarget.hasP9Vector()) { 239 setOperationAction(ISD::ABS, MVT::v4i32, Legal); 240 setOperationAction(ISD::ABS, MVT::v8i16, Legal); 241 setOperationAction(ISD::ABS, MVT::v16i8, Legal); 242 } 243 244 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 245 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 246 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 247 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 248 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 249 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 250 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 251 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 252 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 253 254 // We don't support sin/cos/sqrt/fmod/pow 255 setOperationAction(ISD::FSIN , MVT::f64, Expand); 256 setOperationAction(ISD::FCOS , MVT::f64, Expand); 257 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 258 setOperationAction(ISD::FREM , MVT::f64, Expand); 259 setOperationAction(ISD::FPOW , MVT::f64, Expand); 260 setOperationAction(ISD::FMA , MVT::f64, Legal); 261 setOperationAction(ISD::FSIN , MVT::f32, Expand); 262 setOperationAction(ISD::FCOS , MVT::f32, Expand); 263 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 264 setOperationAction(ISD::FREM , MVT::f32, Expand); 265 setOperationAction(ISD::FPOW , MVT::f32, Expand); 266 setOperationAction(ISD::FMA , MVT::f32, Legal); 267 268 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 269 270 // If we're enabling GP optimizations, use hardware square root 271 if (!Subtarget.hasFSQRT() && 272 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 273 Subtarget.hasFRE())) 274 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 275 276 if (!Subtarget.hasFSQRT() && 277 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 278 Subtarget.hasFRES())) 279 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 280 281 if (Subtarget.hasFCPSGN()) { 282 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 283 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 284 } else { 285 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 286 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 287 } 288 289 if (Subtarget.hasFPRND()) { 290 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 291 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 292 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 293 setOperationAction(ISD::FROUND, MVT::f64, Legal); 294 295 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 296 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 297 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 298 setOperationAction(ISD::FROUND, MVT::f32, Legal); 299 } 300 301 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 302 // to speed up scalar BSWAP64. 303 // CTPOP or CTTZ were introduced in P8/P9 respectivelly 304 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 305 if (Subtarget.isISA3_0()) { 306 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 307 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 308 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 309 } else { 310 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 311 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 312 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 313 } 314 315 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 316 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 317 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 318 } else { 319 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 320 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 321 } 322 323 // PowerPC does not have ROTR 324 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 325 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 326 327 if (!Subtarget.useCRBits()) { 328 // PowerPC does not have Select 329 setOperationAction(ISD::SELECT, MVT::i32, Expand); 330 setOperationAction(ISD::SELECT, MVT::i64, Expand); 331 setOperationAction(ISD::SELECT, MVT::f32, Expand); 332 setOperationAction(ISD::SELECT, MVT::f64, Expand); 333 } 334 335 // PowerPC wants to turn select_cc of FP into fsel when possible. 336 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 337 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 338 339 // PowerPC wants to optimize integer setcc a bit 340 if (!Subtarget.useCRBits()) 341 setOperationAction(ISD::SETCC, MVT::i32, Custom); 342 343 // PowerPC does not have BRCOND which requires SetCC 344 if (!Subtarget.useCRBits()) 345 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 346 347 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 348 349 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 350 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 351 352 // PowerPC does not have [U|S]INT_TO_FP 353 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 354 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 355 356 if (Subtarget.hasDirectMove() && isPPC64) { 357 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 358 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 359 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 360 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 361 } else { 362 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 363 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 364 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 365 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 366 } 367 368 // We cannot sextinreg(i1). Expand to shifts. 369 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 370 371 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 372 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 373 // support continuation, user-level threading, and etc.. As a result, no 374 // other SjLj exception interfaces are implemented and please don't build 375 // your own exception handling based on them. 376 // LLVM/Clang supports zero-cost DWARF exception handling. 377 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 378 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 379 380 // We want to legalize GlobalAddress and ConstantPool nodes into the 381 // appropriate instructions to materialize the address. 382 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 383 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 384 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 385 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 386 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 387 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 388 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 389 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 390 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 391 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 392 393 // TRAP is legal. 394 setOperationAction(ISD::TRAP, MVT::Other, Legal); 395 396 // TRAMPOLINE is custom lowered. 397 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 398 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 399 400 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 401 setOperationAction(ISD::VASTART , MVT::Other, Custom); 402 403 if (Subtarget.isSVR4ABI()) { 404 if (isPPC64) { 405 // VAARG always uses double-word chunks, so promote anything smaller. 406 setOperationAction(ISD::VAARG, MVT::i1, Promote); 407 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 408 setOperationAction(ISD::VAARG, MVT::i8, Promote); 409 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 410 setOperationAction(ISD::VAARG, MVT::i16, Promote); 411 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 412 setOperationAction(ISD::VAARG, MVT::i32, Promote); 413 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 414 setOperationAction(ISD::VAARG, MVT::Other, Expand); 415 } else { 416 // VAARG is custom lowered with the 32-bit SVR4 ABI. 417 setOperationAction(ISD::VAARG, MVT::Other, Custom); 418 setOperationAction(ISD::VAARG, MVT::i64, Custom); 419 } 420 } else 421 setOperationAction(ISD::VAARG, MVT::Other, Expand); 422 423 if (Subtarget.isSVR4ABI() && !isPPC64) 424 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 425 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 426 else 427 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 428 429 // Use the default implementation. 430 setOperationAction(ISD::VAEND , MVT::Other, Expand); 431 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 432 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 433 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 434 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 435 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 436 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 437 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 438 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 439 440 // We want to custom lower some of our intrinsics. 441 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 442 443 // To handle counter-based loop conditions. 444 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 445 446 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 447 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 448 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 449 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 450 451 // Comparisons that require checking two conditions. 452 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 453 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 454 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 455 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 456 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 457 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 458 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 459 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 460 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 461 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 462 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 463 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 464 465 if (Subtarget.has64BitSupport()) { 466 // They also have instructions for converting between i64 and fp. 467 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 468 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 469 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 470 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 471 // This is just the low 32 bits of a (signed) fp->i64 conversion. 472 // We cannot do this with Promote because i64 is not a legal type. 473 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 474 475 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 476 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 477 } else { 478 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 479 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 480 } 481 482 // With the instructions enabled under FPCVT, we can do everything. 483 if (Subtarget.hasFPCVT()) { 484 if (Subtarget.has64BitSupport()) { 485 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 486 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 487 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 488 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 489 } 490 491 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 492 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 493 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 494 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 495 } 496 497 if (Subtarget.use64BitRegs()) { 498 // 64-bit PowerPC implementations can support i64 types directly 499 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 500 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 501 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 502 // 64-bit PowerPC wants to expand i128 shifts itself. 503 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 504 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 505 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 506 } else { 507 // 32-bit PowerPC wants to expand i64 shifts itself. 508 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 509 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 510 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 511 } 512 513 if (Subtarget.hasAltivec()) { 514 // First set operation action for all vector types to expand. Then we 515 // will selectively turn on ones that can be effectively codegen'd. 516 for (MVT VT : MVT::vector_valuetypes()) { 517 // add/sub are legal for all supported vector VT's. 518 setOperationAction(ISD::ADD, VT, Legal); 519 setOperationAction(ISD::SUB, VT, Legal); 520 521 // Vector instructions introduced in P8 522 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 523 setOperationAction(ISD::CTPOP, VT, Legal); 524 setOperationAction(ISD::CTLZ, VT, Legal); 525 } 526 else { 527 setOperationAction(ISD::CTPOP, VT, Expand); 528 setOperationAction(ISD::CTLZ, VT, Expand); 529 } 530 531 // Vector instructions introduced in P9 532 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 533 setOperationAction(ISD::CTTZ, VT, Legal); 534 else 535 setOperationAction(ISD::CTTZ, VT, Expand); 536 537 // We promote all shuffles to v16i8. 538 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 539 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 540 541 // We promote all non-typed operations to v4i32. 542 setOperationAction(ISD::AND , VT, Promote); 543 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 544 setOperationAction(ISD::OR , VT, Promote); 545 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 546 setOperationAction(ISD::XOR , VT, Promote); 547 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 548 setOperationAction(ISD::LOAD , VT, Promote); 549 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 550 setOperationAction(ISD::SELECT, VT, Promote); 551 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 552 setOperationAction(ISD::SELECT_CC, VT, Promote); 553 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 554 setOperationAction(ISD::STORE, VT, Promote); 555 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 556 557 // No other operations are legal. 558 setOperationAction(ISD::MUL , VT, Expand); 559 setOperationAction(ISD::SDIV, VT, Expand); 560 setOperationAction(ISD::SREM, VT, Expand); 561 setOperationAction(ISD::UDIV, VT, Expand); 562 setOperationAction(ISD::UREM, VT, Expand); 563 setOperationAction(ISD::FDIV, VT, Expand); 564 setOperationAction(ISD::FREM, VT, Expand); 565 setOperationAction(ISD::FNEG, VT, Expand); 566 setOperationAction(ISD::FSQRT, VT, Expand); 567 setOperationAction(ISD::FLOG, VT, Expand); 568 setOperationAction(ISD::FLOG10, VT, Expand); 569 setOperationAction(ISD::FLOG2, VT, Expand); 570 setOperationAction(ISD::FEXP, VT, Expand); 571 setOperationAction(ISD::FEXP2, VT, Expand); 572 setOperationAction(ISD::FSIN, VT, Expand); 573 setOperationAction(ISD::FCOS, VT, Expand); 574 setOperationAction(ISD::FABS, VT, Expand); 575 setOperationAction(ISD::FFLOOR, VT, Expand); 576 setOperationAction(ISD::FCEIL, VT, Expand); 577 setOperationAction(ISD::FTRUNC, VT, Expand); 578 setOperationAction(ISD::FRINT, VT, Expand); 579 setOperationAction(ISD::FNEARBYINT, VT, Expand); 580 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 581 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 582 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 583 setOperationAction(ISD::MULHU, VT, Expand); 584 setOperationAction(ISD::MULHS, VT, Expand); 585 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 586 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 587 setOperationAction(ISD::UDIVREM, VT, Expand); 588 setOperationAction(ISD::SDIVREM, VT, Expand); 589 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 590 setOperationAction(ISD::FPOW, VT, Expand); 591 setOperationAction(ISD::BSWAP, VT, Expand); 592 setOperationAction(ISD::VSELECT, VT, Expand); 593 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 594 setOperationAction(ISD::ROTL, VT, Expand); 595 setOperationAction(ISD::ROTR, VT, Expand); 596 597 for (MVT InnerVT : MVT::vector_valuetypes()) { 598 setTruncStoreAction(VT, InnerVT, Expand); 599 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 600 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 601 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 602 } 603 } 604 605 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 606 // with merges, splats, etc. 607 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 608 609 setOperationAction(ISD::AND , MVT::v4i32, Legal); 610 setOperationAction(ISD::OR , MVT::v4i32, Legal); 611 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 612 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 613 setOperationAction(ISD::SELECT, MVT::v4i32, 614 Subtarget.useCRBits() ? Legal : Expand); 615 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 616 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 617 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 618 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 619 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 620 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 621 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 622 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 623 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 624 625 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 626 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 627 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 628 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 629 630 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 631 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 632 633 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 634 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 635 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 636 } 637 638 if (Subtarget.hasP8Altivec()) 639 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 640 else 641 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 642 643 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 644 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 645 646 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 647 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 648 649 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 650 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 651 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 652 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 653 654 // Altivec does not contain unordered floating-point compare instructions 655 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 656 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 657 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 658 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 659 660 if (Subtarget.hasVSX()) { 661 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 663 if (Subtarget.hasP8Vector()) { 664 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 665 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 666 } 667 if (Subtarget.hasDirectMove() && isPPC64) { 668 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 669 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 670 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 671 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 672 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 673 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 674 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 675 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 676 } 677 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 678 679 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 680 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 681 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 682 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 683 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 684 685 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 686 687 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 688 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 689 690 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 691 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 692 693 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 694 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal); 695 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 696 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 697 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 698 699 // Share the Altivec comparison restrictions. 700 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 701 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 702 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 703 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 704 705 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 706 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 707 708 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 709 710 if (Subtarget.hasP8Vector()) 711 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 712 713 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 714 715 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 716 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 717 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 718 719 if (Subtarget.hasP8Altivec()) { 720 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 721 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 722 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 723 724 // 128 bit shifts can be accomplished via 3 instructions for SHL and 725 // SRL, but not for SRA because of the instructions available: 726 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 727 // doing 728 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 729 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 730 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 731 732 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 733 } 734 else { 735 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 736 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 737 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 738 739 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 740 741 // VSX v2i64 only supports non-arithmetic operations. 742 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 743 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 744 } 745 746 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 747 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 748 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 749 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 750 751 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 752 753 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 754 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 755 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 756 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 757 758 // Vector operation legalization checks the result type of 759 // SIGN_EXTEND_INREG, overall legalization checks the inner type. 760 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 761 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 762 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 763 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 764 765 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 766 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 767 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 768 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 769 770 if (Subtarget.hasDirectMove()) 771 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 772 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 773 774 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 775 } 776 777 if (Subtarget.hasP8Altivec()) { 778 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 779 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 780 } 781 782 if (Subtarget.hasP9Vector()) { 783 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 784 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 785 786 // 128 bit shifts can be accomplished via 3 instructions for SHL and 787 // SRL, but not for SRA because of the instructions available: 788 // VS{RL} and VS{RL}O. 789 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 790 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 791 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 792 793 if (EnableQuadPrecision) { 794 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 795 setOperationAction(ISD::FADD, MVT::f128, Legal); 796 setOperationAction(ISD::FSUB, MVT::f128, Legal); 797 setOperationAction(ISD::FDIV, MVT::f128, Legal); 798 setOperationAction(ISD::FMUL, MVT::f128, Legal); 799 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 800 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand); 801 setOperationAction(ISD::FMA, MVT::f128, Legal); 802 } 803 804 } 805 806 if (Subtarget.hasP9Altivec()) { 807 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 808 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 809 } 810 } 811 812 if (Subtarget.hasQPX()) { 813 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 814 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 815 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 816 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 817 818 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 819 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 820 821 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 822 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 823 824 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 825 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 826 827 if (!Subtarget.useCRBits()) 828 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 829 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 830 831 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 832 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 833 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 834 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 835 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 836 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 837 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 838 839 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 840 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 841 842 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 843 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 844 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 845 846 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 847 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 848 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 849 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 850 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 851 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 852 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 853 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 854 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 855 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 856 857 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 858 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 859 860 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 861 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 862 863 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 864 865 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 866 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 867 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 868 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 869 870 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 871 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 872 873 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 874 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 875 876 if (!Subtarget.useCRBits()) 877 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 878 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 879 880 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 881 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 882 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 883 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 884 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 885 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 886 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 887 888 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 889 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 890 891 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 892 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 893 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 894 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 895 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 896 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 897 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 898 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 899 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 900 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 901 902 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 903 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 904 905 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 906 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 907 908 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 909 910 setOperationAction(ISD::AND , MVT::v4i1, Legal); 911 setOperationAction(ISD::OR , MVT::v4i1, Legal); 912 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 913 914 if (!Subtarget.useCRBits()) 915 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 916 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 917 918 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 919 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 920 921 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 922 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 923 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 924 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 925 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 926 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 927 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 928 929 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 930 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 931 932 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 933 934 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 935 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 936 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 937 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 938 939 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 940 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 941 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 942 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 943 944 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 945 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 946 947 // These need to set FE_INEXACT, and so cannot be vectorized here. 948 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 949 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 950 951 if (TM.Options.UnsafeFPMath) { 952 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 953 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 954 955 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 956 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 957 } else { 958 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 959 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 960 961 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 962 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 963 } 964 } 965 966 if (Subtarget.has64BitSupport()) 967 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 968 969 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 970 971 if (!isPPC64) { 972 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 973 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 974 } 975 976 setBooleanContents(ZeroOrOneBooleanContent); 977 978 if (Subtarget.hasAltivec()) { 979 // Altivec instructions set fields to all zeros or all ones. 980 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 981 } 982 983 if (!isPPC64) { 984 // These libcalls are not available in 32-bit. 985 setLibcallName(RTLIB::SHL_I128, nullptr); 986 setLibcallName(RTLIB::SRL_I128, nullptr); 987 setLibcallName(RTLIB::SRA_I128, nullptr); 988 } 989 990 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 991 992 // We have target-specific dag combine patterns for the following nodes: 993 setTargetDAGCombine(ISD::SHL); 994 setTargetDAGCombine(ISD::SRA); 995 setTargetDAGCombine(ISD::SRL); 996 setTargetDAGCombine(ISD::SINT_TO_FP); 997 setTargetDAGCombine(ISD::BUILD_VECTOR); 998 if (Subtarget.hasFPCVT()) 999 setTargetDAGCombine(ISD::UINT_TO_FP); 1000 setTargetDAGCombine(ISD::LOAD); 1001 setTargetDAGCombine(ISD::STORE); 1002 setTargetDAGCombine(ISD::BR_CC); 1003 if (Subtarget.useCRBits()) 1004 setTargetDAGCombine(ISD::BRCOND); 1005 setTargetDAGCombine(ISD::BSWAP); 1006 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1007 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1008 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1009 1010 setTargetDAGCombine(ISD::SIGN_EXTEND); 1011 setTargetDAGCombine(ISD::ZERO_EXTEND); 1012 setTargetDAGCombine(ISD::ANY_EXTEND); 1013 1014 if (Subtarget.useCRBits()) { 1015 setTargetDAGCombine(ISD::TRUNCATE); 1016 setTargetDAGCombine(ISD::SETCC); 1017 setTargetDAGCombine(ISD::SELECT_CC); 1018 } 1019 1020 // Use reciprocal estimates. 1021 if (TM.Options.UnsafeFPMath) { 1022 setTargetDAGCombine(ISD::FDIV); 1023 setTargetDAGCombine(ISD::FSQRT); 1024 } 1025 1026 // Darwin long double math library functions have $LDBL128 appended. 1027 if (Subtarget.isDarwin()) { 1028 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1029 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1030 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1031 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1032 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1033 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1034 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1035 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1036 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1037 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1038 } 1039 1040 // With 32 condition bits, we don't need to sink (and duplicate) compares 1041 // aggressively in CodeGenPrep. 1042 if (Subtarget.useCRBits()) { 1043 setHasMultipleConditionRegisters(); 1044 setJumpIsExpensive(); 1045 } 1046 1047 setMinFunctionAlignment(2); 1048 if (Subtarget.isDarwin()) 1049 setPrefFunctionAlignment(4); 1050 1051 switch (Subtarget.getDarwinDirective()) { 1052 default: break; 1053 case PPC::DIR_970: 1054 case PPC::DIR_A2: 1055 case PPC::DIR_E500mc: 1056 case PPC::DIR_E5500: 1057 case PPC::DIR_PWR4: 1058 case PPC::DIR_PWR5: 1059 case PPC::DIR_PWR5X: 1060 case PPC::DIR_PWR6: 1061 case PPC::DIR_PWR6X: 1062 case PPC::DIR_PWR7: 1063 case PPC::DIR_PWR8: 1064 case PPC::DIR_PWR9: 1065 setPrefFunctionAlignment(4); 1066 setPrefLoopAlignment(4); 1067 break; 1068 } 1069 1070 if (Subtarget.enableMachineScheduler()) 1071 setSchedulingPreference(Sched::Source); 1072 else 1073 setSchedulingPreference(Sched::Hybrid); 1074 1075 computeRegisterProperties(STI.getRegisterInfo()); 1076 1077 // The Freescale cores do better with aggressive inlining of memcpy and 1078 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1079 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1080 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1081 MaxStoresPerMemset = 32; 1082 MaxStoresPerMemsetOptSize = 16; 1083 MaxStoresPerMemcpy = 32; 1084 MaxStoresPerMemcpyOptSize = 8; 1085 MaxStoresPerMemmove = 32; 1086 MaxStoresPerMemmoveOptSize = 8; 1087 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1088 // The A2 also benefits from (very) aggressive inlining of memcpy and 1089 // friends. The overhead of a the function call, even when warm, can be 1090 // over one hundred cycles. 1091 MaxStoresPerMemset = 128; 1092 MaxStoresPerMemcpy = 128; 1093 MaxStoresPerMemmove = 128; 1094 MaxLoadsPerMemcmp = 128; 1095 } else { 1096 MaxLoadsPerMemcmp = 8; 1097 MaxLoadsPerMemcmpOptSize = 4; 1098 } 1099 } 1100 1101 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1102 /// the desired ByVal argument alignment. 1103 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1104 unsigned MaxMaxAlign) { 1105 if (MaxAlign == MaxMaxAlign) 1106 return; 1107 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1108 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1109 MaxAlign = 32; 1110 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1111 MaxAlign = 16; 1112 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1113 unsigned EltAlign = 0; 1114 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1115 if (EltAlign > MaxAlign) 1116 MaxAlign = EltAlign; 1117 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1118 for (auto *EltTy : STy->elements()) { 1119 unsigned EltAlign = 0; 1120 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1121 if (EltAlign > MaxAlign) 1122 MaxAlign = EltAlign; 1123 if (MaxAlign == MaxMaxAlign) 1124 break; 1125 } 1126 } 1127 } 1128 1129 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1130 /// function arguments in the caller parameter area. 1131 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1132 const DataLayout &DL) const { 1133 // Darwin passes everything on 4 byte boundary. 1134 if (Subtarget.isDarwin()) 1135 return 4; 1136 1137 // 16byte and wider vectors are passed on 16byte boundary. 1138 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1139 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1140 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1141 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1142 return Align; 1143 } 1144 1145 bool PPCTargetLowering::useSoftFloat() const { 1146 return Subtarget.useSoftFloat(); 1147 } 1148 1149 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1150 switch ((PPCISD::NodeType)Opcode) { 1151 case PPCISD::FIRST_NUMBER: break; 1152 case PPCISD::FSEL: return "PPCISD::FSEL"; 1153 case PPCISD::FCFID: return "PPCISD::FCFID"; 1154 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1155 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1156 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1157 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1158 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1159 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1160 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1161 case PPCISD::FRE: return "PPCISD::FRE"; 1162 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1163 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1164 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1165 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1166 case PPCISD::VPERM: return "PPCISD::VPERM"; 1167 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1168 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1169 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1170 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1171 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1172 case PPCISD::CMPB: return "PPCISD::CMPB"; 1173 case PPCISD::Hi: return "PPCISD::Hi"; 1174 case PPCISD::Lo: return "PPCISD::Lo"; 1175 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1176 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1177 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1178 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1179 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1180 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1181 case PPCISD::SRL: return "PPCISD::SRL"; 1182 case PPCISD::SRA: return "PPCISD::SRA"; 1183 case PPCISD::SHL: return "PPCISD::SHL"; 1184 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1185 case PPCISD::CALL: return "PPCISD::CALL"; 1186 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1187 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1188 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1189 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1190 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1191 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1192 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1193 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1194 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1195 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1196 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1197 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1198 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1199 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1200 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1201 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1202 case PPCISD::VCMP: return "PPCISD::VCMP"; 1203 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1204 case PPCISD::LBRX: return "PPCISD::LBRX"; 1205 case PPCISD::STBRX: return "PPCISD::STBRX"; 1206 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1207 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1208 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1209 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1210 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1211 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1212 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1213 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1214 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1215 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1216 case PPCISD::BDZ: return "PPCISD::BDZ"; 1217 case PPCISD::MFFS: return "PPCISD::MFFS"; 1218 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1219 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1220 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1221 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1222 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1223 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1224 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1225 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1226 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1227 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1228 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1229 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1230 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1231 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1232 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1233 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1234 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1235 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1236 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1237 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1238 case PPCISD::SC: return "PPCISD::SC"; 1239 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1240 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1241 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1242 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1243 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1244 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1245 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1246 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1247 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1248 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1249 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1250 } 1251 return nullptr; 1252 } 1253 1254 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1255 EVT VT) const { 1256 if (!VT.isVector()) 1257 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1258 1259 if (Subtarget.hasQPX()) 1260 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1261 1262 return VT.changeVectorElementTypeToInteger(); 1263 } 1264 1265 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1266 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1267 return true; 1268 } 1269 1270 //===----------------------------------------------------------------------===// 1271 // Node matching predicates, for use by the tblgen matching code. 1272 //===----------------------------------------------------------------------===// 1273 1274 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1275 static bool isFloatingPointZero(SDValue Op) { 1276 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1277 return CFP->getValueAPF().isZero(); 1278 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1279 // Maybe this has already been legalized into the constant pool? 1280 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1281 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1282 return CFP->getValueAPF().isZero(); 1283 } 1284 return false; 1285 } 1286 1287 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1288 /// true if Op is undef or if it matches the specified value. 1289 static bool isConstantOrUndef(int Op, int Val) { 1290 return Op < 0 || Op == Val; 1291 } 1292 1293 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1294 /// VPKUHUM instruction. 1295 /// The ShuffleKind distinguishes between big-endian operations with 1296 /// two different inputs (0), either-endian operations with two identical 1297 /// inputs (1), and little-endian operations with two different inputs (2). 1298 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1299 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1300 SelectionDAG &DAG) { 1301 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1302 if (ShuffleKind == 0) { 1303 if (IsLE) 1304 return false; 1305 for (unsigned i = 0; i != 16; ++i) 1306 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1307 return false; 1308 } else if (ShuffleKind == 2) { 1309 if (!IsLE) 1310 return false; 1311 for (unsigned i = 0; i != 16; ++i) 1312 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1313 return false; 1314 } else if (ShuffleKind == 1) { 1315 unsigned j = IsLE ? 0 : 1; 1316 for (unsigned i = 0; i != 8; ++i) 1317 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1318 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1319 return false; 1320 } 1321 return true; 1322 } 1323 1324 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1325 /// VPKUWUM instruction. 1326 /// The ShuffleKind distinguishes between big-endian operations with 1327 /// two different inputs (0), either-endian operations with two identical 1328 /// inputs (1), and little-endian operations with two different inputs (2). 1329 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1330 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1331 SelectionDAG &DAG) { 1332 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1333 if (ShuffleKind == 0) { 1334 if (IsLE) 1335 return false; 1336 for (unsigned i = 0; i != 16; i += 2) 1337 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1338 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1339 return false; 1340 } else if (ShuffleKind == 2) { 1341 if (!IsLE) 1342 return false; 1343 for (unsigned i = 0; i != 16; i += 2) 1344 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1345 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1346 return false; 1347 } else if (ShuffleKind == 1) { 1348 unsigned j = IsLE ? 0 : 2; 1349 for (unsigned i = 0; i != 8; i += 2) 1350 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1351 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1352 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1353 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1354 return false; 1355 } 1356 return true; 1357 } 1358 1359 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1360 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1361 /// current subtarget. 1362 /// 1363 /// The ShuffleKind distinguishes between big-endian operations with 1364 /// two different inputs (0), either-endian operations with two identical 1365 /// inputs (1), and little-endian operations with two different inputs (2). 1366 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1367 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1368 SelectionDAG &DAG) { 1369 const PPCSubtarget& Subtarget = 1370 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1371 if (!Subtarget.hasP8Vector()) 1372 return false; 1373 1374 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1375 if (ShuffleKind == 0) { 1376 if (IsLE) 1377 return false; 1378 for (unsigned i = 0; i != 16; i += 4) 1379 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1380 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1381 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1382 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1383 return false; 1384 } else if (ShuffleKind == 2) { 1385 if (!IsLE) 1386 return false; 1387 for (unsigned i = 0; i != 16; i += 4) 1388 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1389 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1390 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1391 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1392 return false; 1393 } else if (ShuffleKind == 1) { 1394 unsigned j = IsLE ? 0 : 4; 1395 for (unsigned i = 0; i != 8; i += 4) 1396 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1397 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1398 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1399 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1400 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1401 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1402 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1403 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1404 return false; 1405 } 1406 return true; 1407 } 1408 1409 /// isVMerge - Common function, used to match vmrg* shuffles. 1410 /// 1411 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1412 unsigned LHSStart, unsigned RHSStart) { 1413 if (N->getValueType(0) != MVT::v16i8) 1414 return false; 1415 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1416 "Unsupported merge size!"); 1417 1418 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1419 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1420 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1421 LHSStart+j+i*UnitSize) || 1422 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1423 RHSStart+j+i*UnitSize)) 1424 return false; 1425 } 1426 return true; 1427 } 1428 1429 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1430 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1431 /// The ShuffleKind distinguishes between big-endian merges with two 1432 /// different inputs (0), either-endian merges with two identical inputs (1), 1433 /// and little-endian merges with two different inputs (2). For the latter, 1434 /// the input operands are swapped (see PPCInstrAltivec.td). 1435 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1436 unsigned ShuffleKind, SelectionDAG &DAG) { 1437 if (DAG.getDataLayout().isLittleEndian()) { 1438 if (ShuffleKind == 1) // unary 1439 return isVMerge(N, UnitSize, 0, 0); 1440 else if (ShuffleKind == 2) // swapped 1441 return isVMerge(N, UnitSize, 0, 16); 1442 else 1443 return false; 1444 } else { 1445 if (ShuffleKind == 1) // unary 1446 return isVMerge(N, UnitSize, 8, 8); 1447 else if (ShuffleKind == 0) // normal 1448 return isVMerge(N, UnitSize, 8, 24); 1449 else 1450 return false; 1451 } 1452 } 1453 1454 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1455 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1456 /// The ShuffleKind distinguishes between big-endian merges with two 1457 /// different inputs (0), either-endian merges with two identical inputs (1), 1458 /// and little-endian merges with two different inputs (2). For the latter, 1459 /// the input operands are swapped (see PPCInstrAltivec.td). 1460 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1461 unsigned ShuffleKind, SelectionDAG &DAG) { 1462 if (DAG.getDataLayout().isLittleEndian()) { 1463 if (ShuffleKind == 1) // unary 1464 return isVMerge(N, UnitSize, 8, 8); 1465 else if (ShuffleKind == 2) // swapped 1466 return isVMerge(N, UnitSize, 8, 24); 1467 else 1468 return false; 1469 } else { 1470 if (ShuffleKind == 1) // unary 1471 return isVMerge(N, UnitSize, 0, 0); 1472 else if (ShuffleKind == 0) // normal 1473 return isVMerge(N, UnitSize, 0, 16); 1474 else 1475 return false; 1476 } 1477 } 1478 1479 /** 1480 * Common function used to match vmrgew and vmrgow shuffles 1481 * 1482 * The indexOffset determines whether to look for even or odd words in 1483 * the shuffle mask. This is based on the of the endianness of the target 1484 * machine. 1485 * - Little Endian: 1486 * - Use offset of 0 to check for odd elements 1487 * - Use offset of 4 to check for even elements 1488 * - Big Endian: 1489 * - Use offset of 0 to check for even elements 1490 * - Use offset of 4 to check for odd elements 1491 * A detailed description of the vector element ordering for little endian and 1492 * big endian can be found at 1493 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1494 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1495 * compiler differences mean to you 1496 * 1497 * The mask to the shuffle vector instruction specifies the indices of the 1498 * elements from the two input vectors to place in the result. The elements are 1499 * numbered in array-access order, starting with the first vector. These vectors 1500 * are always of type v16i8, thus each vector will contain 16 elements of size 1501 * 8. More info on the shuffle vector can be found in the 1502 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1503 * Language Reference. 1504 * 1505 * The RHSStartValue indicates whether the same input vectors are used (unary) 1506 * or two different input vectors are used, based on the following: 1507 * - If the instruction uses the same vector for both inputs, the range of the 1508 * indices will be 0 to 15. In this case, the RHSStart value passed should 1509 * be 0. 1510 * - If the instruction has two different vectors then the range of the 1511 * indices will be 0 to 31. In this case, the RHSStart value passed should 1512 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1513 * to 31 specify elements in the second vector). 1514 * 1515 * \param[in] N The shuffle vector SD Node to analyze 1516 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1517 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1518 * vector to the shuffle_vector instruction 1519 * \return true iff this shuffle vector represents an even or odd word merge 1520 */ 1521 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1522 unsigned RHSStartValue) { 1523 if (N->getValueType(0) != MVT::v16i8) 1524 return false; 1525 1526 for (unsigned i = 0; i < 2; ++i) 1527 for (unsigned j = 0; j < 4; ++j) 1528 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1529 i*RHSStartValue+j+IndexOffset) || 1530 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1531 i*RHSStartValue+j+IndexOffset+8)) 1532 return false; 1533 return true; 1534 } 1535 1536 /** 1537 * Determine if the specified shuffle mask is suitable for the vmrgew or 1538 * vmrgow instructions. 1539 * 1540 * \param[in] N The shuffle vector SD Node to analyze 1541 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1542 * \param[in] ShuffleKind Identify the type of merge: 1543 * - 0 = big-endian merge with two different inputs; 1544 * - 1 = either-endian merge with two identical inputs; 1545 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1546 * little-endian merges). 1547 * \param[in] DAG The current SelectionDAG 1548 * \return true iff this shuffle mask 1549 */ 1550 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1551 unsigned ShuffleKind, SelectionDAG &DAG) { 1552 if (DAG.getDataLayout().isLittleEndian()) { 1553 unsigned indexOffset = CheckEven ? 4 : 0; 1554 if (ShuffleKind == 1) // Unary 1555 return isVMerge(N, indexOffset, 0); 1556 else if (ShuffleKind == 2) // swapped 1557 return isVMerge(N, indexOffset, 16); 1558 else 1559 return false; 1560 } 1561 else { 1562 unsigned indexOffset = CheckEven ? 0 : 4; 1563 if (ShuffleKind == 1) // Unary 1564 return isVMerge(N, indexOffset, 0); 1565 else if (ShuffleKind == 0) // Normal 1566 return isVMerge(N, indexOffset, 16); 1567 else 1568 return false; 1569 } 1570 return false; 1571 } 1572 1573 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1574 /// amount, otherwise return -1. 1575 /// The ShuffleKind distinguishes between big-endian operations with two 1576 /// different inputs (0), either-endian operations with two identical inputs 1577 /// (1), and little-endian operations with two different inputs (2). For the 1578 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1579 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1580 SelectionDAG &DAG) { 1581 if (N->getValueType(0) != MVT::v16i8) 1582 return -1; 1583 1584 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1585 1586 // Find the first non-undef value in the shuffle mask. 1587 unsigned i; 1588 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1589 /*search*/; 1590 1591 if (i == 16) return -1; // all undef. 1592 1593 // Otherwise, check to see if the rest of the elements are consecutively 1594 // numbered from this value. 1595 unsigned ShiftAmt = SVOp->getMaskElt(i); 1596 if (ShiftAmt < i) return -1; 1597 1598 ShiftAmt -= i; 1599 bool isLE = DAG.getDataLayout().isLittleEndian(); 1600 1601 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1602 // Check the rest of the elements to see if they are consecutive. 1603 for (++i; i != 16; ++i) 1604 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1605 return -1; 1606 } else if (ShuffleKind == 1) { 1607 // Check the rest of the elements to see if they are consecutive. 1608 for (++i; i != 16; ++i) 1609 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1610 return -1; 1611 } else 1612 return -1; 1613 1614 if (isLE) 1615 ShiftAmt = 16 - ShiftAmt; 1616 1617 return ShiftAmt; 1618 } 1619 1620 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1621 /// specifies a splat of a single element that is suitable for input to 1622 /// VSPLTB/VSPLTH/VSPLTW. 1623 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1624 assert(N->getValueType(0) == MVT::v16i8 && 1625 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1626 1627 // The consecutive indices need to specify an element, not part of two 1628 // different elements. So abandon ship early if this isn't the case. 1629 if (N->getMaskElt(0) % EltSize != 0) 1630 return false; 1631 1632 // This is a splat operation if each element of the permute is the same, and 1633 // if the value doesn't reference the second vector. 1634 unsigned ElementBase = N->getMaskElt(0); 1635 1636 // FIXME: Handle UNDEF elements too! 1637 if (ElementBase >= 16) 1638 return false; 1639 1640 // Check that the indices are consecutive, in the case of a multi-byte element 1641 // splatted with a v16i8 mask. 1642 for (unsigned i = 1; i != EltSize; ++i) 1643 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1644 return false; 1645 1646 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1647 if (N->getMaskElt(i) < 0) continue; 1648 for (unsigned j = 0; j != EltSize; ++j) 1649 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1650 return false; 1651 } 1652 return true; 1653 } 1654 1655 /// Check that the mask is shuffling N byte elements. Within each N byte 1656 /// element of the mask, the indices could be either in increasing or 1657 /// decreasing order as long as they are consecutive. 1658 /// \param[in] N the shuffle vector SD Node to analyze 1659 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1660 /// Word/DoubleWord/QuadWord). 1661 /// \param[in] StepLen the delta indices number among the N byte element, if 1662 /// the mask is in increasing/decreasing order then it is 1/-1. 1663 /// \return true iff the mask is shuffling N byte elements. 1664 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1665 int StepLen) { 1666 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1667 "Unexpected element width."); 1668 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1669 1670 unsigned NumOfElem = 16 / Width; 1671 unsigned MaskVal[16]; // Width is never greater than 16 1672 for (unsigned i = 0; i < NumOfElem; ++i) { 1673 MaskVal[0] = N->getMaskElt(i * Width); 1674 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1675 return false; 1676 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1677 return false; 1678 } 1679 1680 for (unsigned int j = 1; j < Width; ++j) { 1681 MaskVal[j] = N->getMaskElt(i * Width + j); 1682 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1683 return false; 1684 } 1685 } 1686 } 1687 1688 return true; 1689 } 1690 1691 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1692 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1693 if (!isNByteElemShuffleMask(N, 4, 1)) 1694 return false; 1695 1696 // Now we look at mask elements 0,4,8,12 1697 unsigned M0 = N->getMaskElt(0) / 4; 1698 unsigned M1 = N->getMaskElt(4) / 4; 1699 unsigned M2 = N->getMaskElt(8) / 4; 1700 unsigned M3 = N->getMaskElt(12) / 4; 1701 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1702 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1703 1704 // Below, let H and L be arbitrary elements of the shuffle mask 1705 // where H is in the range [4,7] and L is in the range [0,3]. 1706 // H, 1, 2, 3 or L, 5, 6, 7 1707 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1708 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1709 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1710 InsertAtByte = IsLE ? 12 : 0; 1711 Swap = M0 < 4; 1712 return true; 1713 } 1714 // 0, H, 2, 3 or 4, L, 6, 7 1715 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1716 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1717 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1718 InsertAtByte = IsLE ? 8 : 4; 1719 Swap = M1 < 4; 1720 return true; 1721 } 1722 // 0, 1, H, 3 or 4, 5, L, 7 1723 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1724 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1725 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1726 InsertAtByte = IsLE ? 4 : 8; 1727 Swap = M2 < 4; 1728 return true; 1729 } 1730 // 0, 1, 2, H or 4, 5, 6, L 1731 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1732 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1733 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1734 InsertAtByte = IsLE ? 0 : 12; 1735 Swap = M3 < 4; 1736 return true; 1737 } 1738 1739 // If both vector operands for the shuffle are the same vector, the mask will 1740 // contain only elements from the first one and the second one will be undef. 1741 if (N->getOperand(1).isUndef()) { 1742 ShiftElts = 0; 1743 Swap = true; 1744 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1745 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1746 InsertAtByte = IsLE ? 12 : 0; 1747 return true; 1748 } 1749 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1750 InsertAtByte = IsLE ? 8 : 4; 1751 return true; 1752 } 1753 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1754 InsertAtByte = IsLE ? 4 : 8; 1755 return true; 1756 } 1757 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1758 InsertAtByte = IsLE ? 0 : 12; 1759 return true; 1760 } 1761 } 1762 1763 return false; 1764 } 1765 1766 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1767 bool &Swap, bool IsLE) { 1768 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1769 // Ensure each byte index of the word is consecutive. 1770 if (!isNByteElemShuffleMask(N, 4, 1)) 1771 return false; 1772 1773 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1774 unsigned M0 = N->getMaskElt(0) / 4; 1775 unsigned M1 = N->getMaskElt(4) / 4; 1776 unsigned M2 = N->getMaskElt(8) / 4; 1777 unsigned M3 = N->getMaskElt(12) / 4; 1778 1779 // If both vector operands for the shuffle are the same vector, the mask will 1780 // contain only elements from the first one and the second one will be undef. 1781 if (N->getOperand(1).isUndef()) { 1782 assert(M0 < 4 && "Indexing into an undef vector?"); 1783 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1784 return false; 1785 1786 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1787 Swap = false; 1788 return true; 1789 } 1790 1791 // Ensure each word index of the ShuffleVector Mask is consecutive. 1792 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1793 return false; 1794 1795 if (IsLE) { 1796 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1797 // Input vectors don't need to be swapped if the leading element 1798 // of the result is one of the 3 left elements of the second vector 1799 // (or if there is no shift to be done at all). 1800 Swap = false; 1801 ShiftElts = (8 - M0) % 8; 1802 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1803 // Input vectors need to be swapped if the leading element 1804 // of the result is one of the 3 left elements of the first vector 1805 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1806 Swap = true; 1807 ShiftElts = (4 - M0) % 4; 1808 } 1809 1810 return true; 1811 } else { // BE 1812 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1813 // Input vectors don't need to be swapped if the leading element 1814 // of the result is one of the 4 elements of the first vector. 1815 Swap = false; 1816 ShiftElts = M0; 1817 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1818 // Input vectors need to be swapped if the leading element 1819 // of the result is one of the 4 elements of the right vector. 1820 Swap = true; 1821 ShiftElts = M0 - 4; 1822 } 1823 1824 return true; 1825 } 1826 } 1827 1828 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1829 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1830 1831 if (!isNByteElemShuffleMask(N, Width, -1)) 1832 return false; 1833 1834 for (int i = 0; i < 16; i += Width) 1835 if (N->getMaskElt(i) != i + Width - 1) 1836 return false; 1837 1838 return true; 1839 } 1840 1841 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1842 return isXXBRShuffleMaskHelper(N, 2); 1843 } 1844 1845 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1846 return isXXBRShuffleMaskHelper(N, 4); 1847 } 1848 1849 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 1850 return isXXBRShuffleMaskHelper(N, 8); 1851 } 1852 1853 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 1854 return isXXBRShuffleMaskHelper(N, 16); 1855 } 1856 1857 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 1858 /// if the inputs to the instruction should be swapped and set \p DM to the 1859 /// value for the immediate. 1860 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 1861 /// AND element 0 of the result comes from the first input (LE) or second input 1862 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 1863 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 1864 /// mask. 1865 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 1866 bool &Swap, bool IsLE) { 1867 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1868 1869 // Ensure each byte index of the double word is consecutive. 1870 if (!isNByteElemShuffleMask(N, 8, 1)) 1871 return false; 1872 1873 unsigned M0 = N->getMaskElt(0) / 8; 1874 unsigned M1 = N->getMaskElt(8) / 8; 1875 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 1876 1877 // If both vector operands for the shuffle are the same vector, the mask will 1878 // contain only elements from the first one and the second one will be undef. 1879 if (N->getOperand(1).isUndef()) { 1880 if ((M0 | M1) < 2) { 1881 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 1882 Swap = false; 1883 return true; 1884 } else 1885 return false; 1886 } 1887 1888 if (IsLE) { 1889 if (M0 > 1 && M1 < 2) { 1890 Swap = false; 1891 } else if (M0 < 2 && M1 > 1) { 1892 M0 = (M0 + 2) % 4; 1893 M1 = (M1 + 2) % 4; 1894 Swap = true; 1895 } else 1896 return false; 1897 1898 // Note: if control flow comes here that means Swap is already set above 1899 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 1900 return true; 1901 } else { // BE 1902 if (M0 < 2 && M1 > 1) { 1903 Swap = false; 1904 } else if (M0 > 1 && M1 < 2) { 1905 M0 = (M0 + 2) % 4; 1906 M1 = (M1 + 2) % 4; 1907 Swap = true; 1908 } else 1909 return false; 1910 1911 // Note: if control flow comes here that means Swap is already set above 1912 DM = (M0 << 1) + (M1 & 1); 1913 return true; 1914 } 1915 } 1916 1917 1918 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 1919 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 1920 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 1921 SelectionDAG &DAG) { 1922 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1923 assert(isSplatShuffleMask(SVOp, EltSize)); 1924 if (DAG.getDataLayout().isLittleEndian()) 1925 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 1926 else 1927 return SVOp->getMaskElt(0) / EltSize; 1928 } 1929 1930 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 1931 /// by using a vspltis[bhw] instruction of the specified element size, return 1932 /// the constant being splatted. The ByteSize field indicates the number of 1933 /// bytes of each element [124] -> [bhw]. 1934 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 1935 SDValue OpVal(nullptr, 0); 1936 1937 // If ByteSize of the splat is bigger than the element size of the 1938 // build_vector, then we have a case where we are checking for a splat where 1939 // multiple elements of the buildvector are folded together into a single 1940 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 1941 unsigned EltSize = 16/N->getNumOperands(); 1942 if (EltSize < ByteSize) { 1943 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 1944 SDValue UniquedVals[4]; 1945 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 1946 1947 // See if all of the elements in the buildvector agree across. 1948 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1949 if (N->getOperand(i).isUndef()) continue; 1950 // If the element isn't a constant, bail fully out. 1951 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 1952 1953 if (!UniquedVals[i&(Multiple-1)].getNode()) 1954 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 1955 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 1956 return SDValue(); // no match. 1957 } 1958 1959 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 1960 // either constant or undef values that are identical for each chunk. See 1961 // if these chunks can form into a larger vspltis*. 1962 1963 // Check to see if all of the leading entries are either 0 or -1. If 1964 // neither, then this won't fit into the immediate field. 1965 bool LeadingZero = true; 1966 bool LeadingOnes = true; 1967 for (unsigned i = 0; i != Multiple-1; ++i) { 1968 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 1969 1970 LeadingZero &= isNullConstant(UniquedVals[i]); 1971 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 1972 } 1973 // Finally, check the least significant entry. 1974 if (LeadingZero) { 1975 if (!UniquedVals[Multiple-1].getNode()) 1976 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 1977 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 1978 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 1979 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1980 } 1981 if (LeadingOnes) { 1982 if (!UniquedVals[Multiple-1].getNode()) 1983 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 1984 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 1985 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 1986 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1987 } 1988 1989 return SDValue(); 1990 } 1991 1992 // Check to see if this buildvec has a single non-undef value in its elements. 1993 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1994 if (N->getOperand(i).isUndef()) continue; 1995 if (!OpVal.getNode()) 1996 OpVal = N->getOperand(i); 1997 else if (OpVal != N->getOperand(i)) 1998 return SDValue(); 1999 } 2000 2001 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2002 2003 unsigned ValSizeInBytes = EltSize; 2004 uint64_t Value = 0; 2005 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2006 Value = CN->getZExtValue(); 2007 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2008 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2009 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2010 } 2011 2012 // If the splat value is larger than the element value, then we can never do 2013 // this splat. The only case that we could fit the replicated bits into our 2014 // immediate field for would be zero, and we prefer to use vxor for it. 2015 if (ValSizeInBytes < ByteSize) return SDValue(); 2016 2017 // If the element value is larger than the splat value, check if it consists 2018 // of a repeated bit pattern of size ByteSize. 2019 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2020 return SDValue(); 2021 2022 // Properly sign extend the value. 2023 int MaskVal = SignExtend32(Value, ByteSize * 8); 2024 2025 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2026 if (MaskVal == 0) return SDValue(); 2027 2028 // Finally, if this value fits in a 5 bit sext field, return it 2029 if (SignExtend32<5>(MaskVal) == MaskVal) 2030 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2031 return SDValue(); 2032 } 2033 2034 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2035 /// amount, otherwise return -1. 2036 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2037 EVT VT = N->getValueType(0); 2038 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2039 return -1; 2040 2041 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2042 2043 // Find the first non-undef value in the shuffle mask. 2044 unsigned i; 2045 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2046 /*search*/; 2047 2048 if (i == 4) return -1; // all undef. 2049 2050 // Otherwise, check to see if the rest of the elements are consecutively 2051 // numbered from this value. 2052 unsigned ShiftAmt = SVOp->getMaskElt(i); 2053 if (ShiftAmt < i) return -1; 2054 ShiftAmt -= i; 2055 2056 // Check the rest of the elements to see if they are consecutive. 2057 for (++i; i != 4; ++i) 2058 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2059 return -1; 2060 2061 return ShiftAmt; 2062 } 2063 2064 //===----------------------------------------------------------------------===// 2065 // Addressing Mode Selection 2066 //===----------------------------------------------------------------------===// 2067 2068 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2069 /// or 64-bit immediate, and if the value can be accurately represented as a 2070 /// sign extension from a 16-bit value. If so, this returns true and the 2071 /// immediate. 2072 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2073 if (!isa<ConstantSDNode>(N)) 2074 return false; 2075 2076 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2077 if (N->getValueType(0) == MVT::i32) 2078 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2079 else 2080 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2081 } 2082 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2083 return isIntS16Immediate(Op.getNode(), Imm); 2084 } 2085 2086 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2087 /// can be represented as an indexed [r+r] operation. Returns false if it 2088 /// can be more efficiently represented with [r+imm]. 2089 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2090 SDValue &Index, 2091 SelectionDAG &DAG) const { 2092 int16_t imm = 0; 2093 if (N.getOpcode() == ISD::ADD) { 2094 if (isIntS16Immediate(N.getOperand(1), imm)) 2095 return false; // r+i 2096 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2097 return false; // r+i 2098 2099 Base = N.getOperand(0); 2100 Index = N.getOperand(1); 2101 return true; 2102 } else if (N.getOpcode() == ISD::OR) { 2103 if (isIntS16Immediate(N.getOperand(1), imm)) 2104 return false; // r+i can fold it if we can. 2105 2106 // If this is an or of disjoint bitfields, we can codegen this as an add 2107 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2108 // disjoint. 2109 KnownBits LHSKnown, RHSKnown; 2110 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2111 2112 if (LHSKnown.Zero.getBoolValue()) { 2113 DAG.computeKnownBits(N.getOperand(1), RHSKnown); 2114 // If all of the bits are known zero on the LHS or RHS, the add won't 2115 // carry. 2116 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2117 Base = N.getOperand(0); 2118 Index = N.getOperand(1); 2119 return true; 2120 } 2121 } 2122 } 2123 2124 return false; 2125 } 2126 2127 // If we happen to be doing an i64 load or store into a stack slot that has 2128 // less than a 4-byte alignment, then the frame-index elimination may need to 2129 // use an indexed load or store instruction (because the offset may not be a 2130 // multiple of 4). The extra register needed to hold the offset comes from the 2131 // register scavenger, and it is possible that the scavenger will need to use 2132 // an emergency spill slot. As a result, we need to make sure that a spill slot 2133 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2134 // stack slot. 2135 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2136 // FIXME: This does not handle the LWA case. 2137 if (VT != MVT::i64) 2138 return; 2139 2140 // NOTE: We'll exclude negative FIs here, which come from argument 2141 // lowering, because there are no known test cases triggering this problem 2142 // using packed structures (or similar). We can remove this exclusion if 2143 // we find such a test case. The reason why this is so test-case driven is 2144 // because this entire 'fixup' is only to prevent crashes (from the 2145 // register scavenger) on not-really-valid inputs. For example, if we have: 2146 // %a = alloca i1 2147 // %b = bitcast i1* %a to i64* 2148 // store i64* a, i64 b 2149 // then the store should really be marked as 'align 1', but is not. If it 2150 // were marked as 'align 1' then the indexed form would have been 2151 // instruction-selected initially, and the problem this 'fixup' is preventing 2152 // won't happen regardless. 2153 if (FrameIdx < 0) 2154 return; 2155 2156 MachineFunction &MF = DAG.getMachineFunction(); 2157 MachineFrameInfo &MFI = MF.getFrameInfo(); 2158 2159 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2160 if (Align >= 4) 2161 return; 2162 2163 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2164 FuncInfo->setHasNonRISpills(); 2165 } 2166 2167 /// Returns true if the address N can be represented by a base register plus 2168 /// a signed 16-bit displacement [r+imm], and if it is not better 2169 /// represented as reg+reg. If \p Alignment is non-zero, only accept 2170 /// displacements that are multiples of that value. 2171 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2172 SDValue &Base, 2173 SelectionDAG &DAG, 2174 unsigned Alignment) const { 2175 // FIXME dl should come from parent load or store, not from address 2176 SDLoc dl(N); 2177 // If this can be more profitably realized as r+r, fail. 2178 if (SelectAddressRegReg(N, Disp, Base, DAG)) 2179 return false; 2180 2181 if (N.getOpcode() == ISD::ADD) { 2182 int16_t imm = 0; 2183 if (isIntS16Immediate(N.getOperand(1), imm) && 2184 (!Alignment || (imm % Alignment) == 0)) { 2185 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2186 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2187 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2188 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2189 } else { 2190 Base = N.getOperand(0); 2191 } 2192 return true; // [r+i] 2193 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2194 // Match LOAD (ADD (X, Lo(G))). 2195 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2196 && "Cannot handle constant offsets yet!"); 2197 Disp = N.getOperand(1).getOperand(0); // The global address. 2198 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2199 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2200 Disp.getOpcode() == ISD::TargetConstantPool || 2201 Disp.getOpcode() == ISD::TargetJumpTable); 2202 Base = N.getOperand(0); 2203 return true; // [&g+r] 2204 } 2205 } else if (N.getOpcode() == ISD::OR) { 2206 int16_t imm = 0; 2207 if (isIntS16Immediate(N.getOperand(1), imm) && 2208 (!Alignment || (imm % Alignment) == 0)) { 2209 // If this is an or of disjoint bitfields, we can codegen this as an add 2210 // (for better address arithmetic) if the LHS and RHS of the OR are 2211 // provably disjoint. 2212 KnownBits LHSKnown; 2213 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2214 2215 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2216 // If all of the bits are known zero on the LHS or RHS, the add won't 2217 // carry. 2218 if (FrameIndexSDNode *FI = 2219 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2220 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2221 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2222 } else { 2223 Base = N.getOperand(0); 2224 } 2225 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2226 return true; 2227 } 2228 } 2229 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2230 // Loading from a constant address. 2231 2232 // If this address fits entirely in a 16-bit sext immediate field, codegen 2233 // this as "d, 0" 2234 int16_t Imm; 2235 if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) { 2236 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2237 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2238 CN->getValueType(0)); 2239 return true; 2240 } 2241 2242 // Handle 32-bit sext immediates with LIS + addr mode. 2243 if ((CN->getValueType(0) == MVT::i32 || 2244 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2245 (!Alignment || (CN->getZExtValue() % Alignment) == 0)) { 2246 int Addr = (int)CN->getZExtValue(); 2247 2248 // Otherwise, break this down into an LIS + disp. 2249 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2250 2251 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2252 MVT::i32); 2253 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2254 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2255 return true; 2256 } 2257 } 2258 2259 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2260 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2261 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2262 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2263 } else 2264 Base = N; 2265 return true; // [r+0] 2266 } 2267 2268 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2269 /// represented as an indexed [r+r] operation. 2270 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2271 SDValue &Index, 2272 SelectionDAG &DAG) const { 2273 // Check to see if we can easily represent this as an [r+r] address. This 2274 // will fail if it thinks that the address is more profitably represented as 2275 // reg+imm, e.g. where imm = 0. 2276 if (SelectAddressRegReg(N, Base, Index, DAG)) 2277 return true; 2278 2279 // If the address is the result of an add, we will utilize the fact that the 2280 // address calculation includes an implicit add. However, we can reduce 2281 // register pressure if we do not materialize a constant just for use as the 2282 // index register. We only get rid of the add if it is not an add of a 2283 // value and a 16-bit signed constant and both have a single use. 2284 int16_t imm = 0; 2285 if (N.getOpcode() == ISD::ADD && 2286 (!isIntS16Immediate(N.getOperand(1), imm) || 2287 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2288 Base = N.getOperand(0); 2289 Index = N.getOperand(1); 2290 return true; 2291 } 2292 2293 // Otherwise, do it the hard way, using R0 as the base register. 2294 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2295 N.getValueType()); 2296 Index = N; 2297 return true; 2298 } 2299 2300 /// getPreIndexedAddressParts - returns true by value, base pointer and 2301 /// offset pointer and addressing mode by reference if the node's address 2302 /// can be legally represented as pre-indexed load / store address. 2303 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2304 SDValue &Offset, 2305 ISD::MemIndexedMode &AM, 2306 SelectionDAG &DAG) const { 2307 if (DisablePPCPreinc) return false; 2308 2309 bool isLoad = true; 2310 SDValue Ptr; 2311 EVT VT; 2312 unsigned Alignment; 2313 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2314 Ptr = LD->getBasePtr(); 2315 VT = LD->getMemoryVT(); 2316 Alignment = LD->getAlignment(); 2317 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2318 Ptr = ST->getBasePtr(); 2319 VT = ST->getMemoryVT(); 2320 Alignment = ST->getAlignment(); 2321 isLoad = false; 2322 } else 2323 return false; 2324 2325 // PowerPC doesn't have preinc load/store instructions for vectors (except 2326 // for QPX, which does have preinc r+r forms). 2327 if (VT.isVector()) { 2328 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2329 return false; 2330 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2331 AM = ISD::PRE_INC; 2332 return true; 2333 } 2334 } 2335 2336 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2337 // Common code will reject creating a pre-inc form if the base pointer 2338 // is a frame index, or if N is a store and the base pointer is either 2339 // the same as or a predecessor of the value being stored. Check for 2340 // those situations here, and try with swapped Base/Offset instead. 2341 bool Swap = false; 2342 2343 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2344 Swap = true; 2345 else if (!isLoad) { 2346 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2347 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2348 Swap = true; 2349 } 2350 2351 if (Swap) 2352 std::swap(Base, Offset); 2353 2354 AM = ISD::PRE_INC; 2355 return true; 2356 } 2357 2358 // LDU/STU can only handle immediates that are a multiple of 4. 2359 if (VT != MVT::i64) { 2360 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2361 return false; 2362 } else { 2363 // LDU/STU need an address with at least 4-byte alignment. 2364 if (Alignment < 4) 2365 return false; 2366 2367 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2368 return false; 2369 } 2370 2371 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2372 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2373 // sext i32 to i64 when addr mode is r+i. 2374 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2375 LD->getExtensionType() == ISD::SEXTLOAD && 2376 isa<ConstantSDNode>(Offset)) 2377 return false; 2378 } 2379 2380 AM = ISD::PRE_INC; 2381 return true; 2382 } 2383 2384 //===----------------------------------------------------------------------===// 2385 // LowerOperation implementation 2386 //===----------------------------------------------------------------------===// 2387 2388 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2389 /// and LoOpFlags to the target MO flags. 2390 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2391 unsigned &HiOpFlags, unsigned &LoOpFlags, 2392 const GlobalValue *GV = nullptr) { 2393 HiOpFlags = PPCII::MO_HA; 2394 LoOpFlags = PPCII::MO_LO; 2395 2396 // Don't use the pic base if not in PIC relocation model. 2397 if (IsPIC) { 2398 HiOpFlags |= PPCII::MO_PIC_FLAG; 2399 LoOpFlags |= PPCII::MO_PIC_FLAG; 2400 } 2401 2402 // If this is a reference to a global value that requires a non-lazy-ptr, make 2403 // sure that instruction lowering adds it. 2404 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2405 HiOpFlags |= PPCII::MO_NLP_FLAG; 2406 LoOpFlags |= PPCII::MO_NLP_FLAG; 2407 2408 if (GV->hasHiddenVisibility()) { 2409 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2410 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2411 } 2412 } 2413 } 2414 2415 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2416 SelectionDAG &DAG) { 2417 SDLoc DL(HiPart); 2418 EVT PtrVT = HiPart.getValueType(); 2419 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2420 2421 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2422 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2423 2424 // With PIC, the first instruction is actually "GR+hi(&G)". 2425 if (isPIC) 2426 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2427 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2428 2429 // Generate non-pic code that has direct accesses to the constant pool. 2430 // The address of the global is just (hi(&g)+lo(&g)). 2431 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2432 } 2433 2434 static void setUsesTOCBasePtr(MachineFunction &MF) { 2435 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2436 FuncInfo->setUsesTOCBasePtr(); 2437 } 2438 2439 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2440 setUsesTOCBasePtr(DAG.getMachineFunction()); 2441 } 2442 2443 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2444 SDValue GA) { 2445 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2446 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2447 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2448 2449 SDValue Ops[] = { GA, Reg }; 2450 return DAG.getMemIntrinsicNode( 2451 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2452 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2453 MachineMemOperand::MOLoad); 2454 } 2455 2456 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2457 SelectionDAG &DAG) const { 2458 EVT PtrVT = Op.getValueType(); 2459 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2460 const Constant *C = CP->getConstVal(); 2461 2462 // 64-bit SVR4 ABI code is always position-independent. 2463 // The actual address of the GlobalValue is stored in the TOC. 2464 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2465 setUsesTOCBasePtr(DAG); 2466 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2467 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2468 } 2469 2470 unsigned MOHiFlag, MOLoFlag; 2471 bool IsPIC = isPositionIndependent(); 2472 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2473 2474 if (IsPIC && Subtarget.isSVR4ABI()) { 2475 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2476 PPCII::MO_PIC_FLAG); 2477 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2478 } 2479 2480 SDValue CPIHi = 2481 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2482 SDValue CPILo = 2483 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2484 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2485 } 2486 2487 // For 64-bit PowerPC, prefer the more compact relative encodings. 2488 // This trades 32 bits per jump table entry for one or two instructions 2489 // on the jump site. 2490 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2491 if (isJumpTableRelative()) 2492 return MachineJumpTableInfo::EK_LabelDifference32; 2493 2494 return TargetLowering::getJumpTableEncoding(); 2495 } 2496 2497 bool PPCTargetLowering::isJumpTableRelative() const { 2498 if (Subtarget.isPPC64()) 2499 return true; 2500 return TargetLowering::isJumpTableRelative(); 2501 } 2502 2503 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2504 SelectionDAG &DAG) const { 2505 if (!Subtarget.isPPC64()) 2506 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2507 2508 switch (getTargetMachine().getCodeModel()) { 2509 case CodeModel::Small: 2510 case CodeModel::Medium: 2511 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2512 default: 2513 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2514 getPointerTy(DAG.getDataLayout())); 2515 } 2516 } 2517 2518 const MCExpr * 2519 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2520 unsigned JTI, 2521 MCContext &Ctx) const { 2522 if (!Subtarget.isPPC64()) 2523 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2524 2525 switch (getTargetMachine().getCodeModel()) { 2526 case CodeModel::Small: 2527 case CodeModel::Medium: 2528 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2529 default: 2530 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2531 } 2532 } 2533 2534 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2535 EVT PtrVT = Op.getValueType(); 2536 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2537 2538 // 64-bit SVR4 ABI code is always position-independent. 2539 // The actual address of the GlobalValue is stored in the TOC. 2540 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2541 setUsesTOCBasePtr(DAG); 2542 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2543 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2544 } 2545 2546 unsigned MOHiFlag, MOLoFlag; 2547 bool IsPIC = isPositionIndependent(); 2548 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2549 2550 if (IsPIC && Subtarget.isSVR4ABI()) { 2551 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2552 PPCII::MO_PIC_FLAG); 2553 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2554 } 2555 2556 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2557 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2558 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2559 } 2560 2561 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2562 SelectionDAG &DAG) const { 2563 EVT PtrVT = Op.getValueType(); 2564 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2565 const BlockAddress *BA = BASDN->getBlockAddress(); 2566 2567 // 64-bit SVR4 ABI code is always position-independent. 2568 // The actual BlockAddress is stored in the TOC. 2569 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2570 setUsesTOCBasePtr(DAG); 2571 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2572 return getTOCEntry(DAG, SDLoc(BASDN), true, GA); 2573 } 2574 2575 unsigned MOHiFlag, MOLoFlag; 2576 bool IsPIC = isPositionIndependent(); 2577 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2578 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2579 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2580 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2581 } 2582 2583 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2584 SelectionDAG &DAG) const { 2585 // FIXME: TLS addresses currently use medium model code sequences, 2586 // which is the most useful form. Eventually support for small and 2587 // large models could be added if users need it, at the cost of 2588 // additional complexity. 2589 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2590 if (DAG.getTarget().useEmulatedTLS()) 2591 return LowerToTLSEmulatedModel(GA, DAG); 2592 2593 SDLoc dl(GA); 2594 const GlobalValue *GV = GA->getGlobal(); 2595 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2596 bool is64bit = Subtarget.isPPC64(); 2597 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2598 PICLevel::Level picLevel = M->getPICLevel(); 2599 2600 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 2601 2602 if (Model == TLSModel::LocalExec) { 2603 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2604 PPCII::MO_TPREL_HA); 2605 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2606 PPCII::MO_TPREL_LO); 2607 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2608 : DAG.getRegister(PPC::R2, MVT::i32); 2609 2610 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2611 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2612 } 2613 2614 if (Model == TLSModel::InitialExec) { 2615 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2616 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2617 PPCII::MO_TLS); 2618 SDValue GOTPtr; 2619 if (is64bit) { 2620 setUsesTOCBasePtr(DAG); 2621 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2622 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2623 PtrVT, GOTReg, TGA); 2624 } else 2625 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2626 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2627 PtrVT, TGA, GOTPtr); 2628 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2629 } 2630 2631 if (Model == TLSModel::GeneralDynamic) { 2632 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2633 SDValue GOTPtr; 2634 if (is64bit) { 2635 setUsesTOCBasePtr(DAG); 2636 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2637 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2638 GOTReg, TGA); 2639 } else { 2640 if (picLevel == PICLevel::SmallPIC) 2641 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2642 else 2643 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2644 } 2645 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2646 GOTPtr, TGA, TGA); 2647 } 2648 2649 if (Model == TLSModel::LocalDynamic) { 2650 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2651 SDValue GOTPtr; 2652 if (is64bit) { 2653 setUsesTOCBasePtr(DAG); 2654 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2655 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2656 GOTReg, TGA); 2657 } else { 2658 if (picLevel == PICLevel::SmallPIC) 2659 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2660 else 2661 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2662 } 2663 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2664 PtrVT, GOTPtr, TGA, TGA); 2665 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2666 PtrVT, TLSAddr, TGA); 2667 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2668 } 2669 2670 llvm_unreachable("Unknown TLS model!"); 2671 } 2672 2673 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2674 SelectionDAG &DAG) const { 2675 EVT PtrVT = Op.getValueType(); 2676 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2677 SDLoc DL(GSDN); 2678 const GlobalValue *GV = GSDN->getGlobal(); 2679 2680 // 64-bit SVR4 ABI code is always position-independent. 2681 // The actual address of the GlobalValue is stored in the TOC. 2682 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2683 setUsesTOCBasePtr(DAG); 2684 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2685 return getTOCEntry(DAG, DL, true, GA); 2686 } 2687 2688 unsigned MOHiFlag, MOLoFlag; 2689 bool IsPIC = isPositionIndependent(); 2690 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2691 2692 if (IsPIC && Subtarget.isSVR4ABI()) { 2693 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2694 GSDN->getOffset(), 2695 PPCII::MO_PIC_FLAG); 2696 return getTOCEntry(DAG, DL, false, GA); 2697 } 2698 2699 SDValue GAHi = 2700 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2701 SDValue GALo = 2702 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2703 2704 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2705 2706 // If the global reference is actually to a non-lazy-pointer, we have to do an 2707 // extra load to get the address of the global. 2708 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2709 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2710 return Ptr; 2711 } 2712 2713 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2714 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2715 SDLoc dl(Op); 2716 2717 if (Op.getValueType() == MVT::v2i64) { 2718 // When the operands themselves are v2i64 values, we need to do something 2719 // special because VSX has no underlying comparison operations for these. 2720 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2721 // Equality can be handled by casting to the legal type for Altivec 2722 // comparisons, everything else needs to be expanded. 2723 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2724 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2725 DAG.getSetCC(dl, MVT::v4i32, 2726 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2727 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2728 CC)); 2729 } 2730 2731 return SDValue(); 2732 } 2733 2734 // We handle most of these in the usual way. 2735 return Op; 2736 } 2737 2738 // If we're comparing for equality to zero, expose the fact that this is 2739 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2740 // fold the new nodes. 2741 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2742 return V; 2743 2744 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2745 // Leave comparisons against 0 and -1 alone for now, since they're usually 2746 // optimized. FIXME: revisit this when we can custom lower all setcc 2747 // optimizations. 2748 if (C->isAllOnesValue() || C->isNullValue()) 2749 return SDValue(); 2750 } 2751 2752 // If we have an integer seteq/setne, turn it into a compare against zero 2753 // by xor'ing the rhs with the lhs, which is faster than setting a 2754 // condition register, reading it back out, and masking the correct bit. The 2755 // normal approach here uses sub to do this instead of xor. Using xor exposes 2756 // the result to other bit-twiddling opportunities. 2757 EVT LHSVT = Op.getOperand(0).getValueType(); 2758 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2759 EVT VT = Op.getValueType(); 2760 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2761 Op.getOperand(1)); 2762 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2763 } 2764 return SDValue(); 2765 } 2766 2767 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2768 SDNode *Node = Op.getNode(); 2769 EVT VT = Node->getValueType(0); 2770 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2771 SDValue InChain = Node->getOperand(0); 2772 SDValue VAListPtr = Node->getOperand(1); 2773 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2774 SDLoc dl(Node); 2775 2776 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2777 2778 // gpr_index 2779 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2780 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2781 InChain = GprIndex.getValue(1); 2782 2783 if (VT == MVT::i64) { 2784 // Check if GprIndex is even 2785 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2786 DAG.getConstant(1, dl, MVT::i32)); 2787 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2788 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2789 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2790 DAG.getConstant(1, dl, MVT::i32)); 2791 // Align GprIndex to be even if it isn't 2792 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2793 GprIndex); 2794 } 2795 2796 // fpr index is 1 byte after gpr 2797 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2798 DAG.getConstant(1, dl, MVT::i32)); 2799 2800 // fpr 2801 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2802 FprPtr, MachinePointerInfo(SV), MVT::i8); 2803 InChain = FprIndex.getValue(1); 2804 2805 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2806 DAG.getConstant(8, dl, MVT::i32)); 2807 2808 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2809 DAG.getConstant(4, dl, MVT::i32)); 2810 2811 // areas 2812 SDValue OverflowArea = 2813 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 2814 InChain = OverflowArea.getValue(1); 2815 2816 SDValue RegSaveArea = 2817 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 2818 InChain = RegSaveArea.getValue(1); 2819 2820 // select overflow_area if index > 8 2821 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2822 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 2823 2824 // adjustment constant gpr_index * 4/8 2825 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2826 VT.isInteger() ? GprIndex : FprIndex, 2827 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 2828 MVT::i32)); 2829 2830 // OurReg = RegSaveArea + RegConstant 2831 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2832 RegConstant); 2833 2834 // Floating types are 32 bytes into RegSaveArea 2835 if (VT.isFloatingPoint()) 2836 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 2837 DAG.getConstant(32, dl, MVT::i32)); 2838 2839 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 2840 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 2841 VT.isInteger() ? GprIndex : FprIndex, 2842 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 2843 MVT::i32)); 2844 2845 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 2846 VT.isInteger() ? VAListPtr : FprPtr, 2847 MachinePointerInfo(SV), MVT::i8); 2848 2849 // determine if we should load from reg_save_area or overflow_area 2850 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 2851 2852 // increase overflow_area by 4/8 if gpr/fpr > 8 2853 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 2854 DAG.getConstant(VT.isInteger() ? 4 : 8, 2855 dl, MVT::i32)); 2856 2857 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 2858 OverflowAreaPlusN); 2859 2860 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 2861 MachinePointerInfo(), MVT::i32); 2862 2863 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 2864 } 2865 2866 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 2867 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 2868 2869 // We have to copy the entire va_list struct: 2870 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 2871 return DAG.getMemcpy(Op.getOperand(0), Op, 2872 Op.getOperand(1), Op.getOperand(2), 2873 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 2874 false, MachinePointerInfo(), MachinePointerInfo()); 2875 } 2876 2877 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 2878 SelectionDAG &DAG) const { 2879 return Op.getOperand(0); 2880 } 2881 2882 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 2883 SelectionDAG &DAG) const { 2884 SDValue Chain = Op.getOperand(0); 2885 SDValue Trmp = Op.getOperand(1); // trampoline 2886 SDValue FPtr = Op.getOperand(2); // nested function 2887 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 2888 SDLoc dl(Op); 2889 2890 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2891 bool isPPC64 = (PtrVT == MVT::i64); 2892 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 2893 2894 TargetLowering::ArgListTy Args; 2895 TargetLowering::ArgListEntry Entry; 2896 2897 Entry.Ty = IntPtrTy; 2898 Entry.Node = Trmp; Args.push_back(Entry); 2899 2900 // TrampSize == (isPPC64 ? 48 : 40); 2901 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 2902 isPPC64 ? MVT::i64 : MVT::i32); 2903 Args.push_back(Entry); 2904 2905 Entry.Node = FPtr; Args.push_back(Entry); 2906 Entry.Node = Nest; Args.push_back(Entry); 2907 2908 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 2909 TargetLowering::CallLoweringInfo CLI(DAG); 2910 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2911 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 2912 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 2913 2914 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2915 return CallResult.second; 2916 } 2917 2918 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 2919 MachineFunction &MF = DAG.getMachineFunction(); 2920 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2921 EVT PtrVT = getPointerTy(MF.getDataLayout()); 2922 2923 SDLoc dl(Op); 2924 2925 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 2926 // vastart just stores the address of the VarArgsFrameIndex slot into the 2927 // memory location argument. 2928 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2929 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2930 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2931 MachinePointerInfo(SV)); 2932 } 2933 2934 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 2935 // We suppose the given va_list is already allocated. 2936 // 2937 // typedef struct { 2938 // char gpr; /* index into the array of 8 GPRs 2939 // * stored in the register save area 2940 // * gpr=0 corresponds to r3, 2941 // * gpr=1 to r4, etc. 2942 // */ 2943 // char fpr; /* index into the array of 8 FPRs 2944 // * stored in the register save area 2945 // * fpr=0 corresponds to f1, 2946 // * fpr=1 to f2, etc. 2947 // */ 2948 // char *overflow_arg_area; 2949 // /* location on stack that holds 2950 // * the next overflow argument 2951 // */ 2952 // char *reg_save_area; 2953 // /* where r3:r10 and f1:f8 (if saved) 2954 // * are stored 2955 // */ 2956 // } va_list[1]; 2957 2958 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 2959 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 2960 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 2961 PtrVT); 2962 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 2963 PtrVT); 2964 2965 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 2966 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 2967 2968 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 2969 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 2970 2971 uint64_t FPROffset = 1; 2972 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 2973 2974 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2975 2976 // Store first byte : number of int regs 2977 SDValue firstStore = 2978 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 2979 MachinePointerInfo(SV), MVT::i8); 2980 uint64_t nextOffset = FPROffset; 2981 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 2982 ConstFPROffset); 2983 2984 // Store second byte : number of float regs 2985 SDValue secondStore = 2986 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 2987 MachinePointerInfo(SV, nextOffset), MVT::i8); 2988 nextOffset += StackOffset; 2989 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 2990 2991 // Store second word : arguments given on stack 2992 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 2993 MachinePointerInfo(SV, nextOffset)); 2994 nextOffset += FrameOffset; 2995 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 2996 2997 // Store third word : arguments given in registers 2998 return DAG.getStore(thirdStore, dl, FR, nextPtr, 2999 MachinePointerInfo(SV, nextOffset)); 3000 } 3001 3002 #include "PPCGenCallingConv.inc" 3003 3004 // Function whose sole purpose is to kill compiler warnings 3005 // stemming from unused functions included from PPCGenCallingConv.inc. 3006 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { 3007 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; 3008 } 3009 3010 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 3011 CCValAssign::LocInfo &LocInfo, 3012 ISD::ArgFlagsTy &ArgFlags, 3013 CCState &State) { 3014 return true; 3015 } 3016 3017 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 3018 MVT &LocVT, 3019 CCValAssign::LocInfo &LocInfo, 3020 ISD::ArgFlagsTy &ArgFlags, 3021 CCState &State) { 3022 static const MCPhysReg ArgRegs[] = { 3023 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3024 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3025 }; 3026 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3027 3028 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3029 3030 // Skip one register if the first unallocated register has an even register 3031 // number and there are still argument registers available which have not been 3032 // allocated yet. RegNum is actually an index into ArgRegs, which means we 3033 // need to skip a register if RegNum is odd. 3034 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 3035 State.AllocateReg(ArgRegs[RegNum]); 3036 } 3037 3038 // Always return false here, as this function only makes sure that the first 3039 // unallocated register has an odd register number and does not actually 3040 // allocate a register for the current argument. 3041 return false; 3042 } 3043 3044 bool 3045 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT, 3046 MVT &LocVT, 3047 CCValAssign::LocInfo &LocInfo, 3048 ISD::ArgFlagsTy &ArgFlags, 3049 CCState &State) { 3050 static const MCPhysReg ArgRegs[] = { 3051 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3052 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3053 }; 3054 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3055 3056 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3057 int RegsLeft = NumArgRegs - RegNum; 3058 3059 // Skip if there is not enough registers left for long double type (4 gpr regs 3060 // in soft float mode) and put long double argument on the stack. 3061 if (RegNum != NumArgRegs && RegsLeft < 4) { 3062 for (int i = 0; i < RegsLeft; i++) { 3063 State.AllocateReg(ArgRegs[RegNum + i]); 3064 } 3065 } 3066 3067 return false; 3068 } 3069 3070 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 3071 MVT &LocVT, 3072 CCValAssign::LocInfo &LocInfo, 3073 ISD::ArgFlagsTy &ArgFlags, 3074 CCState &State) { 3075 static const MCPhysReg ArgRegs[] = { 3076 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3077 PPC::F8 3078 }; 3079 3080 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3081 3082 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3083 3084 // If there is only one Floating-point register left we need to put both f64 3085 // values of a split ppc_fp128 value on the stack. 3086 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 3087 State.AllocateReg(ArgRegs[RegNum]); 3088 } 3089 3090 // Always return false here, as this function only makes sure that the two f64 3091 // values a ppc_fp128 value is split into are both passed in registers or both 3092 // passed on the stack and does not actually allocate a register for the 3093 // current argument. 3094 return false; 3095 } 3096 3097 /// FPR - The set of FP registers that should be allocated for arguments, 3098 /// on Darwin. 3099 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3100 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3101 PPC::F11, PPC::F12, PPC::F13}; 3102 3103 /// QFPR - The set of QPX registers that should be allocated for arguments. 3104 static const MCPhysReg QFPR[] = { 3105 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3106 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3107 3108 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3109 /// the stack. 3110 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3111 unsigned PtrByteSize) { 3112 unsigned ArgSize = ArgVT.getStoreSize(); 3113 if (Flags.isByVal()) 3114 ArgSize = Flags.getByValSize(); 3115 3116 // Round up to multiples of the pointer size, except for array members, 3117 // which are always packed. 3118 if (!Flags.isInConsecutiveRegs()) 3119 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3120 3121 return ArgSize; 3122 } 3123 3124 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3125 /// on the stack. 3126 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3127 ISD::ArgFlagsTy Flags, 3128 unsigned PtrByteSize) { 3129 unsigned Align = PtrByteSize; 3130 3131 // Altivec parameters are padded to a 16 byte boundary. 3132 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3133 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3134 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3135 ArgVT == MVT::v1i128) 3136 Align = 16; 3137 // QPX vector types stored in double-precision are padded to a 32 byte 3138 // boundary. 3139 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3140 Align = 32; 3141 3142 // ByVal parameters are aligned as requested. 3143 if (Flags.isByVal()) { 3144 unsigned BVAlign = Flags.getByValAlign(); 3145 if (BVAlign > PtrByteSize) { 3146 if (BVAlign % PtrByteSize != 0) 3147 llvm_unreachable( 3148 "ByVal alignment is not a multiple of the pointer size"); 3149 3150 Align = BVAlign; 3151 } 3152 } 3153 3154 // Array members are always packed to their original alignment. 3155 if (Flags.isInConsecutiveRegs()) { 3156 // If the array member was split into multiple registers, the first 3157 // needs to be aligned to the size of the full type. (Except for 3158 // ppcf128, which is only aligned as its f64 components.) 3159 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3160 Align = OrigVT.getStoreSize(); 3161 else 3162 Align = ArgVT.getStoreSize(); 3163 } 3164 3165 return Align; 3166 } 3167 3168 /// CalculateStackSlotUsed - Return whether this argument will use its 3169 /// stack slot (instead of being passed in registers). ArgOffset, 3170 /// AvailableFPRs, and AvailableVRs must hold the current argument 3171 /// position, and will be updated to account for this argument. 3172 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3173 ISD::ArgFlagsTy Flags, 3174 unsigned PtrByteSize, 3175 unsigned LinkageSize, 3176 unsigned ParamAreaSize, 3177 unsigned &ArgOffset, 3178 unsigned &AvailableFPRs, 3179 unsigned &AvailableVRs, bool HasQPX) { 3180 bool UseMemory = false; 3181 3182 // Respect alignment of argument on the stack. 3183 unsigned Align = 3184 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3185 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3186 // If there's no space left in the argument save area, we must 3187 // use memory (this check also catches zero-sized arguments). 3188 if (ArgOffset >= LinkageSize + ParamAreaSize) 3189 UseMemory = true; 3190 3191 // Allocate argument on the stack. 3192 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3193 if (Flags.isInConsecutiveRegsLast()) 3194 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3195 // If we overran the argument save area, we must use memory 3196 // (this check catches arguments passed partially in memory) 3197 if (ArgOffset > LinkageSize + ParamAreaSize) 3198 UseMemory = true; 3199 3200 // However, if the argument is actually passed in an FPR or a VR, 3201 // we don't use memory after all. 3202 if (!Flags.isByVal()) { 3203 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3204 // QPX registers overlap with the scalar FP registers. 3205 (HasQPX && (ArgVT == MVT::v4f32 || 3206 ArgVT == MVT::v4f64 || 3207 ArgVT == MVT::v4i1))) 3208 if (AvailableFPRs > 0) { 3209 --AvailableFPRs; 3210 return false; 3211 } 3212 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3213 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3214 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3215 ArgVT == MVT::v1i128) 3216 if (AvailableVRs > 0) { 3217 --AvailableVRs; 3218 return false; 3219 } 3220 } 3221 3222 return UseMemory; 3223 } 3224 3225 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3226 /// ensure minimum alignment required for target. 3227 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3228 unsigned NumBytes) { 3229 unsigned TargetAlign = Lowering->getStackAlignment(); 3230 unsigned AlignMask = TargetAlign - 1; 3231 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3232 return NumBytes; 3233 } 3234 3235 SDValue PPCTargetLowering::LowerFormalArguments( 3236 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3237 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3238 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3239 if (Subtarget.isSVR4ABI()) { 3240 if (Subtarget.isPPC64()) 3241 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3242 dl, DAG, InVals); 3243 else 3244 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3245 dl, DAG, InVals); 3246 } else { 3247 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3248 dl, DAG, InVals); 3249 } 3250 } 3251 3252 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3253 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3254 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3255 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3256 3257 // 32-bit SVR4 ABI Stack Frame Layout: 3258 // +-----------------------------------+ 3259 // +--> | Back chain | 3260 // | +-----------------------------------+ 3261 // | | Floating-point register save area | 3262 // | +-----------------------------------+ 3263 // | | General register save area | 3264 // | +-----------------------------------+ 3265 // | | CR save word | 3266 // | +-----------------------------------+ 3267 // | | VRSAVE save word | 3268 // | +-----------------------------------+ 3269 // | | Alignment padding | 3270 // | +-----------------------------------+ 3271 // | | Vector register save area | 3272 // | +-----------------------------------+ 3273 // | | Local variable space | 3274 // | +-----------------------------------+ 3275 // | | Parameter list area | 3276 // | +-----------------------------------+ 3277 // | | LR save word | 3278 // | +-----------------------------------+ 3279 // SP--> +--- | Back chain | 3280 // +-----------------------------------+ 3281 // 3282 // Specifications: 3283 // System V Application Binary Interface PowerPC Processor Supplement 3284 // AltiVec Technology Programming Interface Manual 3285 3286 MachineFunction &MF = DAG.getMachineFunction(); 3287 MachineFrameInfo &MFI = MF.getFrameInfo(); 3288 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3289 3290 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3291 // Potential tail calls could cause overwriting of argument stack slots. 3292 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3293 (CallConv == CallingConv::Fast)); 3294 unsigned PtrByteSize = 4; 3295 3296 // Assign locations to all of the incoming arguments. 3297 SmallVector<CCValAssign, 16> ArgLocs; 3298 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3299 *DAG.getContext()); 3300 3301 // Reserve space for the linkage area on the stack. 3302 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3303 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3304 if (useSoftFloat()) 3305 CCInfo.PreAnalyzeFormalArguments(Ins); 3306 3307 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3308 CCInfo.clearWasPPCF128(); 3309 3310 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3311 CCValAssign &VA = ArgLocs[i]; 3312 3313 // Arguments stored in registers. 3314 if (VA.isRegLoc()) { 3315 const TargetRegisterClass *RC; 3316 EVT ValVT = VA.getValVT(); 3317 3318 switch (ValVT.getSimpleVT().SimpleTy) { 3319 default: 3320 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3321 case MVT::i1: 3322 case MVT::i32: 3323 RC = &PPC::GPRCRegClass; 3324 break; 3325 case MVT::f32: 3326 if (Subtarget.hasP8Vector()) 3327 RC = &PPC::VSSRCRegClass; 3328 else 3329 RC = &PPC::F4RCRegClass; 3330 break; 3331 case MVT::f64: 3332 if (Subtarget.hasVSX()) 3333 RC = &PPC::VSFRCRegClass; 3334 else 3335 RC = &PPC::F8RCRegClass; 3336 break; 3337 case MVT::v16i8: 3338 case MVT::v8i16: 3339 case MVT::v4i32: 3340 RC = &PPC::VRRCRegClass; 3341 break; 3342 case MVT::v4f32: 3343 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3344 break; 3345 case MVT::v2f64: 3346 case MVT::v2i64: 3347 RC = &PPC::VRRCRegClass; 3348 break; 3349 case MVT::v4f64: 3350 RC = &PPC::QFRCRegClass; 3351 break; 3352 case MVT::v4i1: 3353 RC = &PPC::QBRCRegClass; 3354 break; 3355 } 3356 3357 // Transform the arguments stored in physical registers into virtual ones. 3358 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3359 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3360 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3361 3362 if (ValVT == MVT::i1) 3363 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3364 3365 InVals.push_back(ArgValue); 3366 } else { 3367 // Argument stored in memory. 3368 assert(VA.isMemLoc()); 3369 3370 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3371 int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(), 3372 isImmutable); 3373 3374 // Create load nodes to retrieve arguments from the stack. 3375 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3376 InVals.push_back( 3377 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3378 } 3379 } 3380 3381 // Assign locations to all of the incoming aggregate by value arguments. 3382 // Aggregates passed by value are stored in the local variable space of the 3383 // caller's stack frame, right above the parameter list area. 3384 SmallVector<CCValAssign, 16> ByValArgLocs; 3385 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3386 ByValArgLocs, *DAG.getContext()); 3387 3388 // Reserve stack space for the allocations in CCInfo. 3389 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3390 3391 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3392 3393 // Area that is at least reserved in the caller of this function. 3394 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3395 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3396 3397 // Set the size that is at least reserved in caller of this function. Tail 3398 // call optimized function's reserved stack space needs to be aligned so that 3399 // taking the difference between two stack areas will result in an aligned 3400 // stack. 3401 MinReservedArea = 3402 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3403 FuncInfo->setMinReservedArea(MinReservedArea); 3404 3405 SmallVector<SDValue, 8> MemOps; 3406 3407 // If the function takes variable number of arguments, make a frame index for 3408 // the start of the first vararg value... for expansion of llvm.va_start. 3409 if (isVarArg) { 3410 static const MCPhysReg GPArgRegs[] = { 3411 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3412 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3413 }; 3414 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3415 3416 static const MCPhysReg FPArgRegs[] = { 3417 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3418 PPC::F8 3419 }; 3420 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3421 3422 if (useSoftFloat()) 3423 NumFPArgRegs = 0; 3424 3425 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3426 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3427 3428 // Make room for NumGPArgRegs and NumFPArgRegs. 3429 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3430 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3431 3432 FuncInfo->setVarArgsStackOffset( 3433 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3434 CCInfo.getNextStackOffset(), true)); 3435 3436 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3437 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3438 3439 // The fixed integer arguments of a variadic function are stored to the 3440 // VarArgsFrameIndex on the stack so that they may be loaded by 3441 // dereferencing the result of va_next. 3442 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3443 // Get an existing live-in vreg, or add a new one. 3444 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3445 if (!VReg) 3446 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3447 3448 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3449 SDValue Store = 3450 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3451 MemOps.push_back(Store); 3452 // Increment the address by four for the next argument to store 3453 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3454 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3455 } 3456 3457 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3458 // is set. 3459 // The double arguments are stored to the VarArgsFrameIndex 3460 // on the stack. 3461 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3462 // Get an existing live-in vreg, or add a new one. 3463 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3464 if (!VReg) 3465 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3466 3467 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3468 SDValue Store = 3469 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3470 MemOps.push_back(Store); 3471 // Increment the address by eight for the next argument to store 3472 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3473 PtrVT); 3474 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3475 } 3476 } 3477 3478 if (!MemOps.empty()) 3479 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3480 3481 return Chain; 3482 } 3483 3484 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3485 // value to MVT::i64 and then truncate to the correct register size. 3486 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3487 EVT ObjectVT, SelectionDAG &DAG, 3488 SDValue ArgVal, 3489 const SDLoc &dl) const { 3490 if (Flags.isSExt()) 3491 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3492 DAG.getValueType(ObjectVT)); 3493 else if (Flags.isZExt()) 3494 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3495 DAG.getValueType(ObjectVT)); 3496 3497 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3498 } 3499 3500 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3501 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3502 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3503 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3504 // TODO: add description of PPC stack frame format, or at least some docs. 3505 // 3506 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3507 bool isLittleEndian = Subtarget.isLittleEndian(); 3508 MachineFunction &MF = DAG.getMachineFunction(); 3509 MachineFrameInfo &MFI = MF.getFrameInfo(); 3510 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3511 3512 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3513 "fastcc not supported on varargs functions"); 3514 3515 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3516 // Potential tail calls could cause overwriting of argument stack slots. 3517 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3518 (CallConv == CallingConv::Fast)); 3519 unsigned PtrByteSize = 8; 3520 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3521 3522 static const MCPhysReg GPR[] = { 3523 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3524 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3525 }; 3526 static const MCPhysReg VR[] = { 3527 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3528 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3529 }; 3530 3531 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3532 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3533 const unsigned Num_VR_Regs = array_lengthof(VR); 3534 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3535 3536 // Do a first pass over the arguments to determine whether the ABI 3537 // guarantees that our caller has allocated the parameter save area 3538 // on its stack frame. In the ELFv1 ABI, this is always the case; 3539 // in the ELFv2 ABI, it is true if this is a vararg function or if 3540 // any parameter is located in a stack slot. 3541 3542 bool HasParameterArea = !isELFv2ABI || isVarArg; 3543 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3544 unsigned NumBytes = LinkageSize; 3545 unsigned AvailableFPRs = Num_FPR_Regs; 3546 unsigned AvailableVRs = Num_VR_Regs; 3547 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3548 if (Ins[i].Flags.isNest()) 3549 continue; 3550 3551 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3552 PtrByteSize, LinkageSize, ParamAreaSize, 3553 NumBytes, AvailableFPRs, AvailableVRs, 3554 Subtarget.hasQPX())) 3555 HasParameterArea = true; 3556 } 3557 3558 // Add DAG nodes to load the arguments or copy them out of registers. On 3559 // entry to a function on PPC, the arguments start after the linkage area, 3560 // although the first ones are often in registers. 3561 3562 unsigned ArgOffset = LinkageSize; 3563 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3564 unsigned &QFPR_idx = FPR_idx; 3565 SmallVector<SDValue, 8> MemOps; 3566 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3567 unsigned CurArgIdx = 0; 3568 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3569 SDValue ArgVal; 3570 bool needsLoad = false; 3571 EVT ObjectVT = Ins[ArgNo].VT; 3572 EVT OrigVT = Ins[ArgNo].ArgVT; 3573 unsigned ObjSize = ObjectVT.getStoreSize(); 3574 unsigned ArgSize = ObjSize; 3575 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3576 if (Ins[ArgNo].isOrigArg()) { 3577 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3578 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3579 } 3580 // We re-align the argument offset for each argument, except when using the 3581 // fast calling convention, when we need to make sure we do that only when 3582 // we'll actually use a stack slot. 3583 unsigned CurArgOffset, Align; 3584 auto ComputeArgOffset = [&]() { 3585 /* Respect alignment of argument on the stack. */ 3586 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3587 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3588 CurArgOffset = ArgOffset; 3589 }; 3590 3591 if (CallConv != CallingConv::Fast) { 3592 ComputeArgOffset(); 3593 3594 /* Compute GPR index associated with argument offset. */ 3595 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3596 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3597 } 3598 3599 // FIXME the codegen can be much improved in some cases. 3600 // We do not have to keep everything in memory. 3601 if (Flags.isByVal()) { 3602 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3603 3604 if (CallConv == CallingConv::Fast) 3605 ComputeArgOffset(); 3606 3607 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3608 ObjSize = Flags.getByValSize(); 3609 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3610 // Empty aggregate parameters do not take up registers. Examples: 3611 // struct { } a; 3612 // union { } b; 3613 // int c[0]; 3614 // etc. However, we have to provide a place-holder in InVals, so 3615 // pretend we have an 8-byte item at the current address for that 3616 // purpose. 3617 if (!ObjSize) { 3618 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3619 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3620 InVals.push_back(FIN); 3621 continue; 3622 } 3623 3624 // Create a stack object covering all stack doublewords occupied 3625 // by the argument. If the argument is (fully or partially) on 3626 // the stack, or if the argument is fully in registers but the 3627 // caller has allocated the parameter save anyway, we can refer 3628 // directly to the caller's stack frame. Otherwise, create a 3629 // local copy in our own frame. 3630 int FI; 3631 if (HasParameterArea || 3632 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3633 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3634 else 3635 FI = MFI.CreateStackObject(ArgSize, Align, false); 3636 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3637 3638 // Handle aggregates smaller than 8 bytes. 3639 if (ObjSize < PtrByteSize) { 3640 // The value of the object is its address, which differs from the 3641 // address of the enclosing doubleword on big-endian systems. 3642 SDValue Arg = FIN; 3643 if (!isLittleEndian) { 3644 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3645 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3646 } 3647 InVals.push_back(Arg); 3648 3649 if (GPR_idx != Num_GPR_Regs) { 3650 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3651 FuncInfo->addLiveInAttr(VReg, Flags); 3652 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3653 SDValue Store; 3654 3655 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3656 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3657 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3658 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3659 MachinePointerInfo(&*FuncArg), ObjType); 3660 } else { 3661 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3662 // store the whole register as-is to the parameter save area 3663 // slot. 3664 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3665 MachinePointerInfo(&*FuncArg)); 3666 } 3667 3668 MemOps.push_back(Store); 3669 } 3670 // Whether we copied from a register or not, advance the offset 3671 // into the parameter save area by a full doubleword. 3672 ArgOffset += PtrByteSize; 3673 continue; 3674 } 3675 3676 // The value of the object is its address, which is the address of 3677 // its first stack doubleword. 3678 InVals.push_back(FIN); 3679 3680 // Store whatever pieces of the object are in registers to memory. 3681 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3682 if (GPR_idx == Num_GPR_Regs) 3683 break; 3684 3685 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3686 FuncInfo->addLiveInAttr(VReg, Flags); 3687 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3688 SDValue Addr = FIN; 3689 if (j) { 3690 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3691 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3692 } 3693 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3694 MachinePointerInfo(&*FuncArg, j)); 3695 MemOps.push_back(Store); 3696 ++GPR_idx; 3697 } 3698 ArgOffset += ArgSize; 3699 continue; 3700 } 3701 3702 switch (ObjectVT.getSimpleVT().SimpleTy) { 3703 default: llvm_unreachable("Unhandled argument type!"); 3704 case MVT::i1: 3705 case MVT::i32: 3706 case MVT::i64: 3707 if (Flags.isNest()) { 3708 // The 'nest' parameter, if any, is passed in R11. 3709 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3710 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3711 3712 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3713 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3714 3715 break; 3716 } 3717 3718 // These can be scalar arguments or elements of an integer array type 3719 // passed directly. Clang may use those instead of "byval" aggregate 3720 // types to avoid forcing arguments to memory unnecessarily. 3721 if (GPR_idx != Num_GPR_Regs) { 3722 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3723 FuncInfo->addLiveInAttr(VReg, Flags); 3724 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3725 3726 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3727 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3728 // value to MVT::i64 and then truncate to the correct register size. 3729 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3730 } else { 3731 if (CallConv == CallingConv::Fast) 3732 ComputeArgOffset(); 3733 3734 needsLoad = true; 3735 ArgSize = PtrByteSize; 3736 } 3737 if (CallConv != CallingConv::Fast || needsLoad) 3738 ArgOffset += 8; 3739 break; 3740 3741 case MVT::f32: 3742 case MVT::f64: 3743 // These can be scalar arguments or elements of a float array type 3744 // passed directly. The latter are used to implement ELFv2 homogenous 3745 // float aggregates. 3746 if (FPR_idx != Num_FPR_Regs) { 3747 unsigned VReg; 3748 3749 if (ObjectVT == MVT::f32) 3750 VReg = MF.addLiveIn(FPR[FPR_idx], 3751 Subtarget.hasP8Vector() 3752 ? &PPC::VSSRCRegClass 3753 : &PPC::F4RCRegClass); 3754 else 3755 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3756 ? &PPC::VSFRCRegClass 3757 : &PPC::F8RCRegClass); 3758 3759 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3760 ++FPR_idx; 3761 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3762 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3763 // once we support fp <-> gpr moves. 3764 3765 // This can only ever happen in the presence of f32 array types, 3766 // since otherwise we never run out of FPRs before running out 3767 // of GPRs. 3768 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3769 FuncInfo->addLiveInAttr(VReg, Flags); 3770 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3771 3772 if (ObjectVT == MVT::f32) { 3773 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3774 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3775 DAG.getConstant(32, dl, MVT::i32)); 3776 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3777 } 3778 3779 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3780 } else { 3781 if (CallConv == CallingConv::Fast) 3782 ComputeArgOffset(); 3783 3784 needsLoad = true; 3785 } 3786 3787 // When passing an array of floats, the array occupies consecutive 3788 // space in the argument area; only round up to the next doubleword 3789 // at the end of the array. Otherwise, each float takes 8 bytes. 3790 if (CallConv != CallingConv::Fast || needsLoad) { 3791 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3792 ArgOffset += ArgSize; 3793 if (Flags.isInConsecutiveRegsLast()) 3794 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3795 } 3796 break; 3797 case MVT::v4f32: 3798 case MVT::v4i32: 3799 case MVT::v8i16: 3800 case MVT::v16i8: 3801 case MVT::v2f64: 3802 case MVT::v2i64: 3803 case MVT::v1i128: 3804 if (!Subtarget.hasQPX()) { 3805 // These can be scalar arguments or elements of a vector array type 3806 // passed directly. The latter are used to implement ELFv2 homogenous 3807 // vector aggregates. 3808 if (VR_idx != Num_VR_Regs) { 3809 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3810 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3811 ++VR_idx; 3812 } else { 3813 if (CallConv == CallingConv::Fast) 3814 ComputeArgOffset(); 3815 needsLoad = true; 3816 } 3817 if (CallConv != CallingConv::Fast || needsLoad) 3818 ArgOffset += 16; 3819 break; 3820 } // not QPX 3821 3822 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3823 "Invalid QPX parameter type"); 3824 /* fall through */ 3825 3826 case MVT::v4f64: 3827 case MVT::v4i1: 3828 // QPX vectors are treated like their scalar floating-point subregisters 3829 // (except that they're larger). 3830 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3831 if (QFPR_idx != Num_QFPR_Regs) { 3832 const TargetRegisterClass *RC; 3833 switch (ObjectVT.getSimpleVT().SimpleTy) { 3834 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3835 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3836 default: RC = &PPC::QBRCRegClass; break; 3837 } 3838 3839 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3840 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3841 ++QFPR_idx; 3842 } else { 3843 if (CallConv == CallingConv::Fast) 3844 ComputeArgOffset(); 3845 needsLoad = true; 3846 } 3847 if (CallConv != CallingConv::Fast || needsLoad) 3848 ArgOffset += Sz; 3849 break; 3850 } 3851 3852 // We need to load the argument to a virtual register if we determined 3853 // above that we ran out of physical registers of the appropriate type. 3854 if (needsLoad) { 3855 if (ObjSize < ArgSize && !isLittleEndian) 3856 CurArgOffset += ArgSize - ObjSize; 3857 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3858 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3859 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3860 } 3861 3862 InVals.push_back(ArgVal); 3863 } 3864 3865 // Area that is at least reserved in the caller of this function. 3866 unsigned MinReservedArea; 3867 if (HasParameterArea) 3868 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 3869 else 3870 MinReservedArea = LinkageSize; 3871 3872 // Set the size that is at least reserved in caller of this function. Tail 3873 // call optimized functions' reserved stack space needs to be aligned so that 3874 // taking the difference between two stack areas will result in an aligned 3875 // stack. 3876 MinReservedArea = 3877 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3878 FuncInfo->setMinReservedArea(MinReservedArea); 3879 3880 // If the function takes variable number of arguments, make a frame index for 3881 // the start of the first vararg value... for expansion of llvm.va_start. 3882 if (isVarArg) { 3883 int Depth = ArgOffset; 3884 3885 FuncInfo->setVarArgsFrameIndex( 3886 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 3887 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3888 3889 // If this function is vararg, store any remaining integer argument regs 3890 // to their spots on the stack so that they may be loaded by dereferencing 3891 // the result of va_next. 3892 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3893 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 3894 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3895 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3896 SDValue Store = 3897 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3898 MemOps.push_back(Store); 3899 // Increment the address by four for the next argument to store 3900 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 3901 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3902 } 3903 } 3904 3905 if (!MemOps.empty()) 3906 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3907 3908 return Chain; 3909 } 3910 3911 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 3912 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3913 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3914 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3915 // TODO: add description of PPC stack frame format, or at least some docs. 3916 // 3917 MachineFunction &MF = DAG.getMachineFunction(); 3918 MachineFrameInfo &MFI = MF.getFrameInfo(); 3919 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3920 3921 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3922 bool isPPC64 = PtrVT == MVT::i64; 3923 // Potential tail calls could cause overwriting of argument stack slots. 3924 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3925 (CallConv == CallingConv::Fast)); 3926 unsigned PtrByteSize = isPPC64 ? 8 : 4; 3927 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3928 unsigned ArgOffset = LinkageSize; 3929 // Area that is at least reserved in caller of this function. 3930 unsigned MinReservedArea = ArgOffset; 3931 3932 static const MCPhysReg GPR_32[] = { // 32-bit registers. 3933 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3934 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3935 }; 3936 static const MCPhysReg GPR_64[] = { // 64-bit registers. 3937 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3938 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3939 }; 3940 static const MCPhysReg VR[] = { 3941 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3942 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3943 }; 3944 3945 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 3946 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3947 const unsigned Num_VR_Regs = array_lengthof( VR); 3948 3949 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3950 3951 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 3952 3953 // In 32-bit non-varargs functions, the stack space for vectors is after the 3954 // stack space for non-vectors. We do not use this space unless we have 3955 // too many vectors to fit in registers, something that only occurs in 3956 // constructed examples:), but we have to walk the arglist to figure 3957 // that out...for the pathological case, compute VecArgOffset as the 3958 // start of the vector parameter area. Computing VecArgOffset is the 3959 // entire point of the following loop. 3960 unsigned VecArgOffset = ArgOffset; 3961 if (!isVarArg && !isPPC64) { 3962 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 3963 ++ArgNo) { 3964 EVT ObjectVT = Ins[ArgNo].VT; 3965 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3966 3967 if (Flags.isByVal()) { 3968 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 3969 unsigned ObjSize = Flags.getByValSize(); 3970 unsigned ArgSize = 3971 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3972 VecArgOffset += ArgSize; 3973 continue; 3974 } 3975 3976 switch(ObjectVT.getSimpleVT().SimpleTy) { 3977 default: llvm_unreachable("Unhandled argument type!"); 3978 case MVT::i1: 3979 case MVT::i32: 3980 case MVT::f32: 3981 VecArgOffset += 4; 3982 break; 3983 case MVT::i64: // PPC64 3984 case MVT::f64: 3985 // FIXME: We are guaranteed to be !isPPC64 at this point. 3986 // Does MVT::i64 apply? 3987 VecArgOffset += 8; 3988 break; 3989 case MVT::v4f32: 3990 case MVT::v4i32: 3991 case MVT::v8i16: 3992 case MVT::v16i8: 3993 // Nothing to do, we're only looking at Nonvector args here. 3994 break; 3995 } 3996 } 3997 } 3998 // We've found where the vector parameter area in memory is. Skip the 3999 // first 12 parameters; these don't use that memory. 4000 VecArgOffset = ((VecArgOffset+15)/16)*16; 4001 VecArgOffset += 12*16; 4002 4003 // Add DAG nodes to load the arguments or copy them out of registers. On 4004 // entry to a function on PPC, the arguments start after the linkage area, 4005 // although the first ones are often in registers. 4006 4007 SmallVector<SDValue, 8> MemOps; 4008 unsigned nAltivecParamsAtEnd = 0; 4009 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4010 unsigned CurArgIdx = 0; 4011 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4012 SDValue ArgVal; 4013 bool needsLoad = false; 4014 EVT ObjectVT = Ins[ArgNo].VT; 4015 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4016 unsigned ArgSize = ObjSize; 4017 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4018 if (Ins[ArgNo].isOrigArg()) { 4019 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4020 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4021 } 4022 unsigned CurArgOffset = ArgOffset; 4023 4024 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4025 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4026 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4027 if (isVarArg || isPPC64) { 4028 MinReservedArea = ((MinReservedArea+15)/16)*16; 4029 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4030 Flags, 4031 PtrByteSize); 4032 } else nAltivecParamsAtEnd++; 4033 } else 4034 // Calculate min reserved area. 4035 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4036 Flags, 4037 PtrByteSize); 4038 4039 // FIXME the codegen can be much improved in some cases. 4040 // We do not have to keep everything in memory. 4041 if (Flags.isByVal()) { 4042 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4043 4044 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4045 ObjSize = Flags.getByValSize(); 4046 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4047 // Objects of size 1 and 2 are right justified, everything else is 4048 // left justified. This means the memory address is adjusted forwards. 4049 if (ObjSize==1 || ObjSize==2) { 4050 CurArgOffset = CurArgOffset + (4 - ObjSize); 4051 } 4052 // The value of the object is its address. 4053 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4054 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4055 InVals.push_back(FIN); 4056 if (ObjSize==1 || ObjSize==2) { 4057 if (GPR_idx != Num_GPR_Regs) { 4058 unsigned VReg; 4059 if (isPPC64) 4060 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4061 else 4062 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4063 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4064 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4065 SDValue Store = 4066 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4067 MachinePointerInfo(&*FuncArg), ObjType); 4068 MemOps.push_back(Store); 4069 ++GPR_idx; 4070 } 4071 4072 ArgOffset += PtrByteSize; 4073 4074 continue; 4075 } 4076 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4077 // Store whatever pieces of the object are in registers 4078 // to memory. ArgOffset will be the address of the beginning 4079 // of the object. 4080 if (GPR_idx != Num_GPR_Regs) { 4081 unsigned VReg; 4082 if (isPPC64) 4083 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4084 else 4085 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4086 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4087 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4088 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4089 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4090 MachinePointerInfo(&*FuncArg, j)); 4091 MemOps.push_back(Store); 4092 ++GPR_idx; 4093 ArgOffset += PtrByteSize; 4094 } else { 4095 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4096 break; 4097 } 4098 } 4099 continue; 4100 } 4101 4102 switch (ObjectVT.getSimpleVT().SimpleTy) { 4103 default: llvm_unreachable("Unhandled argument type!"); 4104 case MVT::i1: 4105 case MVT::i32: 4106 if (!isPPC64) { 4107 if (GPR_idx != Num_GPR_Regs) { 4108 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4109 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4110 4111 if (ObjectVT == MVT::i1) 4112 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4113 4114 ++GPR_idx; 4115 } else { 4116 needsLoad = true; 4117 ArgSize = PtrByteSize; 4118 } 4119 // All int arguments reserve stack space in the Darwin ABI. 4120 ArgOffset += PtrByteSize; 4121 break; 4122 } 4123 LLVM_FALLTHROUGH; 4124 case MVT::i64: // PPC64 4125 if (GPR_idx != Num_GPR_Regs) { 4126 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4127 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4128 4129 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4130 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4131 // value to MVT::i64 and then truncate to the correct register size. 4132 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4133 4134 ++GPR_idx; 4135 } else { 4136 needsLoad = true; 4137 ArgSize = PtrByteSize; 4138 } 4139 // All int arguments reserve stack space in the Darwin ABI. 4140 ArgOffset += 8; 4141 break; 4142 4143 case MVT::f32: 4144 case MVT::f64: 4145 // Every 4 bytes of argument space consumes one of the GPRs available for 4146 // argument passing. 4147 if (GPR_idx != Num_GPR_Regs) { 4148 ++GPR_idx; 4149 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4150 ++GPR_idx; 4151 } 4152 if (FPR_idx != Num_FPR_Regs) { 4153 unsigned VReg; 4154 4155 if (ObjectVT == MVT::f32) 4156 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4157 else 4158 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4159 4160 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4161 ++FPR_idx; 4162 } else { 4163 needsLoad = true; 4164 } 4165 4166 // All FP arguments reserve stack space in the Darwin ABI. 4167 ArgOffset += isPPC64 ? 8 : ObjSize; 4168 break; 4169 case MVT::v4f32: 4170 case MVT::v4i32: 4171 case MVT::v8i16: 4172 case MVT::v16i8: 4173 // Note that vector arguments in registers don't reserve stack space, 4174 // except in varargs functions. 4175 if (VR_idx != Num_VR_Regs) { 4176 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4177 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4178 if (isVarArg) { 4179 while ((ArgOffset % 16) != 0) { 4180 ArgOffset += PtrByteSize; 4181 if (GPR_idx != Num_GPR_Regs) 4182 GPR_idx++; 4183 } 4184 ArgOffset += 16; 4185 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4186 } 4187 ++VR_idx; 4188 } else { 4189 if (!isVarArg && !isPPC64) { 4190 // Vectors go after all the nonvectors. 4191 CurArgOffset = VecArgOffset; 4192 VecArgOffset += 16; 4193 } else { 4194 // Vectors are aligned. 4195 ArgOffset = ((ArgOffset+15)/16)*16; 4196 CurArgOffset = ArgOffset; 4197 ArgOffset += 16; 4198 } 4199 needsLoad = true; 4200 } 4201 break; 4202 } 4203 4204 // We need to load the argument to a virtual register if we determined above 4205 // that we ran out of physical registers of the appropriate type. 4206 if (needsLoad) { 4207 int FI = MFI.CreateFixedObject(ObjSize, 4208 CurArgOffset + (ArgSize - ObjSize), 4209 isImmutable); 4210 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4211 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4212 } 4213 4214 InVals.push_back(ArgVal); 4215 } 4216 4217 // Allow for Altivec parameters at the end, if needed. 4218 if (nAltivecParamsAtEnd) { 4219 MinReservedArea = ((MinReservedArea+15)/16)*16; 4220 MinReservedArea += 16*nAltivecParamsAtEnd; 4221 } 4222 4223 // Area that is at least reserved in the caller of this function. 4224 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4225 4226 // Set the size that is at least reserved in caller of this function. Tail 4227 // call optimized functions' reserved stack space needs to be aligned so that 4228 // taking the difference between two stack areas will result in an aligned 4229 // stack. 4230 MinReservedArea = 4231 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4232 FuncInfo->setMinReservedArea(MinReservedArea); 4233 4234 // If the function takes variable number of arguments, make a frame index for 4235 // the start of the first vararg value... for expansion of llvm.va_start. 4236 if (isVarArg) { 4237 int Depth = ArgOffset; 4238 4239 FuncInfo->setVarArgsFrameIndex( 4240 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4241 Depth, true)); 4242 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4243 4244 // If this function is vararg, store any remaining integer argument regs 4245 // to their spots on the stack so that they may be loaded by dereferencing 4246 // the result of va_next. 4247 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4248 unsigned VReg; 4249 4250 if (isPPC64) 4251 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4252 else 4253 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4254 4255 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4256 SDValue Store = 4257 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4258 MemOps.push_back(Store); 4259 // Increment the address by four for the next argument to store 4260 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4261 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4262 } 4263 } 4264 4265 if (!MemOps.empty()) 4266 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4267 4268 return Chain; 4269 } 4270 4271 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4272 /// adjusted to accommodate the arguments for the tailcall. 4273 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4274 unsigned ParamSize) { 4275 4276 if (!isTailCall) return 0; 4277 4278 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4279 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4280 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4281 // Remember only if the new adjustement is bigger. 4282 if (SPDiff < FI->getTailCallSPDelta()) 4283 FI->setTailCallSPDelta(SPDiff); 4284 4285 return SPDiff; 4286 } 4287 4288 static bool isFunctionGlobalAddress(SDValue Callee); 4289 4290 static bool 4291 callsShareTOCBase(const Function *Caller, SDValue Callee, 4292 const TargetMachine &TM) { 4293 // If !G, Callee can be an external symbol. 4294 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4295 if (!G) 4296 return false; 4297 4298 // The medium and large code models are expected to provide a sufficiently 4299 // large TOC to provide all data addressing needs of a module with a 4300 // single TOC. Since each module will be addressed with a single TOC then we 4301 // only need to check that caller and callee don't cross dso boundaries. 4302 if (CodeModel::Medium == TM.getCodeModel() || 4303 CodeModel::Large == TM.getCodeModel()) 4304 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal()); 4305 4306 // Otherwise we need to ensure callee and caller are in the same section, 4307 // since the linker may allocate multiple TOCs, and we don't know which 4308 // sections will belong to the same TOC base. 4309 4310 const GlobalValue *GV = G->getGlobal(); 4311 if (!GV->isStrongDefinitionForLinker()) 4312 return false; 4313 4314 // Any explicitly-specified sections and section prefixes must also match. 4315 // Also, if we're using -ffunction-sections, then each function is always in 4316 // a different section (the same is true for COMDAT functions). 4317 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4318 GV->getSection() != Caller->getSection()) 4319 return false; 4320 if (const auto *F = dyn_cast<Function>(GV)) { 4321 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4322 return false; 4323 } 4324 4325 // If the callee might be interposed, then we can't assume the ultimate call 4326 // target will be in the same section. Even in cases where we can assume that 4327 // interposition won't happen, in any case where the linker might insert a 4328 // stub to allow for interposition, we must generate code as though 4329 // interposition might occur. To understand why this matters, consider a 4330 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4331 // in the same section, but a is in a different module (i.e. has a different 4332 // TOC base pointer). If the linker allows for interposition between b and c, 4333 // then it will generate a stub for the call edge between b and c which will 4334 // save the TOC pointer into the designated stack slot allocated by b. If we 4335 // return true here, and therefore allow a tail call between b and c, that 4336 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4337 // pointer into the stack slot allocated by a (where the a -> b stub saved 4338 // a's TOC base pointer). If we're not considering a tail call, but rather, 4339 // whether a nop is needed after the call instruction in b, because the linker 4340 // will insert a stub, it might complain about a missing nop if we omit it 4341 // (although many don't complain in this case). 4342 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4343 return false; 4344 4345 return true; 4346 } 4347 4348 static bool 4349 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4350 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4351 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4352 4353 const unsigned PtrByteSize = 8; 4354 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4355 4356 static const MCPhysReg GPR[] = { 4357 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4358 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4359 }; 4360 static const MCPhysReg VR[] = { 4361 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4362 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4363 }; 4364 4365 const unsigned NumGPRs = array_lengthof(GPR); 4366 const unsigned NumFPRs = 13; 4367 const unsigned NumVRs = array_lengthof(VR); 4368 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4369 4370 unsigned NumBytes = LinkageSize; 4371 unsigned AvailableFPRs = NumFPRs; 4372 unsigned AvailableVRs = NumVRs; 4373 4374 for (const ISD::OutputArg& Param : Outs) { 4375 if (Param.Flags.isNest()) continue; 4376 4377 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4378 PtrByteSize, LinkageSize, ParamAreaSize, 4379 NumBytes, AvailableFPRs, AvailableVRs, 4380 Subtarget.hasQPX())) 4381 return true; 4382 } 4383 return false; 4384 } 4385 4386 static bool 4387 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4388 if (CS.arg_size() != CallerFn->arg_size()) 4389 return false; 4390 4391 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4392 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4393 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4394 4395 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4396 const Value* CalleeArg = *CalleeArgIter; 4397 const Value* CallerArg = &(*CallerArgIter); 4398 if (CalleeArg == CallerArg) 4399 continue; 4400 4401 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4402 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4403 // } 4404 // 1st argument of callee is undef and has the same type as caller. 4405 if (CalleeArg->getType() == CallerArg->getType() && 4406 isa<UndefValue>(CalleeArg)) 4407 continue; 4408 4409 return false; 4410 } 4411 4412 return true; 4413 } 4414 4415 // Returns true if TCO is possible between the callers and callees 4416 // calling conventions. 4417 static bool 4418 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4419 CallingConv::ID CalleeCC) { 4420 // Tail calls are possible with fastcc and ccc. 4421 auto isTailCallableCC = [] (CallingConv::ID CC){ 4422 return CC == CallingConv::C || CC == CallingConv::Fast; 4423 }; 4424 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4425 return false; 4426 4427 // We can safely tail call both fastcc and ccc callees from a c calling 4428 // convention caller. If the caller is fastcc, we may have less stack space 4429 // than a non-fastcc caller with the same signature so disable tail-calls in 4430 // that case. 4431 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4432 } 4433 4434 bool 4435 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4436 SDValue Callee, 4437 CallingConv::ID CalleeCC, 4438 ImmutableCallSite CS, 4439 bool isVarArg, 4440 const SmallVectorImpl<ISD::OutputArg> &Outs, 4441 const SmallVectorImpl<ISD::InputArg> &Ins, 4442 SelectionDAG& DAG) const { 4443 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4444 4445 if (DisableSCO && !TailCallOpt) return false; 4446 4447 // Variadic argument functions are not supported. 4448 if (isVarArg) return false; 4449 4450 auto &Caller = DAG.getMachineFunction().getFunction(); 4451 // Check that the calling conventions are compatible for tco. 4452 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4453 return false; 4454 4455 // Caller contains any byval parameter is not supported. 4456 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4457 return false; 4458 4459 // Callee contains any byval parameter is not supported, too. 4460 // Note: This is a quick work around, because in some cases, e.g. 4461 // caller's stack size > callee's stack size, we are still able to apply 4462 // sibling call optimization. For example, gcc is able to do SCO for caller1 4463 // in the following example, but not for caller2. 4464 // struct test { 4465 // long int a; 4466 // char ary[56]; 4467 // } gTest; 4468 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4469 // b->a = v.a; 4470 // return 0; 4471 // } 4472 // void caller1(struct test a, struct test c, struct test *b) { 4473 // callee(gTest, b); } 4474 // void caller2(struct test *b) { callee(gTest, b); } 4475 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4476 return false; 4477 4478 // If callee and caller use different calling conventions, we cannot pass 4479 // parameters on stack since offsets for the parameter area may be different. 4480 if (Caller.getCallingConv() != CalleeCC && 4481 needStackSlotPassParameters(Subtarget, Outs)) 4482 return false; 4483 4484 // No TCO/SCO on indirect call because Caller have to restore its TOC 4485 if (!isFunctionGlobalAddress(Callee) && 4486 !isa<ExternalSymbolSDNode>(Callee)) 4487 return false; 4488 4489 // If the caller and callee potentially have different TOC bases then we 4490 // cannot tail call since we need to restore the TOC pointer after the call. 4491 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4492 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4493 return false; 4494 4495 // TCO allows altering callee ABI, so we don't have to check further. 4496 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4497 return true; 4498 4499 if (DisableSCO) return false; 4500 4501 // If callee use the same argument list that caller is using, then we can 4502 // apply SCO on this case. If it is not, then we need to check if callee needs 4503 // stack for passing arguments. 4504 if (!hasSameArgumentList(&Caller, CS) && 4505 needStackSlotPassParameters(Subtarget, Outs)) { 4506 return false; 4507 } 4508 4509 return true; 4510 } 4511 4512 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4513 /// for tail call optimization. Targets which want to do tail call 4514 /// optimization should implement this function. 4515 bool 4516 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4517 CallingConv::ID CalleeCC, 4518 bool isVarArg, 4519 const SmallVectorImpl<ISD::InputArg> &Ins, 4520 SelectionDAG& DAG) const { 4521 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4522 return false; 4523 4524 // Variable argument functions are not supported. 4525 if (isVarArg) 4526 return false; 4527 4528 MachineFunction &MF = DAG.getMachineFunction(); 4529 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4530 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4531 // Functions containing by val parameters are not supported. 4532 for (unsigned i = 0; i != Ins.size(); i++) { 4533 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4534 if (Flags.isByVal()) return false; 4535 } 4536 4537 // Non-PIC/GOT tail calls are supported. 4538 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4539 return true; 4540 4541 // At the moment we can only do local tail calls (in same module, hidden 4542 // or protected) if we are generating PIC. 4543 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4544 return G->getGlobal()->hasHiddenVisibility() 4545 || G->getGlobal()->hasProtectedVisibility(); 4546 } 4547 4548 return false; 4549 } 4550 4551 /// isCallCompatibleAddress - Return the immediate to use if the specified 4552 /// 32-bit value is representable in the immediate field of a BxA instruction. 4553 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4554 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4555 if (!C) return nullptr; 4556 4557 int Addr = C->getZExtValue(); 4558 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4559 SignExtend32<26>(Addr) != Addr) 4560 return nullptr; // Top 6 bits have to be sext of immediate. 4561 4562 return DAG 4563 .getConstant( 4564 (int)C->getZExtValue() >> 2, SDLoc(Op), 4565 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4566 .getNode(); 4567 } 4568 4569 namespace { 4570 4571 struct TailCallArgumentInfo { 4572 SDValue Arg; 4573 SDValue FrameIdxOp; 4574 int FrameIdx = 0; 4575 4576 TailCallArgumentInfo() = default; 4577 }; 4578 4579 } // end anonymous namespace 4580 4581 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4582 static void StoreTailCallArgumentsToStackSlot( 4583 SelectionDAG &DAG, SDValue Chain, 4584 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4585 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4586 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4587 SDValue Arg = TailCallArgs[i].Arg; 4588 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4589 int FI = TailCallArgs[i].FrameIdx; 4590 // Store relative to framepointer. 4591 MemOpChains.push_back(DAG.getStore( 4592 Chain, dl, Arg, FIN, 4593 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4594 } 4595 } 4596 4597 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4598 /// the appropriate stack slot for the tail call optimized function call. 4599 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4600 SDValue OldRetAddr, SDValue OldFP, 4601 int SPDiff, const SDLoc &dl) { 4602 if (SPDiff) { 4603 // Calculate the new stack slot for the return address. 4604 MachineFunction &MF = DAG.getMachineFunction(); 4605 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4606 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4607 bool isPPC64 = Subtarget.isPPC64(); 4608 int SlotSize = isPPC64 ? 8 : 4; 4609 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4610 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4611 NewRetAddrLoc, true); 4612 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4613 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4614 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4615 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4616 4617 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4618 // slot as the FP is never overwritten. 4619 if (Subtarget.isDarwinABI()) { 4620 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4621 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4622 true); 4623 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4624 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4625 MachinePointerInfo::getFixedStack( 4626 DAG.getMachineFunction(), NewFPIdx)); 4627 } 4628 } 4629 return Chain; 4630 } 4631 4632 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4633 /// the position of the argument. 4634 static void 4635 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4636 SDValue Arg, int SPDiff, unsigned ArgOffset, 4637 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4638 int Offset = ArgOffset + SPDiff; 4639 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4640 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4641 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4642 SDValue FIN = DAG.getFrameIndex(FI, VT); 4643 TailCallArgumentInfo Info; 4644 Info.Arg = Arg; 4645 Info.FrameIdxOp = FIN; 4646 Info.FrameIdx = FI; 4647 TailCallArguments.push_back(Info); 4648 } 4649 4650 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4651 /// stack slot. Returns the chain as result and the loaded frame pointers in 4652 /// LROpOut/FPOpout. Used when tail calling. 4653 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4654 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4655 SDValue &FPOpOut, const SDLoc &dl) const { 4656 if (SPDiff) { 4657 // Load the LR and FP stack slot for later adjusting. 4658 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4659 LROpOut = getReturnAddrFrameIndex(DAG); 4660 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4661 Chain = SDValue(LROpOut.getNode(), 1); 4662 4663 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4664 // slot as the FP is never overwritten. 4665 if (Subtarget.isDarwinABI()) { 4666 FPOpOut = getFramePointerFrameIndex(DAG); 4667 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4668 Chain = SDValue(FPOpOut.getNode(), 1); 4669 } 4670 } 4671 return Chain; 4672 } 4673 4674 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4675 /// by "Src" to address "Dst" of size "Size". Alignment information is 4676 /// specified by the specific parameter attribute. The copy will be passed as 4677 /// a byval function parameter. 4678 /// Sometimes what we are copying is the end of a larger object, the part that 4679 /// does not fit in registers. 4680 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4681 SDValue Chain, ISD::ArgFlagsTy Flags, 4682 SelectionDAG &DAG, const SDLoc &dl) { 4683 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4684 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4685 false, false, false, MachinePointerInfo(), 4686 MachinePointerInfo()); 4687 } 4688 4689 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4690 /// tail calls. 4691 static void LowerMemOpCallTo( 4692 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4693 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4694 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4695 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4696 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4697 if (!isTailCall) { 4698 if (isVector) { 4699 SDValue StackPtr; 4700 if (isPPC64) 4701 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4702 else 4703 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4704 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4705 DAG.getConstant(ArgOffset, dl, PtrVT)); 4706 } 4707 MemOpChains.push_back( 4708 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4709 // Calculate and remember argument location. 4710 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4711 TailCallArguments); 4712 } 4713 4714 static void 4715 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4716 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4717 SDValue FPOp, 4718 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4719 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4720 // might overwrite each other in case of tail call optimization. 4721 SmallVector<SDValue, 8> MemOpChains2; 4722 // Do not flag preceding copytoreg stuff together with the following stuff. 4723 InFlag = SDValue(); 4724 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4725 MemOpChains2, dl); 4726 if (!MemOpChains2.empty()) 4727 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4728 4729 // Store the return address to the appropriate stack slot. 4730 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4731 4732 // Emit callseq_end just before tailcall node. 4733 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4734 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4735 InFlag = Chain.getValue(1); 4736 } 4737 4738 // Is this global address that of a function that can be called by name? (as 4739 // opposed to something that must hold a descriptor for an indirect call). 4740 static bool isFunctionGlobalAddress(SDValue Callee) { 4741 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4742 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4743 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4744 return false; 4745 4746 return G->getGlobal()->getValueType()->isFunctionTy(); 4747 } 4748 4749 return false; 4750 } 4751 4752 static unsigned 4753 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4754 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4755 bool isPatchPoint, bool hasNest, 4756 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4757 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4758 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4759 bool isPPC64 = Subtarget.isPPC64(); 4760 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4761 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4762 4763 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4764 NodeTys.push_back(MVT::Other); // Returns a chain 4765 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4766 4767 unsigned CallOpc = PPCISD::CALL; 4768 4769 bool needIndirectCall = true; 4770 if (!isSVR4ABI || !isPPC64) 4771 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4772 // If this is an absolute destination address, use the munged value. 4773 Callee = SDValue(Dest, 0); 4774 needIndirectCall = false; 4775 } 4776 4777 // PC-relative references to external symbols should go through $stub, unless 4778 // we're building with the leopard linker or later, which automatically 4779 // synthesizes these stubs. 4780 const TargetMachine &TM = DAG.getTarget(); 4781 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4782 const GlobalValue *GV = nullptr; 4783 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4784 GV = G->getGlobal(); 4785 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4786 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4787 4788 if (isFunctionGlobalAddress(Callee)) { 4789 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4790 // A call to a TLS address is actually an indirect call to a 4791 // thread-specific pointer. 4792 unsigned OpFlags = 0; 4793 if (UsePlt) 4794 OpFlags = PPCII::MO_PLT; 4795 4796 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4797 // every direct call is) turn it into a TargetGlobalAddress / 4798 // TargetExternalSymbol node so that legalize doesn't hack it. 4799 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4800 Callee.getValueType(), 0, OpFlags); 4801 needIndirectCall = false; 4802 } 4803 4804 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4805 unsigned char OpFlags = 0; 4806 4807 if (UsePlt) 4808 OpFlags = PPCII::MO_PLT; 4809 4810 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4811 OpFlags); 4812 needIndirectCall = false; 4813 } 4814 4815 if (isPatchPoint) { 4816 // We'll form an invalid direct call when lowering a patchpoint; the full 4817 // sequence for an indirect call is complicated, and many of the 4818 // instructions introduced might have side effects (and, thus, can't be 4819 // removed later). The call itself will be removed as soon as the 4820 // argument/return lowering is complete, so the fact that it has the wrong 4821 // kind of operands should not really matter. 4822 needIndirectCall = false; 4823 } 4824 4825 if (needIndirectCall) { 4826 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4827 // to do the call, we can't use PPCISD::CALL. 4828 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4829 4830 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4831 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4832 // entry point, but to the function descriptor (the function entry point 4833 // address is part of the function descriptor though). 4834 // The function descriptor is a three doubleword structure with the 4835 // following fields: function entry point, TOC base address and 4836 // environment pointer. 4837 // Thus for a call through a function pointer, the following actions need 4838 // to be performed: 4839 // 1. Save the TOC of the caller in the TOC save area of its stack 4840 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4841 // 2. Load the address of the function entry point from the function 4842 // descriptor. 4843 // 3. Load the TOC of the callee from the function descriptor into r2. 4844 // 4. Load the environment pointer from the function descriptor into 4845 // r11. 4846 // 5. Branch to the function entry point address. 4847 // 6. On return of the callee, the TOC of the caller needs to be 4848 // restored (this is done in FinishCall()). 4849 // 4850 // The loads are scheduled at the beginning of the call sequence, and the 4851 // register copies are flagged together to ensure that no other 4852 // operations can be scheduled in between. E.g. without flagging the 4853 // copies together, a TOC access in the caller could be scheduled between 4854 // the assignment of the callee TOC and the branch to the callee, which 4855 // results in the TOC access going through the TOC of the callee instead 4856 // of going through the TOC of the caller, which leads to incorrect code. 4857 4858 // Load the address of the function entry point from the function 4859 // descriptor. 4860 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 4861 if (LDChain.getValueType() == MVT::Glue) 4862 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 4863 4864 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 4865 ? (MachineMemOperand::MODereferenceable | 4866 MachineMemOperand::MOInvariant) 4867 : MachineMemOperand::MONone; 4868 4869 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 4870 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 4871 /* Alignment = */ 8, MMOFlags); 4872 4873 // Load environment pointer into r11. 4874 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 4875 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 4876 SDValue LoadEnvPtr = 4877 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 4878 /* Alignment = */ 8, MMOFlags); 4879 4880 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 4881 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 4882 SDValue TOCPtr = 4883 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 4884 /* Alignment = */ 8, MMOFlags); 4885 4886 setUsesTOCBasePtr(DAG); 4887 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 4888 InFlag); 4889 Chain = TOCVal.getValue(0); 4890 InFlag = TOCVal.getValue(1); 4891 4892 // If the function call has an explicit 'nest' parameter, it takes the 4893 // place of the environment pointer. 4894 if (!hasNest) { 4895 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 4896 InFlag); 4897 4898 Chain = EnvVal.getValue(0); 4899 InFlag = EnvVal.getValue(1); 4900 } 4901 4902 MTCTROps[0] = Chain; 4903 MTCTROps[1] = LoadFuncPtr; 4904 MTCTROps[2] = InFlag; 4905 } 4906 4907 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 4908 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 4909 InFlag = Chain.getValue(1); 4910 4911 NodeTys.clear(); 4912 NodeTys.push_back(MVT::Other); 4913 NodeTys.push_back(MVT::Glue); 4914 Ops.push_back(Chain); 4915 CallOpc = PPCISD::BCTRL; 4916 Callee.setNode(nullptr); 4917 // Add use of X11 (holding environment pointer) 4918 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 4919 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 4920 // Add CTR register as callee so a bctr can be emitted later. 4921 if (isTailCall) 4922 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 4923 } 4924 4925 // If this is a direct call, pass the chain and the callee. 4926 if (Callee.getNode()) { 4927 Ops.push_back(Chain); 4928 Ops.push_back(Callee); 4929 } 4930 // If this is a tail call add stack pointer delta. 4931 if (isTailCall) 4932 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 4933 4934 // Add argument registers to the end of the list so that they are known live 4935 // into the call. 4936 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 4937 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 4938 RegsToPass[i].second.getValueType())); 4939 4940 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 4941 // into the call. 4942 if (isSVR4ABI && isPPC64 && !isPatchPoint) { 4943 setUsesTOCBasePtr(DAG); 4944 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 4945 } 4946 4947 return CallOpc; 4948 } 4949 4950 SDValue PPCTargetLowering::LowerCallResult( 4951 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4952 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4953 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4954 SmallVector<CCValAssign, 16> RVLocs; 4955 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4956 *DAG.getContext()); 4957 4958 CCRetInfo.AnalyzeCallResult( 4959 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 4960 ? RetCC_PPC_Cold 4961 : RetCC_PPC); 4962 4963 // Copy all of the result registers out of their specified physreg. 4964 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4965 CCValAssign &VA = RVLocs[i]; 4966 assert(VA.isRegLoc() && "Can only return in registers!"); 4967 4968 SDValue Val = DAG.getCopyFromReg(Chain, dl, 4969 VA.getLocReg(), VA.getLocVT(), InFlag); 4970 Chain = Val.getValue(1); 4971 InFlag = Val.getValue(2); 4972 4973 switch (VA.getLocInfo()) { 4974 default: llvm_unreachable("Unknown loc info!"); 4975 case CCValAssign::Full: break; 4976 case CCValAssign::AExt: 4977 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4978 break; 4979 case CCValAssign::ZExt: 4980 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4981 DAG.getValueType(VA.getValVT())); 4982 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4983 break; 4984 case CCValAssign::SExt: 4985 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 4986 DAG.getValueType(VA.getValVT())); 4987 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4988 break; 4989 } 4990 4991 InVals.push_back(Val); 4992 } 4993 4994 return Chain; 4995 } 4996 4997 SDValue PPCTargetLowering::FinishCall( 4998 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 4999 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5000 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 5001 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5002 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5003 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5004 std::vector<EVT> NodeTys; 5005 SmallVector<SDValue, 8> Ops; 5006 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 5007 SPDiff, isTailCall, isPatchPoint, hasNest, 5008 RegsToPass, Ops, NodeTys, CS, Subtarget); 5009 5010 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5011 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5012 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5013 5014 // When performing tail call optimization the callee pops its arguments off 5015 // the stack. Account for this here so these bytes can be pushed back on in 5016 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5017 int BytesCalleePops = 5018 (CallConv == CallingConv::Fast && 5019 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5020 5021 // Add a register mask operand representing the call-preserved registers. 5022 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5023 const uint32_t *Mask = 5024 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5025 assert(Mask && "Missing call preserved mask for calling convention"); 5026 Ops.push_back(DAG.getRegisterMask(Mask)); 5027 5028 if (InFlag.getNode()) 5029 Ops.push_back(InFlag); 5030 5031 // Emit tail call. 5032 if (isTailCall) { 5033 assert(((Callee.getOpcode() == ISD::Register && 5034 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5035 Callee.getOpcode() == ISD::TargetExternalSymbol || 5036 Callee.getOpcode() == ISD::TargetGlobalAddress || 5037 isa<ConstantSDNode>(Callee)) && 5038 "Expecting an global address, external symbol, absolute value or register"); 5039 5040 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5041 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5042 } 5043 5044 // Add a NOP immediately after the branch instruction when using the 64-bit 5045 // SVR4 ABI. At link time, if caller and callee are in a different module and 5046 // thus have a different TOC, the call will be replaced with a call to a stub 5047 // function which saves the current TOC, loads the TOC of the callee and 5048 // branches to the callee. The NOP will be replaced with a load instruction 5049 // which restores the TOC of the caller from the TOC save slot of the current 5050 // stack frame. If caller and callee belong to the same module (and have the 5051 // same TOC), the NOP will remain unchanged. 5052 5053 MachineFunction &MF = DAG.getMachineFunction(); 5054 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 5055 !isPatchPoint) { 5056 if (CallOpc == PPCISD::BCTRL) { 5057 // This is a call through a function pointer. 5058 // Restore the caller TOC from the save area into R2. 5059 // See PrepareCall() for more information about calls through function 5060 // pointers in the 64-bit SVR4 ABI. 5061 // We are using a target-specific load with r2 hard coded, because the 5062 // result of a target-independent load would never go directly into r2, 5063 // since r2 is a reserved register (which prevents the register allocator 5064 // from allocating it), resulting in an additional register being 5065 // allocated and an unnecessary move instruction being generated. 5066 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5067 5068 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5069 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5070 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5071 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5072 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5073 5074 // The address needs to go after the chain input but before the flag (or 5075 // any other variadic arguments). 5076 Ops.insert(std::next(Ops.begin()), AddTOC); 5077 } else if (CallOpc == PPCISD::CALL && 5078 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5079 // Otherwise insert NOP for non-local calls. 5080 CallOpc = PPCISD::CALL_NOP; 5081 } 5082 } 5083 5084 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5085 InFlag = Chain.getValue(1); 5086 5087 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5088 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5089 InFlag, dl); 5090 if (!Ins.empty()) 5091 InFlag = Chain.getValue(1); 5092 5093 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5094 Ins, dl, DAG, InVals); 5095 } 5096 5097 SDValue 5098 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5099 SmallVectorImpl<SDValue> &InVals) const { 5100 SelectionDAG &DAG = CLI.DAG; 5101 SDLoc &dl = CLI.DL; 5102 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5103 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5104 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5105 SDValue Chain = CLI.Chain; 5106 SDValue Callee = CLI.Callee; 5107 bool &isTailCall = CLI.IsTailCall; 5108 CallingConv::ID CallConv = CLI.CallConv; 5109 bool isVarArg = CLI.IsVarArg; 5110 bool isPatchPoint = CLI.IsPatchPoint; 5111 ImmutableCallSite CS = CLI.CS; 5112 5113 if (isTailCall) { 5114 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5115 isTailCall = false; 5116 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5117 isTailCall = 5118 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5119 isVarArg, Outs, Ins, DAG); 5120 else 5121 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5122 Ins, DAG); 5123 if (isTailCall) { 5124 ++NumTailCalls; 5125 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5126 ++NumSiblingCalls; 5127 5128 assert(isa<GlobalAddressSDNode>(Callee) && 5129 "Callee should be an llvm::Function object."); 5130 DEBUG( 5131 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5132 const unsigned Width = 80 - strlen("TCO caller: ") 5133 - strlen(", callee linkage: 0, 0"); 5134 dbgs() << "TCO caller: " 5135 << left_justify(DAG.getMachineFunction().getName(), Width) 5136 << ", callee linkage: " 5137 << GV->getVisibility() << ", " << GV->getLinkage() << "\n" 5138 ); 5139 } 5140 } 5141 5142 if (!isTailCall && CS && CS.isMustTailCall()) 5143 report_fatal_error("failed to perform tail call elimination on a call " 5144 "site marked musttail"); 5145 5146 // When long calls (i.e. indirect calls) are always used, calls are always 5147 // made via function pointer. If we have a function name, first translate it 5148 // into a pointer. 5149 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5150 !isTailCall) 5151 Callee = LowerGlobalAddress(Callee, DAG); 5152 5153 if (Subtarget.isSVR4ABI()) { 5154 if (Subtarget.isPPC64()) 5155 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5156 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5157 dl, DAG, InVals, CS); 5158 else 5159 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5160 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5161 dl, DAG, InVals, CS); 5162 } 5163 5164 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5165 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5166 dl, DAG, InVals, CS); 5167 } 5168 5169 SDValue PPCTargetLowering::LowerCall_32SVR4( 5170 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5171 bool isTailCall, bool isPatchPoint, 5172 const SmallVectorImpl<ISD::OutputArg> &Outs, 5173 const SmallVectorImpl<SDValue> &OutVals, 5174 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5175 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5176 ImmutableCallSite CS) const { 5177 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5178 // of the 32-bit SVR4 ABI stack frame layout. 5179 5180 assert((CallConv == CallingConv::C || 5181 CallConv == CallingConv::Cold || 5182 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5183 5184 unsigned PtrByteSize = 4; 5185 5186 MachineFunction &MF = DAG.getMachineFunction(); 5187 5188 // Mark this function as potentially containing a function that contains a 5189 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5190 // and restoring the callers stack pointer in this functions epilog. This is 5191 // done because by tail calling the called function might overwrite the value 5192 // in this function's (MF) stack pointer stack slot 0(SP). 5193 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5194 CallConv == CallingConv::Fast) 5195 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5196 5197 // Count how many bytes are to be pushed on the stack, including the linkage 5198 // area, parameter list area and the part of the local variable space which 5199 // contains copies of aggregates which are passed by value. 5200 5201 // Assign locations to all of the outgoing arguments. 5202 SmallVector<CCValAssign, 16> ArgLocs; 5203 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5204 5205 // Reserve space for the linkage area on the stack. 5206 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5207 PtrByteSize); 5208 if (useSoftFloat()) 5209 CCInfo.PreAnalyzeCallOperands(Outs); 5210 5211 if (isVarArg) { 5212 // Handle fixed and variable vector arguments differently. 5213 // Fixed vector arguments go into registers as long as registers are 5214 // available. Variable vector arguments always go into memory. 5215 unsigned NumArgs = Outs.size(); 5216 5217 for (unsigned i = 0; i != NumArgs; ++i) { 5218 MVT ArgVT = Outs[i].VT; 5219 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5220 bool Result; 5221 5222 if (Outs[i].IsFixed) { 5223 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5224 CCInfo); 5225 } else { 5226 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5227 ArgFlags, CCInfo); 5228 } 5229 5230 if (Result) { 5231 #ifndef NDEBUG 5232 errs() << "Call operand #" << i << " has unhandled type " 5233 << EVT(ArgVT).getEVTString() << "\n"; 5234 #endif 5235 llvm_unreachable(nullptr); 5236 } 5237 } 5238 } else { 5239 // All arguments are treated the same. 5240 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5241 } 5242 CCInfo.clearWasPPCF128(); 5243 5244 // Assign locations to all of the outgoing aggregate by value arguments. 5245 SmallVector<CCValAssign, 16> ByValArgLocs; 5246 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5247 5248 // Reserve stack space for the allocations in CCInfo. 5249 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5250 5251 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5252 5253 // Size of the linkage area, parameter list area and the part of the local 5254 // space variable where copies of aggregates which are passed by value are 5255 // stored. 5256 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5257 5258 // Calculate by how many bytes the stack has to be adjusted in case of tail 5259 // call optimization. 5260 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5261 5262 // Adjust the stack pointer for the new arguments... 5263 // These operations are automatically eliminated by the prolog/epilog pass 5264 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5265 SDValue CallSeqStart = Chain; 5266 5267 // Load the return address and frame pointer so it can be moved somewhere else 5268 // later. 5269 SDValue LROp, FPOp; 5270 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5271 5272 // Set up a copy of the stack pointer for use loading and storing any 5273 // arguments that may not fit in the registers available for argument 5274 // passing. 5275 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5276 5277 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5278 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5279 SmallVector<SDValue, 8> MemOpChains; 5280 5281 bool seenFloatArg = false; 5282 // Walk the register/memloc assignments, inserting copies/loads. 5283 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 5284 i != e; 5285 ++i) { 5286 CCValAssign &VA = ArgLocs[i]; 5287 SDValue Arg = OutVals[i]; 5288 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5289 5290 if (Flags.isByVal()) { 5291 // Argument is an aggregate which is passed by value, thus we need to 5292 // create a copy of it in the local variable space of the current stack 5293 // frame (which is the stack frame of the caller) and pass the address of 5294 // this copy to the callee. 5295 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5296 CCValAssign &ByValVA = ByValArgLocs[j++]; 5297 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5298 5299 // Memory reserved in the local variable space of the callers stack frame. 5300 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5301 5302 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5303 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5304 StackPtr, PtrOff); 5305 5306 // Create a copy of the argument in the local area of the current 5307 // stack frame. 5308 SDValue MemcpyCall = 5309 CreateCopyOfByValArgument(Arg, PtrOff, 5310 CallSeqStart.getNode()->getOperand(0), 5311 Flags, DAG, dl); 5312 5313 // This must go outside the CALLSEQ_START..END. 5314 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5315 SDLoc(MemcpyCall)); 5316 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5317 NewCallSeqStart.getNode()); 5318 Chain = CallSeqStart = NewCallSeqStart; 5319 5320 // Pass the address of the aggregate copy on the stack either in a 5321 // physical register or in the parameter list area of the current stack 5322 // frame to the callee. 5323 Arg = PtrOff; 5324 } 5325 5326 if (VA.isRegLoc()) { 5327 if (Arg.getValueType() == MVT::i1) 5328 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg); 5329 5330 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5331 // Put argument in a physical register. 5332 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5333 } else { 5334 // Put argument in the parameter list area of the current stack frame. 5335 assert(VA.isMemLoc()); 5336 unsigned LocMemOffset = VA.getLocMemOffset(); 5337 5338 if (!isTailCall) { 5339 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5340 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5341 StackPtr, PtrOff); 5342 5343 MemOpChains.push_back( 5344 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5345 } else { 5346 // Calculate and remember argument location. 5347 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5348 TailCallArguments); 5349 } 5350 } 5351 } 5352 5353 if (!MemOpChains.empty()) 5354 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5355 5356 // Build a sequence of copy-to-reg nodes chained together with token chain 5357 // and flag operands which copy the outgoing args into the appropriate regs. 5358 SDValue InFlag; 5359 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5360 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5361 RegsToPass[i].second, InFlag); 5362 InFlag = Chain.getValue(1); 5363 } 5364 5365 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5366 // registers. 5367 if (isVarArg) { 5368 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5369 SDValue Ops[] = { Chain, InFlag }; 5370 5371 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5372 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5373 5374 InFlag = Chain.getValue(1); 5375 } 5376 5377 if (isTailCall) 5378 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5379 TailCallArguments); 5380 5381 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5382 /* unused except on PPC64 ELFv1 */ false, DAG, 5383 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5384 NumBytes, Ins, InVals, CS); 5385 } 5386 5387 // Copy an argument into memory, being careful to do this outside the 5388 // call sequence for the call to which the argument belongs. 5389 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5390 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5391 SelectionDAG &DAG, const SDLoc &dl) const { 5392 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5393 CallSeqStart.getNode()->getOperand(0), 5394 Flags, DAG, dl); 5395 // The MEMCPY must go outside the CALLSEQ_START..END. 5396 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5397 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5398 SDLoc(MemcpyCall)); 5399 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5400 NewCallSeqStart.getNode()); 5401 return NewCallSeqStart; 5402 } 5403 5404 SDValue PPCTargetLowering::LowerCall_64SVR4( 5405 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5406 bool isTailCall, bool isPatchPoint, 5407 const SmallVectorImpl<ISD::OutputArg> &Outs, 5408 const SmallVectorImpl<SDValue> &OutVals, 5409 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5410 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5411 ImmutableCallSite CS) const { 5412 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5413 bool isLittleEndian = Subtarget.isLittleEndian(); 5414 unsigned NumOps = Outs.size(); 5415 bool hasNest = false; 5416 bool IsSibCall = false; 5417 5418 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5419 unsigned PtrByteSize = 8; 5420 5421 MachineFunction &MF = DAG.getMachineFunction(); 5422 5423 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5424 IsSibCall = true; 5425 5426 // Mark this function as potentially containing a function that contains a 5427 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5428 // and restoring the callers stack pointer in this functions epilog. This is 5429 // done because by tail calling the called function might overwrite the value 5430 // in this function's (MF) stack pointer stack slot 0(SP). 5431 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5432 CallConv == CallingConv::Fast) 5433 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5434 5435 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5436 "fastcc not supported on varargs functions"); 5437 5438 // Count how many bytes are to be pushed on the stack, including the linkage 5439 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5440 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5441 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5442 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5443 unsigned NumBytes = LinkageSize; 5444 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5445 unsigned &QFPR_idx = FPR_idx; 5446 5447 static const MCPhysReg GPR[] = { 5448 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5449 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5450 }; 5451 static const MCPhysReg VR[] = { 5452 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5453 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5454 }; 5455 5456 const unsigned NumGPRs = array_lengthof(GPR); 5457 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5458 const unsigned NumVRs = array_lengthof(VR); 5459 const unsigned NumQFPRs = NumFPRs; 5460 5461 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5462 // can be passed to the callee in registers. 5463 // For the fast calling convention, there is another check below. 5464 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5465 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5466 if (!HasParameterArea) { 5467 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5468 unsigned AvailableFPRs = NumFPRs; 5469 unsigned AvailableVRs = NumVRs; 5470 unsigned NumBytesTmp = NumBytes; 5471 for (unsigned i = 0; i != NumOps; ++i) { 5472 if (Outs[i].Flags.isNest()) continue; 5473 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5474 PtrByteSize, LinkageSize, ParamAreaSize, 5475 NumBytesTmp, AvailableFPRs, AvailableVRs, 5476 Subtarget.hasQPX())) 5477 HasParameterArea = true; 5478 } 5479 } 5480 5481 // When using the fast calling convention, we don't provide backing for 5482 // arguments that will be in registers. 5483 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5484 5485 // Avoid allocating parameter area for fastcc functions if all the arguments 5486 // can be passed in the registers. 5487 if (CallConv == CallingConv::Fast) 5488 HasParameterArea = false; 5489 5490 // Add up all the space actually used. 5491 for (unsigned i = 0; i != NumOps; ++i) { 5492 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5493 EVT ArgVT = Outs[i].VT; 5494 EVT OrigVT = Outs[i].ArgVT; 5495 5496 if (Flags.isNest()) 5497 continue; 5498 5499 if (CallConv == CallingConv::Fast) { 5500 if (Flags.isByVal()) { 5501 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5502 if (NumGPRsUsed > NumGPRs) 5503 HasParameterArea = true; 5504 } else { 5505 switch (ArgVT.getSimpleVT().SimpleTy) { 5506 default: llvm_unreachable("Unexpected ValueType for argument!"); 5507 case MVT::i1: 5508 case MVT::i32: 5509 case MVT::i64: 5510 if (++NumGPRsUsed <= NumGPRs) 5511 continue; 5512 break; 5513 case MVT::v4i32: 5514 case MVT::v8i16: 5515 case MVT::v16i8: 5516 case MVT::v2f64: 5517 case MVT::v2i64: 5518 case MVT::v1i128: 5519 if (++NumVRsUsed <= NumVRs) 5520 continue; 5521 break; 5522 case MVT::v4f32: 5523 // When using QPX, this is handled like a FP register, otherwise, it 5524 // is an Altivec register. 5525 if (Subtarget.hasQPX()) { 5526 if (++NumFPRsUsed <= NumFPRs) 5527 continue; 5528 } else { 5529 if (++NumVRsUsed <= NumVRs) 5530 continue; 5531 } 5532 break; 5533 case MVT::f32: 5534 case MVT::f64: 5535 case MVT::v4f64: // QPX 5536 case MVT::v4i1: // QPX 5537 if (++NumFPRsUsed <= NumFPRs) 5538 continue; 5539 break; 5540 } 5541 HasParameterArea = true; 5542 } 5543 } 5544 5545 /* Respect alignment of argument on the stack. */ 5546 unsigned Align = 5547 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5548 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5549 5550 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5551 if (Flags.isInConsecutiveRegsLast()) 5552 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5553 } 5554 5555 unsigned NumBytesActuallyUsed = NumBytes; 5556 5557 // In the old ELFv1 ABI, 5558 // the prolog code of the callee may store up to 8 GPR argument registers to 5559 // the stack, allowing va_start to index over them in memory if its varargs. 5560 // Because we cannot tell if this is needed on the caller side, we have to 5561 // conservatively assume that it is needed. As such, make sure we have at 5562 // least enough stack space for the caller to store the 8 GPRs. 5563 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5564 // really requires memory operands, e.g. a vararg function. 5565 if (HasParameterArea) 5566 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5567 else 5568 NumBytes = LinkageSize; 5569 5570 // Tail call needs the stack to be aligned. 5571 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5572 CallConv == CallingConv::Fast) 5573 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5574 5575 int SPDiff = 0; 5576 5577 // Calculate by how many bytes the stack has to be adjusted in case of tail 5578 // call optimization. 5579 if (!IsSibCall) 5580 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5581 5582 // To protect arguments on the stack from being clobbered in a tail call, 5583 // force all the loads to happen before doing any other lowering. 5584 if (isTailCall) 5585 Chain = DAG.getStackArgumentTokenFactor(Chain); 5586 5587 // Adjust the stack pointer for the new arguments... 5588 // These operations are automatically eliminated by the prolog/epilog pass 5589 if (!IsSibCall) 5590 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5591 SDValue CallSeqStart = Chain; 5592 5593 // Load the return address and frame pointer so it can be move somewhere else 5594 // later. 5595 SDValue LROp, FPOp; 5596 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5597 5598 // Set up a copy of the stack pointer for use loading and storing any 5599 // arguments that may not fit in the registers available for argument 5600 // passing. 5601 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5602 5603 // Figure out which arguments are going to go in registers, and which in 5604 // memory. Also, if this is a vararg function, floating point operations 5605 // must be stored to our stack, and loaded into integer regs as well, if 5606 // any integer regs are available for argument passing. 5607 unsigned ArgOffset = LinkageSize; 5608 5609 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5610 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5611 5612 SmallVector<SDValue, 8> MemOpChains; 5613 for (unsigned i = 0; i != NumOps; ++i) { 5614 SDValue Arg = OutVals[i]; 5615 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5616 EVT ArgVT = Outs[i].VT; 5617 EVT OrigVT = Outs[i].ArgVT; 5618 5619 // PtrOff will be used to store the current argument to the stack if a 5620 // register cannot be found for it. 5621 SDValue PtrOff; 5622 5623 // We re-align the argument offset for each argument, except when using the 5624 // fast calling convention, when we need to make sure we do that only when 5625 // we'll actually use a stack slot. 5626 auto ComputePtrOff = [&]() { 5627 /* Respect alignment of argument on the stack. */ 5628 unsigned Align = 5629 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5630 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5631 5632 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5633 5634 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5635 }; 5636 5637 if (CallConv != CallingConv::Fast) { 5638 ComputePtrOff(); 5639 5640 /* Compute GPR index associated with argument offset. */ 5641 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5642 GPR_idx = std::min(GPR_idx, NumGPRs); 5643 } 5644 5645 // Promote integers to 64-bit values. 5646 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5647 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5648 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5649 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5650 } 5651 5652 // FIXME memcpy is used way more than necessary. Correctness first. 5653 // Note: "by value" is code for passing a structure by value, not 5654 // basic types. 5655 if (Flags.isByVal()) { 5656 // Note: Size includes alignment padding, so 5657 // struct x { short a; char b; } 5658 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5659 // These are the proper values we need for right-justifying the 5660 // aggregate in a parameter register. 5661 unsigned Size = Flags.getByValSize(); 5662 5663 // An empty aggregate parameter takes up no storage and no 5664 // registers. 5665 if (Size == 0) 5666 continue; 5667 5668 if (CallConv == CallingConv::Fast) 5669 ComputePtrOff(); 5670 5671 // All aggregates smaller than 8 bytes must be passed right-justified. 5672 if (Size==1 || Size==2 || Size==4) { 5673 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5674 if (GPR_idx != NumGPRs) { 5675 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5676 MachinePointerInfo(), VT); 5677 MemOpChains.push_back(Load.getValue(1)); 5678 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5679 5680 ArgOffset += PtrByteSize; 5681 continue; 5682 } 5683 } 5684 5685 if (GPR_idx == NumGPRs && Size < 8) { 5686 SDValue AddPtr = PtrOff; 5687 if (!isLittleEndian) { 5688 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5689 PtrOff.getValueType()); 5690 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5691 } 5692 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5693 CallSeqStart, 5694 Flags, DAG, dl); 5695 ArgOffset += PtrByteSize; 5696 continue; 5697 } 5698 // Copy entire object into memory. There are cases where gcc-generated 5699 // code assumes it is there, even if it could be put entirely into 5700 // registers. (This is not what the doc says.) 5701 5702 // FIXME: The above statement is likely due to a misunderstanding of the 5703 // documents. All arguments must be copied into the parameter area BY 5704 // THE CALLEE in the event that the callee takes the address of any 5705 // formal argument. That has not yet been implemented. However, it is 5706 // reasonable to use the stack area as a staging area for the register 5707 // load. 5708 5709 // Skip this for small aggregates, as we will use the same slot for a 5710 // right-justified copy, below. 5711 if (Size >= 8) 5712 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5713 CallSeqStart, 5714 Flags, DAG, dl); 5715 5716 // When a register is available, pass a small aggregate right-justified. 5717 if (Size < 8 && GPR_idx != NumGPRs) { 5718 // The easiest way to get this right-justified in a register 5719 // is to copy the structure into the rightmost portion of a 5720 // local variable slot, then load the whole slot into the 5721 // register. 5722 // FIXME: The memcpy seems to produce pretty awful code for 5723 // small aggregates, particularly for packed ones. 5724 // FIXME: It would be preferable to use the slot in the 5725 // parameter save area instead of a new local variable. 5726 SDValue AddPtr = PtrOff; 5727 if (!isLittleEndian) { 5728 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5729 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5730 } 5731 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5732 CallSeqStart, 5733 Flags, DAG, dl); 5734 5735 // Load the slot into the register. 5736 SDValue Load = 5737 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5738 MemOpChains.push_back(Load.getValue(1)); 5739 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5740 5741 // Done with this argument. 5742 ArgOffset += PtrByteSize; 5743 continue; 5744 } 5745 5746 // For aggregates larger than PtrByteSize, copy the pieces of the 5747 // object that fit into registers from the parameter save area. 5748 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5749 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5750 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5751 if (GPR_idx != NumGPRs) { 5752 SDValue Load = 5753 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5754 MemOpChains.push_back(Load.getValue(1)); 5755 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5756 ArgOffset += PtrByteSize; 5757 } else { 5758 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5759 break; 5760 } 5761 } 5762 continue; 5763 } 5764 5765 switch (Arg.getSimpleValueType().SimpleTy) { 5766 default: llvm_unreachable("Unexpected ValueType for argument!"); 5767 case MVT::i1: 5768 case MVT::i32: 5769 case MVT::i64: 5770 if (Flags.isNest()) { 5771 // The 'nest' parameter, if any, is passed in R11. 5772 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5773 hasNest = true; 5774 break; 5775 } 5776 5777 // These can be scalar arguments or elements of an integer array type 5778 // passed directly. Clang may use those instead of "byval" aggregate 5779 // types to avoid forcing arguments to memory unnecessarily. 5780 if (GPR_idx != NumGPRs) { 5781 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5782 } else { 5783 if (CallConv == CallingConv::Fast) 5784 ComputePtrOff(); 5785 5786 assert(HasParameterArea && 5787 "Parameter area must exist to pass an argument in memory."); 5788 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5789 true, isTailCall, false, MemOpChains, 5790 TailCallArguments, dl); 5791 if (CallConv == CallingConv::Fast) 5792 ArgOffset += PtrByteSize; 5793 } 5794 if (CallConv != CallingConv::Fast) 5795 ArgOffset += PtrByteSize; 5796 break; 5797 case MVT::f32: 5798 case MVT::f64: { 5799 // These can be scalar arguments or elements of a float array type 5800 // passed directly. The latter are used to implement ELFv2 homogenous 5801 // float aggregates. 5802 5803 // Named arguments go into FPRs first, and once they overflow, the 5804 // remaining arguments go into GPRs and then the parameter save area. 5805 // Unnamed arguments for vararg functions always go to GPRs and 5806 // then the parameter save area. For now, put all arguments to vararg 5807 // routines always in both locations (FPR *and* GPR or stack slot). 5808 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5809 bool NeededLoad = false; 5810 5811 // First load the argument into the next available FPR. 5812 if (FPR_idx != NumFPRs) 5813 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5814 5815 // Next, load the argument into GPR or stack slot if needed. 5816 if (!NeedGPROrStack) 5817 ; 5818 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5819 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5820 // once we support fp <-> gpr moves. 5821 5822 // In the non-vararg case, this can only ever happen in the 5823 // presence of f32 array types, since otherwise we never run 5824 // out of FPRs before running out of GPRs. 5825 SDValue ArgVal; 5826 5827 // Double values are always passed in a single GPR. 5828 if (Arg.getValueType() != MVT::f32) { 5829 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5830 5831 // Non-array float values are extended and passed in a GPR. 5832 } else if (!Flags.isInConsecutiveRegs()) { 5833 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5834 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5835 5836 // If we have an array of floats, we collect every odd element 5837 // together with its predecessor into one GPR. 5838 } else if (ArgOffset % PtrByteSize != 0) { 5839 SDValue Lo, Hi; 5840 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5841 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5842 if (!isLittleEndian) 5843 std::swap(Lo, Hi); 5844 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5845 5846 // The final element, if even, goes into the first half of a GPR. 5847 } else if (Flags.isInConsecutiveRegsLast()) { 5848 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5849 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5850 if (!isLittleEndian) 5851 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 5852 DAG.getConstant(32, dl, MVT::i32)); 5853 5854 // Non-final even elements are skipped; they will be handled 5855 // together the with subsequent argument on the next go-around. 5856 } else 5857 ArgVal = SDValue(); 5858 5859 if (ArgVal.getNode()) 5860 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 5861 } else { 5862 if (CallConv == CallingConv::Fast) 5863 ComputePtrOff(); 5864 5865 // Single-precision floating-point values are mapped to the 5866 // second (rightmost) word of the stack doubleword. 5867 if (Arg.getValueType() == MVT::f32 && 5868 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 5869 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5870 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5871 } 5872 5873 assert(HasParameterArea && 5874 "Parameter area must exist to pass an argument in memory."); 5875 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5876 true, isTailCall, false, MemOpChains, 5877 TailCallArguments, dl); 5878 5879 NeededLoad = true; 5880 } 5881 // When passing an array of floats, the array occupies consecutive 5882 // space in the argument area; only round up to the next doubleword 5883 // at the end of the array. Otherwise, each float takes 8 bytes. 5884 if (CallConv != CallingConv::Fast || NeededLoad) { 5885 ArgOffset += (Arg.getValueType() == MVT::f32 && 5886 Flags.isInConsecutiveRegs()) ? 4 : 8; 5887 if (Flags.isInConsecutiveRegsLast()) 5888 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5889 } 5890 break; 5891 } 5892 case MVT::v4f32: 5893 case MVT::v4i32: 5894 case MVT::v8i16: 5895 case MVT::v16i8: 5896 case MVT::v2f64: 5897 case MVT::v2i64: 5898 case MVT::v1i128: 5899 if (!Subtarget.hasQPX()) { 5900 // These can be scalar arguments or elements of a vector array type 5901 // passed directly. The latter are used to implement ELFv2 homogenous 5902 // vector aggregates. 5903 5904 // For a varargs call, named arguments go into VRs or on the stack as 5905 // usual; unnamed arguments always go to the stack or the corresponding 5906 // GPRs when within range. For now, we always put the value in both 5907 // locations (or even all three). 5908 if (isVarArg) { 5909 assert(HasParameterArea && 5910 "Parameter area must exist if we have a varargs call."); 5911 // We could elide this store in the case where the object fits 5912 // entirely in R registers. Maybe later. 5913 SDValue Store = 5914 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5915 MemOpChains.push_back(Store); 5916 if (VR_idx != NumVRs) { 5917 SDValue Load = 5918 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 5919 MemOpChains.push_back(Load.getValue(1)); 5920 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 5921 } 5922 ArgOffset += 16; 5923 for (unsigned i=0; i<16; i+=PtrByteSize) { 5924 if (GPR_idx == NumGPRs) 5925 break; 5926 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5927 DAG.getConstant(i, dl, PtrVT)); 5928 SDValue Load = 5929 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5930 MemOpChains.push_back(Load.getValue(1)); 5931 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5932 } 5933 break; 5934 } 5935 5936 // Non-varargs Altivec params go into VRs or on the stack. 5937 if (VR_idx != NumVRs) { 5938 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 5939 } else { 5940 if (CallConv == CallingConv::Fast) 5941 ComputePtrOff(); 5942 5943 assert(HasParameterArea && 5944 "Parameter area must exist to pass an argument in memory."); 5945 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5946 true, isTailCall, true, MemOpChains, 5947 TailCallArguments, dl); 5948 if (CallConv == CallingConv::Fast) 5949 ArgOffset += 16; 5950 } 5951 5952 if (CallConv != CallingConv::Fast) 5953 ArgOffset += 16; 5954 break; 5955 } // not QPX 5956 5957 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 5958 "Invalid QPX parameter type"); 5959 5960 /* fall through */ 5961 case MVT::v4f64: 5962 case MVT::v4i1: { 5963 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 5964 if (isVarArg) { 5965 assert(HasParameterArea && 5966 "Parameter area must exist if we have a varargs call."); 5967 // We could elide this store in the case where the object fits 5968 // entirely in R registers. Maybe later. 5969 SDValue Store = 5970 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5971 MemOpChains.push_back(Store); 5972 if (QFPR_idx != NumQFPRs) { 5973 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 5974 PtrOff, MachinePointerInfo()); 5975 MemOpChains.push_back(Load.getValue(1)); 5976 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 5977 } 5978 ArgOffset += (IsF32 ? 16 : 32); 5979 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 5980 if (GPR_idx == NumGPRs) 5981 break; 5982 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5983 DAG.getConstant(i, dl, PtrVT)); 5984 SDValue Load = 5985 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5986 MemOpChains.push_back(Load.getValue(1)); 5987 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5988 } 5989 break; 5990 } 5991 5992 // Non-varargs QPX params go into registers or on the stack. 5993 if (QFPR_idx != NumQFPRs) { 5994 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 5995 } else { 5996 if (CallConv == CallingConv::Fast) 5997 ComputePtrOff(); 5998 5999 assert(HasParameterArea && 6000 "Parameter area must exist to pass an argument in memory."); 6001 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6002 true, isTailCall, true, MemOpChains, 6003 TailCallArguments, dl); 6004 if (CallConv == CallingConv::Fast) 6005 ArgOffset += (IsF32 ? 16 : 32); 6006 } 6007 6008 if (CallConv != CallingConv::Fast) 6009 ArgOffset += (IsF32 ? 16 : 32); 6010 break; 6011 } 6012 } 6013 } 6014 6015 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6016 "mismatch in size of parameter area"); 6017 (void)NumBytesActuallyUsed; 6018 6019 if (!MemOpChains.empty()) 6020 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6021 6022 // Check if this is an indirect call (MTCTR/BCTRL). 6023 // See PrepareCall() for more information about calls through function 6024 // pointers in the 64-bit SVR4 ABI. 6025 if (!isTailCall && !isPatchPoint && 6026 !isFunctionGlobalAddress(Callee) && 6027 !isa<ExternalSymbolSDNode>(Callee)) { 6028 // Load r2 into a virtual register and store it to the TOC save area. 6029 setUsesTOCBasePtr(DAG); 6030 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6031 // TOC save area offset. 6032 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6033 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6034 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6035 Chain = DAG.getStore( 6036 Val.getValue(1), dl, Val, AddPtr, 6037 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6038 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6039 // This does not mean the MTCTR instruction must use R12; it's easier 6040 // to model this as an extra parameter, so do that. 6041 if (isELFv2ABI && !isPatchPoint) 6042 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6043 } 6044 6045 // Build a sequence of copy-to-reg nodes chained together with token chain 6046 // and flag operands which copy the outgoing args into the appropriate regs. 6047 SDValue InFlag; 6048 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6049 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6050 RegsToPass[i].second, InFlag); 6051 InFlag = Chain.getValue(1); 6052 } 6053 6054 if (isTailCall && !IsSibCall) 6055 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6056 TailCallArguments); 6057 6058 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6059 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6060 SPDiff, NumBytes, Ins, InVals, CS); 6061 } 6062 6063 SDValue PPCTargetLowering::LowerCall_Darwin( 6064 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6065 bool isTailCall, bool isPatchPoint, 6066 const SmallVectorImpl<ISD::OutputArg> &Outs, 6067 const SmallVectorImpl<SDValue> &OutVals, 6068 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6069 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6070 ImmutableCallSite CS) const { 6071 unsigned NumOps = Outs.size(); 6072 6073 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6074 bool isPPC64 = PtrVT == MVT::i64; 6075 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6076 6077 MachineFunction &MF = DAG.getMachineFunction(); 6078 6079 // Mark this function as potentially containing a function that contains a 6080 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6081 // and restoring the callers stack pointer in this functions epilog. This is 6082 // done because by tail calling the called function might overwrite the value 6083 // in this function's (MF) stack pointer stack slot 0(SP). 6084 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6085 CallConv == CallingConv::Fast) 6086 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6087 6088 // Count how many bytes are to be pushed on the stack, including the linkage 6089 // area, and parameter passing area. We start with 24/48 bytes, which is 6090 // prereserved space for [SP][CR][LR][3 x unused]. 6091 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6092 unsigned NumBytes = LinkageSize; 6093 6094 // Add up all the space actually used. 6095 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6096 // they all go in registers, but we must reserve stack space for them for 6097 // possible use by the caller. In varargs or 64-bit calls, parameters are 6098 // assigned stack space in order, with padding so Altivec parameters are 6099 // 16-byte aligned. 6100 unsigned nAltivecParamsAtEnd = 0; 6101 for (unsigned i = 0; i != NumOps; ++i) { 6102 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6103 EVT ArgVT = Outs[i].VT; 6104 // Varargs Altivec parameters are padded to a 16 byte boundary. 6105 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6106 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6107 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6108 if (!isVarArg && !isPPC64) { 6109 // Non-varargs Altivec parameters go after all the non-Altivec 6110 // parameters; handle those later so we know how much padding we need. 6111 nAltivecParamsAtEnd++; 6112 continue; 6113 } 6114 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6115 NumBytes = ((NumBytes+15)/16)*16; 6116 } 6117 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6118 } 6119 6120 // Allow for Altivec parameters at the end, if needed. 6121 if (nAltivecParamsAtEnd) { 6122 NumBytes = ((NumBytes+15)/16)*16; 6123 NumBytes += 16*nAltivecParamsAtEnd; 6124 } 6125 6126 // The prolog code of the callee may store up to 8 GPR argument registers to 6127 // the stack, allowing va_start to index over them in memory if its varargs. 6128 // Because we cannot tell if this is needed on the caller side, we have to 6129 // conservatively assume that it is needed. As such, make sure we have at 6130 // least enough stack space for the caller to store the 8 GPRs. 6131 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6132 6133 // Tail call needs the stack to be aligned. 6134 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6135 CallConv == CallingConv::Fast) 6136 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6137 6138 // Calculate by how many bytes the stack has to be adjusted in case of tail 6139 // call optimization. 6140 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6141 6142 // To protect arguments on the stack from being clobbered in a tail call, 6143 // force all the loads to happen before doing any other lowering. 6144 if (isTailCall) 6145 Chain = DAG.getStackArgumentTokenFactor(Chain); 6146 6147 // Adjust the stack pointer for the new arguments... 6148 // These operations are automatically eliminated by the prolog/epilog pass 6149 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6150 SDValue CallSeqStart = Chain; 6151 6152 // Load the return address and frame pointer so it can be move somewhere else 6153 // later. 6154 SDValue LROp, FPOp; 6155 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6156 6157 // Set up a copy of the stack pointer for use loading and storing any 6158 // arguments that may not fit in the registers available for argument 6159 // passing. 6160 SDValue StackPtr; 6161 if (isPPC64) 6162 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6163 else 6164 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6165 6166 // Figure out which arguments are going to go in registers, and which in 6167 // memory. Also, if this is a vararg function, floating point operations 6168 // must be stored to our stack, and loaded into integer regs as well, if 6169 // any integer regs are available for argument passing. 6170 unsigned ArgOffset = LinkageSize; 6171 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6172 6173 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6174 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6175 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6176 }; 6177 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6178 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6179 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6180 }; 6181 static const MCPhysReg VR[] = { 6182 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6183 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6184 }; 6185 const unsigned NumGPRs = array_lengthof(GPR_32); 6186 const unsigned NumFPRs = 13; 6187 const unsigned NumVRs = array_lengthof(VR); 6188 6189 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6190 6191 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6192 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6193 6194 SmallVector<SDValue, 8> MemOpChains; 6195 for (unsigned i = 0; i != NumOps; ++i) { 6196 SDValue Arg = OutVals[i]; 6197 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6198 6199 // PtrOff will be used to store the current argument to the stack if a 6200 // register cannot be found for it. 6201 SDValue PtrOff; 6202 6203 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6204 6205 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6206 6207 // On PPC64, promote integers to 64-bit values. 6208 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6209 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6210 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6211 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6212 } 6213 6214 // FIXME memcpy is used way more than necessary. Correctness first. 6215 // Note: "by value" is code for passing a structure by value, not 6216 // basic types. 6217 if (Flags.isByVal()) { 6218 unsigned Size = Flags.getByValSize(); 6219 // Very small objects are passed right-justified. Everything else is 6220 // passed left-justified. 6221 if (Size==1 || Size==2) { 6222 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6223 if (GPR_idx != NumGPRs) { 6224 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6225 MachinePointerInfo(), VT); 6226 MemOpChains.push_back(Load.getValue(1)); 6227 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6228 6229 ArgOffset += PtrByteSize; 6230 } else { 6231 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6232 PtrOff.getValueType()); 6233 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6234 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6235 CallSeqStart, 6236 Flags, DAG, dl); 6237 ArgOffset += PtrByteSize; 6238 } 6239 continue; 6240 } 6241 // Copy entire object into memory. There are cases where gcc-generated 6242 // code assumes it is there, even if it could be put entirely into 6243 // registers. (This is not what the doc says.) 6244 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6245 CallSeqStart, 6246 Flags, DAG, dl); 6247 6248 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6249 // copy the pieces of the object that fit into registers from the 6250 // parameter save area. 6251 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6252 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6253 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6254 if (GPR_idx != NumGPRs) { 6255 SDValue Load = 6256 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6257 MemOpChains.push_back(Load.getValue(1)); 6258 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6259 ArgOffset += PtrByteSize; 6260 } else { 6261 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6262 break; 6263 } 6264 } 6265 continue; 6266 } 6267 6268 switch (Arg.getSimpleValueType().SimpleTy) { 6269 default: llvm_unreachable("Unexpected ValueType for argument!"); 6270 case MVT::i1: 6271 case MVT::i32: 6272 case MVT::i64: 6273 if (GPR_idx != NumGPRs) { 6274 if (Arg.getValueType() == MVT::i1) 6275 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6276 6277 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6278 } else { 6279 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6280 isPPC64, isTailCall, false, MemOpChains, 6281 TailCallArguments, dl); 6282 } 6283 ArgOffset += PtrByteSize; 6284 break; 6285 case MVT::f32: 6286 case MVT::f64: 6287 if (FPR_idx != NumFPRs) { 6288 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6289 6290 if (isVarArg) { 6291 SDValue Store = 6292 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6293 MemOpChains.push_back(Store); 6294 6295 // Float varargs are always shadowed in available integer registers 6296 if (GPR_idx != NumGPRs) { 6297 SDValue Load = 6298 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6299 MemOpChains.push_back(Load.getValue(1)); 6300 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6301 } 6302 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6303 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6304 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6305 SDValue Load = 6306 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6307 MemOpChains.push_back(Load.getValue(1)); 6308 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6309 } 6310 } else { 6311 // If we have any FPRs remaining, we may also have GPRs remaining. 6312 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6313 // GPRs. 6314 if (GPR_idx != NumGPRs) 6315 ++GPR_idx; 6316 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6317 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6318 ++GPR_idx; 6319 } 6320 } else 6321 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6322 isPPC64, isTailCall, false, MemOpChains, 6323 TailCallArguments, dl); 6324 if (isPPC64) 6325 ArgOffset += 8; 6326 else 6327 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6328 break; 6329 case MVT::v4f32: 6330 case MVT::v4i32: 6331 case MVT::v8i16: 6332 case MVT::v16i8: 6333 if (isVarArg) { 6334 // These go aligned on the stack, or in the corresponding R registers 6335 // when within range. The Darwin PPC ABI doc claims they also go in 6336 // V registers; in fact gcc does this only for arguments that are 6337 // prototyped, not for those that match the ... We do it for all 6338 // arguments, seems to work. 6339 while (ArgOffset % 16 !=0) { 6340 ArgOffset += PtrByteSize; 6341 if (GPR_idx != NumGPRs) 6342 GPR_idx++; 6343 } 6344 // We could elide this store in the case where the object fits 6345 // entirely in R registers. Maybe later. 6346 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6347 DAG.getConstant(ArgOffset, dl, PtrVT)); 6348 SDValue Store = 6349 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6350 MemOpChains.push_back(Store); 6351 if (VR_idx != NumVRs) { 6352 SDValue Load = 6353 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6354 MemOpChains.push_back(Load.getValue(1)); 6355 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6356 } 6357 ArgOffset += 16; 6358 for (unsigned i=0; i<16; i+=PtrByteSize) { 6359 if (GPR_idx == NumGPRs) 6360 break; 6361 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6362 DAG.getConstant(i, dl, PtrVT)); 6363 SDValue Load = 6364 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6365 MemOpChains.push_back(Load.getValue(1)); 6366 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6367 } 6368 break; 6369 } 6370 6371 // Non-varargs Altivec params generally go in registers, but have 6372 // stack space allocated at the end. 6373 if (VR_idx != NumVRs) { 6374 // Doesn't have GPR space allocated. 6375 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6376 } else if (nAltivecParamsAtEnd==0) { 6377 // We are emitting Altivec params in order. 6378 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6379 isPPC64, isTailCall, true, MemOpChains, 6380 TailCallArguments, dl); 6381 ArgOffset += 16; 6382 } 6383 break; 6384 } 6385 } 6386 // If all Altivec parameters fit in registers, as they usually do, 6387 // they get stack space following the non-Altivec parameters. We 6388 // don't track this here because nobody below needs it. 6389 // If there are more Altivec parameters than fit in registers emit 6390 // the stores here. 6391 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6392 unsigned j = 0; 6393 // Offset is aligned; skip 1st 12 params which go in V registers. 6394 ArgOffset = ((ArgOffset+15)/16)*16; 6395 ArgOffset += 12*16; 6396 for (unsigned i = 0; i != NumOps; ++i) { 6397 SDValue Arg = OutVals[i]; 6398 EVT ArgType = Outs[i].VT; 6399 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6400 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6401 if (++j > NumVRs) { 6402 SDValue PtrOff; 6403 // We are emitting Altivec params in order. 6404 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6405 isPPC64, isTailCall, true, MemOpChains, 6406 TailCallArguments, dl); 6407 ArgOffset += 16; 6408 } 6409 } 6410 } 6411 } 6412 6413 if (!MemOpChains.empty()) 6414 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6415 6416 // On Darwin, R12 must contain the address of an indirect callee. This does 6417 // not mean the MTCTR instruction must use R12; it's easier to model this as 6418 // an extra parameter, so do that. 6419 if (!isTailCall && 6420 !isFunctionGlobalAddress(Callee) && 6421 !isa<ExternalSymbolSDNode>(Callee) && 6422 !isBLACompatibleAddress(Callee, DAG)) 6423 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6424 PPC::R12), Callee)); 6425 6426 // Build a sequence of copy-to-reg nodes chained together with token chain 6427 // and flag operands which copy the outgoing args into the appropriate regs. 6428 SDValue InFlag; 6429 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6430 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6431 RegsToPass[i].second, InFlag); 6432 InFlag = Chain.getValue(1); 6433 } 6434 6435 if (isTailCall) 6436 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6437 TailCallArguments); 6438 6439 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6440 /* unused except on PPC64 ELFv1 */ false, DAG, 6441 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6442 NumBytes, Ins, InVals, CS); 6443 } 6444 6445 bool 6446 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6447 MachineFunction &MF, bool isVarArg, 6448 const SmallVectorImpl<ISD::OutputArg> &Outs, 6449 LLVMContext &Context) const { 6450 SmallVector<CCValAssign, 16> RVLocs; 6451 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6452 return CCInfo.CheckReturn( 6453 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6454 ? RetCC_PPC_Cold 6455 : RetCC_PPC); 6456 } 6457 6458 SDValue 6459 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6460 bool isVarArg, 6461 const SmallVectorImpl<ISD::OutputArg> &Outs, 6462 const SmallVectorImpl<SDValue> &OutVals, 6463 const SDLoc &dl, SelectionDAG &DAG) const { 6464 SmallVector<CCValAssign, 16> RVLocs; 6465 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6466 *DAG.getContext()); 6467 CCInfo.AnalyzeReturn(Outs, 6468 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6469 ? RetCC_PPC_Cold 6470 : RetCC_PPC); 6471 6472 SDValue Flag; 6473 SmallVector<SDValue, 4> RetOps(1, Chain); 6474 6475 // Copy the result values into the output registers. 6476 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6477 CCValAssign &VA = RVLocs[i]; 6478 assert(VA.isRegLoc() && "Can only return in registers!"); 6479 6480 SDValue Arg = OutVals[i]; 6481 6482 switch (VA.getLocInfo()) { 6483 default: llvm_unreachable("Unknown loc info!"); 6484 case CCValAssign::Full: break; 6485 case CCValAssign::AExt: 6486 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6487 break; 6488 case CCValAssign::ZExt: 6489 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6490 break; 6491 case CCValAssign::SExt: 6492 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6493 break; 6494 } 6495 6496 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6497 Flag = Chain.getValue(1); 6498 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6499 } 6500 6501 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6502 const MCPhysReg *I = 6503 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6504 if (I) { 6505 for (; *I; ++I) { 6506 6507 if (PPC::G8RCRegClass.contains(*I)) 6508 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6509 else if (PPC::F8RCRegClass.contains(*I)) 6510 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6511 else if (PPC::CRRCRegClass.contains(*I)) 6512 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6513 else if (PPC::VRRCRegClass.contains(*I)) 6514 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6515 else 6516 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6517 } 6518 } 6519 6520 RetOps[0] = Chain; // Update chain. 6521 6522 // Add the flag if we have it. 6523 if (Flag.getNode()) 6524 RetOps.push_back(Flag); 6525 6526 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6527 } 6528 6529 SDValue 6530 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6531 SelectionDAG &DAG) const { 6532 SDLoc dl(Op); 6533 6534 // Get the correct type for integers. 6535 EVT IntVT = Op.getValueType(); 6536 6537 // Get the inputs. 6538 SDValue Chain = Op.getOperand(0); 6539 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6540 // Build a DYNAREAOFFSET node. 6541 SDValue Ops[2] = {Chain, FPSIdx}; 6542 SDVTList VTs = DAG.getVTList(IntVT); 6543 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6544 } 6545 6546 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6547 SelectionDAG &DAG) const { 6548 // When we pop the dynamic allocation we need to restore the SP link. 6549 SDLoc dl(Op); 6550 6551 // Get the correct type for pointers. 6552 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6553 6554 // Construct the stack pointer operand. 6555 bool isPPC64 = Subtarget.isPPC64(); 6556 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6557 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6558 6559 // Get the operands for the STACKRESTORE. 6560 SDValue Chain = Op.getOperand(0); 6561 SDValue SaveSP = Op.getOperand(1); 6562 6563 // Load the old link SP. 6564 SDValue LoadLinkSP = 6565 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6566 6567 // Restore the stack pointer. 6568 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6569 6570 // Store the old link SP. 6571 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6572 } 6573 6574 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6575 MachineFunction &MF = DAG.getMachineFunction(); 6576 bool isPPC64 = Subtarget.isPPC64(); 6577 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6578 6579 // Get current frame pointer save index. The users of this index will be 6580 // primarily DYNALLOC instructions. 6581 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6582 int RASI = FI->getReturnAddrSaveIndex(); 6583 6584 // If the frame pointer save index hasn't been defined yet. 6585 if (!RASI) { 6586 // Find out what the fix offset of the frame pointer save area. 6587 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6588 // Allocate the frame index for frame pointer save area. 6589 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6590 // Save the result. 6591 FI->setReturnAddrSaveIndex(RASI); 6592 } 6593 return DAG.getFrameIndex(RASI, PtrVT); 6594 } 6595 6596 SDValue 6597 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6598 MachineFunction &MF = DAG.getMachineFunction(); 6599 bool isPPC64 = Subtarget.isPPC64(); 6600 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6601 6602 // Get current frame pointer save index. The users of this index will be 6603 // primarily DYNALLOC instructions. 6604 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6605 int FPSI = FI->getFramePointerSaveIndex(); 6606 6607 // If the frame pointer save index hasn't been defined yet. 6608 if (!FPSI) { 6609 // Find out what the fix offset of the frame pointer save area. 6610 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6611 // Allocate the frame index for frame pointer save area. 6612 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6613 // Save the result. 6614 FI->setFramePointerSaveIndex(FPSI); 6615 } 6616 return DAG.getFrameIndex(FPSI, PtrVT); 6617 } 6618 6619 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6620 SelectionDAG &DAG) const { 6621 // Get the inputs. 6622 SDValue Chain = Op.getOperand(0); 6623 SDValue Size = Op.getOperand(1); 6624 SDLoc dl(Op); 6625 6626 // Get the correct type for pointers. 6627 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6628 // Negate the size. 6629 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6630 DAG.getConstant(0, dl, PtrVT), Size); 6631 // Construct a node for the frame pointer save index. 6632 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6633 // Build a DYNALLOC node. 6634 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6635 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6636 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6637 } 6638 6639 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6640 SelectionDAG &DAG) const { 6641 MachineFunction &MF = DAG.getMachineFunction(); 6642 6643 bool isPPC64 = Subtarget.isPPC64(); 6644 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6645 6646 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6647 return DAG.getFrameIndex(FI, PtrVT); 6648 } 6649 6650 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6651 SelectionDAG &DAG) const { 6652 SDLoc DL(Op); 6653 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6654 DAG.getVTList(MVT::i32, MVT::Other), 6655 Op.getOperand(0), Op.getOperand(1)); 6656 } 6657 6658 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6659 SelectionDAG &DAG) const { 6660 SDLoc DL(Op); 6661 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6662 Op.getOperand(0), Op.getOperand(1)); 6663 } 6664 6665 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6666 if (Op.getValueType().isVector()) 6667 return LowerVectorLoad(Op, DAG); 6668 6669 assert(Op.getValueType() == MVT::i1 && 6670 "Custom lowering only for i1 loads"); 6671 6672 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6673 6674 SDLoc dl(Op); 6675 LoadSDNode *LD = cast<LoadSDNode>(Op); 6676 6677 SDValue Chain = LD->getChain(); 6678 SDValue BasePtr = LD->getBasePtr(); 6679 MachineMemOperand *MMO = LD->getMemOperand(); 6680 6681 SDValue NewLD = 6682 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6683 BasePtr, MVT::i8, MMO); 6684 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6685 6686 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6687 return DAG.getMergeValues(Ops, dl); 6688 } 6689 6690 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6691 if (Op.getOperand(1).getValueType().isVector()) 6692 return LowerVectorStore(Op, DAG); 6693 6694 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6695 "Custom lowering only for i1 stores"); 6696 6697 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6698 6699 SDLoc dl(Op); 6700 StoreSDNode *ST = cast<StoreSDNode>(Op); 6701 6702 SDValue Chain = ST->getChain(); 6703 SDValue BasePtr = ST->getBasePtr(); 6704 SDValue Value = ST->getValue(); 6705 MachineMemOperand *MMO = ST->getMemOperand(); 6706 6707 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6708 Value); 6709 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6710 } 6711 6712 // FIXME: Remove this once the ANDI glue bug is fixed: 6713 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6714 assert(Op.getValueType() == MVT::i1 && 6715 "Custom lowering only for i1 results"); 6716 6717 SDLoc DL(Op); 6718 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6719 Op.getOperand(0)); 6720 } 6721 6722 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6723 /// possible. 6724 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6725 // Not FP? Not a fsel. 6726 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6727 !Op.getOperand(2).getValueType().isFloatingPoint()) 6728 return Op; 6729 6730 // We might be able to do better than this under some circumstances, but in 6731 // general, fsel-based lowering of select is a finite-math-only optimization. 6732 // For more information, see section F.3 of the 2.06 ISA specification. 6733 if (!DAG.getTarget().Options.NoInfsFPMath || 6734 !DAG.getTarget().Options.NoNaNsFPMath) 6735 return Op; 6736 // TODO: Propagate flags from the select rather than global settings. 6737 SDNodeFlags Flags; 6738 Flags.setNoInfs(true); 6739 Flags.setNoNaNs(true); 6740 6741 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6742 6743 EVT ResVT = Op.getValueType(); 6744 EVT CmpVT = Op.getOperand(0).getValueType(); 6745 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6746 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6747 SDLoc dl(Op); 6748 6749 // If the RHS of the comparison is a 0.0, we don't need to do the 6750 // subtraction at all. 6751 SDValue Sel1; 6752 if (isFloatingPointZero(RHS)) 6753 switch (CC) { 6754 default: break; // SETUO etc aren't handled by fsel. 6755 case ISD::SETNE: 6756 std::swap(TV, FV); 6757 LLVM_FALLTHROUGH; 6758 case ISD::SETEQ: 6759 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6760 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6761 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6762 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6763 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6764 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6765 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6766 case ISD::SETULT: 6767 case ISD::SETLT: 6768 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6769 LLVM_FALLTHROUGH; 6770 case ISD::SETOGE: 6771 case ISD::SETGE: 6772 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6773 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6774 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6775 case ISD::SETUGT: 6776 case ISD::SETGT: 6777 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6778 LLVM_FALLTHROUGH; 6779 case ISD::SETOLE: 6780 case ISD::SETLE: 6781 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6782 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6783 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6784 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6785 } 6786 6787 SDValue Cmp; 6788 switch (CC) { 6789 default: break; // SETUO etc aren't handled by fsel. 6790 case ISD::SETNE: 6791 std::swap(TV, FV); 6792 LLVM_FALLTHROUGH; 6793 case ISD::SETEQ: 6794 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6795 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6796 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6797 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6798 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6799 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6800 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6801 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6802 case ISD::SETULT: 6803 case ISD::SETLT: 6804 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6805 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6806 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6807 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6808 case ISD::SETOGE: 6809 case ISD::SETGE: 6810 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6811 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6812 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6813 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6814 case ISD::SETUGT: 6815 case ISD::SETGT: 6816 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6817 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6818 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6819 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6820 case ISD::SETOLE: 6821 case ISD::SETLE: 6822 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6823 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6824 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6825 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6826 } 6827 return Op; 6828 } 6829 6830 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 6831 SelectionDAG &DAG, 6832 const SDLoc &dl) const { 6833 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6834 SDValue Src = Op.getOperand(0); 6835 if (Src.getValueType() == MVT::f32) 6836 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6837 6838 SDValue Tmp; 6839 switch (Op.getSimpleValueType().SimpleTy) { 6840 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6841 case MVT::i32: 6842 Tmp = DAG.getNode( 6843 Op.getOpcode() == ISD::FP_TO_SINT 6844 ? PPCISD::FCTIWZ 6845 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6846 dl, MVT::f64, Src); 6847 break; 6848 case MVT::i64: 6849 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6850 "i64 FP_TO_UINT is supported only with FPCVT"); 6851 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6852 PPCISD::FCTIDUZ, 6853 dl, MVT::f64, Src); 6854 break; 6855 } 6856 6857 // Convert the FP value to an int value through memory. 6858 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 6859 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 6860 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 6861 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 6862 MachinePointerInfo MPI = 6863 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 6864 6865 // Emit a store to the stack slot. 6866 SDValue Chain; 6867 if (i32Stack) { 6868 MachineFunction &MF = DAG.getMachineFunction(); 6869 MachineMemOperand *MMO = 6870 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 6871 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 6872 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 6873 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 6874 } else 6875 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 6876 6877 // Result is a load from the stack slot. If loading 4 bytes, make sure to 6878 // add in a bias on big endian. 6879 if (Op.getValueType() == MVT::i32 && !i32Stack) { 6880 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 6881 DAG.getConstant(4, dl, FIPtr.getValueType())); 6882 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 6883 } 6884 6885 RLI.Chain = Chain; 6886 RLI.Ptr = FIPtr; 6887 RLI.MPI = MPI; 6888 } 6889 6890 /// Custom lowers floating point to integer conversions to use 6891 /// the direct move instructions available in ISA 2.07 to avoid the 6892 /// need for load/store combinations. 6893 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 6894 SelectionDAG &DAG, 6895 const SDLoc &dl) const { 6896 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6897 SDValue Src = Op.getOperand(0); 6898 6899 if (Src.getValueType() == MVT::f32) 6900 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6901 6902 SDValue Tmp; 6903 switch (Op.getSimpleValueType().SimpleTy) { 6904 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6905 case MVT::i32: 6906 Tmp = DAG.getNode( 6907 Op.getOpcode() == ISD::FP_TO_SINT 6908 ? PPCISD::FCTIWZ 6909 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6910 dl, MVT::f64, Src); 6911 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 6912 break; 6913 case MVT::i64: 6914 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6915 "i64 FP_TO_UINT is supported only with FPCVT"); 6916 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6917 PPCISD::FCTIDUZ, 6918 dl, MVT::f64, Src); 6919 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 6920 break; 6921 } 6922 return Tmp; 6923 } 6924 6925 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 6926 const SDLoc &dl) const { 6927 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 6928 // PPC (the libcall is not available). 6929 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 6930 if (Op.getValueType() == MVT::i32) { 6931 if (Op.getOpcode() == ISD::FP_TO_SINT) { 6932 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 6933 MVT::f64, Op.getOperand(0), 6934 DAG.getIntPtrConstant(0, dl)); 6935 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 6936 MVT::f64, Op.getOperand(0), 6937 DAG.getIntPtrConstant(1, dl)); 6938 6939 // Add the two halves of the long double in round-to-zero mode. 6940 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 6941 6942 // Now use a smaller FP_TO_SINT. 6943 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 6944 } 6945 if (Op.getOpcode() == ISD::FP_TO_UINT) { 6946 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 6947 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 6948 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 6949 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 6950 // FIXME: generated code sucks. 6951 // TODO: Are there fast-math-flags to propagate to this FSUB? 6952 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 6953 Op.getOperand(0), Tmp); 6954 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 6955 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 6956 DAG.getConstant(0x80000000, dl, MVT::i32)); 6957 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 6958 Op.getOperand(0)); 6959 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 6960 ISD::SETGE); 6961 } 6962 } 6963 6964 return SDValue(); 6965 } 6966 6967 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 6968 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 6969 6970 ReuseLoadInfo RLI; 6971 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6972 6973 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 6974 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 6975 } 6976 6977 // We're trying to insert a regular store, S, and then a load, L. If the 6978 // incoming value, O, is a load, we might just be able to have our load use the 6979 // address used by O. However, we don't know if anything else will store to 6980 // that address before we can load from it. To prevent this situation, we need 6981 // to insert our load, L, into the chain as a peer of O. To do this, we give L 6982 // the same chain operand as O, we create a token factor from the chain results 6983 // of O and L, and we replace all uses of O's chain result with that token 6984 // factor (see spliceIntoChain below for this last part). 6985 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 6986 ReuseLoadInfo &RLI, 6987 SelectionDAG &DAG, 6988 ISD::LoadExtType ET) const { 6989 SDLoc dl(Op); 6990 if (ET == ISD::NON_EXTLOAD && 6991 (Op.getOpcode() == ISD::FP_TO_UINT || 6992 Op.getOpcode() == ISD::FP_TO_SINT) && 6993 isOperationLegalOrCustom(Op.getOpcode(), 6994 Op.getOperand(0).getValueType())) { 6995 6996 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6997 return true; 6998 } 6999 7000 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7001 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7002 LD->isNonTemporal()) 7003 return false; 7004 if (LD->getMemoryVT() != MemVT) 7005 return false; 7006 7007 RLI.Ptr = LD->getBasePtr(); 7008 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7009 assert(LD->getAddressingMode() == ISD::PRE_INC && 7010 "Non-pre-inc AM on PPC?"); 7011 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7012 LD->getOffset()); 7013 } 7014 7015 RLI.Chain = LD->getChain(); 7016 RLI.MPI = LD->getPointerInfo(); 7017 RLI.IsDereferenceable = LD->isDereferenceable(); 7018 RLI.IsInvariant = LD->isInvariant(); 7019 RLI.Alignment = LD->getAlignment(); 7020 RLI.AAInfo = LD->getAAInfo(); 7021 RLI.Ranges = LD->getRanges(); 7022 7023 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7024 return true; 7025 } 7026 7027 // Given the head of the old chain, ResChain, insert a token factor containing 7028 // it and NewResChain, and make users of ResChain now be users of that token 7029 // factor. 7030 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7031 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7032 SDValue NewResChain, 7033 SelectionDAG &DAG) const { 7034 if (!ResChain) 7035 return; 7036 7037 SDLoc dl(NewResChain); 7038 7039 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7040 NewResChain, DAG.getUNDEF(MVT::Other)); 7041 assert(TF.getNode() != NewResChain.getNode() && 7042 "A new TF really is required here"); 7043 7044 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7045 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7046 } 7047 7048 /// Analyze profitability of direct move 7049 /// prefer float load to int load plus direct move 7050 /// when there is no integer use of int load 7051 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7052 SDNode *Origin = Op.getOperand(0).getNode(); 7053 if (Origin->getOpcode() != ISD::LOAD) 7054 return true; 7055 7056 // If there is no LXSIBZX/LXSIHZX, like Power8, 7057 // prefer direct move if the memory size is 1 or 2 bytes. 7058 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7059 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7060 return true; 7061 7062 for (SDNode::use_iterator UI = Origin->use_begin(), 7063 UE = Origin->use_end(); 7064 UI != UE; ++UI) { 7065 7066 // Only look at the users of the loaded value. 7067 if (UI.getUse().get().getResNo() != 0) 7068 continue; 7069 7070 if (UI->getOpcode() != ISD::SINT_TO_FP && 7071 UI->getOpcode() != ISD::UINT_TO_FP) 7072 return true; 7073 } 7074 7075 return false; 7076 } 7077 7078 /// Custom lowers integer to floating point conversions to use 7079 /// the direct move instructions available in ISA 2.07 to avoid the 7080 /// need for load/store combinations. 7081 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7082 SelectionDAG &DAG, 7083 const SDLoc &dl) const { 7084 assert((Op.getValueType() == MVT::f32 || 7085 Op.getValueType() == MVT::f64) && 7086 "Invalid floating point type as target of conversion"); 7087 assert(Subtarget.hasFPCVT() && 7088 "Int to FP conversions with direct moves require FPCVT"); 7089 SDValue FP; 7090 SDValue Src = Op.getOperand(0); 7091 bool SinglePrec = Op.getValueType() == MVT::f32; 7092 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7093 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7094 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7095 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7096 7097 if (WordInt) { 7098 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7099 dl, MVT::f64, Src); 7100 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7101 } 7102 else { 7103 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7104 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7105 } 7106 7107 return FP; 7108 } 7109 7110 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7111 SelectionDAG &DAG) const { 7112 SDLoc dl(Op); 7113 7114 // Conversions to f128 are legal. 7115 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7116 return Op; 7117 7118 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7119 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7120 return SDValue(); 7121 7122 SDValue Value = Op.getOperand(0); 7123 // The values are now known to be -1 (false) or 1 (true). To convert this 7124 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7125 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7126 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7127 7128 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7129 7130 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7131 7132 if (Op.getValueType() != MVT::v4f64) 7133 Value = DAG.getNode(ISD::FP_ROUND, dl, 7134 Op.getValueType(), Value, 7135 DAG.getIntPtrConstant(1, dl)); 7136 return Value; 7137 } 7138 7139 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7140 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7141 return SDValue(); 7142 7143 if (Op.getOperand(0).getValueType() == MVT::i1) 7144 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7145 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7146 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7147 7148 // If we have direct moves, we can do all the conversion, skip the store/load 7149 // however, without FPCVT we can't do most conversions. 7150 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7151 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7152 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7153 7154 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7155 "UINT_TO_FP is supported only with FPCVT"); 7156 7157 // If we have FCFIDS, then use it when converting to single-precision. 7158 // Otherwise, convert to double-precision and then round. 7159 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7160 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7161 : PPCISD::FCFIDS) 7162 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7163 : PPCISD::FCFID); 7164 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7165 ? MVT::f32 7166 : MVT::f64; 7167 7168 if (Op.getOperand(0).getValueType() == MVT::i64) { 7169 SDValue SINT = Op.getOperand(0); 7170 // When converting to single-precision, we actually need to convert 7171 // to double-precision first and then round to single-precision. 7172 // To avoid double-rounding effects during that operation, we have 7173 // to prepare the input operand. Bits that might be truncated when 7174 // converting to double-precision are replaced by a bit that won't 7175 // be lost at this stage, but is below the single-precision rounding 7176 // position. 7177 // 7178 // However, if -enable-unsafe-fp-math is in effect, accept double 7179 // rounding to avoid the extra overhead. 7180 if (Op.getValueType() == MVT::f32 && 7181 !Subtarget.hasFPCVT() && 7182 !DAG.getTarget().Options.UnsafeFPMath) { 7183 7184 // Twiddle input to make sure the low 11 bits are zero. (If this 7185 // is the case, we are guaranteed the value will fit into the 53 bit 7186 // mantissa of an IEEE double-precision value without rounding.) 7187 // If any of those low 11 bits were not zero originally, make sure 7188 // bit 12 (value 2048) is set instead, so that the final rounding 7189 // to single-precision gets the correct result. 7190 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7191 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7192 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7193 Round, DAG.getConstant(2047, dl, MVT::i64)); 7194 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7195 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7196 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7197 7198 // However, we cannot use that value unconditionally: if the magnitude 7199 // of the input value is small, the bit-twiddling we did above might 7200 // end up visibly changing the output. Fortunately, in that case, we 7201 // don't need to twiddle bits since the original input will convert 7202 // exactly to double-precision floating-point already. Therefore, 7203 // construct a conditional to use the original value if the top 11 7204 // bits are all sign-bit copies, and use the rounded value computed 7205 // above otherwise. 7206 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7207 SINT, DAG.getConstant(53, dl, MVT::i32)); 7208 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7209 Cond, DAG.getConstant(1, dl, MVT::i64)); 7210 Cond = DAG.getSetCC(dl, MVT::i32, 7211 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7212 7213 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7214 } 7215 7216 ReuseLoadInfo RLI; 7217 SDValue Bits; 7218 7219 MachineFunction &MF = DAG.getMachineFunction(); 7220 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7221 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7222 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7223 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7224 } else if (Subtarget.hasLFIWAX() && 7225 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7226 MachineMemOperand *MMO = 7227 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7228 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7229 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7230 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7231 DAG.getVTList(MVT::f64, MVT::Other), 7232 Ops, MVT::i32, MMO); 7233 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7234 } else if (Subtarget.hasFPCVT() && 7235 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7236 MachineMemOperand *MMO = 7237 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7238 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7239 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7240 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7241 DAG.getVTList(MVT::f64, MVT::Other), 7242 Ops, MVT::i32, MMO); 7243 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7244 } else if (((Subtarget.hasLFIWAX() && 7245 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7246 (Subtarget.hasFPCVT() && 7247 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7248 SINT.getOperand(0).getValueType() == MVT::i32) { 7249 MachineFrameInfo &MFI = MF.getFrameInfo(); 7250 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7251 7252 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7253 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7254 7255 SDValue Store = 7256 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7257 MachinePointerInfo::getFixedStack( 7258 DAG.getMachineFunction(), FrameIdx)); 7259 7260 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7261 "Expected an i32 store"); 7262 7263 RLI.Ptr = FIdx; 7264 RLI.Chain = Store; 7265 RLI.MPI = 7266 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7267 RLI.Alignment = 4; 7268 7269 MachineMemOperand *MMO = 7270 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7271 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7272 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7273 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7274 PPCISD::LFIWZX : PPCISD::LFIWAX, 7275 dl, DAG.getVTList(MVT::f64, MVT::Other), 7276 Ops, MVT::i32, MMO); 7277 } else 7278 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7279 7280 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7281 7282 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7283 FP = DAG.getNode(ISD::FP_ROUND, dl, 7284 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7285 return FP; 7286 } 7287 7288 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7289 "Unhandled INT_TO_FP type in custom expander!"); 7290 // Since we only generate this in 64-bit mode, we can take advantage of 7291 // 64-bit registers. In particular, sign extend the input value into the 7292 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7293 // then lfd it and fcfid it. 7294 MachineFunction &MF = DAG.getMachineFunction(); 7295 MachineFrameInfo &MFI = MF.getFrameInfo(); 7296 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7297 7298 SDValue Ld; 7299 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7300 ReuseLoadInfo RLI; 7301 bool ReusingLoad; 7302 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7303 DAG))) { 7304 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7305 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7306 7307 SDValue Store = 7308 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7309 MachinePointerInfo::getFixedStack( 7310 DAG.getMachineFunction(), FrameIdx)); 7311 7312 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7313 "Expected an i32 store"); 7314 7315 RLI.Ptr = FIdx; 7316 RLI.Chain = Store; 7317 RLI.MPI = 7318 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7319 RLI.Alignment = 4; 7320 } 7321 7322 MachineMemOperand *MMO = 7323 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7324 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7325 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7326 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7327 PPCISD::LFIWZX : PPCISD::LFIWAX, 7328 dl, DAG.getVTList(MVT::f64, MVT::Other), 7329 Ops, MVT::i32, MMO); 7330 if (ReusingLoad) 7331 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7332 } else { 7333 assert(Subtarget.isPPC64() && 7334 "i32->FP without LFIWAX supported only on PPC64"); 7335 7336 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7337 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7338 7339 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7340 Op.getOperand(0)); 7341 7342 // STD the extended value into the stack slot. 7343 SDValue Store = DAG.getStore( 7344 DAG.getEntryNode(), dl, Ext64, FIdx, 7345 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7346 7347 // Load the value as a double. 7348 Ld = DAG.getLoad( 7349 MVT::f64, dl, Store, FIdx, 7350 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7351 } 7352 7353 // FCFID it and return it. 7354 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7355 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7356 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7357 DAG.getIntPtrConstant(0, dl)); 7358 return FP; 7359 } 7360 7361 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7362 SelectionDAG &DAG) const { 7363 SDLoc dl(Op); 7364 /* 7365 The rounding mode is in bits 30:31 of FPSR, and has the following 7366 settings: 7367 00 Round to nearest 7368 01 Round to 0 7369 10 Round to +inf 7370 11 Round to -inf 7371 7372 FLT_ROUNDS, on the other hand, expects the following: 7373 -1 Undefined 7374 0 Round to 0 7375 1 Round to nearest 7376 2 Round to +inf 7377 3 Round to -inf 7378 7379 To perform the conversion, we do: 7380 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7381 */ 7382 7383 MachineFunction &MF = DAG.getMachineFunction(); 7384 EVT VT = Op.getValueType(); 7385 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7386 7387 // Save FP Control Word to register 7388 EVT NodeTys[] = { 7389 MVT::f64, // return register 7390 MVT::Glue // unused in this context 7391 }; 7392 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7393 7394 // Save FP register to stack slot 7395 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7396 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7397 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7398 MachinePointerInfo()); 7399 7400 // Load FP Control Word from low 32 bits of stack slot. 7401 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7402 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7403 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7404 7405 // Transform as necessary 7406 SDValue CWD1 = 7407 DAG.getNode(ISD::AND, dl, MVT::i32, 7408 CWD, DAG.getConstant(3, dl, MVT::i32)); 7409 SDValue CWD2 = 7410 DAG.getNode(ISD::SRL, dl, MVT::i32, 7411 DAG.getNode(ISD::AND, dl, MVT::i32, 7412 DAG.getNode(ISD::XOR, dl, MVT::i32, 7413 CWD, DAG.getConstant(3, dl, MVT::i32)), 7414 DAG.getConstant(3, dl, MVT::i32)), 7415 DAG.getConstant(1, dl, MVT::i32)); 7416 7417 SDValue RetVal = 7418 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7419 7420 return DAG.getNode((VT.getSizeInBits() < 16 ? 7421 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7422 } 7423 7424 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7425 EVT VT = Op.getValueType(); 7426 unsigned BitWidth = VT.getSizeInBits(); 7427 SDLoc dl(Op); 7428 assert(Op.getNumOperands() == 3 && 7429 VT == Op.getOperand(1).getValueType() && 7430 "Unexpected SHL!"); 7431 7432 // Expand into a bunch of logical ops. Note that these ops 7433 // depend on the PPC behavior for oversized shift amounts. 7434 SDValue Lo = Op.getOperand(0); 7435 SDValue Hi = Op.getOperand(1); 7436 SDValue Amt = Op.getOperand(2); 7437 EVT AmtVT = Amt.getValueType(); 7438 7439 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7440 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7441 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7442 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7443 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7444 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7445 DAG.getConstant(-BitWidth, dl, AmtVT)); 7446 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7447 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7448 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7449 SDValue OutOps[] = { OutLo, OutHi }; 7450 return DAG.getMergeValues(OutOps, dl); 7451 } 7452 7453 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7454 EVT VT = Op.getValueType(); 7455 SDLoc dl(Op); 7456 unsigned BitWidth = VT.getSizeInBits(); 7457 assert(Op.getNumOperands() == 3 && 7458 VT == Op.getOperand(1).getValueType() && 7459 "Unexpected SRL!"); 7460 7461 // Expand into a bunch of logical ops. Note that these ops 7462 // depend on the PPC behavior for oversized shift amounts. 7463 SDValue Lo = Op.getOperand(0); 7464 SDValue Hi = Op.getOperand(1); 7465 SDValue Amt = Op.getOperand(2); 7466 EVT AmtVT = Amt.getValueType(); 7467 7468 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7469 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7470 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7471 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7472 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7473 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7474 DAG.getConstant(-BitWidth, dl, AmtVT)); 7475 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7476 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7477 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7478 SDValue OutOps[] = { OutLo, OutHi }; 7479 return DAG.getMergeValues(OutOps, dl); 7480 } 7481 7482 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7483 SDLoc dl(Op); 7484 EVT VT = Op.getValueType(); 7485 unsigned BitWidth = VT.getSizeInBits(); 7486 assert(Op.getNumOperands() == 3 && 7487 VT == Op.getOperand(1).getValueType() && 7488 "Unexpected SRA!"); 7489 7490 // Expand into a bunch of logical ops, followed by a select_cc. 7491 SDValue Lo = Op.getOperand(0); 7492 SDValue Hi = Op.getOperand(1); 7493 SDValue Amt = Op.getOperand(2); 7494 EVT AmtVT = Amt.getValueType(); 7495 7496 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7497 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7498 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7499 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7500 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7501 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7502 DAG.getConstant(-BitWidth, dl, AmtVT)); 7503 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7504 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7505 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7506 Tmp4, Tmp6, ISD::SETLE); 7507 SDValue OutOps[] = { OutLo, OutHi }; 7508 return DAG.getMergeValues(OutOps, dl); 7509 } 7510 7511 //===----------------------------------------------------------------------===// 7512 // Vector related lowering. 7513 // 7514 7515 /// BuildSplatI - Build a canonical splati of Val with an element size of 7516 /// SplatSize. Cast the result to VT. 7517 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7518 SelectionDAG &DAG, const SDLoc &dl) { 7519 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7520 7521 static const MVT VTys[] = { // canonical VT to use for each size. 7522 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7523 }; 7524 7525 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7526 7527 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7528 if (Val == -1) 7529 SplatSize = 1; 7530 7531 EVT CanonicalVT = VTys[SplatSize-1]; 7532 7533 // Build a canonical splat for this value. 7534 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7535 } 7536 7537 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7538 /// specified intrinsic ID. 7539 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7540 const SDLoc &dl, EVT DestVT = MVT::Other) { 7541 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7542 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7543 DAG.getConstant(IID, dl, MVT::i32), Op); 7544 } 7545 7546 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7547 /// specified intrinsic ID. 7548 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7549 SelectionDAG &DAG, const SDLoc &dl, 7550 EVT DestVT = MVT::Other) { 7551 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7552 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7553 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7554 } 7555 7556 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7557 /// specified intrinsic ID. 7558 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7559 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7560 EVT DestVT = MVT::Other) { 7561 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7562 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7563 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7564 } 7565 7566 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7567 /// amount. The result has the specified value type. 7568 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7569 SelectionDAG &DAG, const SDLoc &dl) { 7570 // Force LHS/RHS to be the right type. 7571 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7572 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7573 7574 int Ops[16]; 7575 for (unsigned i = 0; i != 16; ++i) 7576 Ops[i] = i + Amt; 7577 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7578 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7579 } 7580 7581 /// Do we have an efficient pattern in a .td file for this node? 7582 /// 7583 /// \param V - pointer to the BuildVectorSDNode being matched 7584 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7585 /// 7586 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7587 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7588 /// the opposite is true (expansion is beneficial) are: 7589 /// - The node builds a vector out of integers that are not 32 or 64-bits 7590 /// - The node builds a vector out of constants 7591 /// - The node is a "load-and-splat" 7592 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7593 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7594 bool HasDirectMove, 7595 bool HasP8Vector) { 7596 EVT VecVT = V->getValueType(0); 7597 bool RightType = VecVT == MVT::v2f64 || 7598 (HasP8Vector && VecVT == MVT::v4f32) || 7599 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7600 if (!RightType) 7601 return false; 7602 7603 bool IsSplat = true; 7604 bool IsLoad = false; 7605 SDValue Op0 = V->getOperand(0); 7606 7607 // This function is called in a block that confirms the node is not a constant 7608 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7609 // different constants. 7610 if (V->isConstant()) 7611 return false; 7612 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7613 if (V->getOperand(i).isUndef()) 7614 return false; 7615 // We want to expand nodes that represent load-and-splat even if the 7616 // loaded value is a floating point truncation or conversion to int. 7617 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7618 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7619 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7620 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7621 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7622 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7623 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7624 IsLoad = true; 7625 // If the operands are different or the input is not a load and has more 7626 // uses than just this BV node, then it isn't a splat. 7627 if (V->getOperand(i) != Op0 || 7628 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7629 IsSplat = false; 7630 } 7631 return !(IsSplat && IsLoad); 7632 } 7633 7634 // If this is a case we can't handle, return null and let the default 7635 // expansion code take care of it. If we CAN select this case, and if it 7636 // selects to a single instruction, return Op. Otherwise, if we can codegen 7637 // this case more efficiently than a constant pool load, lower it to the 7638 // sequence of ops that should be used. 7639 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7640 SelectionDAG &DAG) const { 7641 SDLoc dl(Op); 7642 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7643 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7644 7645 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7646 // We first build an i32 vector, load it into a QPX register, 7647 // then convert it to a floating-point vector and compare it 7648 // to a zero vector to get the boolean result. 7649 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7650 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7651 MachinePointerInfo PtrInfo = 7652 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7653 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7654 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7655 7656 assert(BVN->getNumOperands() == 4 && 7657 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7658 7659 bool IsConst = true; 7660 for (unsigned i = 0; i < 4; ++i) { 7661 if (BVN->getOperand(i).isUndef()) continue; 7662 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7663 IsConst = false; 7664 break; 7665 } 7666 } 7667 7668 if (IsConst) { 7669 Constant *One = 7670 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7671 Constant *NegOne = 7672 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7673 7674 Constant *CV[4]; 7675 for (unsigned i = 0; i < 4; ++i) { 7676 if (BVN->getOperand(i).isUndef()) 7677 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7678 else if (isNullConstant(BVN->getOperand(i))) 7679 CV[i] = NegOne; 7680 else 7681 CV[i] = One; 7682 } 7683 7684 Constant *CP = ConstantVector::get(CV); 7685 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7686 16 /* alignment */); 7687 7688 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7689 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7690 return DAG.getMemIntrinsicNode( 7691 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7692 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7693 } 7694 7695 SmallVector<SDValue, 4> Stores; 7696 for (unsigned i = 0; i < 4; ++i) { 7697 if (BVN->getOperand(i).isUndef()) continue; 7698 7699 unsigned Offset = 4*i; 7700 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7701 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7702 7703 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7704 if (StoreSize > 4) { 7705 Stores.push_back( 7706 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7707 PtrInfo.getWithOffset(Offset), MVT::i32)); 7708 } else { 7709 SDValue StoreValue = BVN->getOperand(i); 7710 if (StoreSize < 4) 7711 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7712 7713 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7714 PtrInfo.getWithOffset(Offset))); 7715 } 7716 } 7717 7718 SDValue StoreChain; 7719 if (!Stores.empty()) 7720 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7721 else 7722 StoreChain = DAG.getEntryNode(); 7723 7724 // Now load from v4i32 into the QPX register; this will extend it to 7725 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7726 // is typed as v4f64 because the QPX register integer states are not 7727 // explicitly represented. 7728 7729 SDValue Ops[] = {StoreChain, 7730 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7731 FIdx}; 7732 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7733 7734 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 7735 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7736 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7737 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 7738 LoadedVect); 7739 7740 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 7741 7742 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 7743 } 7744 7745 // All other QPX vectors are handled by generic code. 7746 if (Subtarget.hasQPX()) 7747 return SDValue(); 7748 7749 // Check if this is a splat of a constant value. 7750 APInt APSplatBits, APSplatUndef; 7751 unsigned SplatBitSize; 7752 bool HasAnyUndefs; 7753 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 7754 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 7755 SplatBitSize > 32) { 7756 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 7757 // lowered to VSX instructions under certain conditions. 7758 // Without VSX, there is no pattern more efficient than expanding the node. 7759 if (Subtarget.hasVSX() && 7760 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 7761 Subtarget.hasP8Vector())) 7762 return Op; 7763 return SDValue(); 7764 } 7765 7766 unsigned SplatBits = APSplatBits.getZExtValue(); 7767 unsigned SplatUndef = APSplatUndef.getZExtValue(); 7768 unsigned SplatSize = SplatBitSize / 8; 7769 7770 // First, handle single instruction cases. 7771 7772 // All zeros? 7773 if (SplatBits == 0) { 7774 // Canonicalize all zero vectors to be v4i32. 7775 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 7776 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 7777 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 7778 } 7779 return Op; 7780 } 7781 7782 // We have XXSPLTIB for constant splats one byte wide 7783 if (Subtarget.hasP9Vector() && SplatSize == 1) { 7784 // This is a splat of 1-byte elements with some elements potentially undef. 7785 // Rather than trying to match undef in the SDAG patterns, ensure that all 7786 // elements are the same constant. 7787 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 7788 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 7789 dl, MVT::i32)); 7790 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 7791 if (Op.getValueType() != MVT::v16i8) 7792 return DAG.getBitcast(Op.getValueType(), NewBV); 7793 return NewBV; 7794 } 7795 7796 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 7797 // detect that constant splats like v8i16: 0xABAB are really just splats 7798 // of a 1-byte constant. In this case, we need to convert the node to a 7799 // splat of v16i8 and a bitcast. 7800 if (Op.getValueType() != MVT::v16i8) 7801 return DAG.getBitcast(Op.getValueType(), 7802 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 7803 7804 return Op; 7805 } 7806 7807 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 7808 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 7809 (32-SplatBitSize)); 7810 if (SextVal >= -16 && SextVal <= 15) 7811 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 7812 7813 // Two instruction sequences. 7814 7815 // If this value is in the range [-32,30] and is even, use: 7816 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 7817 // If this value is in the range [17,31] and is odd, use: 7818 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 7819 // If this value is in the range [-31,-17] and is odd, use: 7820 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 7821 // Note the last two are three-instruction sequences. 7822 if (SextVal >= -32 && SextVal <= 31) { 7823 // To avoid having these optimizations undone by constant folding, 7824 // we convert to a pseudo that will be expanded later into one of 7825 // the above forms. 7826 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 7827 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 7828 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 7829 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 7830 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 7831 if (VT == Op.getValueType()) 7832 return RetVal; 7833 else 7834 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 7835 } 7836 7837 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 7838 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 7839 // for fneg/fabs. 7840 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 7841 // Make -1 and vspltisw -1: 7842 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 7843 7844 // Make the VSLW intrinsic, computing 0x8000_0000. 7845 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 7846 OnesV, DAG, dl); 7847 7848 // xor by OnesV to invert it. 7849 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 7850 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7851 } 7852 7853 // Check to see if this is a wide variety of vsplti*, binop self cases. 7854 static const signed char SplatCsts[] = { 7855 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 7856 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 7857 }; 7858 7859 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 7860 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 7861 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 7862 int i = SplatCsts[idx]; 7863 7864 // Figure out what shift amount will be used by altivec if shifted by i in 7865 // this splat size. 7866 unsigned TypeShiftAmt = i & (SplatBitSize-1); 7867 7868 // vsplti + shl self. 7869 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 7870 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7871 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7872 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 7873 Intrinsic::ppc_altivec_vslw 7874 }; 7875 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7876 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7877 } 7878 7879 // vsplti + srl self. 7880 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7881 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7882 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7883 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 7884 Intrinsic::ppc_altivec_vsrw 7885 }; 7886 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7887 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7888 } 7889 7890 // vsplti + sra self. 7891 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7892 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7893 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7894 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 7895 Intrinsic::ppc_altivec_vsraw 7896 }; 7897 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7898 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7899 } 7900 7901 // vsplti + rol self. 7902 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 7903 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 7904 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7905 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7906 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 7907 Intrinsic::ppc_altivec_vrlw 7908 }; 7909 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7910 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7911 } 7912 7913 // t = vsplti c, result = vsldoi t, t, 1 7914 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 7915 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7916 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 7917 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7918 } 7919 // t = vsplti c, result = vsldoi t, t, 2 7920 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 7921 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7922 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 7923 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7924 } 7925 // t = vsplti c, result = vsldoi t, t, 3 7926 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 7927 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7928 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 7929 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7930 } 7931 } 7932 7933 return SDValue(); 7934 } 7935 7936 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7937 /// the specified operations to build the shuffle. 7938 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7939 SDValue RHS, SelectionDAG &DAG, 7940 const SDLoc &dl) { 7941 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7942 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7943 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7944 7945 enum { 7946 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7947 OP_VMRGHW, 7948 OP_VMRGLW, 7949 OP_VSPLTISW0, 7950 OP_VSPLTISW1, 7951 OP_VSPLTISW2, 7952 OP_VSPLTISW3, 7953 OP_VSLDOI4, 7954 OP_VSLDOI8, 7955 OP_VSLDOI12 7956 }; 7957 7958 if (OpNum == OP_COPY) { 7959 if (LHSID == (1*9+2)*9+3) return LHS; 7960 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7961 return RHS; 7962 } 7963 7964 SDValue OpLHS, OpRHS; 7965 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7966 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7967 7968 int ShufIdxs[16]; 7969 switch (OpNum) { 7970 default: llvm_unreachable("Unknown i32 permute!"); 7971 case OP_VMRGHW: 7972 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 7973 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 7974 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 7975 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 7976 break; 7977 case OP_VMRGLW: 7978 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 7979 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 7980 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 7981 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 7982 break; 7983 case OP_VSPLTISW0: 7984 for (unsigned i = 0; i != 16; ++i) 7985 ShufIdxs[i] = (i&3)+0; 7986 break; 7987 case OP_VSPLTISW1: 7988 for (unsigned i = 0; i != 16; ++i) 7989 ShufIdxs[i] = (i&3)+4; 7990 break; 7991 case OP_VSPLTISW2: 7992 for (unsigned i = 0; i != 16; ++i) 7993 ShufIdxs[i] = (i&3)+8; 7994 break; 7995 case OP_VSPLTISW3: 7996 for (unsigned i = 0; i != 16; ++i) 7997 ShufIdxs[i] = (i&3)+12; 7998 break; 7999 case OP_VSLDOI4: 8000 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8001 case OP_VSLDOI8: 8002 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8003 case OP_VSLDOI12: 8004 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8005 } 8006 EVT VT = OpLHS.getValueType(); 8007 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8008 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8009 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8010 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8011 } 8012 8013 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8014 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8015 /// SDValue. 8016 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8017 SelectionDAG &DAG) const { 8018 const unsigned BytesInVector = 16; 8019 bool IsLE = Subtarget.isLittleEndian(); 8020 SDLoc dl(N); 8021 SDValue V1 = N->getOperand(0); 8022 SDValue V2 = N->getOperand(1); 8023 unsigned ShiftElts = 0, InsertAtByte = 0; 8024 bool Swap = false; 8025 8026 // Shifts required to get the byte we want at element 7. 8027 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8028 0, 15, 14, 13, 12, 11, 10, 9}; 8029 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8030 1, 2, 3, 4, 5, 6, 7, 8}; 8031 8032 ArrayRef<int> Mask = N->getMask(); 8033 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8034 8035 // For each mask element, find out if we're just inserting something 8036 // from V2 into V1 or vice versa. 8037 // Possible permutations inserting an element from V2 into V1: 8038 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8039 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8040 // ... 8041 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8042 // Inserting from V1 into V2 will be similar, except mask range will be 8043 // [16,31]. 8044 8045 bool FoundCandidate = false; 8046 // If both vector operands for the shuffle are the same vector, the mask 8047 // will contain only elements from the first one and the second one will be 8048 // undef. 8049 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8050 // Go through the mask of half-words to find an element that's being moved 8051 // from one vector to the other. 8052 for (unsigned i = 0; i < BytesInVector; ++i) { 8053 unsigned CurrentElement = Mask[i]; 8054 // If 2nd operand is undefined, we should only look for element 7 in the 8055 // Mask. 8056 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8057 continue; 8058 8059 bool OtherElementsInOrder = true; 8060 // Examine the other elements in the Mask to see if they're in original 8061 // order. 8062 for (unsigned j = 0; j < BytesInVector; ++j) { 8063 if (j == i) 8064 continue; 8065 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8066 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8067 // in which we always assume we're always picking from the 1st operand. 8068 int MaskOffset = 8069 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8070 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8071 OtherElementsInOrder = false; 8072 break; 8073 } 8074 } 8075 // If other elements are in original order, we record the number of shifts 8076 // we need to get the element we want into element 7. Also record which byte 8077 // in the vector we should insert into. 8078 if (OtherElementsInOrder) { 8079 // If 2nd operand is undefined, we assume no shifts and no swapping. 8080 if (V2.isUndef()) { 8081 ShiftElts = 0; 8082 Swap = false; 8083 } else { 8084 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8085 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8086 : BigEndianShifts[CurrentElement & 0xF]; 8087 Swap = CurrentElement < BytesInVector; 8088 } 8089 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8090 FoundCandidate = true; 8091 break; 8092 } 8093 } 8094 8095 if (!FoundCandidate) 8096 return SDValue(); 8097 8098 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8099 // optionally with VECSHL if shift is required. 8100 if (Swap) 8101 std::swap(V1, V2); 8102 if (V2.isUndef()) 8103 V2 = V1; 8104 if (ShiftElts) { 8105 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8106 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8107 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8108 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8109 } 8110 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8111 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8112 } 8113 8114 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8115 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8116 /// SDValue. 8117 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8118 SelectionDAG &DAG) const { 8119 const unsigned NumHalfWords = 8; 8120 const unsigned BytesInVector = NumHalfWords * 2; 8121 // Check that the shuffle is on half-words. 8122 if (!isNByteElemShuffleMask(N, 2, 1)) 8123 return SDValue(); 8124 8125 bool IsLE = Subtarget.isLittleEndian(); 8126 SDLoc dl(N); 8127 SDValue V1 = N->getOperand(0); 8128 SDValue V2 = N->getOperand(1); 8129 unsigned ShiftElts = 0, InsertAtByte = 0; 8130 bool Swap = false; 8131 8132 // Shifts required to get the half-word we want at element 3. 8133 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8134 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8135 8136 uint32_t Mask = 0; 8137 uint32_t OriginalOrderLow = 0x1234567; 8138 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8139 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8140 // 32-bit space, only need 4-bit nibbles per element. 8141 for (unsigned i = 0; i < NumHalfWords; ++i) { 8142 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8143 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8144 } 8145 8146 // For each mask element, find out if we're just inserting something 8147 // from V2 into V1 or vice versa. Possible permutations inserting an element 8148 // from V2 into V1: 8149 // X, 1, 2, 3, 4, 5, 6, 7 8150 // 0, X, 2, 3, 4, 5, 6, 7 8151 // 0, 1, X, 3, 4, 5, 6, 7 8152 // 0, 1, 2, X, 4, 5, 6, 7 8153 // 0, 1, 2, 3, X, 5, 6, 7 8154 // 0, 1, 2, 3, 4, X, 6, 7 8155 // 0, 1, 2, 3, 4, 5, X, 7 8156 // 0, 1, 2, 3, 4, 5, 6, X 8157 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8158 8159 bool FoundCandidate = false; 8160 // Go through the mask of half-words to find an element that's being moved 8161 // from one vector to the other. 8162 for (unsigned i = 0; i < NumHalfWords; ++i) { 8163 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8164 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8165 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8166 uint32_t TargetOrder = 0x0; 8167 8168 // If both vector operands for the shuffle are the same vector, the mask 8169 // will contain only elements from the first one and the second one will be 8170 // undef. 8171 if (V2.isUndef()) { 8172 ShiftElts = 0; 8173 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8174 TargetOrder = OriginalOrderLow; 8175 Swap = false; 8176 // Skip if not the correct element or mask of other elements don't equal 8177 // to our expected order. 8178 if (MaskOneElt == VINSERTHSrcElem && 8179 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8180 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8181 FoundCandidate = true; 8182 break; 8183 } 8184 } else { // If both operands are defined. 8185 // Target order is [8,15] if the current mask is between [0,7]. 8186 TargetOrder = 8187 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8188 // Skip if mask of other elements don't equal our expected order. 8189 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8190 // We only need the last 3 bits for the number of shifts. 8191 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8192 : BigEndianShifts[MaskOneElt & 0x7]; 8193 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8194 Swap = MaskOneElt < NumHalfWords; 8195 FoundCandidate = true; 8196 break; 8197 } 8198 } 8199 } 8200 8201 if (!FoundCandidate) 8202 return SDValue(); 8203 8204 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8205 // optionally with VECSHL if shift is required. 8206 if (Swap) 8207 std::swap(V1, V2); 8208 if (V2.isUndef()) 8209 V2 = V1; 8210 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8211 if (ShiftElts) { 8212 // Double ShiftElts because we're left shifting on v16i8 type. 8213 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8214 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8215 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8216 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8217 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8218 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8219 } 8220 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8221 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8222 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8223 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8224 } 8225 8226 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8227 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8228 /// return the code it can be lowered into. Worst case, it can always be 8229 /// lowered into a vperm. 8230 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8231 SelectionDAG &DAG) const { 8232 SDLoc dl(Op); 8233 SDValue V1 = Op.getOperand(0); 8234 SDValue V2 = Op.getOperand(1); 8235 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8236 EVT VT = Op.getValueType(); 8237 bool isLittleEndian = Subtarget.isLittleEndian(); 8238 8239 unsigned ShiftElts, InsertAtByte; 8240 bool Swap = false; 8241 if (Subtarget.hasP9Vector() && 8242 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8243 isLittleEndian)) { 8244 if (Swap) 8245 std::swap(V1, V2); 8246 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8247 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8248 if (ShiftElts) { 8249 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8250 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8251 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8252 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8253 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8254 } 8255 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8256 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8257 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8258 } 8259 8260 if (Subtarget.hasP9Altivec()) { 8261 SDValue NewISDNode; 8262 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8263 return NewISDNode; 8264 8265 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8266 return NewISDNode; 8267 } 8268 8269 if (Subtarget.hasVSX() && 8270 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8271 if (Swap) 8272 std::swap(V1, V2); 8273 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8274 SDValue Conv2 = 8275 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8276 8277 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8278 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8279 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8280 } 8281 8282 if (Subtarget.hasVSX() && 8283 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8284 if (Swap) 8285 std::swap(V1, V2); 8286 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8287 SDValue Conv2 = 8288 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8289 8290 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8291 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8292 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8293 } 8294 8295 if (Subtarget.hasP9Vector()) { 8296 if (PPC::isXXBRHShuffleMask(SVOp)) { 8297 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8298 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8299 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8300 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8301 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8302 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8303 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8304 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8305 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8306 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8307 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8308 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8309 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8310 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8311 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8312 } 8313 } 8314 8315 if (Subtarget.hasVSX()) { 8316 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8317 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8318 8319 // If the source for the shuffle is a scalar_to_vector that came from a 8320 // 32-bit load, it will have used LXVWSX so we don't need to splat again. 8321 if (Subtarget.hasP9Vector() && 8322 ((isLittleEndian && SplatIdx == 3) || 8323 (!isLittleEndian && SplatIdx == 0))) { 8324 SDValue Src = V1.getOperand(0); 8325 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR && 8326 Src.getOperand(0).getOpcode() == ISD::LOAD && 8327 Src.getOperand(0).hasOneUse()) 8328 return V1; 8329 } 8330 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8331 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8332 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8333 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8334 } 8335 8336 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8337 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8338 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8339 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8340 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8341 } 8342 } 8343 8344 if (Subtarget.hasQPX()) { 8345 if (VT.getVectorNumElements() != 4) 8346 return SDValue(); 8347 8348 if (V2.isUndef()) V2 = V1; 8349 8350 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8351 if (AlignIdx != -1) { 8352 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8353 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8354 } else if (SVOp->isSplat()) { 8355 int SplatIdx = SVOp->getSplatIndex(); 8356 if (SplatIdx >= 4) { 8357 std::swap(V1, V2); 8358 SplatIdx -= 4; 8359 } 8360 8361 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8362 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8363 } 8364 8365 // Lower this into a qvgpci/qvfperm pair. 8366 8367 // Compute the qvgpci literal 8368 unsigned idx = 0; 8369 for (unsigned i = 0; i < 4; ++i) { 8370 int m = SVOp->getMaskElt(i); 8371 unsigned mm = m >= 0 ? (unsigned) m : i; 8372 idx |= mm << (3-i)*3; 8373 } 8374 8375 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8376 DAG.getConstant(idx, dl, MVT::i32)); 8377 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8378 } 8379 8380 // Cases that are handled by instructions that take permute immediates 8381 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8382 // selected by the instruction selector. 8383 if (V2.isUndef()) { 8384 if (PPC::isSplatShuffleMask(SVOp, 1) || 8385 PPC::isSplatShuffleMask(SVOp, 2) || 8386 PPC::isSplatShuffleMask(SVOp, 4) || 8387 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8388 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8389 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8390 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8391 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8392 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8393 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8394 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8395 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8396 (Subtarget.hasP8Altivec() && ( 8397 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8398 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8399 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8400 return Op; 8401 } 8402 } 8403 8404 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8405 // and produce a fixed permutation. If any of these match, do not lower to 8406 // VPERM. 8407 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8408 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8409 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8410 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8411 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8412 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8413 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8414 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8415 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8416 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8417 (Subtarget.hasP8Altivec() && ( 8418 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8419 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8420 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8421 return Op; 8422 8423 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8424 // perfect shuffle table to emit an optimal matching sequence. 8425 ArrayRef<int> PermMask = SVOp->getMask(); 8426 8427 unsigned PFIndexes[4]; 8428 bool isFourElementShuffle = true; 8429 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8430 unsigned EltNo = 8; // Start out undef. 8431 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8432 if (PermMask[i*4+j] < 0) 8433 continue; // Undef, ignore it. 8434 8435 unsigned ByteSource = PermMask[i*4+j]; 8436 if ((ByteSource & 3) != j) { 8437 isFourElementShuffle = false; 8438 break; 8439 } 8440 8441 if (EltNo == 8) { 8442 EltNo = ByteSource/4; 8443 } else if (EltNo != ByteSource/4) { 8444 isFourElementShuffle = false; 8445 break; 8446 } 8447 } 8448 PFIndexes[i] = EltNo; 8449 } 8450 8451 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8452 // perfect shuffle vector to determine if it is cost effective to do this as 8453 // discrete instructions, or whether we should use a vperm. 8454 // For now, we skip this for little endian until such time as we have a 8455 // little-endian perfect shuffle table. 8456 if (isFourElementShuffle && !isLittleEndian) { 8457 // Compute the index in the perfect shuffle table. 8458 unsigned PFTableIndex = 8459 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8460 8461 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8462 unsigned Cost = (PFEntry >> 30); 8463 8464 // Determining when to avoid vperm is tricky. Many things affect the cost 8465 // of vperm, particularly how many times the perm mask needs to be computed. 8466 // For example, if the perm mask can be hoisted out of a loop or is already 8467 // used (perhaps because there are multiple permutes with the same shuffle 8468 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8469 // the loop requires an extra register. 8470 // 8471 // As a compromise, we only emit discrete instructions if the shuffle can be 8472 // generated in 3 or fewer operations. When we have loop information 8473 // available, if this block is within a loop, we should avoid using vperm 8474 // for 3-operation perms and use a constant pool load instead. 8475 if (Cost < 3) 8476 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8477 } 8478 8479 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8480 // vector that will get spilled to the constant pool. 8481 if (V2.isUndef()) V2 = V1; 8482 8483 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8484 // that it is in input element units, not in bytes. Convert now. 8485 8486 // For little endian, the order of the input vectors is reversed, and 8487 // the permutation mask is complemented with respect to 31. This is 8488 // necessary to produce proper semantics with the big-endian-biased vperm 8489 // instruction. 8490 EVT EltVT = V1.getValueType().getVectorElementType(); 8491 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8492 8493 SmallVector<SDValue, 16> ResultMask; 8494 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8495 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8496 8497 for (unsigned j = 0; j != BytesPerElement; ++j) 8498 if (isLittleEndian) 8499 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8500 dl, MVT::i32)); 8501 else 8502 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8503 MVT::i32)); 8504 } 8505 8506 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8507 if (isLittleEndian) 8508 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8509 V2, V1, VPermMask); 8510 else 8511 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8512 V1, V2, VPermMask); 8513 } 8514 8515 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 8516 /// vector comparison. If it is, return true and fill in Opc/isDot with 8517 /// information about the intrinsic. 8518 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 8519 bool &isDot, const PPCSubtarget &Subtarget) { 8520 unsigned IntrinsicID = 8521 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 8522 CompareOpc = -1; 8523 isDot = false; 8524 switch (IntrinsicID) { 8525 default: 8526 return false; 8527 // Comparison predicates. 8528 case Intrinsic::ppc_altivec_vcmpbfp_p: 8529 CompareOpc = 966; 8530 isDot = true; 8531 break; 8532 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8533 CompareOpc = 198; 8534 isDot = true; 8535 break; 8536 case Intrinsic::ppc_altivec_vcmpequb_p: 8537 CompareOpc = 6; 8538 isDot = true; 8539 break; 8540 case Intrinsic::ppc_altivec_vcmpequh_p: 8541 CompareOpc = 70; 8542 isDot = true; 8543 break; 8544 case Intrinsic::ppc_altivec_vcmpequw_p: 8545 CompareOpc = 134; 8546 isDot = true; 8547 break; 8548 case Intrinsic::ppc_altivec_vcmpequd_p: 8549 if (Subtarget.hasP8Altivec()) { 8550 CompareOpc = 199; 8551 isDot = true; 8552 } else 8553 return false; 8554 break; 8555 case Intrinsic::ppc_altivec_vcmpneb_p: 8556 case Intrinsic::ppc_altivec_vcmpneh_p: 8557 case Intrinsic::ppc_altivec_vcmpnew_p: 8558 case Intrinsic::ppc_altivec_vcmpnezb_p: 8559 case Intrinsic::ppc_altivec_vcmpnezh_p: 8560 case Intrinsic::ppc_altivec_vcmpnezw_p: 8561 if (Subtarget.hasP9Altivec()) { 8562 switch (IntrinsicID) { 8563 default: 8564 llvm_unreachable("Unknown comparison intrinsic."); 8565 case Intrinsic::ppc_altivec_vcmpneb_p: 8566 CompareOpc = 7; 8567 break; 8568 case Intrinsic::ppc_altivec_vcmpneh_p: 8569 CompareOpc = 71; 8570 break; 8571 case Intrinsic::ppc_altivec_vcmpnew_p: 8572 CompareOpc = 135; 8573 break; 8574 case Intrinsic::ppc_altivec_vcmpnezb_p: 8575 CompareOpc = 263; 8576 break; 8577 case Intrinsic::ppc_altivec_vcmpnezh_p: 8578 CompareOpc = 327; 8579 break; 8580 case Intrinsic::ppc_altivec_vcmpnezw_p: 8581 CompareOpc = 391; 8582 break; 8583 } 8584 isDot = true; 8585 } else 8586 return false; 8587 break; 8588 case Intrinsic::ppc_altivec_vcmpgefp_p: 8589 CompareOpc = 454; 8590 isDot = true; 8591 break; 8592 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8593 CompareOpc = 710; 8594 isDot = true; 8595 break; 8596 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8597 CompareOpc = 774; 8598 isDot = true; 8599 break; 8600 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8601 CompareOpc = 838; 8602 isDot = true; 8603 break; 8604 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8605 CompareOpc = 902; 8606 isDot = true; 8607 break; 8608 case Intrinsic::ppc_altivec_vcmpgtsd_p: 8609 if (Subtarget.hasP8Altivec()) { 8610 CompareOpc = 967; 8611 isDot = true; 8612 } else 8613 return false; 8614 break; 8615 case Intrinsic::ppc_altivec_vcmpgtub_p: 8616 CompareOpc = 518; 8617 isDot = true; 8618 break; 8619 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8620 CompareOpc = 582; 8621 isDot = true; 8622 break; 8623 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8624 CompareOpc = 646; 8625 isDot = true; 8626 break; 8627 case Intrinsic::ppc_altivec_vcmpgtud_p: 8628 if (Subtarget.hasP8Altivec()) { 8629 CompareOpc = 711; 8630 isDot = true; 8631 } else 8632 return false; 8633 break; 8634 8635 // VSX predicate comparisons use the same infrastructure 8636 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8637 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8638 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8639 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8640 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8641 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8642 if (Subtarget.hasVSX()) { 8643 switch (IntrinsicID) { 8644 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8645 CompareOpc = 99; 8646 break; 8647 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8648 CompareOpc = 115; 8649 break; 8650 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8651 CompareOpc = 107; 8652 break; 8653 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8654 CompareOpc = 67; 8655 break; 8656 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8657 CompareOpc = 83; 8658 break; 8659 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8660 CompareOpc = 75; 8661 break; 8662 } 8663 isDot = true; 8664 } else 8665 return false; 8666 break; 8667 8668 // Normal Comparisons. 8669 case Intrinsic::ppc_altivec_vcmpbfp: 8670 CompareOpc = 966; 8671 break; 8672 case Intrinsic::ppc_altivec_vcmpeqfp: 8673 CompareOpc = 198; 8674 break; 8675 case Intrinsic::ppc_altivec_vcmpequb: 8676 CompareOpc = 6; 8677 break; 8678 case Intrinsic::ppc_altivec_vcmpequh: 8679 CompareOpc = 70; 8680 break; 8681 case Intrinsic::ppc_altivec_vcmpequw: 8682 CompareOpc = 134; 8683 break; 8684 case Intrinsic::ppc_altivec_vcmpequd: 8685 if (Subtarget.hasP8Altivec()) 8686 CompareOpc = 199; 8687 else 8688 return false; 8689 break; 8690 case Intrinsic::ppc_altivec_vcmpneb: 8691 case Intrinsic::ppc_altivec_vcmpneh: 8692 case Intrinsic::ppc_altivec_vcmpnew: 8693 case Intrinsic::ppc_altivec_vcmpnezb: 8694 case Intrinsic::ppc_altivec_vcmpnezh: 8695 case Intrinsic::ppc_altivec_vcmpnezw: 8696 if (Subtarget.hasP9Altivec()) 8697 switch (IntrinsicID) { 8698 default: 8699 llvm_unreachable("Unknown comparison intrinsic."); 8700 case Intrinsic::ppc_altivec_vcmpneb: 8701 CompareOpc = 7; 8702 break; 8703 case Intrinsic::ppc_altivec_vcmpneh: 8704 CompareOpc = 71; 8705 break; 8706 case Intrinsic::ppc_altivec_vcmpnew: 8707 CompareOpc = 135; 8708 break; 8709 case Intrinsic::ppc_altivec_vcmpnezb: 8710 CompareOpc = 263; 8711 break; 8712 case Intrinsic::ppc_altivec_vcmpnezh: 8713 CompareOpc = 327; 8714 break; 8715 case Intrinsic::ppc_altivec_vcmpnezw: 8716 CompareOpc = 391; 8717 break; 8718 } 8719 else 8720 return false; 8721 break; 8722 case Intrinsic::ppc_altivec_vcmpgefp: 8723 CompareOpc = 454; 8724 break; 8725 case Intrinsic::ppc_altivec_vcmpgtfp: 8726 CompareOpc = 710; 8727 break; 8728 case Intrinsic::ppc_altivec_vcmpgtsb: 8729 CompareOpc = 774; 8730 break; 8731 case Intrinsic::ppc_altivec_vcmpgtsh: 8732 CompareOpc = 838; 8733 break; 8734 case Intrinsic::ppc_altivec_vcmpgtsw: 8735 CompareOpc = 902; 8736 break; 8737 case Intrinsic::ppc_altivec_vcmpgtsd: 8738 if (Subtarget.hasP8Altivec()) 8739 CompareOpc = 967; 8740 else 8741 return false; 8742 break; 8743 case Intrinsic::ppc_altivec_vcmpgtub: 8744 CompareOpc = 518; 8745 break; 8746 case Intrinsic::ppc_altivec_vcmpgtuh: 8747 CompareOpc = 582; 8748 break; 8749 case Intrinsic::ppc_altivec_vcmpgtuw: 8750 CompareOpc = 646; 8751 break; 8752 case Intrinsic::ppc_altivec_vcmpgtud: 8753 if (Subtarget.hasP8Altivec()) 8754 CompareOpc = 711; 8755 else 8756 return false; 8757 break; 8758 } 8759 return true; 8760 } 8761 8762 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 8763 /// lower, do it, otherwise return null. 8764 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 8765 SelectionDAG &DAG) const { 8766 unsigned IntrinsicID = 8767 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8768 8769 SDLoc dl(Op); 8770 8771 if (IntrinsicID == Intrinsic::thread_pointer) { 8772 // Reads the thread pointer register, used for __builtin_thread_pointer. 8773 if (Subtarget.isPPC64()) 8774 return DAG.getRegister(PPC::X13, MVT::i64); 8775 return DAG.getRegister(PPC::R2, MVT::i32); 8776 } 8777 8778 // We are looking for absolute values here. 8779 // The idea is to try to fit one of two patterns: 8780 // max (a, (0-a)) OR max ((0-a), a) 8781 if (Subtarget.hasP9Vector() && 8782 (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw || 8783 IntrinsicID == Intrinsic::ppc_altivec_vmaxsh || 8784 IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) { 8785 SDValue V1 = Op.getOperand(1); 8786 SDValue V2 = Op.getOperand(2); 8787 if (V1.getSimpleValueType() == V2.getSimpleValueType() && 8788 (V1.getSimpleValueType() == MVT::v4i32 || 8789 V1.getSimpleValueType() == MVT::v8i16 || 8790 V1.getSimpleValueType() == MVT::v16i8)) { 8791 if ( V1.getOpcode() == ISD::SUB && 8792 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 8793 V1.getOperand(1) == V2 ) { 8794 // Generate the abs instruction with the operands 8795 return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2); 8796 } 8797 8798 if ( V2.getOpcode() == ISD::SUB && 8799 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 8800 V2.getOperand(1) == V1 ) { 8801 // Generate the abs instruction with the operands 8802 return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1); 8803 } 8804 } 8805 } 8806 8807 // If this is a lowered altivec predicate compare, CompareOpc is set to the 8808 // opcode number of the comparison. 8809 int CompareOpc; 8810 bool isDot; 8811 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 8812 return SDValue(); // Don't custom lower most intrinsics. 8813 8814 // If this is a non-dot comparison, make the VCMP node and we are done. 8815 if (!isDot) { 8816 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 8817 Op.getOperand(1), Op.getOperand(2), 8818 DAG.getConstant(CompareOpc, dl, MVT::i32)); 8819 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 8820 } 8821 8822 // Create the PPCISD altivec 'dot' comparison node. 8823 SDValue Ops[] = { 8824 Op.getOperand(2), // LHS 8825 Op.getOperand(3), // RHS 8826 DAG.getConstant(CompareOpc, dl, MVT::i32) 8827 }; 8828 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 8829 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 8830 8831 // Now that we have the comparison, emit a copy from the CR to a GPR. 8832 // This is flagged to the above dot comparison. 8833 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 8834 DAG.getRegister(PPC::CR6, MVT::i32), 8835 CompNode.getValue(1)); 8836 8837 // Unpack the result based on how the target uses it. 8838 unsigned BitNo; // Bit # of CR6. 8839 bool InvertBit; // Invert result? 8840 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 8841 default: // Can't happen, don't crash on invalid number though. 8842 case 0: // Return the value of the EQ bit of CR6. 8843 BitNo = 0; InvertBit = false; 8844 break; 8845 case 1: // Return the inverted value of the EQ bit of CR6. 8846 BitNo = 0; InvertBit = true; 8847 break; 8848 case 2: // Return the value of the LT bit of CR6. 8849 BitNo = 2; InvertBit = false; 8850 break; 8851 case 3: // Return the inverted value of the LT bit of CR6. 8852 BitNo = 2; InvertBit = true; 8853 break; 8854 } 8855 8856 // Shift the bit into the low position. 8857 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 8858 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 8859 // Isolate the bit. 8860 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 8861 DAG.getConstant(1, dl, MVT::i32)); 8862 8863 // If we are supposed to, toggle the bit. 8864 if (InvertBit) 8865 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 8866 DAG.getConstant(1, dl, MVT::i32)); 8867 return Flags; 8868 } 8869 8870 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 8871 SelectionDAG &DAG) const { 8872 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 8873 // the beginning of the argument list. 8874 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 8875 SDLoc DL(Op); 8876 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 8877 case Intrinsic::ppc_cfence: { 8878 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 8879 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 8880 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 8881 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 8882 Op.getOperand(ArgStart + 1)), 8883 Op.getOperand(0)), 8884 0); 8885 } 8886 default: 8887 break; 8888 } 8889 return SDValue(); 8890 } 8891 8892 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 8893 // Check for a DIV with the same operands as this REM. 8894 for (auto UI : Op.getOperand(1)->uses()) { 8895 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 8896 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 8897 if (UI->getOperand(0) == Op.getOperand(0) && 8898 UI->getOperand(1) == Op.getOperand(1)) 8899 return SDValue(); 8900 } 8901 return Op; 8902 } 8903 8904 // Lower scalar BSWAP64 to xxbrd. 8905 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 8906 SDLoc dl(Op); 8907 // MTVSRDD 8908 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 8909 Op.getOperand(0)); 8910 // XXBRD 8911 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 8912 // MFVSRD 8913 int VectorIndex = 0; 8914 if (Subtarget.isLittleEndian()) 8915 VectorIndex = 1; 8916 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 8917 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 8918 return Op; 8919 } 8920 8921 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 8922 // compared to a value that is atomically loaded (atomic loads zero-extend). 8923 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 8924 SelectionDAG &DAG) const { 8925 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 8926 "Expecting an atomic compare-and-swap here."); 8927 SDLoc dl(Op); 8928 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 8929 EVT MemVT = AtomicNode->getMemoryVT(); 8930 if (MemVT.getSizeInBits() >= 32) 8931 return Op; 8932 8933 SDValue CmpOp = Op.getOperand(2); 8934 // If this is already correctly zero-extended, leave it alone. 8935 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 8936 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 8937 return Op; 8938 8939 // Clear the high bits of the compare operand. 8940 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 8941 SDValue NewCmpOp = 8942 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 8943 DAG.getConstant(MaskVal, dl, MVT::i32)); 8944 8945 // Replace the existing compare operand with the properly zero-extended one. 8946 SmallVector<SDValue, 4> Ops; 8947 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 8948 Ops.push_back(AtomicNode->getOperand(i)); 8949 Ops[2] = NewCmpOp; 8950 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 8951 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 8952 auto NodeTy = 8953 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 8954 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 8955 } 8956 8957 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 8958 SelectionDAG &DAG) const { 8959 SDLoc dl(Op); 8960 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int 8961 // instructions), but for smaller types, we need to first extend up to v2i32 8962 // before doing going farther. 8963 if (Op.getValueType() == MVT::v2i64) { 8964 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 8965 if (ExtVT != MVT::v2i32) { 8966 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)); 8967 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op, 8968 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(), 8969 ExtVT.getVectorElementType(), 4))); 8970 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op); 8971 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op, 8972 DAG.getValueType(MVT::v2i32)); 8973 } 8974 8975 return Op; 8976 } 8977 8978 return SDValue(); 8979 } 8980 8981 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 8982 SelectionDAG &DAG) const { 8983 SDLoc dl(Op); 8984 // Create a stack slot that is 16-byte aligned. 8985 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8986 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8987 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8988 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8989 8990 // Store the input value into Value#0 of the stack slot. 8991 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8992 MachinePointerInfo()); 8993 // Load it out. 8994 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 8995 } 8996 8997 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8998 SelectionDAG &DAG) const { 8999 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9000 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9001 9002 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9003 // We have legal lowering for constant indices but not for variable ones. 9004 if (!C) 9005 return SDValue(); 9006 9007 EVT VT = Op.getValueType(); 9008 SDLoc dl(Op); 9009 SDValue V1 = Op.getOperand(0); 9010 SDValue V2 = Op.getOperand(1); 9011 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9012 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9013 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9014 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9015 unsigned InsertAtElement = C->getZExtValue(); 9016 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9017 if (Subtarget.isLittleEndian()) { 9018 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9019 } 9020 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9021 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9022 } 9023 return Op; 9024 } 9025 9026 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9027 SelectionDAG &DAG) const { 9028 SDLoc dl(Op); 9029 SDNode *N = Op.getNode(); 9030 9031 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9032 "Unknown extract_vector_elt type"); 9033 9034 SDValue Value = N->getOperand(0); 9035 9036 // The first part of this is like the store lowering except that we don't 9037 // need to track the chain. 9038 9039 // The values are now known to be -1 (false) or 1 (true). To convert this 9040 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9041 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9042 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9043 9044 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9045 // understand how to form the extending load. 9046 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9047 9048 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9049 9050 // Now convert to an integer and store. 9051 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9052 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9053 Value); 9054 9055 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9056 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9057 MachinePointerInfo PtrInfo = 9058 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9059 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9060 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9061 9062 SDValue StoreChain = DAG.getEntryNode(); 9063 SDValue Ops[] = {StoreChain, 9064 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9065 Value, FIdx}; 9066 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9067 9068 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9069 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9070 9071 // Extract the value requested. 9072 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9073 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9074 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9075 9076 SDValue IntVal = 9077 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9078 9079 if (!Subtarget.useCRBits()) 9080 return IntVal; 9081 9082 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9083 } 9084 9085 /// Lowering for QPX v4i1 loads 9086 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9087 SelectionDAG &DAG) const { 9088 SDLoc dl(Op); 9089 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9090 SDValue LoadChain = LN->getChain(); 9091 SDValue BasePtr = LN->getBasePtr(); 9092 9093 if (Op.getValueType() == MVT::v4f64 || 9094 Op.getValueType() == MVT::v4f32) { 9095 EVT MemVT = LN->getMemoryVT(); 9096 unsigned Alignment = LN->getAlignment(); 9097 9098 // If this load is properly aligned, then it is legal. 9099 if (Alignment >= MemVT.getStoreSize()) 9100 return Op; 9101 9102 EVT ScalarVT = Op.getValueType().getScalarType(), 9103 ScalarMemVT = MemVT.getScalarType(); 9104 unsigned Stride = ScalarMemVT.getStoreSize(); 9105 9106 SDValue Vals[4], LoadChains[4]; 9107 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9108 SDValue Load; 9109 if (ScalarVT != ScalarMemVT) 9110 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9111 BasePtr, 9112 LN->getPointerInfo().getWithOffset(Idx * Stride), 9113 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9114 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9115 else 9116 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9117 LN->getPointerInfo().getWithOffset(Idx * Stride), 9118 MinAlign(Alignment, Idx * Stride), 9119 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9120 9121 if (Idx == 0 && LN->isIndexed()) { 9122 assert(LN->getAddressingMode() == ISD::PRE_INC && 9123 "Unknown addressing mode on vector load"); 9124 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9125 LN->getAddressingMode()); 9126 } 9127 9128 Vals[Idx] = Load; 9129 LoadChains[Idx] = Load.getValue(1); 9130 9131 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9132 DAG.getConstant(Stride, dl, 9133 BasePtr.getValueType())); 9134 } 9135 9136 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9137 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9138 9139 if (LN->isIndexed()) { 9140 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9141 return DAG.getMergeValues(RetOps, dl); 9142 } 9143 9144 SDValue RetOps[] = { Value, TF }; 9145 return DAG.getMergeValues(RetOps, dl); 9146 } 9147 9148 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9149 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9150 9151 // To lower v4i1 from a byte array, we load the byte elements of the 9152 // vector and then reuse the BUILD_VECTOR logic. 9153 9154 SDValue VectElmts[4], VectElmtChains[4]; 9155 for (unsigned i = 0; i < 4; ++i) { 9156 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9157 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9158 9159 VectElmts[i] = DAG.getExtLoad( 9160 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9161 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9162 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9163 VectElmtChains[i] = VectElmts[i].getValue(1); 9164 } 9165 9166 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9167 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9168 9169 SDValue RVals[] = { Value, LoadChain }; 9170 return DAG.getMergeValues(RVals, dl); 9171 } 9172 9173 /// Lowering for QPX v4i1 stores 9174 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9175 SelectionDAG &DAG) const { 9176 SDLoc dl(Op); 9177 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9178 SDValue StoreChain = SN->getChain(); 9179 SDValue BasePtr = SN->getBasePtr(); 9180 SDValue Value = SN->getValue(); 9181 9182 if (Value.getValueType() == MVT::v4f64 || 9183 Value.getValueType() == MVT::v4f32) { 9184 EVT MemVT = SN->getMemoryVT(); 9185 unsigned Alignment = SN->getAlignment(); 9186 9187 // If this store is properly aligned, then it is legal. 9188 if (Alignment >= MemVT.getStoreSize()) 9189 return Op; 9190 9191 EVT ScalarVT = Value.getValueType().getScalarType(), 9192 ScalarMemVT = MemVT.getScalarType(); 9193 unsigned Stride = ScalarMemVT.getStoreSize(); 9194 9195 SDValue Stores[4]; 9196 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9197 SDValue Ex = DAG.getNode( 9198 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9199 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9200 SDValue Store; 9201 if (ScalarVT != ScalarMemVT) 9202 Store = 9203 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9204 SN->getPointerInfo().getWithOffset(Idx * Stride), 9205 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9206 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9207 else 9208 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9209 SN->getPointerInfo().getWithOffset(Idx * Stride), 9210 MinAlign(Alignment, Idx * Stride), 9211 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9212 9213 if (Idx == 0 && SN->isIndexed()) { 9214 assert(SN->getAddressingMode() == ISD::PRE_INC && 9215 "Unknown addressing mode on vector store"); 9216 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9217 SN->getAddressingMode()); 9218 } 9219 9220 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9221 DAG.getConstant(Stride, dl, 9222 BasePtr.getValueType())); 9223 Stores[Idx] = Store; 9224 } 9225 9226 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9227 9228 if (SN->isIndexed()) { 9229 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9230 return DAG.getMergeValues(RetOps, dl); 9231 } 9232 9233 return TF; 9234 } 9235 9236 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9237 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9238 9239 // The values are now known to be -1 (false) or 1 (true). To convert this 9240 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9241 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9242 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9243 9244 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9245 // understand how to form the extending load. 9246 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9247 9248 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9249 9250 // Now convert to an integer and store. 9251 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9252 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9253 Value); 9254 9255 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9256 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9257 MachinePointerInfo PtrInfo = 9258 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9259 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9260 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9261 9262 SDValue Ops[] = {StoreChain, 9263 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9264 Value, FIdx}; 9265 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9266 9267 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9268 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9269 9270 // Move data into the byte array. 9271 SDValue Loads[4], LoadChains[4]; 9272 for (unsigned i = 0; i < 4; ++i) { 9273 unsigned Offset = 4*i; 9274 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9275 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9276 9277 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9278 PtrInfo.getWithOffset(Offset)); 9279 LoadChains[i] = Loads[i].getValue(1); 9280 } 9281 9282 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9283 9284 SDValue Stores[4]; 9285 for (unsigned i = 0; i < 4; ++i) { 9286 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9287 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9288 9289 Stores[i] = DAG.getTruncStore( 9290 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9291 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9292 SN->getAAInfo()); 9293 } 9294 9295 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9296 9297 return StoreChain; 9298 } 9299 9300 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9301 SDLoc dl(Op); 9302 if (Op.getValueType() == MVT::v4i32) { 9303 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9304 9305 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9306 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9307 9308 SDValue RHSSwap = // = vrlw RHS, 16 9309 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9310 9311 // Shrinkify inputs to v8i16. 9312 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9313 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9314 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9315 9316 // Low parts multiplied together, generating 32-bit results (we ignore the 9317 // top parts). 9318 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9319 LHS, RHS, DAG, dl, MVT::v4i32); 9320 9321 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9322 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9323 // Shift the high parts up 16 bits. 9324 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9325 Neg16, DAG, dl); 9326 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9327 } else if (Op.getValueType() == MVT::v8i16) { 9328 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9329 9330 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9331 9332 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9333 LHS, RHS, Zero, DAG, dl); 9334 } else if (Op.getValueType() == MVT::v16i8) { 9335 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9336 bool isLittleEndian = Subtarget.isLittleEndian(); 9337 9338 // Multiply the even 8-bit parts, producing 16-bit sums. 9339 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9340 LHS, RHS, DAG, dl, MVT::v8i16); 9341 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9342 9343 // Multiply the odd 8-bit parts, producing 16-bit sums. 9344 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9345 LHS, RHS, DAG, dl, MVT::v8i16); 9346 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9347 9348 // Merge the results together. Because vmuleub and vmuloub are 9349 // instructions with a big-endian bias, we must reverse the 9350 // element numbering and reverse the meaning of "odd" and "even" 9351 // when generating little endian code. 9352 int Ops[16]; 9353 for (unsigned i = 0; i != 8; ++i) { 9354 if (isLittleEndian) { 9355 Ops[i*2 ] = 2*i; 9356 Ops[i*2+1] = 2*i+16; 9357 } else { 9358 Ops[i*2 ] = 2*i+1; 9359 Ops[i*2+1] = 2*i+1+16; 9360 } 9361 } 9362 if (isLittleEndian) 9363 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9364 else 9365 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9366 } else { 9367 llvm_unreachable("Unknown mul to lower!"); 9368 } 9369 } 9370 9371 /// LowerOperation - Provide custom lowering hooks for some operations. 9372 /// 9373 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9374 switch (Op.getOpcode()) { 9375 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9376 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9377 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9378 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9379 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9380 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9381 case ISD::SETCC: return LowerSETCC(Op, DAG); 9382 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9383 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9384 9385 // Variable argument lowering. 9386 case ISD::VASTART: return LowerVASTART(Op, DAG); 9387 case ISD::VAARG: return LowerVAARG(Op, DAG); 9388 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9389 9390 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 9391 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9392 case ISD::GET_DYNAMIC_AREA_OFFSET: 9393 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9394 9395 // Exception handling lowering. 9396 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 9397 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9398 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9399 9400 case ISD::LOAD: return LowerLOAD(Op, DAG); 9401 case ISD::STORE: return LowerSTORE(Op, DAG); 9402 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9403 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9404 case ISD::FP_TO_UINT: 9405 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 9406 case ISD::UINT_TO_FP: 9407 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9408 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9409 9410 // Lower 64-bit shifts. 9411 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9412 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9413 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9414 9415 // Vector-related lowering. 9416 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9417 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9418 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9419 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9420 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG); 9421 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9422 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9423 case ISD::MUL: return LowerMUL(Op, DAG); 9424 9425 // For counter-based loop handling. 9426 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9427 9428 // Frame & Return address. 9429 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9430 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9431 9432 case ISD::INTRINSIC_VOID: 9433 return LowerINTRINSIC_VOID(Op, DAG); 9434 case ISD::SREM: 9435 case ISD::UREM: 9436 return LowerREM(Op, DAG); 9437 case ISD::BSWAP: 9438 return LowerBSWAP(Op, DAG); 9439 case ISD::ATOMIC_CMP_SWAP: 9440 return LowerATOMIC_CMP_SWAP(Op, DAG); 9441 } 9442 } 9443 9444 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9445 SmallVectorImpl<SDValue>&Results, 9446 SelectionDAG &DAG) const { 9447 SDLoc dl(N); 9448 switch (N->getOpcode()) { 9449 default: 9450 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9451 case ISD::READCYCLECOUNTER: { 9452 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9453 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9454 9455 Results.push_back(RTB); 9456 Results.push_back(RTB.getValue(1)); 9457 Results.push_back(RTB.getValue(2)); 9458 break; 9459 } 9460 case ISD::INTRINSIC_W_CHAIN: { 9461 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9462 Intrinsic::ppc_is_decremented_ctr_nonzero) 9463 break; 9464 9465 assert(N->getValueType(0) == MVT::i1 && 9466 "Unexpected result type for CTR decrement intrinsic"); 9467 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9468 N->getValueType(0)); 9469 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9470 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9471 N->getOperand(1)); 9472 9473 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 9474 Results.push_back(NewInt.getValue(1)); 9475 break; 9476 } 9477 case ISD::VAARG: { 9478 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 9479 return; 9480 9481 EVT VT = N->getValueType(0); 9482 9483 if (VT == MVT::i64) { 9484 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 9485 9486 Results.push_back(NewNode); 9487 Results.push_back(NewNode.getValue(1)); 9488 } 9489 return; 9490 } 9491 case ISD::FP_TO_SINT: 9492 case ISD::FP_TO_UINT: 9493 // LowerFP_TO_INT() can only handle f32 and f64. 9494 if (N->getOperand(0).getValueType() == MVT::ppcf128) 9495 return; 9496 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 9497 return; 9498 } 9499 } 9500 9501 //===----------------------------------------------------------------------===// 9502 // Other Lowering Code 9503 //===----------------------------------------------------------------------===// 9504 9505 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 9506 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9507 Function *Func = Intrinsic::getDeclaration(M, Id); 9508 return Builder.CreateCall(Func, {}); 9509 } 9510 9511 // The mappings for emitLeading/TrailingFence is taken from 9512 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 9513 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 9514 Instruction *Inst, 9515 AtomicOrdering Ord) const { 9516 if (Ord == AtomicOrdering::SequentiallyConsistent) 9517 return callIntrinsic(Builder, Intrinsic::ppc_sync); 9518 if (isReleaseOrStronger(Ord)) 9519 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9520 return nullptr; 9521 } 9522 9523 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 9524 Instruction *Inst, 9525 AtomicOrdering Ord) const { 9526 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 9527 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 9528 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 9529 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 9530 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 9531 return Builder.CreateCall( 9532 Intrinsic::getDeclaration( 9533 Builder.GetInsertBlock()->getParent()->getParent(), 9534 Intrinsic::ppc_cfence, {Inst->getType()}), 9535 {Inst}); 9536 // FIXME: Can use isync for rmw operation. 9537 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9538 } 9539 return nullptr; 9540 } 9541 9542 MachineBasicBlock * 9543 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 9544 unsigned AtomicSize, 9545 unsigned BinOpcode, 9546 unsigned CmpOpcode, 9547 unsigned CmpPred) const { 9548 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9549 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9550 9551 auto LoadMnemonic = PPC::LDARX; 9552 auto StoreMnemonic = PPC::STDCX; 9553 switch (AtomicSize) { 9554 default: 9555 llvm_unreachable("Unexpected size of atomic entity"); 9556 case 1: 9557 LoadMnemonic = PPC::LBARX; 9558 StoreMnemonic = PPC::STBCX; 9559 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9560 break; 9561 case 2: 9562 LoadMnemonic = PPC::LHARX; 9563 StoreMnemonic = PPC::STHCX; 9564 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9565 break; 9566 case 4: 9567 LoadMnemonic = PPC::LWARX; 9568 StoreMnemonic = PPC::STWCX; 9569 break; 9570 case 8: 9571 LoadMnemonic = PPC::LDARX; 9572 StoreMnemonic = PPC::STDCX; 9573 break; 9574 } 9575 9576 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9577 MachineFunction *F = BB->getParent(); 9578 MachineFunction::iterator It = ++BB->getIterator(); 9579 9580 unsigned dest = MI.getOperand(0).getReg(); 9581 unsigned ptrA = MI.getOperand(1).getReg(); 9582 unsigned ptrB = MI.getOperand(2).getReg(); 9583 unsigned incr = MI.getOperand(3).getReg(); 9584 DebugLoc dl = MI.getDebugLoc(); 9585 9586 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9587 MachineBasicBlock *loop2MBB = 9588 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9589 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9590 F->insert(It, loopMBB); 9591 if (CmpOpcode) 9592 F->insert(It, loop2MBB); 9593 F->insert(It, exitMBB); 9594 exitMBB->splice(exitMBB->begin(), BB, 9595 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9596 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9597 9598 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9599 unsigned TmpReg = (!BinOpcode) ? incr : 9600 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 9601 : &PPC::GPRCRegClass); 9602 9603 // thisMBB: 9604 // ... 9605 // fallthrough --> loopMBB 9606 BB->addSuccessor(loopMBB); 9607 9608 // loopMBB: 9609 // l[wd]arx dest, ptr 9610 // add r0, dest, incr 9611 // st[wd]cx. r0, ptr 9612 // bne- loopMBB 9613 // fallthrough --> exitMBB 9614 9615 // For max/min... 9616 // loopMBB: 9617 // l[wd]arx dest, ptr 9618 // cmpl?[wd] incr, dest 9619 // bgt exitMBB 9620 // loop2MBB: 9621 // st[wd]cx. dest, ptr 9622 // bne- loopMBB 9623 // fallthrough --> exitMBB 9624 9625 BB = loopMBB; 9626 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9627 .addReg(ptrA).addReg(ptrB); 9628 if (BinOpcode) 9629 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 9630 if (CmpOpcode) { 9631 // Signed comparisons of byte or halfword values must be sign-extended. 9632 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 9633 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9634 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 9635 ExtReg).addReg(dest); 9636 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9637 .addReg(incr).addReg(ExtReg); 9638 } else 9639 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9640 .addReg(incr).addReg(dest); 9641 9642 BuildMI(BB, dl, TII->get(PPC::BCC)) 9643 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9644 BB->addSuccessor(loop2MBB); 9645 BB->addSuccessor(exitMBB); 9646 BB = loop2MBB; 9647 } 9648 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9649 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 9650 BuildMI(BB, dl, TII->get(PPC::BCC)) 9651 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9652 BB->addSuccessor(loopMBB); 9653 BB->addSuccessor(exitMBB); 9654 9655 // exitMBB: 9656 // ... 9657 BB = exitMBB; 9658 return BB; 9659 } 9660 9661 MachineBasicBlock * 9662 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI, 9663 MachineBasicBlock *BB, 9664 bool is8bit, // operation 9665 unsigned BinOpcode, 9666 unsigned CmpOpcode, 9667 unsigned CmpPred) const { 9668 // If we support part-word atomic mnemonics, just use them 9669 if (Subtarget.hasPartwordAtomics()) 9670 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, 9671 CmpOpcode, CmpPred); 9672 9673 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9674 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9675 // In 64 bit mode we have to use 64 bits for addresses, even though the 9676 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 9677 // registers without caring whether they're 32 or 64, but here we're 9678 // doing actual arithmetic on the addresses. 9679 bool is64bit = Subtarget.isPPC64(); 9680 bool isLittleEndian = Subtarget.isLittleEndian(); 9681 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9682 9683 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9684 MachineFunction *F = BB->getParent(); 9685 MachineFunction::iterator It = ++BB->getIterator(); 9686 9687 unsigned dest = MI.getOperand(0).getReg(); 9688 unsigned ptrA = MI.getOperand(1).getReg(); 9689 unsigned ptrB = MI.getOperand(2).getReg(); 9690 unsigned incr = MI.getOperand(3).getReg(); 9691 DebugLoc dl = MI.getDebugLoc(); 9692 9693 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9694 MachineBasicBlock *loop2MBB = 9695 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9696 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9697 F->insert(It, loopMBB); 9698 if (CmpOpcode) 9699 F->insert(It, loop2MBB); 9700 F->insert(It, exitMBB); 9701 exitMBB->splice(exitMBB->begin(), BB, 9702 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9703 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9704 9705 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9706 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 9707 : &PPC::GPRCRegClass; 9708 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9709 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 9710 unsigned ShiftReg = 9711 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 9712 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 9713 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 9714 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 9715 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 9716 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 9717 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 9718 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 9719 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 9720 unsigned Ptr1Reg; 9721 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 9722 9723 // thisMBB: 9724 // ... 9725 // fallthrough --> loopMBB 9726 BB->addSuccessor(loopMBB); 9727 9728 // The 4-byte load must be aligned, while a char or short may be 9729 // anywhere in the word. Hence all this nasty bookkeeping code. 9730 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9731 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9732 // xori shift, shift1, 24 [16] 9733 // rlwinm ptr, ptr1, 0, 0, 29 9734 // slw incr2, incr, shift 9735 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9736 // slw mask, mask2, shift 9737 // loopMBB: 9738 // lwarx tmpDest, ptr 9739 // add tmp, tmpDest, incr2 9740 // andc tmp2, tmpDest, mask 9741 // and tmp3, tmp, mask 9742 // or tmp4, tmp3, tmp2 9743 // stwcx. tmp4, ptr 9744 // bne- loopMBB 9745 // fallthrough --> exitMBB 9746 // srw dest, tmpDest, shift 9747 if (ptrA != ZeroReg) { 9748 Ptr1Reg = RegInfo.createVirtualRegister(RC); 9749 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 9750 .addReg(ptrA).addReg(ptrB); 9751 } else { 9752 Ptr1Reg = ptrB; 9753 } 9754 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 9755 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 9756 if (!isLittleEndian) 9757 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 9758 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 9759 if (is64bit) 9760 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 9761 .addReg(Ptr1Reg).addImm(0).addImm(61); 9762 else 9763 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 9764 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 9765 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 9766 .addReg(incr).addReg(ShiftReg); 9767 if (is8bit) 9768 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 9769 else { 9770 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 9771 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 9772 } 9773 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 9774 .addReg(Mask2Reg).addReg(ShiftReg); 9775 9776 BB = loopMBB; 9777 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 9778 .addReg(ZeroReg).addReg(PtrReg); 9779 if (BinOpcode) 9780 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 9781 .addReg(Incr2Reg).addReg(TmpDestReg); 9782 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 9783 .addReg(TmpDestReg).addReg(MaskReg); 9784 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 9785 .addReg(TmpReg).addReg(MaskReg); 9786 if (CmpOpcode) { 9787 // For unsigned comparisons, we can directly compare the shifted values. 9788 // For signed comparisons we shift and sign extend. 9789 unsigned SReg = RegInfo.createVirtualRegister(RC); 9790 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg) 9791 .addReg(TmpDestReg).addReg(MaskReg); 9792 unsigned ValueReg = SReg; 9793 unsigned CmpReg = Incr2Reg; 9794 if (CmpOpcode == PPC::CMPW) { 9795 ValueReg = RegInfo.createVirtualRegister(RC); 9796 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 9797 .addReg(SReg).addReg(ShiftReg); 9798 unsigned ValueSReg = RegInfo.createVirtualRegister(RC); 9799 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 9800 .addReg(ValueReg); 9801 ValueReg = ValueSReg; 9802 CmpReg = incr; 9803 } 9804 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9805 .addReg(CmpReg).addReg(ValueReg); 9806 BuildMI(BB, dl, TII->get(PPC::BCC)) 9807 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9808 BB->addSuccessor(loop2MBB); 9809 BB->addSuccessor(exitMBB); 9810 BB = loop2MBB; 9811 } 9812 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 9813 .addReg(Tmp3Reg).addReg(Tmp2Reg); 9814 BuildMI(BB, dl, TII->get(PPC::STWCX)) 9815 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 9816 BuildMI(BB, dl, TII->get(PPC::BCC)) 9817 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9818 BB->addSuccessor(loopMBB); 9819 BB->addSuccessor(exitMBB); 9820 9821 // exitMBB: 9822 // ... 9823 BB = exitMBB; 9824 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 9825 .addReg(ShiftReg); 9826 return BB; 9827 } 9828 9829 llvm::MachineBasicBlock * 9830 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 9831 MachineBasicBlock *MBB) const { 9832 DebugLoc DL = MI.getDebugLoc(); 9833 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9834 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9835 9836 MachineFunction *MF = MBB->getParent(); 9837 MachineRegisterInfo &MRI = MF->getRegInfo(); 9838 9839 const BasicBlock *BB = MBB->getBasicBlock(); 9840 MachineFunction::iterator I = ++MBB->getIterator(); 9841 9842 // Memory Reference 9843 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9844 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9845 9846 unsigned DstReg = MI.getOperand(0).getReg(); 9847 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 9848 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 9849 unsigned mainDstReg = MRI.createVirtualRegister(RC); 9850 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 9851 9852 MVT PVT = getPointerTy(MF->getDataLayout()); 9853 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9854 "Invalid Pointer Size!"); 9855 // For v = setjmp(buf), we generate 9856 // 9857 // thisMBB: 9858 // SjLjSetup mainMBB 9859 // bl mainMBB 9860 // v_restore = 1 9861 // b sinkMBB 9862 // 9863 // mainMBB: 9864 // buf[LabelOffset] = LR 9865 // v_main = 0 9866 // 9867 // sinkMBB: 9868 // v = phi(main, restore) 9869 // 9870 9871 MachineBasicBlock *thisMBB = MBB; 9872 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 9873 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 9874 MF->insert(I, mainMBB); 9875 MF->insert(I, sinkMBB); 9876 9877 MachineInstrBuilder MIB; 9878 9879 // Transfer the remainder of BB and its successor edges to sinkMBB. 9880 sinkMBB->splice(sinkMBB->begin(), MBB, 9881 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9882 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 9883 9884 // Note that the structure of the jmp_buf used here is not compatible 9885 // with that used by libc, and is not designed to be. Specifically, it 9886 // stores only those 'reserved' registers that LLVM does not otherwise 9887 // understand how to spill. Also, by convention, by the time this 9888 // intrinsic is called, Clang has already stored the frame address in the 9889 // first slot of the buffer and stack address in the third. Following the 9890 // X86 target code, we'll store the jump address in the second slot. We also 9891 // need to save the TOC pointer (R2) to handle jumps between shared 9892 // libraries, and that will be stored in the fourth slot. The thread 9893 // identifier (R13) is not affected. 9894 9895 // thisMBB: 9896 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9897 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9898 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9899 9900 // Prepare IP either in reg. 9901 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 9902 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 9903 unsigned BufReg = MI.getOperand(1).getReg(); 9904 9905 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 9906 setUsesTOCBasePtr(*MBB->getParent()); 9907 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 9908 .addReg(PPC::X2) 9909 .addImm(TOCOffset) 9910 .addReg(BufReg); 9911 MIB.setMemRefs(MMOBegin, MMOEnd); 9912 } 9913 9914 // Naked functions never have a base pointer, and so we use r1. For all 9915 // other functions, this decision must be delayed until during PEI. 9916 unsigned BaseReg; 9917 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 9918 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 9919 else 9920 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 9921 9922 MIB = BuildMI(*thisMBB, MI, DL, 9923 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 9924 .addReg(BaseReg) 9925 .addImm(BPOffset) 9926 .addReg(BufReg); 9927 MIB.setMemRefs(MMOBegin, MMOEnd); 9928 9929 // Setup 9930 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 9931 MIB.addRegMask(TRI->getNoPreservedMask()); 9932 9933 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 9934 9935 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 9936 .addMBB(mainMBB); 9937 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 9938 9939 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 9940 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 9941 9942 // mainMBB: 9943 // mainDstReg = 0 9944 MIB = 9945 BuildMI(mainMBB, DL, 9946 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 9947 9948 // Store IP 9949 if (Subtarget.isPPC64()) { 9950 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 9951 .addReg(LabelReg) 9952 .addImm(LabelOffset) 9953 .addReg(BufReg); 9954 } else { 9955 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 9956 .addReg(LabelReg) 9957 .addImm(LabelOffset) 9958 .addReg(BufReg); 9959 } 9960 9961 MIB.setMemRefs(MMOBegin, MMOEnd); 9962 9963 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 9964 mainMBB->addSuccessor(sinkMBB); 9965 9966 // sinkMBB: 9967 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 9968 TII->get(PPC::PHI), DstReg) 9969 .addReg(mainDstReg).addMBB(mainMBB) 9970 .addReg(restoreDstReg).addMBB(thisMBB); 9971 9972 MI.eraseFromParent(); 9973 return sinkMBB; 9974 } 9975 9976 MachineBasicBlock * 9977 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 9978 MachineBasicBlock *MBB) const { 9979 DebugLoc DL = MI.getDebugLoc(); 9980 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9981 9982 MachineFunction *MF = MBB->getParent(); 9983 MachineRegisterInfo &MRI = MF->getRegInfo(); 9984 9985 // Memory Reference 9986 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9987 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9988 9989 MVT PVT = getPointerTy(MF->getDataLayout()); 9990 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9991 "Invalid Pointer Size!"); 9992 9993 const TargetRegisterClass *RC = 9994 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 9995 unsigned Tmp = MRI.createVirtualRegister(RC); 9996 // Since FP is only updated here but NOT referenced, it's treated as GPR. 9997 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 9998 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 9999 unsigned BP = 10000 (PVT == MVT::i64) 10001 ? PPC::X30 10002 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10003 : PPC::R30); 10004 10005 MachineInstrBuilder MIB; 10006 10007 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10008 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10009 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10010 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10011 10012 unsigned BufReg = MI.getOperand(0).getReg(); 10013 10014 // Reload FP (the jumped-to function may not have had a 10015 // frame pointer, and if so, then its r31 will be restored 10016 // as necessary). 10017 if (PVT == MVT::i64) { 10018 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10019 .addImm(0) 10020 .addReg(BufReg); 10021 } else { 10022 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10023 .addImm(0) 10024 .addReg(BufReg); 10025 } 10026 MIB.setMemRefs(MMOBegin, MMOEnd); 10027 10028 // Reload IP 10029 if (PVT == MVT::i64) { 10030 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10031 .addImm(LabelOffset) 10032 .addReg(BufReg); 10033 } else { 10034 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10035 .addImm(LabelOffset) 10036 .addReg(BufReg); 10037 } 10038 MIB.setMemRefs(MMOBegin, MMOEnd); 10039 10040 // Reload SP 10041 if (PVT == MVT::i64) { 10042 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10043 .addImm(SPOffset) 10044 .addReg(BufReg); 10045 } else { 10046 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10047 .addImm(SPOffset) 10048 .addReg(BufReg); 10049 } 10050 MIB.setMemRefs(MMOBegin, MMOEnd); 10051 10052 // Reload BP 10053 if (PVT == MVT::i64) { 10054 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10055 .addImm(BPOffset) 10056 .addReg(BufReg); 10057 } else { 10058 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10059 .addImm(BPOffset) 10060 .addReg(BufReg); 10061 } 10062 MIB.setMemRefs(MMOBegin, MMOEnd); 10063 10064 // Reload TOC 10065 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10066 setUsesTOCBasePtr(*MBB->getParent()); 10067 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10068 .addImm(TOCOffset) 10069 .addReg(BufReg); 10070 10071 MIB.setMemRefs(MMOBegin, MMOEnd); 10072 } 10073 10074 // Jump 10075 BuildMI(*MBB, MI, DL, 10076 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10077 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10078 10079 MI.eraseFromParent(); 10080 return MBB; 10081 } 10082 10083 MachineBasicBlock * 10084 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10085 MachineBasicBlock *BB) const { 10086 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10087 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10088 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10089 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10090 // Call lowering should have added an r2 operand to indicate a dependence 10091 // on the TOC base pointer value. It can't however, because there is no 10092 // way to mark the dependence as implicit there, and so the stackmap code 10093 // will confuse it with a regular operand. Instead, add the dependence 10094 // here. 10095 setUsesTOCBasePtr(*BB->getParent()); 10096 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10097 } 10098 10099 return emitPatchPoint(MI, BB); 10100 } 10101 10102 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10103 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10104 return emitEHSjLjSetJmp(MI, BB); 10105 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10106 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10107 return emitEHSjLjLongJmp(MI, BB); 10108 } 10109 10110 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10111 10112 // To "insert" these instructions we actually have to insert their 10113 // control-flow patterns. 10114 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10115 MachineFunction::iterator It = ++BB->getIterator(); 10116 10117 MachineFunction *F = BB->getParent(); 10118 10119 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10120 MI.getOpcode() == PPC::SELECT_CC_I8 || 10121 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) { 10122 SmallVector<MachineOperand, 2> Cond; 10123 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10124 MI.getOpcode() == PPC::SELECT_CC_I8) 10125 Cond.push_back(MI.getOperand(4)); 10126 else 10127 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10128 Cond.push_back(MI.getOperand(1)); 10129 10130 DebugLoc dl = MI.getDebugLoc(); 10131 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10132 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10133 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10134 MI.getOpcode() == PPC::SELECT_CC_I8 || 10135 MI.getOpcode() == PPC::SELECT_CC_F4 || 10136 MI.getOpcode() == PPC::SELECT_CC_F8 || 10137 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10138 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10139 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10140 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10141 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10142 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10143 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10144 MI.getOpcode() == PPC::SELECT_I4 || 10145 MI.getOpcode() == PPC::SELECT_I8 || 10146 MI.getOpcode() == PPC::SELECT_F4 || 10147 MI.getOpcode() == PPC::SELECT_F8 || 10148 MI.getOpcode() == PPC::SELECT_QFRC || 10149 MI.getOpcode() == PPC::SELECT_QSRC || 10150 MI.getOpcode() == PPC::SELECT_QBRC || 10151 MI.getOpcode() == PPC::SELECT_VRRC || 10152 MI.getOpcode() == PPC::SELECT_VSFRC || 10153 MI.getOpcode() == PPC::SELECT_VSSRC || 10154 MI.getOpcode() == PPC::SELECT_VSRC) { 10155 // The incoming instruction knows the destination vreg to set, the 10156 // condition code register to branch on, the true/false values to 10157 // select between, and a branch opcode to use. 10158 10159 // thisMBB: 10160 // ... 10161 // TrueVal = ... 10162 // cmpTY ccX, r1, r2 10163 // bCC copy1MBB 10164 // fallthrough --> copy0MBB 10165 MachineBasicBlock *thisMBB = BB; 10166 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10167 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10168 DebugLoc dl = MI.getDebugLoc(); 10169 F->insert(It, copy0MBB); 10170 F->insert(It, sinkMBB); 10171 10172 // Transfer the remainder of BB and its successor edges to sinkMBB. 10173 sinkMBB->splice(sinkMBB->begin(), BB, 10174 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10175 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10176 10177 // Next, add the true and fallthrough blocks as its successors. 10178 BB->addSuccessor(copy0MBB); 10179 BB->addSuccessor(sinkMBB); 10180 10181 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10182 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10183 MI.getOpcode() == PPC::SELECT_QFRC || 10184 MI.getOpcode() == PPC::SELECT_QSRC || 10185 MI.getOpcode() == PPC::SELECT_QBRC || 10186 MI.getOpcode() == PPC::SELECT_VRRC || 10187 MI.getOpcode() == PPC::SELECT_VSFRC || 10188 MI.getOpcode() == PPC::SELECT_VSSRC || 10189 MI.getOpcode() == PPC::SELECT_VSRC) { 10190 BuildMI(BB, dl, TII->get(PPC::BC)) 10191 .addReg(MI.getOperand(1).getReg()) 10192 .addMBB(sinkMBB); 10193 } else { 10194 unsigned SelectPred = MI.getOperand(4).getImm(); 10195 BuildMI(BB, dl, TII->get(PPC::BCC)) 10196 .addImm(SelectPred) 10197 .addReg(MI.getOperand(1).getReg()) 10198 .addMBB(sinkMBB); 10199 } 10200 10201 // copy0MBB: 10202 // %FalseValue = ... 10203 // # fallthrough to sinkMBB 10204 BB = copy0MBB; 10205 10206 // Update machine-CFG edges 10207 BB->addSuccessor(sinkMBB); 10208 10209 // sinkMBB: 10210 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10211 // ... 10212 BB = sinkMBB; 10213 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10214 .addReg(MI.getOperand(3).getReg()) 10215 .addMBB(copy0MBB) 10216 .addReg(MI.getOperand(2).getReg()) 10217 .addMBB(thisMBB); 10218 } else if (MI.getOpcode() == PPC::ReadTB) { 10219 // To read the 64-bit time-base register on a 32-bit target, we read the 10220 // two halves. Should the counter have wrapped while it was being read, we 10221 // need to try again. 10222 // ... 10223 // readLoop: 10224 // mfspr Rx,TBU # load from TBU 10225 // mfspr Ry,TB # load from TB 10226 // mfspr Rz,TBU # load from TBU 10227 // cmpw crX,Rx,Rz # check if 'old'='new' 10228 // bne readLoop # branch if they're not equal 10229 // ... 10230 10231 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10232 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10233 DebugLoc dl = MI.getDebugLoc(); 10234 F->insert(It, readMBB); 10235 F->insert(It, sinkMBB); 10236 10237 // Transfer the remainder of BB and its successor edges to sinkMBB. 10238 sinkMBB->splice(sinkMBB->begin(), BB, 10239 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10240 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10241 10242 BB->addSuccessor(readMBB); 10243 BB = readMBB; 10244 10245 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10246 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10247 unsigned LoReg = MI.getOperand(0).getReg(); 10248 unsigned HiReg = MI.getOperand(1).getReg(); 10249 10250 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10251 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10252 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10253 10254 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10255 10256 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10257 .addReg(HiReg).addReg(ReadAgainReg); 10258 BuildMI(BB, dl, TII->get(PPC::BCC)) 10259 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB); 10260 10261 BB->addSuccessor(readMBB); 10262 BB->addSuccessor(sinkMBB); 10263 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10264 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10265 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10266 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10267 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10268 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10269 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10270 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10271 10272 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10273 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10274 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10275 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10276 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10277 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10278 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10279 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10280 10281 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10282 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10283 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10284 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10285 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10286 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10287 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10288 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10289 10290 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10291 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10292 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10293 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10294 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10295 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10296 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10297 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10298 10299 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10300 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10301 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10302 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10303 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10304 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10305 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10306 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10307 10308 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10309 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10310 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10311 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10312 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10313 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10314 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10315 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10316 10317 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10318 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10319 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10320 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10321 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10322 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10323 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10324 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10325 10326 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10327 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10328 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10329 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10330 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10331 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10332 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10333 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10334 10335 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10336 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10337 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10338 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10339 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10340 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10341 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10342 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10343 10344 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10345 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10346 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10347 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10348 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10349 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10350 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10351 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10352 10353 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10354 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10355 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10356 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10357 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10358 BB = EmitAtomicBinary(MI, BB, 4, 0); 10359 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10360 BB = EmitAtomicBinary(MI, BB, 8, 0); 10361 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10362 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10363 (Subtarget.hasPartwordAtomics() && 10364 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10365 (Subtarget.hasPartwordAtomics() && 10366 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10367 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10368 10369 auto LoadMnemonic = PPC::LDARX; 10370 auto StoreMnemonic = PPC::STDCX; 10371 switch (MI.getOpcode()) { 10372 default: 10373 llvm_unreachable("Compare and swap of unknown size"); 10374 case PPC::ATOMIC_CMP_SWAP_I8: 10375 LoadMnemonic = PPC::LBARX; 10376 StoreMnemonic = PPC::STBCX; 10377 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10378 break; 10379 case PPC::ATOMIC_CMP_SWAP_I16: 10380 LoadMnemonic = PPC::LHARX; 10381 StoreMnemonic = PPC::STHCX; 10382 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10383 break; 10384 case PPC::ATOMIC_CMP_SWAP_I32: 10385 LoadMnemonic = PPC::LWARX; 10386 StoreMnemonic = PPC::STWCX; 10387 break; 10388 case PPC::ATOMIC_CMP_SWAP_I64: 10389 LoadMnemonic = PPC::LDARX; 10390 StoreMnemonic = PPC::STDCX; 10391 break; 10392 } 10393 unsigned dest = MI.getOperand(0).getReg(); 10394 unsigned ptrA = MI.getOperand(1).getReg(); 10395 unsigned ptrB = MI.getOperand(2).getReg(); 10396 unsigned oldval = MI.getOperand(3).getReg(); 10397 unsigned newval = MI.getOperand(4).getReg(); 10398 DebugLoc dl = MI.getDebugLoc(); 10399 10400 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10401 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10402 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10403 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10404 F->insert(It, loop1MBB); 10405 F->insert(It, loop2MBB); 10406 F->insert(It, midMBB); 10407 F->insert(It, exitMBB); 10408 exitMBB->splice(exitMBB->begin(), BB, 10409 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10410 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10411 10412 // thisMBB: 10413 // ... 10414 // fallthrough --> loopMBB 10415 BB->addSuccessor(loop1MBB); 10416 10417 // loop1MBB: 10418 // l[bhwd]arx dest, ptr 10419 // cmp[wd] dest, oldval 10420 // bne- midMBB 10421 // loop2MBB: 10422 // st[bhwd]cx. newval, ptr 10423 // bne- loopMBB 10424 // b exitBB 10425 // midMBB: 10426 // st[bhwd]cx. dest, ptr 10427 // exitBB: 10428 BB = loop1MBB; 10429 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10430 .addReg(ptrA).addReg(ptrB); 10431 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10432 .addReg(oldval).addReg(dest); 10433 BuildMI(BB, dl, TII->get(PPC::BCC)) 10434 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10435 BB->addSuccessor(loop2MBB); 10436 BB->addSuccessor(midMBB); 10437 10438 BB = loop2MBB; 10439 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10440 .addReg(newval).addReg(ptrA).addReg(ptrB); 10441 BuildMI(BB, dl, TII->get(PPC::BCC)) 10442 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10443 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10444 BB->addSuccessor(loop1MBB); 10445 BB->addSuccessor(exitMBB); 10446 10447 BB = midMBB; 10448 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10449 .addReg(dest).addReg(ptrA).addReg(ptrB); 10450 BB->addSuccessor(exitMBB); 10451 10452 // exitMBB: 10453 // ... 10454 BB = exitMBB; 10455 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 10456 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 10457 // We must use 64-bit registers for addresses when targeting 64-bit, 10458 // since we're actually doing arithmetic on them. Other registers 10459 // can be 32-bit. 10460 bool is64bit = Subtarget.isPPC64(); 10461 bool isLittleEndian = Subtarget.isLittleEndian(); 10462 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 10463 10464 unsigned dest = MI.getOperand(0).getReg(); 10465 unsigned ptrA = MI.getOperand(1).getReg(); 10466 unsigned ptrB = MI.getOperand(2).getReg(); 10467 unsigned oldval = MI.getOperand(3).getReg(); 10468 unsigned newval = MI.getOperand(4).getReg(); 10469 DebugLoc dl = MI.getDebugLoc(); 10470 10471 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10472 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10473 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10474 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10475 F->insert(It, loop1MBB); 10476 F->insert(It, loop2MBB); 10477 F->insert(It, midMBB); 10478 F->insert(It, exitMBB); 10479 exitMBB->splice(exitMBB->begin(), BB, 10480 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10481 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10482 10483 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10484 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 10485 : &PPC::GPRCRegClass; 10486 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10487 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 10488 unsigned ShiftReg = 10489 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 10490 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 10491 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 10492 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 10493 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 10494 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 10495 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 10496 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 10497 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 10498 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 10499 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 10500 unsigned Ptr1Reg; 10501 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 10502 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10503 // thisMBB: 10504 // ... 10505 // fallthrough --> loopMBB 10506 BB->addSuccessor(loop1MBB); 10507 10508 // The 4-byte load must be aligned, while a char or short may be 10509 // anywhere in the word. Hence all this nasty bookkeeping code. 10510 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10511 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10512 // xori shift, shift1, 24 [16] 10513 // rlwinm ptr, ptr1, 0, 0, 29 10514 // slw newval2, newval, shift 10515 // slw oldval2, oldval,shift 10516 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10517 // slw mask, mask2, shift 10518 // and newval3, newval2, mask 10519 // and oldval3, oldval2, mask 10520 // loop1MBB: 10521 // lwarx tmpDest, ptr 10522 // and tmp, tmpDest, mask 10523 // cmpw tmp, oldval3 10524 // bne- midMBB 10525 // loop2MBB: 10526 // andc tmp2, tmpDest, mask 10527 // or tmp4, tmp2, newval3 10528 // stwcx. tmp4, ptr 10529 // bne- loop1MBB 10530 // b exitBB 10531 // midMBB: 10532 // stwcx. tmpDest, ptr 10533 // exitBB: 10534 // srw dest, tmpDest, shift 10535 if (ptrA != ZeroReg) { 10536 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10537 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10538 .addReg(ptrA).addReg(ptrB); 10539 } else { 10540 Ptr1Reg = ptrB; 10541 } 10542 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 10543 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 10544 if (!isLittleEndian) 10545 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 10546 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 10547 if (is64bit) 10548 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10549 .addReg(Ptr1Reg).addImm(0).addImm(61); 10550 else 10551 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10552 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 10553 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 10554 .addReg(newval).addReg(ShiftReg); 10555 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 10556 .addReg(oldval).addReg(ShiftReg); 10557 if (is8bit) 10558 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10559 else { 10560 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10561 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10562 .addReg(Mask3Reg).addImm(65535); 10563 } 10564 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10565 .addReg(Mask2Reg).addReg(ShiftReg); 10566 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 10567 .addReg(NewVal2Reg).addReg(MaskReg); 10568 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 10569 .addReg(OldVal2Reg).addReg(MaskReg); 10570 10571 BB = loop1MBB; 10572 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10573 .addReg(ZeroReg).addReg(PtrReg); 10574 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 10575 .addReg(TmpDestReg).addReg(MaskReg); 10576 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 10577 .addReg(TmpReg).addReg(OldVal3Reg); 10578 BuildMI(BB, dl, TII->get(PPC::BCC)) 10579 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10580 BB->addSuccessor(loop2MBB); 10581 BB->addSuccessor(midMBB); 10582 10583 BB = loop2MBB; 10584 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 10585 .addReg(TmpDestReg).addReg(MaskReg); 10586 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 10587 .addReg(Tmp2Reg).addReg(NewVal3Reg); 10588 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 10589 .addReg(ZeroReg).addReg(PtrReg); 10590 BuildMI(BB, dl, TII->get(PPC::BCC)) 10591 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10592 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10593 BB->addSuccessor(loop1MBB); 10594 BB->addSuccessor(exitMBB); 10595 10596 BB = midMBB; 10597 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 10598 .addReg(ZeroReg).addReg(PtrReg); 10599 BB->addSuccessor(exitMBB); 10600 10601 // exitMBB: 10602 // ... 10603 BB = exitMBB; 10604 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 10605 .addReg(ShiftReg); 10606 } else if (MI.getOpcode() == PPC::FADDrtz) { 10607 // This pseudo performs an FADD with rounding mode temporarily forced 10608 // to round-to-zero. We emit this via custom inserter since the FPSCR 10609 // is not modeled at the SelectionDAG level. 10610 unsigned Dest = MI.getOperand(0).getReg(); 10611 unsigned Src1 = MI.getOperand(1).getReg(); 10612 unsigned Src2 = MI.getOperand(2).getReg(); 10613 DebugLoc dl = MI.getDebugLoc(); 10614 10615 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10616 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 10617 10618 // Save FPSCR value. 10619 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 10620 10621 // Set rounding mode to round-to-zero. 10622 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 10623 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 10624 10625 // Perform addition. 10626 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 10627 10628 // Restore FPSCR value. 10629 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 10630 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10631 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 10632 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10633 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 10634 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10635 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 10636 ? PPC::ANDIo8 10637 : PPC::ANDIo; 10638 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10639 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 10640 10641 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10642 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? 10643 &PPC::GPRCRegClass : 10644 &PPC::G8RCRegClass); 10645 10646 DebugLoc dl = MI.getDebugLoc(); 10647 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 10648 .addReg(MI.getOperand(1).getReg()) 10649 .addImm(1); 10650 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 10651 MI.getOperand(0).getReg()) 10652 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 10653 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 10654 DebugLoc Dl = MI.getDebugLoc(); 10655 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10656 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10657 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 10658 return BB; 10659 } else { 10660 llvm_unreachable("Unexpected instr type to insert"); 10661 } 10662 10663 MI.eraseFromParent(); // The pseudo instruction is gone now. 10664 return BB; 10665 } 10666 10667 //===----------------------------------------------------------------------===// 10668 // Target Optimization Hooks 10669 //===----------------------------------------------------------------------===// 10670 10671 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 10672 // For the estimates, convergence is quadratic, so we essentially double the 10673 // number of digits correct after every iteration. For both FRE and FRSQRTE, 10674 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 10675 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 10676 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 10677 if (VT.getScalarType() == MVT::f64) 10678 RefinementSteps++; 10679 return RefinementSteps; 10680 } 10681 10682 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 10683 int Enabled, int &RefinementSteps, 10684 bool &UseOneConstNR, 10685 bool Reciprocal) const { 10686 EVT VT = Operand.getValueType(); 10687 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 10688 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 10689 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10690 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10691 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10692 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10693 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10694 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10695 10696 UseOneConstNR = true; 10697 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 10698 } 10699 return SDValue(); 10700 } 10701 10702 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 10703 int Enabled, 10704 int &RefinementSteps) const { 10705 EVT VT = Operand.getValueType(); 10706 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 10707 (VT == MVT::f64 && Subtarget.hasFRE()) || 10708 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10709 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10710 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10711 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10712 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10713 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10714 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 10715 } 10716 return SDValue(); 10717 } 10718 10719 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 10720 // Note: This functionality is used only when unsafe-fp-math is enabled, and 10721 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 10722 // enabled for division), this functionality is redundant with the default 10723 // combiner logic (once the division -> reciprocal/multiply transformation 10724 // has taken place). As a result, this matters more for older cores than for 10725 // newer ones. 10726 10727 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10728 // reciprocal if there are two or more FDIVs (for embedded cores with only 10729 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 10730 switch (Subtarget.getDarwinDirective()) { 10731 default: 10732 return 3; 10733 case PPC::DIR_440: 10734 case PPC::DIR_A2: 10735 case PPC::DIR_E500mc: 10736 case PPC::DIR_E5500: 10737 return 2; 10738 } 10739 } 10740 10741 // isConsecutiveLSLoc needs to work even if all adds have not yet been 10742 // collapsed, and so we need to look through chains of them. 10743 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 10744 int64_t& Offset, SelectionDAG &DAG) { 10745 if (DAG.isBaseWithConstantOffset(Loc)) { 10746 Base = Loc.getOperand(0); 10747 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 10748 10749 // The base might itself be a base plus an offset, and if so, accumulate 10750 // that as well. 10751 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 10752 } 10753 } 10754 10755 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 10756 unsigned Bytes, int Dist, 10757 SelectionDAG &DAG) { 10758 if (VT.getSizeInBits() / 8 != Bytes) 10759 return false; 10760 10761 SDValue BaseLoc = Base->getBasePtr(); 10762 if (Loc.getOpcode() == ISD::FrameIndex) { 10763 if (BaseLoc.getOpcode() != ISD::FrameIndex) 10764 return false; 10765 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10766 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 10767 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 10768 int FS = MFI.getObjectSize(FI); 10769 int BFS = MFI.getObjectSize(BFI); 10770 if (FS != BFS || FS != (int)Bytes) return false; 10771 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 10772 } 10773 10774 SDValue Base1 = Loc, Base2 = BaseLoc; 10775 int64_t Offset1 = 0, Offset2 = 0; 10776 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 10777 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 10778 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 10779 return true; 10780 10781 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10782 const GlobalValue *GV1 = nullptr; 10783 const GlobalValue *GV2 = nullptr; 10784 Offset1 = 0; 10785 Offset2 = 0; 10786 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 10787 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 10788 if (isGA1 && isGA2 && GV1 == GV2) 10789 return Offset1 == (Offset2 + Dist*Bytes); 10790 return false; 10791 } 10792 10793 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 10794 // not enforce equality of the chain operands. 10795 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 10796 unsigned Bytes, int Dist, 10797 SelectionDAG &DAG) { 10798 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 10799 EVT VT = LS->getMemoryVT(); 10800 SDValue Loc = LS->getBasePtr(); 10801 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 10802 } 10803 10804 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 10805 EVT VT; 10806 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10807 default: return false; 10808 case Intrinsic::ppc_qpx_qvlfd: 10809 case Intrinsic::ppc_qpx_qvlfda: 10810 VT = MVT::v4f64; 10811 break; 10812 case Intrinsic::ppc_qpx_qvlfs: 10813 case Intrinsic::ppc_qpx_qvlfsa: 10814 VT = MVT::v4f32; 10815 break; 10816 case Intrinsic::ppc_qpx_qvlfcd: 10817 case Intrinsic::ppc_qpx_qvlfcda: 10818 VT = MVT::v2f64; 10819 break; 10820 case Intrinsic::ppc_qpx_qvlfcs: 10821 case Intrinsic::ppc_qpx_qvlfcsa: 10822 VT = MVT::v2f32; 10823 break; 10824 case Intrinsic::ppc_qpx_qvlfiwa: 10825 case Intrinsic::ppc_qpx_qvlfiwz: 10826 case Intrinsic::ppc_altivec_lvx: 10827 case Intrinsic::ppc_altivec_lvxl: 10828 case Intrinsic::ppc_vsx_lxvw4x: 10829 case Intrinsic::ppc_vsx_lxvw4x_be: 10830 VT = MVT::v4i32; 10831 break; 10832 case Intrinsic::ppc_vsx_lxvd2x: 10833 case Intrinsic::ppc_vsx_lxvd2x_be: 10834 VT = MVT::v2f64; 10835 break; 10836 case Intrinsic::ppc_altivec_lvebx: 10837 VT = MVT::i8; 10838 break; 10839 case Intrinsic::ppc_altivec_lvehx: 10840 VT = MVT::i16; 10841 break; 10842 case Intrinsic::ppc_altivec_lvewx: 10843 VT = MVT::i32; 10844 break; 10845 } 10846 10847 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 10848 } 10849 10850 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 10851 EVT VT; 10852 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10853 default: return false; 10854 case Intrinsic::ppc_qpx_qvstfd: 10855 case Intrinsic::ppc_qpx_qvstfda: 10856 VT = MVT::v4f64; 10857 break; 10858 case Intrinsic::ppc_qpx_qvstfs: 10859 case Intrinsic::ppc_qpx_qvstfsa: 10860 VT = MVT::v4f32; 10861 break; 10862 case Intrinsic::ppc_qpx_qvstfcd: 10863 case Intrinsic::ppc_qpx_qvstfcda: 10864 VT = MVT::v2f64; 10865 break; 10866 case Intrinsic::ppc_qpx_qvstfcs: 10867 case Intrinsic::ppc_qpx_qvstfcsa: 10868 VT = MVT::v2f32; 10869 break; 10870 case Intrinsic::ppc_qpx_qvstfiw: 10871 case Intrinsic::ppc_qpx_qvstfiwa: 10872 case Intrinsic::ppc_altivec_stvx: 10873 case Intrinsic::ppc_altivec_stvxl: 10874 case Intrinsic::ppc_vsx_stxvw4x: 10875 VT = MVT::v4i32; 10876 break; 10877 case Intrinsic::ppc_vsx_stxvd2x: 10878 VT = MVT::v2f64; 10879 break; 10880 case Intrinsic::ppc_vsx_stxvw4x_be: 10881 VT = MVT::v4i32; 10882 break; 10883 case Intrinsic::ppc_vsx_stxvd2x_be: 10884 VT = MVT::v2f64; 10885 break; 10886 case Intrinsic::ppc_altivec_stvebx: 10887 VT = MVT::i8; 10888 break; 10889 case Intrinsic::ppc_altivec_stvehx: 10890 VT = MVT::i16; 10891 break; 10892 case Intrinsic::ppc_altivec_stvewx: 10893 VT = MVT::i32; 10894 break; 10895 } 10896 10897 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 10898 } 10899 10900 return false; 10901 } 10902 10903 // Return true is there is a nearyby consecutive load to the one provided 10904 // (regardless of alignment). We search up and down the chain, looking though 10905 // token factors and other loads (but nothing else). As a result, a true result 10906 // indicates that it is safe to create a new consecutive load adjacent to the 10907 // load provided. 10908 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 10909 SDValue Chain = LD->getChain(); 10910 EVT VT = LD->getMemoryVT(); 10911 10912 SmallSet<SDNode *, 16> LoadRoots; 10913 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 10914 SmallSet<SDNode *, 16> Visited; 10915 10916 // First, search up the chain, branching to follow all token-factor operands. 10917 // If we find a consecutive load, then we're done, otherwise, record all 10918 // nodes just above the top-level loads and token factors. 10919 while (!Queue.empty()) { 10920 SDNode *ChainNext = Queue.pop_back_val(); 10921 if (!Visited.insert(ChainNext).second) 10922 continue; 10923 10924 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 10925 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10926 return true; 10927 10928 if (!Visited.count(ChainLD->getChain().getNode())) 10929 Queue.push_back(ChainLD->getChain().getNode()); 10930 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 10931 for (const SDUse &O : ChainNext->ops()) 10932 if (!Visited.count(O.getNode())) 10933 Queue.push_back(O.getNode()); 10934 } else 10935 LoadRoots.insert(ChainNext); 10936 } 10937 10938 // Second, search down the chain, starting from the top-level nodes recorded 10939 // in the first phase. These top-level nodes are the nodes just above all 10940 // loads and token factors. Starting with their uses, recursively look though 10941 // all loads (just the chain uses) and token factors to find a consecutive 10942 // load. 10943 Visited.clear(); 10944 Queue.clear(); 10945 10946 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 10947 IE = LoadRoots.end(); I != IE; ++I) { 10948 Queue.push_back(*I); 10949 10950 while (!Queue.empty()) { 10951 SDNode *LoadRoot = Queue.pop_back_val(); 10952 if (!Visited.insert(LoadRoot).second) 10953 continue; 10954 10955 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 10956 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10957 return true; 10958 10959 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 10960 UE = LoadRoot->use_end(); UI != UE; ++UI) 10961 if (((isa<MemSDNode>(*UI) && 10962 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 10963 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 10964 Queue.push_back(*UI); 10965 } 10966 } 10967 10968 return false; 10969 } 10970 10971 /// This function is called when we have proved that a SETCC node can be replaced 10972 /// by subtraction (and other supporting instructions) so that the result of 10973 /// comparison is kept in a GPR instead of CR. This function is purely for 10974 /// codegen purposes and has some flags to guide the codegen process. 10975 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 10976 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 10977 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10978 10979 // Zero extend the operands to the largest legal integer. Originally, they 10980 // must be of a strictly smaller size. 10981 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 10982 DAG.getConstant(Size, DL, MVT::i32)); 10983 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 10984 DAG.getConstant(Size, DL, MVT::i32)); 10985 10986 // Swap if needed. Depends on the condition code. 10987 if (Swap) 10988 std::swap(Op0, Op1); 10989 10990 // Subtract extended integers. 10991 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 10992 10993 // Move the sign bit to the least significant position and zero out the rest. 10994 // Now the least significant bit carries the result of original comparison. 10995 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 10996 DAG.getConstant(Size - 1, DL, MVT::i32)); 10997 auto Final = Shifted; 10998 10999 // Complement the result if needed. Based on the condition code. 11000 if (Complement) 11001 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 11002 DAG.getConstant(1, DL, MVT::i64)); 11003 11004 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11005 } 11006 11007 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11008 DAGCombinerInfo &DCI) const { 11009 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11010 11011 SelectionDAG &DAG = DCI.DAG; 11012 SDLoc DL(N); 11013 11014 // Size of integers being compared has a critical role in the following 11015 // analysis, so we prefer to do this when all types are legal. 11016 if (!DCI.isAfterLegalizeDAG()) 11017 return SDValue(); 11018 11019 // If all users of SETCC extend its value to a legal integer type 11020 // then we replace SETCC with a subtraction 11021 for (SDNode::use_iterator UI = N->use_begin(), 11022 UE = N->use_end(); UI != UE; ++UI) { 11023 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11024 return SDValue(); 11025 } 11026 11027 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11028 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11029 11030 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11031 11032 if (OpSize < Size) { 11033 switch (CC) { 11034 default: break; 11035 case ISD::SETULT: 11036 return generateEquivalentSub(N, Size, false, false, DL, DAG); 11037 case ISD::SETULE: 11038 return generateEquivalentSub(N, Size, true, true, DL, DAG); 11039 case ISD::SETUGT: 11040 return generateEquivalentSub(N, Size, false, true, DL, DAG); 11041 case ISD::SETUGE: 11042 return generateEquivalentSub(N, Size, true, false, DL, DAG); 11043 } 11044 } 11045 11046 return SDValue(); 11047 } 11048 11049 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 11050 DAGCombinerInfo &DCI) const { 11051 SelectionDAG &DAG = DCI.DAG; 11052 SDLoc dl(N); 11053 11054 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11055 // If we're tracking CR bits, we need to be careful that we don't have: 11056 // trunc(binary-ops(zext(x), zext(y))) 11057 // or 11058 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11059 // such that we're unnecessarily moving things into GPRs when it would be 11060 // better to keep them in CR bits. 11061 11062 // Note that trunc here can be an actual i1 trunc, or can be the effective 11063 // truncation that comes from a setcc or select_cc. 11064 if (N->getOpcode() == ISD::TRUNCATE && 11065 N->getValueType(0) != MVT::i1) 11066 return SDValue(); 11067 11068 if (N->getOperand(0).getValueType() != MVT::i32 && 11069 N->getOperand(0).getValueType() != MVT::i64) 11070 return SDValue(); 11071 11072 if (N->getOpcode() == ISD::SETCC || 11073 N->getOpcode() == ISD::SELECT_CC) { 11074 // If we're looking at a comparison, then we need to make sure that the 11075 // high bits (all except for the first) don't matter the result. 11076 ISD::CondCode CC = 11077 cast<CondCodeSDNode>(N->getOperand( 11078 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11079 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11080 11081 if (ISD::isSignedIntSetCC(CC)) { 11082 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11083 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11084 return SDValue(); 11085 } else if (ISD::isUnsignedIntSetCC(CC)) { 11086 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11087 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11088 !DAG.MaskedValueIsZero(N->getOperand(1), 11089 APInt::getHighBitsSet(OpBits, OpBits-1))) 11090 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11091 : SDValue()); 11092 } else { 11093 // This is neither a signed nor an unsigned comparison, just make sure 11094 // that the high bits are equal. 11095 KnownBits Op1Known, Op2Known; 11096 DAG.computeKnownBits(N->getOperand(0), Op1Known); 11097 DAG.computeKnownBits(N->getOperand(1), Op2Known); 11098 11099 // We don't really care about what is known about the first bit (if 11100 // anything), so clear it in all masks prior to comparing them. 11101 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11102 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11103 11104 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11105 return SDValue(); 11106 } 11107 } 11108 11109 // We now know that the higher-order bits are irrelevant, we just need to 11110 // make sure that all of the intermediate operations are bit operations, and 11111 // all inputs are extensions. 11112 if (N->getOperand(0).getOpcode() != ISD::AND && 11113 N->getOperand(0).getOpcode() != ISD::OR && 11114 N->getOperand(0).getOpcode() != ISD::XOR && 11115 N->getOperand(0).getOpcode() != ISD::SELECT && 11116 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11117 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11118 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11119 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11120 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11121 return SDValue(); 11122 11123 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11124 N->getOperand(1).getOpcode() != ISD::AND && 11125 N->getOperand(1).getOpcode() != ISD::OR && 11126 N->getOperand(1).getOpcode() != ISD::XOR && 11127 N->getOperand(1).getOpcode() != ISD::SELECT && 11128 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11129 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11130 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11131 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11132 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11133 return SDValue(); 11134 11135 SmallVector<SDValue, 4> Inputs; 11136 SmallVector<SDValue, 8> BinOps, PromOps; 11137 SmallPtrSet<SDNode *, 16> Visited; 11138 11139 for (unsigned i = 0; i < 2; ++i) { 11140 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11141 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11142 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11143 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11144 isa<ConstantSDNode>(N->getOperand(i))) 11145 Inputs.push_back(N->getOperand(i)); 11146 else 11147 BinOps.push_back(N->getOperand(i)); 11148 11149 if (N->getOpcode() == ISD::TRUNCATE) 11150 break; 11151 } 11152 11153 // Visit all inputs, collect all binary operations (and, or, xor and 11154 // select) that are all fed by extensions. 11155 while (!BinOps.empty()) { 11156 SDValue BinOp = BinOps.back(); 11157 BinOps.pop_back(); 11158 11159 if (!Visited.insert(BinOp.getNode()).second) 11160 continue; 11161 11162 PromOps.push_back(BinOp); 11163 11164 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11165 // The condition of the select is not promoted. 11166 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11167 continue; 11168 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11169 continue; 11170 11171 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11172 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11173 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11174 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11175 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11176 Inputs.push_back(BinOp.getOperand(i)); 11177 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11178 BinOp.getOperand(i).getOpcode() == ISD::OR || 11179 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11180 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11181 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11182 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11183 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11184 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11185 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11186 BinOps.push_back(BinOp.getOperand(i)); 11187 } else { 11188 // We have an input that is not an extension or another binary 11189 // operation; we'll abort this transformation. 11190 return SDValue(); 11191 } 11192 } 11193 } 11194 11195 // Make sure that this is a self-contained cluster of operations (which 11196 // is not quite the same thing as saying that everything has only one 11197 // use). 11198 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11199 if (isa<ConstantSDNode>(Inputs[i])) 11200 continue; 11201 11202 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11203 UE = Inputs[i].getNode()->use_end(); 11204 UI != UE; ++UI) { 11205 SDNode *User = *UI; 11206 if (User != N && !Visited.count(User)) 11207 return SDValue(); 11208 11209 // Make sure that we're not going to promote the non-output-value 11210 // operand(s) or SELECT or SELECT_CC. 11211 // FIXME: Although we could sometimes handle this, and it does occur in 11212 // practice that one of the condition inputs to the select is also one of 11213 // the outputs, we currently can't deal with this. 11214 if (User->getOpcode() == ISD::SELECT) { 11215 if (User->getOperand(0) == Inputs[i]) 11216 return SDValue(); 11217 } else if (User->getOpcode() == ISD::SELECT_CC) { 11218 if (User->getOperand(0) == Inputs[i] || 11219 User->getOperand(1) == Inputs[i]) 11220 return SDValue(); 11221 } 11222 } 11223 } 11224 11225 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11226 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11227 UE = PromOps[i].getNode()->use_end(); 11228 UI != UE; ++UI) { 11229 SDNode *User = *UI; 11230 if (User != N && !Visited.count(User)) 11231 return SDValue(); 11232 11233 // Make sure that we're not going to promote the non-output-value 11234 // operand(s) or SELECT or SELECT_CC. 11235 // FIXME: Although we could sometimes handle this, and it does occur in 11236 // practice that one of the condition inputs to the select is also one of 11237 // the outputs, we currently can't deal with this. 11238 if (User->getOpcode() == ISD::SELECT) { 11239 if (User->getOperand(0) == PromOps[i]) 11240 return SDValue(); 11241 } else if (User->getOpcode() == ISD::SELECT_CC) { 11242 if (User->getOperand(0) == PromOps[i] || 11243 User->getOperand(1) == PromOps[i]) 11244 return SDValue(); 11245 } 11246 } 11247 } 11248 11249 // Replace all inputs with the extension operand. 11250 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11251 // Constants may have users outside the cluster of to-be-promoted nodes, 11252 // and so we need to replace those as we do the promotions. 11253 if (isa<ConstantSDNode>(Inputs[i])) 11254 continue; 11255 else 11256 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 11257 } 11258 11259 std::list<HandleSDNode> PromOpHandles; 11260 for (auto &PromOp : PromOps) 11261 PromOpHandles.emplace_back(PromOp); 11262 11263 // Replace all operations (these are all the same, but have a different 11264 // (i1) return type). DAG.getNode will validate that the types of 11265 // a binary operator match, so go through the list in reverse so that 11266 // we've likely promoted both operands first. Any intermediate truncations or 11267 // extensions disappear. 11268 while (!PromOpHandles.empty()) { 11269 SDValue PromOp = PromOpHandles.back().getValue(); 11270 PromOpHandles.pop_back(); 11271 11272 if (PromOp.getOpcode() == ISD::TRUNCATE || 11273 PromOp.getOpcode() == ISD::SIGN_EXTEND || 11274 PromOp.getOpcode() == ISD::ZERO_EXTEND || 11275 PromOp.getOpcode() == ISD::ANY_EXTEND) { 11276 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 11277 PromOp.getOperand(0).getValueType() != MVT::i1) { 11278 // The operand is not yet ready (see comment below). 11279 PromOpHandles.emplace_front(PromOp); 11280 continue; 11281 } 11282 11283 SDValue RepValue = PromOp.getOperand(0); 11284 if (isa<ConstantSDNode>(RepValue)) 11285 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 11286 11287 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 11288 continue; 11289 } 11290 11291 unsigned C; 11292 switch (PromOp.getOpcode()) { 11293 default: C = 0; break; 11294 case ISD::SELECT: C = 1; break; 11295 case ISD::SELECT_CC: C = 2; break; 11296 } 11297 11298 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11299 PromOp.getOperand(C).getValueType() != MVT::i1) || 11300 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11301 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 11302 // The to-be-promoted operands of this node have not yet been 11303 // promoted (this should be rare because we're going through the 11304 // list backward, but if one of the operands has several users in 11305 // this cluster of to-be-promoted nodes, it is possible). 11306 PromOpHandles.emplace_front(PromOp); 11307 continue; 11308 } 11309 11310 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11311 PromOp.getNode()->op_end()); 11312 11313 // If there are any constant inputs, make sure they're replaced now. 11314 for (unsigned i = 0; i < 2; ++i) 11315 if (isa<ConstantSDNode>(Ops[C+i])) 11316 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 11317 11318 DAG.ReplaceAllUsesOfValueWith(PromOp, 11319 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 11320 } 11321 11322 // Now we're left with the initial truncation itself. 11323 if (N->getOpcode() == ISD::TRUNCATE) 11324 return N->getOperand(0); 11325 11326 // Otherwise, this is a comparison. The operands to be compared have just 11327 // changed type (to i1), but everything else is the same. 11328 return SDValue(N, 0); 11329 } 11330 11331 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 11332 DAGCombinerInfo &DCI) const { 11333 SelectionDAG &DAG = DCI.DAG; 11334 SDLoc dl(N); 11335 11336 // If we're tracking CR bits, we need to be careful that we don't have: 11337 // zext(binary-ops(trunc(x), trunc(y))) 11338 // or 11339 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 11340 // such that we're unnecessarily moving things into CR bits that can more 11341 // efficiently stay in GPRs. Note that if we're not certain that the high 11342 // bits are set as required by the final extension, we still may need to do 11343 // some masking to get the proper behavior. 11344 11345 // This same functionality is important on PPC64 when dealing with 11346 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 11347 // the return values of functions. Because it is so similar, it is handled 11348 // here as well. 11349 11350 if (N->getValueType(0) != MVT::i32 && 11351 N->getValueType(0) != MVT::i64) 11352 return SDValue(); 11353 11354 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 11355 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 11356 return SDValue(); 11357 11358 if (N->getOperand(0).getOpcode() != ISD::AND && 11359 N->getOperand(0).getOpcode() != ISD::OR && 11360 N->getOperand(0).getOpcode() != ISD::XOR && 11361 N->getOperand(0).getOpcode() != ISD::SELECT && 11362 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 11363 return SDValue(); 11364 11365 SmallVector<SDValue, 4> Inputs; 11366 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 11367 SmallPtrSet<SDNode *, 16> Visited; 11368 11369 // Visit all inputs, collect all binary operations (and, or, xor and 11370 // select) that are all fed by truncations. 11371 while (!BinOps.empty()) { 11372 SDValue BinOp = BinOps.back(); 11373 BinOps.pop_back(); 11374 11375 if (!Visited.insert(BinOp.getNode()).second) 11376 continue; 11377 11378 PromOps.push_back(BinOp); 11379 11380 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11381 // The condition of the select is not promoted. 11382 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11383 continue; 11384 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11385 continue; 11386 11387 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11388 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11389 Inputs.push_back(BinOp.getOperand(i)); 11390 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11391 BinOp.getOperand(i).getOpcode() == ISD::OR || 11392 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11393 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11394 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 11395 BinOps.push_back(BinOp.getOperand(i)); 11396 } else { 11397 // We have an input that is not a truncation or another binary 11398 // operation; we'll abort this transformation. 11399 return SDValue(); 11400 } 11401 } 11402 } 11403 11404 // The operands of a select that must be truncated when the select is 11405 // promoted because the operand is actually part of the to-be-promoted set. 11406 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 11407 11408 // Make sure that this is a self-contained cluster of operations (which 11409 // is not quite the same thing as saying that everything has only one 11410 // use). 11411 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11412 if (isa<ConstantSDNode>(Inputs[i])) 11413 continue; 11414 11415 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11416 UE = Inputs[i].getNode()->use_end(); 11417 UI != UE; ++UI) { 11418 SDNode *User = *UI; 11419 if (User != N && !Visited.count(User)) 11420 return SDValue(); 11421 11422 // If we're going to promote the non-output-value operand(s) or SELECT or 11423 // SELECT_CC, record them for truncation. 11424 if (User->getOpcode() == ISD::SELECT) { 11425 if (User->getOperand(0) == Inputs[i]) 11426 SelectTruncOp[0].insert(std::make_pair(User, 11427 User->getOperand(0).getValueType())); 11428 } else if (User->getOpcode() == ISD::SELECT_CC) { 11429 if (User->getOperand(0) == Inputs[i]) 11430 SelectTruncOp[0].insert(std::make_pair(User, 11431 User->getOperand(0).getValueType())); 11432 if (User->getOperand(1) == Inputs[i]) 11433 SelectTruncOp[1].insert(std::make_pair(User, 11434 User->getOperand(1).getValueType())); 11435 } 11436 } 11437 } 11438 11439 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11440 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11441 UE = PromOps[i].getNode()->use_end(); 11442 UI != UE; ++UI) { 11443 SDNode *User = *UI; 11444 if (User != N && !Visited.count(User)) 11445 return SDValue(); 11446 11447 // If we're going to promote the non-output-value operand(s) or SELECT or 11448 // SELECT_CC, record them for truncation. 11449 if (User->getOpcode() == ISD::SELECT) { 11450 if (User->getOperand(0) == PromOps[i]) 11451 SelectTruncOp[0].insert(std::make_pair(User, 11452 User->getOperand(0).getValueType())); 11453 } else if (User->getOpcode() == ISD::SELECT_CC) { 11454 if (User->getOperand(0) == PromOps[i]) 11455 SelectTruncOp[0].insert(std::make_pair(User, 11456 User->getOperand(0).getValueType())); 11457 if (User->getOperand(1) == PromOps[i]) 11458 SelectTruncOp[1].insert(std::make_pair(User, 11459 User->getOperand(1).getValueType())); 11460 } 11461 } 11462 } 11463 11464 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 11465 bool ReallyNeedsExt = false; 11466 if (N->getOpcode() != ISD::ANY_EXTEND) { 11467 // If all of the inputs are not already sign/zero extended, then 11468 // we'll still need to do that at the end. 11469 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11470 if (isa<ConstantSDNode>(Inputs[i])) 11471 continue; 11472 11473 unsigned OpBits = 11474 Inputs[i].getOperand(0).getValueSizeInBits(); 11475 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 11476 11477 if ((N->getOpcode() == ISD::ZERO_EXTEND && 11478 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 11479 APInt::getHighBitsSet(OpBits, 11480 OpBits-PromBits))) || 11481 (N->getOpcode() == ISD::SIGN_EXTEND && 11482 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 11483 (OpBits-(PromBits-1)))) { 11484 ReallyNeedsExt = true; 11485 break; 11486 } 11487 } 11488 } 11489 11490 // Replace all inputs, either with the truncation operand, or a 11491 // truncation or extension to the final output type. 11492 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11493 // Constant inputs need to be replaced with the to-be-promoted nodes that 11494 // use them because they might have users outside of the cluster of 11495 // promoted nodes. 11496 if (isa<ConstantSDNode>(Inputs[i])) 11497 continue; 11498 11499 SDValue InSrc = Inputs[i].getOperand(0); 11500 if (Inputs[i].getValueType() == N->getValueType(0)) 11501 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 11502 else if (N->getOpcode() == ISD::SIGN_EXTEND) 11503 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11504 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 11505 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11506 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11507 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 11508 else 11509 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11510 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 11511 } 11512 11513 std::list<HandleSDNode> PromOpHandles; 11514 for (auto &PromOp : PromOps) 11515 PromOpHandles.emplace_back(PromOp); 11516 11517 // Replace all operations (these are all the same, but have a different 11518 // (promoted) return type). DAG.getNode will validate that the types of 11519 // a binary operator match, so go through the list in reverse so that 11520 // we've likely promoted both operands first. 11521 while (!PromOpHandles.empty()) { 11522 SDValue PromOp = PromOpHandles.back().getValue(); 11523 PromOpHandles.pop_back(); 11524 11525 unsigned C; 11526 switch (PromOp.getOpcode()) { 11527 default: C = 0; break; 11528 case ISD::SELECT: C = 1; break; 11529 case ISD::SELECT_CC: C = 2; break; 11530 } 11531 11532 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11533 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 11534 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11535 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 11536 // The to-be-promoted operands of this node have not yet been 11537 // promoted (this should be rare because we're going through the 11538 // list backward, but if one of the operands has several users in 11539 // this cluster of to-be-promoted nodes, it is possible). 11540 PromOpHandles.emplace_front(PromOp); 11541 continue; 11542 } 11543 11544 // For SELECT and SELECT_CC nodes, we do a similar check for any 11545 // to-be-promoted comparison inputs. 11546 if (PromOp.getOpcode() == ISD::SELECT || 11547 PromOp.getOpcode() == ISD::SELECT_CC) { 11548 if ((SelectTruncOp[0].count(PromOp.getNode()) && 11549 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 11550 (SelectTruncOp[1].count(PromOp.getNode()) && 11551 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 11552 PromOpHandles.emplace_front(PromOp); 11553 continue; 11554 } 11555 } 11556 11557 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11558 PromOp.getNode()->op_end()); 11559 11560 // If this node has constant inputs, then they'll need to be promoted here. 11561 for (unsigned i = 0; i < 2; ++i) { 11562 if (!isa<ConstantSDNode>(Ops[C+i])) 11563 continue; 11564 if (Ops[C+i].getValueType() == N->getValueType(0)) 11565 continue; 11566 11567 if (N->getOpcode() == ISD::SIGN_EXTEND) 11568 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11569 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11570 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11571 else 11572 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11573 } 11574 11575 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 11576 // truncate them again to the original value type. 11577 if (PromOp.getOpcode() == ISD::SELECT || 11578 PromOp.getOpcode() == ISD::SELECT_CC) { 11579 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 11580 if (SI0 != SelectTruncOp[0].end()) 11581 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 11582 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 11583 if (SI1 != SelectTruncOp[1].end()) 11584 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 11585 } 11586 11587 DAG.ReplaceAllUsesOfValueWith(PromOp, 11588 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 11589 } 11590 11591 // Now we're left with the initial extension itself. 11592 if (!ReallyNeedsExt) 11593 return N->getOperand(0); 11594 11595 // To zero extend, just mask off everything except for the first bit (in the 11596 // i1 case). 11597 if (N->getOpcode() == ISD::ZERO_EXTEND) 11598 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 11599 DAG.getConstant(APInt::getLowBitsSet( 11600 N->getValueSizeInBits(0), PromBits), 11601 dl, N->getValueType(0))); 11602 11603 assert(N->getOpcode() == ISD::SIGN_EXTEND && 11604 "Invalid extension type"); 11605 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 11606 SDValue ShiftCst = 11607 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 11608 return DAG.getNode( 11609 ISD::SRA, dl, N->getValueType(0), 11610 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 11611 ShiftCst); 11612 } 11613 11614 /// Reduces the number of fp-to-int conversion when building a vector. 11615 /// 11616 /// If this vector is built out of floating to integer conversions, 11617 /// transform it to a vector built out of floating point values followed by a 11618 /// single floating to integer conversion of the vector. 11619 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 11620 /// becomes (fptosi (build_vector ($A, $B, ...))) 11621 SDValue PPCTargetLowering:: 11622 combineElementTruncationToVectorTruncation(SDNode *N, 11623 DAGCombinerInfo &DCI) const { 11624 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11625 "Should be called with a BUILD_VECTOR node"); 11626 11627 SelectionDAG &DAG = DCI.DAG; 11628 SDLoc dl(N); 11629 11630 SDValue FirstInput = N->getOperand(0); 11631 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 11632 "The input operand must be an fp-to-int conversion."); 11633 11634 // This combine happens after legalization so the fp_to_[su]i nodes are 11635 // already converted to PPCSISD nodes. 11636 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 11637 if (FirstConversion == PPCISD::FCTIDZ || 11638 FirstConversion == PPCISD::FCTIDUZ || 11639 FirstConversion == PPCISD::FCTIWZ || 11640 FirstConversion == PPCISD::FCTIWUZ) { 11641 bool IsSplat = true; 11642 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 11643 FirstConversion == PPCISD::FCTIWUZ; 11644 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 11645 SmallVector<SDValue, 4> Ops; 11646 EVT TargetVT = N->getValueType(0); 11647 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11648 if (N->getOperand(i).getOpcode() != PPCISD::MFVSR) 11649 return SDValue(); 11650 unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode(); 11651 if (NextConversion != FirstConversion) 11652 return SDValue(); 11653 if (N->getOperand(i) != FirstInput) 11654 IsSplat = false; 11655 } 11656 11657 // If this is a splat, we leave it as-is since there will be only a single 11658 // fp-to-int conversion followed by a splat of the integer. This is better 11659 // for 32-bit and smaller ints and neutral for 64-bit ints. 11660 if (IsSplat) 11661 return SDValue(); 11662 11663 // Now that we know we have the right type of node, get its operands 11664 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11665 SDValue In = N->getOperand(i).getOperand(0); 11666 // For 32-bit values, we need to add an FP_ROUND node. 11667 if (Is32Bit) { 11668 if (In.isUndef()) 11669 Ops.push_back(DAG.getUNDEF(SrcVT)); 11670 else { 11671 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 11672 MVT::f32, In.getOperand(0), 11673 DAG.getIntPtrConstant(1, dl)); 11674 Ops.push_back(Trunc); 11675 } 11676 } else 11677 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 11678 } 11679 11680 unsigned Opcode; 11681 if (FirstConversion == PPCISD::FCTIDZ || 11682 FirstConversion == PPCISD::FCTIWZ) 11683 Opcode = ISD::FP_TO_SINT; 11684 else 11685 Opcode = ISD::FP_TO_UINT; 11686 11687 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 11688 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 11689 return DAG.getNode(Opcode, dl, TargetVT, BV); 11690 } 11691 return SDValue(); 11692 } 11693 11694 /// Reduce the number of loads when building a vector. 11695 /// 11696 /// Building a vector out of multiple loads can be converted to a load 11697 /// of the vector type if the loads are consecutive. If the loads are 11698 /// consecutive but in descending order, a shuffle is added at the end 11699 /// to reorder the vector. 11700 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 11701 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11702 "Should be called with a BUILD_VECTOR node"); 11703 11704 SDLoc dl(N); 11705 bool InputsAreConsecutiveLoads = true; 11706 bool InputsAreReverseConsecutive = true; 11707 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8; 11708 SDValue FirstInput = N->getOperand(0); 11709 bool IsRoundOfExtLoad = false; 11710 11711 if (FirstInput.getOpcode() == ISD::FP_ROUND && 11712 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 11713 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 11714 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 11715 } 11716 // Not a build vector of (possibly fp_rounded) loads. 11717 if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) 11718 return SDValue(); 11719 11720 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 11721 // If any inputs are fp_round(extload), they all must be. 11722 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 11723 return SDValue(); 11724 11725 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 11726 N->getOperand(i); 11727 if (NextInput.getOpcode() != ISD::LOAD) 11728 return SDValue(); 11729 11730 SDValue PreviousInput = 11731 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 11732 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 11733 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 11734 11735 // If any inputs are fp_round(extload), they all must be. 11736 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 11737 return SDValue(); 11738 11739 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 11740 InputsAreConsecutiveLoads = false; 11741 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 11742 InputsAreReverseConsecutive = false; 11743 11744 // Exit early if the loads are neither consecutive nor reverse consecutive. 11745 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 11746 return SDValue(); 11747 } 11748 11749 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 11750 "The loads cannot be both consecutive and reverse consecutive."); 11751 11752 SDValue FirstLoadOp = 11753 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 11754 SDValue LastLoadOp = 11755 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 11756 N->getOperand(N->getNumOperands()-1); 11757 11758 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 11759 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 11760 if (InputsAreConsecutiveLoads) { 11761 assert(LD1 && "Input needs to be a LoadSDNode."); 11762 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 11763 LD1->getBasePtr(), LD1->getPointerInfo(), 11764 LD1->getAlignment()); 11765 } 11766 if (InputsAreReverseConsecutive) { 11767 assert(LDL && "Input needs to be a LoadSDNode."); 11768 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 11769 LDL->getBasePtr(), LDL->getPointerInfo(), 11770 LDL->getAlignment()); 11771 SmallVector<int, 16> Ops; 11772 for (int i = N->getNumOperands() - 1; i >= 0; i--) 11773 Ops.push_back(i); 11774 11775 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 11776 DAG.getUNDEF(N->getValueType(0)), Ops); 11777 } 11778 return SDValue(); 11779 } 11780 11781 // This function adds the required vector_shuffle needed to get 11782 // the elements of the vector extract in the correct position 11783 // as specified by the CorrectElems encoding. 11784 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 11785 SDValue Input, uint64_t Elems, 11786 uint64_t CorrectElems) { 11787 SDLoc dl(N); 11788 11789 unsigned NumElems = Input.getValueType().getVectorNumElements(); 11790 SmallVector<int, 16> ShuffleMask(NumElems, -1); 11791 11792 // Knowing the element indices being extracted from the original 11793 // vector and the order in which they're being inserted, just put 11794 // them at element indices required for the instruction. 11795 for (unsigned i = 0; i < N->getNumOperands(); i++) { 11796 if (DAG.getDataLayout().isLittleEndian()) 11797 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 11798 else 11799 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 11800 CorrectElems = CorrectElems >> 8; 11801 Elems = Elems >> 8; 11802 } 11803 11804 SDValue Shuffle = 11805 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 11806 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 11807 11808 EVT Ty = N->getValueType(0); 11809 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 11810 return BV; 11811 } 11812 11813 // Look for build vector patterns where input operands come from sign 11814 // extended vector_extract elements of specific indices. If the correct indices 11815 // aren't used, add a vector shuffle to fix up the indices and create a new 11816 // PPCISD:SExtVElems node which selects the vector sign extend instructions 11817 // during instruction selection. 11818 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 11819 // This array encodes the indices that the vector sign extend instructions 11820 // extract from when extending from one type to another for both BE and LE. 11821 // The right nibble of each byte corresponds to the LE incides. 11822 // and the left nibble of each byte corresponds to the BE incides. 11823 // For example: 0x3074B8FC byte->word 11824 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 11825 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 11826 // For example: 0x000070F8 byte->double word 11827 // For LE: the allowed indices are: 0x0,0x8 11828 // For BE: the allowed indices are: 0x7,0xF 11829 uint64_t TargetElems[] = { 11830 0x3074B8FC, // b->w 11831 0x000070F8, // b->d 11832 0x10325476, // h->w 11833 0x00003074, // h->d 11834 0x00001032, // w->d 11835 }; 11836 11837 uint64_t Elems = 0; 11838 int Index; 11839 SDValue Input; 11840 11841 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 11842 if (!Op) 11843 return false; 11844 if (Op.getOpcode() != ISD::SIGN_EXTEND) 11845 return false; 11846 11847 SDValue Extract = Op.getOperand(0); 11848 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11849 return false; 11850 11851 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 11852 if (!ExtOp) 11853 return false; 11854 11855 Index = ExtOp->getZExtValue(); 11856 if (Input && Input != Extract.getOperand(0)) 11857 return false; 11858 11859 if (!Input) 11860 Input = Extract.getOperand(0); 11861 11862 Elems = Elems << 8; 11863 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 11864 Elems |= Index; 11865 11866 return true; 11867 }; 11868 11869 // If the build vector operands aren't sign extended vector extracts, 11870 // of the same input vector, then return. 11871 for (unsigned i = 0; i < N->getNumOperands(); i++) { 11872 if (!isSExtOfVecExtract(N->getOperand(i))) { 11873 return SDValue(); 11874 } 11875 } 11876 11877 // If the vector extract indicies are not correct, add the appropriate 11878 // vector_shuffle. 11879 int TgtElemArrayIdx; 11880 int InputSize = Input.getValueType().getScalarSizeInBits(); 11881 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 11882 if (InputSize + OutputSize == 40) 11883 TgtElemArrayIdx = 0; 11884 else if (InputSize + OutputSize == 72) 11885 TgtElemArrayIdx = 1; 11886 else if (InputSize + OutputSize == 48) 11887 TgtElemArrayIdx = 2; 11888 else if (InputSize + OutputSize == 80) 11889 TgtElemArrayIdx = 3; 11890 else if (InputSize + OutputSize == 96) 11891 TgtElemArrayIdx = 4; 11892 else 11893 return SDValue(); 11894 11895 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 11896 CorrectElems = DAG.getDataLayout().isLittleEndian() 11897 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 11898 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 11899 if (Elems != CorrectElems) { 11900 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 11901 } 11902 11903 // Regular lowering will catch cases where a shuffle is not needed. 11904 return SDValue(); 11905 } 11906 11907 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 11908 DAGCombinerInfo &DCI) const { 11909 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11910 "Should be called with a BUILD_VECTOR node"); 11911 11912 SelectionDAG &DAG = DCI.DAG; 11913 SDLoc dl(N); 11914 11915 if (!Subtarget.hasVSX()) 11916 return SDValue(); 11917 11918 // The target independent DAG combiner will leave a build_vector of 11919 // float-to-int conversions intact. We can generate MUCH better code for 11920 // a float-to-int conversion of a vector of floats. 11921 SDValue FirstInput = N->getOperand(0); 11922 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 11923 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 11924 if (Reduced) 11925 return Reduced; 11926 } 11927 11928 // If we're building a vector out of consecutive loads, just load that 11929 // vector type. 11930 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 11931 if (Reduced) 11932 return Reduced; 11933 11934 // If we're building a vector out of extended elements from another vector 11935 // we have P9 vector integer extend instructions. 11936 if (Subtarget.hasP9Altivec()) { 11937 Reduced = combineBVOfVecSExt(N, DAG); 11938 if (Reduced) 11939 return Reduced; 11940 } 11941 11942 11943 if (N->getValueType(0) != MVT::v2f64) 11944 return SDValue(); 11945 11946 // Looking for: 11947 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 11948 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 11949 FirstInput.getOpcode() != ISD::UINT_TO_FP) 11950 return SDValue(); 11951 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 11952 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 11953 return SDValue(); 11954 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 11955 return SDValue(); 11956 11957 SDValue Ext1 = FirstInput.getOperand(0); 11958 SDValue Ext2 = N->getOperand(1).getOperand(0); 11959 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11960 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11961 return SDValue(); 11962 11963 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 11964 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 11965 if (!Ext1Op || !Ext2Op) 11966 return SDValue(); 11967 if (Ext1.getValueType() != MVT::i32 || 11968 Ext2.getValueType() != MVT::i32) 11969 if (Ext1.getOperand(0) != Ext2.getOperand(0)) 11970 return SDValue(); 11971 11972 int FirstElem = Ext1Op->getZExtValue(); 11973 int SecondElem = Ext2Op->getZExtValue(); 11974 int SubvecIdx; 11975 if (FirstElem == 0 && SecondElem == 1) 11976 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 11977 else if (FirstElem == 2 && SecondElem == 3) 11978 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 11979 else 11980 return SDValue(); 11981 11982 SDValue SrcVec = Ext1.getOperand(0); 11983 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 11984 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 11985 return DAG.getNode(NodeType, dl, MVT::v2f64, 11986 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 11987 } 11988 11989 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 11990 DAGCombinerInfo &DCI) const { 11991 assert((N->getOpcode() == ISD::SINT_TO_FP || 11992 N->getOpcode() == ISD::UINT_TO_FP) && 11993 "Need an int -> FP conversion node here"); 11994 11995 if (useSoftFloat() || !Subtarget.has64BitSupport()) 11996 return SDValue(); 11997 11998 SelectionDAG &DAG = DCI.DAG; 11999 SDLoc dl(N); 12000 SDValue Op(N, 0); 12001 12002 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 12003 // from the hardware. 12004 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 12005 return SDValue(); 12006 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 12007 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 12008 return SDValue(); 12009 12010 SDValue FirstOperand(Op.getOperand(0)); 12011 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 12012 (FirstOperand.getValueType() == MVT::i8 || 12013 FirstOperand.getValueType() == MVT::i16); 12014 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 12015 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 12016 bool DstDouble = Op.getValueType() == MVT::f64; 12017 unsigned ConvOp = Signed ? 12018 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 12019 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 12020 SDValue WidthConst = 12021 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 12022 dl, false); 12023 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 12024 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 12025 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 12026 DAG.getVTList(MVT::f64, MVT::Other), 12027 Ops, MVT::i8, LDN->getMemOperand()); 12028 12029 // For signed conversion, we need to sign-extend the value in the VSR 12030 if (Signed) { 12031 SDValue ExtOps[] = { Ld, WidthConst }; 12032 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 12033 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 12034 } else 12035 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 12036 } 12037 12038 12039 // For i32 intermediate values, unfortunately, the conversion functions 12040 // leave the upper 32 bits of the value are undefined. Within the set of 12041 // scalar instructions, we have no method for zero- or sign-extending the 12042 // value. Thus, we cannot handle i32 intermediate values here. 12043 if (Op.getOperand(0).getValueType() == MVT::i32) 12044 return SDValue(); 12045 12046 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 12047 "UINT_TO_FP is supported only with FPCVT"); 12048 12049 // If we have FCFIDS, then use it when converting to single-precision. 12050 // Otherwise, convert to double-precision and then round. 12051 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12052 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12053 : PPCISD::FCFIDS) 12054 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12055 : PPCISD::FCFID); 12056 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12057 ? MVT::f32 12058 : MVT::f64; 12059 12060 // If we're converting from a float, to an int, and back to a float again, 12061 // then we don't need the store/load pair at all. 12062 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12063 Subtarget.hasFPCVT()) || 12064 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12065 SDValue Src = Op.getOperand(0).getOperand(0); 12066 if (Src.getValueType() == MVT::f32) { 12067 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12068 DCI.AddToWorklist(Src.getNode()); 12069 } else if (Src.getValueType() != MVT::f64) { 12070 // Make sure that we don't pick up a ppc_fp128 source value. 12071 return SDValue(); 12072 } 12073 12074 unsigned FCTOp = 12075 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12076 PPCISD::FCTIDUZ; 12077 12078 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12079 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12080 12081 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12082 FP = DAG.getNode(ISD::FP_ROUND, dl, 12083 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12084 DCI.AddToWorklist(FP.getNode()); 12085 } 12086 12087 return FP; 12088 } 12089 12090 return SDValue(); 12091 } 12092 12093 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12094 // builtins) into loads with swaps. 12095 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12096 DAGCombinerInfo &DCI) const { 12097 SelectionDAG &DAG = DCI.DAG; 12098 SDLoc dl(N); 12099 SDValue Chain; 12100 SDValue Base; 12101 MachineMemOperand *MMO; 12102 12103 switch (N->getOpcode()) { 12104 default: 12105 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12106 case ISD::LOAD: { 12107 LoadSDNode *LD = cast<LoadSDNode>(N); 12108 Chain = LD->getChain(); 12109 Base = LD->getBasePtr(); 12110 MMO = LD->getMemOperand(); 12111 // If the MMO suggests this isn't a load of a full vector, leave 12112 // things alone. For a built-in, we have to make the change for 12113 // correctness, so if there is a size problem that will be a bug. 12114 if (MMO->getSize() < 16) 12115 return SDValue(); 12116 break; 12117 } 12118 case ISD::INTRINSIC_W_CHAIN: { 12119 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12120 Chain = Intrin->getChain(); 12121 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12122 // us what we want. Get operand 2 instead. 12123 Base = Intrin->getOperand(2); 12124 MMO = Intrin->getMemOperand(); 12125 break; 12126 } 12127 } 12128 12129 MVT VecTy = N->getValueType(0).getSimpleVT(); 12130 12131 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12132 // aligned and the type is a vector with elements up to 4 bytes 12133 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12134 && VecTy.getScalarSizeInBits() <= 32 ) { 12135 return SDValue(); 12136 } 12137 12138 SDValue LoadOps[] = { Chain, Base }; 12139 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12140 DAG.getVTList(MVT::v2f64, MVT::Other), 12141 LoadOps, MVT::v2f64, MMO); 12142 12143 DCI.AddToWorklist(Load.getNode()); 12144 Chain = Load.getValue(1); 12145 SDValue Swap = DAG.getNode( 12146 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12147 DCI.AddToWorklist(Swap.getNode()); 12148 12149 // Add a bitcast if the resulting load type doesn't match v2f64. 12150 if (VecTy != MVT::v2f64) { 12151 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12152 DCI.AddToWorklist(N.getNode()); 12153 // Package {bitcast value, swap's chain} to match Load's shape. 12154 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12155 N, Swap.getValue(1)); 12156 } 12157 12158 return Swap; 12159 } 12160 12161 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12162 // builtins) into stores with swaps. 12163 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12164 DAGCombinerInfo &DCI) const { 12165 SelectionDAG &DAG = DCI.DAG; 12166 SDLoc dl(N); 12167 SDValue Chain; 12168 SDValue Base; 12169 unsigned SrcOpnd; 12170 MachineMemOperand *MMO; 12171 12172 switch (N->getOpcode()) { 12173 default: 12174 llvm_unreachable("Unexpected opcode for little endian VSX store"); 12175 case ISD::STORE: { 12176 StoreSDNode *ST = cast<StoreSDNode>(N); 12177 Chain = ST->getChain(); 12178 Base = ST->getBasePtr(); 12179 MMO = ST->getMemOperand(); 12180 SrcOpnd = 1; 12181 // If the MMO suggests this isn't a store of a full vector, leave 12182 // things alone. For a built-in, we have to make the change for 12183 // correctness, so if there is a size problem that will be a bug. 12184 if (MMO->getSize() < 16) 12185 return SDValue(); 12186 break; 12187 } 12188 case ISD::INTRINSIC_VOID: { 12189 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12190 Chain = Intrin->getChain(); 12191 // Intrin->getBasePtr() oddly does not get what we want. 12192 Base = Intrin->getOperand(3); 12193 MMO = Intrin->getMemOperand(); 12194 SrcOpnd = 2; 12195 break; 12196 } 12197 } 12198 12199 SDValue Src = N->getOperand(SrcOpnd); 12200 MVT VecTy = Src.getValueType().getSimpleVT(); 12201 12202 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 12203 // aligned and the type is a vector with elements up to 4 bytes 12204 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12205 && VecTy.getScalarSizeInBits() <= 32 ) { 12206 return SDValue(); 12207 } 12208 12209 // All stores are done as v2f64 and possible bit cast. 12210 if (VecTy != MVT::v2f64) { 12211 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 12212 DCI.AddToWorklist(Src.getNode()); 12213 } 12214 12215 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 12216 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 12217 DCI.AddToWorklist(Swap.getNode()); 12218 Chain = Swap.getValue(1); 12219 SDValue StoreOps[] = { Chain, Swap, Base }; 12220 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 12221 DAG.getVTList(MVT::Other), 12222 StoreOps, VecTy, MMO); 12223 DCI.AddToWorklist(Store.getNode()); 12224 return Store; 12225 } 12226 12227 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 12228 DAGCombinerInfo &DCI) const { 12229 SelectionDAG &DAG = DCI.DAG; 12230 SDLoc dl(N); 12231 switch (N->getOpcode()) { 12232 default: break; 12233 case ISD::SHL: 12234 return combineSHL(N, DCI); 12235 case ISD::SRA: 12236 return combineSRA(N, DCI); 12237 case ISD::SRL: 12238 return combineSRL(N, DCI); 12239 case PPCISD::SHL: 12240 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 12241 return N->getOperand(0); 12242 break; 12243 case PPCISD::SRL: 12244 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 12245 return N->getOperand(0); 12246 break; 12247 case PPCISD::SRA: 12248 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 12249 if (C->isNullValue() || // 0 >>s V -> 0. 12250 C->isAllOnesValue()) // -1 >>s V -> -1. 12251 return N->getOperand(0); 12252 } 12253 break; 12254 case ISD::SIGN_EXTEND: 12255 case ISD::ZERO_EXTEND: 12256 case ISD::ANY_EXTEND: 12257 return DAGCombineExtBoolTrunc(N, DCI); 12258 case ISD::TRUNCATE: 12259 case ISD::SETCC: 12260 case ISD::SELECT_CC: 12261 return DAGCombineTruncBoolExt(N, DCI); 12262 case ISD::SINT_TO_FP: 12263 case ISD::UINT_TO_FP: 12264 return combineFPToIntToFP(N, DCI); 12265 case ISD::STORE: { 12266 EVT Op1VT = N->getOperand(1).getValueType(); 12267 bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) || 12268 (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16)); 12269 12270 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)). 12271 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() && 12272 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT && 12273 ValidTypeForStoreFltAsInt && 12274 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) { 12275 SDValue Val = N->getOperand(1).getOperand(0); 12276 if (Val.getValueType() == MVT::f32) { 12277 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 12278 DCI.AddToWorklist(Val.getNode()); 12279 } 12280 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val); 12281 DCI.AddToWorklist(Val.getNode()); 12282 12283 if (Op1VT == MVT::i32) { 12284 SDValue Ops[] = { 12285 N->getOperand(0), Val, N->getOperand(2), 12286 DAG.getValueType(N->getOperand(1).getValueType()) 12287 }; 12288 12289 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 12290 DAG.getVTList(MVT::Other), Ops, 12291 cast<StoreSDNode>(N)->getMemoryVT(), 12292 cast<StoreSDNode>(N)->getMemOperand()); 12293 } else { 12294 unsigned WidthInBytes = 12295 N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2; 12296 SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false); 12297 12298 SDValue Ops[] = { 12299 N->getOperand(0), Val, N->getOperand(2), WidthConst, 12300 DAG.getValueType(N->getOperand(1).getValueType()) 12301 }; 12302 Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl, 12303 DAG.getVTList(MVT::Other), Ops, 12304 cast<StoreSDNode>(N)->getMemoryVT(), 12305 cast<StoreSDNode>(N)->getMemOperand()); 12306 } 12307 12308 DCI.AddToWorklist(Val.getNode()); 12309 return Val; 12310 } 12311 12312 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 12313 if (cast<StoreSDNode>(N)->isUnindexed() && 12314 N->getOperand(1).getOpcode() == ISD::BSWAP && 12315 N->getOperand(1).getNode()->hasOneUse() && 12316 (N->getOperand(1).getValueType() == MVT::i32 || 12317 N->getOperand(1).getValueType() == MVT::i16 || 12318 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 12319 N->getOperand(1).getValueType() == MVT::i64))) { 12320 // STBRX can only handle simple types. 12321 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 12322 if (mVT.isExtended()) 12323 break; 12324 12325 SDValue BSwapOp = N->getOperand(1).getOperand(0); 12326 // Do an any-extend to 32-bits if this is a half-word input. 12327 if (BSwapOp.getValueType() == MVT::i16) 12328 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 12329 12330 // If the type of BSWAP operand is wider than stored memory width 12331 // it need to be shifted to the right side before STBRX. 12332 if (Op1VT.bitsGT(mVT)) { 12333 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 12334 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 12335 DAG.getConstant(Shift, dl, MVT::i32)); 12336 // Need to truncate if this is a bswap of i64 stored as i32/i16. 12337 if (Op1VT == MVT::i64) 12338 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 12339 } 12340 12341 SDValue Ops[] = { 12342 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 12343 }; 12344 return 12345 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 12346 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 12347 cast<StoreSDNode>(N)->getMemOperand()); 12348 } 12349 12350 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 12351 // So it can increase the chance of CSE constant construction. 12352 EVT VT = N->getOperand(1).getValueType(); 12353 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 12354 isa<ConstantSDNode>(N->getOperand(1)) && VT == MVT::i32) { 12355 // Need to sign-extended to 64-bits to handle negative values. 12356 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 12357 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 12358 MemVT.getSizeInBits()); 12359 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 12360 12361 // DAG.getTruncStore() can't be used here because it doesn't accept 12362 // the general (base + offset) addressing mode. 12363 // So we use UpdateNodeOperands and setTruncatingStore instead. 12364 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 12365 N->getOperand(3)); 12366 cast<StoreSDNode>(N)->setTruncatingStore(true); 12367 return SDValue(N, 0); 12368 } 12369 12370 // For little endian, VSX stores require generating xxswapd/lxvd2x. 12371 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12372 if (VT.isSimple()) { 12373 MVT StoreVT = VT.getSimpleVT(); 12374 if (Subtarget.needsSwapsForVSXMemOps() && 12375 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 12376 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 12377 return expandVSXStoreForLE(N, DCI); 12378 } 12379 break; 12380 } 12381 case ISD::LOAD: { 12382 LoadSDNode *LD = cast<LoadSDNode>(N); 12383 EVT VT = LD->getValueType(0); 12384 12385 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12386 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12387 if (VT.isSimple()) { 12388 MVT LoadVT = VT.getSimpleVT(); 12389 if (Subtarget.needsSwapsForVSXMemOps() && 12390 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 12391 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 12392 return expandVSXLoadForLE(N, DCI); 12393 } 12394 12395 // We sometimes end up with a 64-bit integer load, from which we extract 12396 // two single-precision floating-point numbers. This happens with 12397 // std::complex<float>, and other similar structures, because of the way we 12398 // canonicalize structure copies. However, if we lack direct moves, 12399 // then the final bitcasts from the extracted integer values to the 12400 // floating-point numbers turn into store/load pairs. Even with direct moves, 12401 // just loading the two floating-point numbers is likely better. 12402 auto ReplaceTwoFloatLoad = [&]() { 12403 if (VT != MVT::i64) 12404 return false; 12405 12406 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 12407 LD->isVolatile()) 12408 return false; 12409 12410 // We're looking for a sequence like this: 12411 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 12412 // t16: i64 = srl t13, Constant:i32<32> 12413 // t17: i32 = truncate t16 12414 // t18: f32 = bitcast t17 12415 // t19: i32 = truncate t13 12416 // t20: f32 = bitcast t19 12417 12418 if (!LD->hasNUsesOfValue(2, 0)) 12419 return false; 12420 12421 auto UI = LD->use_begin(); 12422 while (UI.getUse().getResNo() != 0) ++UI; 12423 SDNode *Trunc = *UI++; 12424 while (UI.getUse().getResNo() != 0) ++UI; 12425 SDNode *RightShift = *UI; 12426 if (Trunc->getOpcode() != ISD::TRUNCATE) 12427 std::swap(Trunc, RightShift); 12428 12429 if (Trunc->getOpcode() != ISD::TRUNCATE || 12430 Trunc->getValueType(0) != MVT::i32 || 12431 !Trunc->hasOneUse()) 12432 return false; 12433 if (RightShift->getOpcode() != ISD::SRL || 12434 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 12435 RightShift->getConstantOperandVal(1) != 32 || 12436 !RightShift->hasOneUse()) 12437 return false; 12438 12439 SDNode *Trunc2 = *RightShift->use_begin(); 12440 if (Trunc2->getOpcode() != ISD::TRUNCATE || 12441 Trunc2->getValueType(0) != MVT::i32 || 12442 !Trunc2->hasOneUse()) 12443 return false; 12444 12445 SDNode *Bitcast = *Trunc->use_begin(); 12446 SDNode *Bitcast2 = *Trunc2->use_begin(); 12447 12448 if (Bitcast->getOpcode() != ISD::BITCAST || 12449 Bitcast->getValueType(0) != MVT::f32) 12450 return false; 12451 if (Bitcast2->getOpcode() != ISD::BITCAST || 12452 Bitcast2->getValueType(0) != MVT::f32) 12453 return false; 12454 12455 if (Subtarget.isLittleEndian()) 12456 std::swap(Bitcast, Bitcast2); 12457 12458 // Bitcast has the second float (in memory-layout order) and Bitcast2 12459 // has the first one. 12460 12461 SDValue BasePtr = LD->getBasePtr(); 12462 if (LD->isIndexed()) { 12463 assert(LD->getAddressingMode() == ISD::PRE_INC && 12464 "Non-pre-inc AM on PPC?"); 12465 BasePtr = 12466 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 12467 LD->getOffset()); 12468 } 12469 12470 auto MMOFlags = 12471 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 12472 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 12473 LD->getPointerInfo(), LD->getAlignment(), 12474 MMOFlags, LD->getAAInfo()); 12475 SDValue AddPtr = 12476 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 12477 BasePtr, DAG.getIntPtrConstant(4, dl)); 12478 SDValue FloatLoad2 = DAG.getLoad( 12479 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 12480 LD->getPointerInfo().getWithOffset(4), 12481 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 12482 12483 if (LD->isIndexed()) { 12484 // Note that DAGCombine should re-form any pre-increment load(s) from 12485 // what is produced here if that makes sense. 12486 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 12487 } 12488 12489 DCI.CombineTo(Bitcast2, FloatLoad); 12490 DCI.CombineTo(Bitcast, FloatLoad2); 12491 12492 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 12493 SDValue(FloatLoad2.getNode(), 1)); 12494 return true; 12495 }; 12496 12497 if (ReplaceTwoFloatLoad()) 12498 return SDValue(N, 0); 12499 12500 EVT MemVT = LD->getMemoryVT(); 12501 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 12502 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 12503 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 12504 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 12505 if (LD->isUnindexed() && VT.isVector() && 12506 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 12507 // P8 and later hardware should just use LOAD. 12508 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 12509 VT == MVT::v4i32 || VT == MVT::v4f32)) || 12510 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 12511 LD->getAlignment() >= ScalarABIAlignment)) && 12512 LD->getAlignment() < ABIAlignment) { 12513 // This is a type-legal unaligned Altivec or QPX load. 12514 SDValue Chain = LD->getChain(); 12515 SDValue Ptr = LD->getBasePtr(); 12516 bool isLittleEndian = Subtarget.isLittleEndian(); 12517 12518 // This implements the loading of unaligned vectors as described in 12519 // the venerable Apple Velocity Engine overview. Specifically: 12520 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 12521 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 12522 // 12523 // The general idea is to expand a sequence of one or more unaligned 12524 // loads into an alignment-based permutation-control instruction (lvsl 12525 // or lvsr), a series of regular vector loads (which always truncate 12526 // their input address to an aligned address), and a series of 12527 // permutations. The results of these permutations are the requested 12528 // loaded values. The trick is that the last "extra" load is not taken 12529 // from the address you might suspect (sizeof(vector) bytes after the 12530 // last requested load), but rather sizeof(vector) - 1 bytes after the 12531 // last requested vector. The point of this is to avoid a page fault if 12532 // the base address happened to be aligned. This works because if the 12533 // base address is aligned, then adding less than a full vector length 12534 // will cause the last vector in the sequence to be (re)loaded. 12535 // Otherwise, the next vector will be fetched as you might suspect was 12536 // necessary. 12537 12538 // We might be able to reuse the permutation generation from 12539 // a different base address offset from this one by an aligned amount. 12540 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 12541 // optimization later. 12542 Intrinsic::ID Intr, IntrLD, IntrPerm; 12543 MVT PermCntlTy, PermTy, LDTy; 12544 if (Subtarget.hasAltivec()) { 12545 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 12546 Intrinsic::ppc_altivec_lvsl; 12547 IntrLD = Intrinsic::ppc_altivec_lvx; 12548 IntrPerm = Intrinsic::ppc_altivec_vperm; 12549 PermCntlTy = MVT::v16i8; 12550 PermTy = MVT::v4i32; 12551 LDTy = MVT::v4i32; 12552 } else { 12553 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 12554 Intrinsic::ppc_qpx_qvlpcls; 12555 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 12556 Intrinsic::ppc_qpx_qvlfs; 12557 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 12558 PermCntlTy = MVT::v4f64; 12559 PermTy = MVT::v4f64; 12560 LDTy = MemVT.getSimpleVT(); 12561 } 12562 12563 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 12564 12565 // Create the new MMO for the new base load. It is like the original MMO, 12566 // but represents an area in memory almost twice the vector size centered 12567 // on the original address. If the address is unaligned, we might start 12568 // reading up to (sizeof(vector)-1) bytes below the address of the 12569 // original unaligned load. 12570 MachineFunction &MF = DAG.getMachineFunction(); 12571 MachineMemOperand *BaseMMO = 12572 MF.getMachineMemOperand(LD->getMemOperand(), 12573 -(long)MemVT.getStoreSize()+1, 12574 2*MemVT.getStoreSize()-1); 12575 12576 // Create the new base load. 12577 SDValue LDXIntID = 12578 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 12579 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 12580 SDValue BaseLoad = 12581 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12582 DAG.getVTList(PermTy, MVT::Other), 12583 BaseLoadOps, LDTy, BaseMMO); 12584 12585 // Note that the value of IncOffset (which is provided to the next 12586 // load's pointer info offset value, and thus used to calculate the 12587 // alignment), and the value of IncValue (which is actually used to 12588 // increment the pointer value) are different! This is because we 12589 // require the next load to appear to be aligned, even though it 12590 // is actually offset from the base pointer by a lesser amount. 12591 int IncOffset = VT.getSizeInBits() / 8; 12592 int IncValue = IncOffset; 12593 12594 // Walk (both up and down) the chain looking for another load at the real 12595 // (aligned) offset (the alignment of the other load does not matter in 12596 // this case). If found, then do not use the offset reduction trick, as 12597 // that will prevent the loads from being later combined (as they would 12598 // otherwise be duplicates). 12599 if (!findConsecutiveLoad(LD, DAG)) 12600 --IncValue; 12601 12602 SDValue Increment = 12603 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 12604 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 12605 12606 MachineMemOperand *ExtraMMO = 12607 MF.getMachineMemOperand(LD->getMemOperand(), 12608 1, 2*MemVT.getStoreSize()-1); 12609 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 12610 SDValue ExtraLoad = 12611 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12612 DAG.getVTList(PermTy, MVT::Other), 12613 ExtraLoadOps, LDTy, ExtraMMO); 12614 12615 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 12616 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 12617 12618 // Because vperm has a big-endian bias, we must reverse the order 12619 // of the input vectors and complement the permute control vector 12620 // when generating little endian code. We have already handled the 12621 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 12622 // and ExtraLoad here. 12623 SDValue Perm; 12624 if (isLittleEndian) 12625 Perm = BuildIntrinsicOp(IntrPerm, 12626 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 12627 else 12628 Perm = BuildIntrinsicOp(IntrPerm, 12629 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 12630 12631 if (VT != PermTy) 12632 Perm = Subtarget.hasAltivec() ? 12633 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 12634 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 12635 DAG.getTargetConstant(1, dl, MVT::i64)); 12636 // second argument is 1 because this rounding 12637 // is always exact. 12638 12639 // The output of the permutation is our loaded result, the TokenFactor is 12640 // our new chain. 12641 DCI.CombineTo(N, Perm, TF); 12642 return SDValue(N, 0); 12643 } 12644 } 12645 break; 12646 case ISD::INTRINSIC_WO_CHAIN: { 12647 bool isLittleEndian = Subtarget.isLittleEndian(); 12648 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12649 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 12650 : Intrinsic::ppc_altivec_lvsl); 12651 if ((IID == Intr || 12652 IID == Intrinsic::ppc_qpx_qvlpcld || 12653 IID == Intrinsic::ppc_qpx_qvlpcls) && 12654 N->getOperand(1)->getOpcode() == ISD::ADD) { 12655 SDValue Add = N->getOperand(1); 12656 12657 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 12658 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 12659 12660 if (DAG.MaskedValueIsZero(Add->getOperand(1), 12661 APInt::getAllOnesValue(Bits /* alignment */) 12662 .zext(Add.getScalarValueSizeInBits()))) { 12663 SDNode *BasePtr = Add->getOperand(0).getNode(); 12664 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12665 UE = BasePtr->use_end(); 12666 UI != UE; ++UI) { 12667 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12668 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 12669 // We've found another LVSL/LVSR, and this address is an aligned 12670 // multiple of that one. The results will be the same, so use the 12671 // one we've just found instead. 12672 12673 return SDValue(*UI, 0); 12674 } 12675 } 12676 } 12677 12678 if (isa<ConstantSDNode>(Add->getOperand(1))) { 12679 SDNode *BasePtr = Add->getOperand(0).getNode(); 12680 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12681 UE = BasePtr->use_end(); UI != UE; ++UI) { 12682 if (UI->getOpcode() == ISD::ADD && 12683 isa<ConstantSDNode>(UI->getOperand(1)) && 12684 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 12685 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 12686 (1ULL << Bits) == 0) { 12687 SDNode *OtherAdd = *UI; 12688 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 12689 VE = OtherAdd->use_end(); VI != VE; ++VI) { 12690 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12691 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 12692 return SDValue(*VI, 0); 12693 } 12694 } 12695 } 12696 } 12697 } 12698 } 12699 } 12700 12701 break; 12702 case ISD::INTRINSIC_W_CHAIN: 12703 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12704 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12705 if (Subtarget.needsSwapsForVSXMemOps()) { 12706 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12707 default: 12708 break; 12709 case Intrinsic::ppc_vsx_lxvw4x: 12710 case Intrinsic::ppc_vsx_lxvd2x: 12711 return expandVSXLoadForLE(N, DCI); 12712 } 12713 } 12714 break; 12715 case ISD::INTRINSIC_VOID: 12716 // For little endian, VSX stores require generating xxswapd/stxvd2x. 12717 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12718 if (Subtarget.needsSwapsForVSXMemOps()) { 12719 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12720 default: 12721 break; 12722 case Intrinsic::ppc_vsx_stxvw4x: 12723 case Intrinsic::ppc_vsx_stxvd2x: 12724 return expandVSXStoreForLE(N, DCI); 12725 } 12726 } 12727 break; 12728 case ISD::BSWAP: 12729 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 12730 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 12731 N->getOperand(0).hasOneUse() && 12732 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 12733 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 12734 N->getValueType(0) == MVT::i64))) { 12735 SDValue Load = N->getOperand(0); 12736 LoadSDNode *LD = cast<LoadSDNode>(Load); 12737 // Create the byte-swapping load. 12738 SDValue Ops[] = { 12739 LD->getChain(), // Chain 12740 LD->getBasePtr(), // Ptr 12741 DAG.getValueType(N->getValueType(0)) // VT 12742 }; 12743 SDValue BSLoad = 12744 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 12745 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 12746 MVT::i64 : MVT::i32, MVT::Other), 12747 Ops, LD->getMemoryVT(), LD->getMemOperand()); 12748 12749 // If this is an i16 load, insert the truncate. 12750 SDValue ResVal = BSLoad; 12751 if (N->getValueType(0) == MVT::i16) 12752 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 12753 12754 // First, combine the bswap away. This makes the value produced by the 12755 // load dead. 12756 DCI.CombineTo(N, ResVal); 12757 12758 // Next, combine the load away, we give it a bogus result value but a real 12759 // chain result. The result value is dead because the bswap is dead. 12760 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 12761 12762 // Return N so it doesn't get rechecked! 12763 return SDValue(N, 0); 12764 } 12765 break; 12766 case PPCISD::VCMP: 12767 // If a VCMPo node already exists with exactly the same operands as this 12768 // node, use its result instead of this node (VCMPo computes both a CR6 and 12769 // a normal output). 12770 // 12771 if (!N->getOperand(0).hasOneUse() && 12772 !N->getOperand(1).hasOneUse() && 12773 !N->getOperand(2).hasOneUse()) { 12774 12775 // Scan all of the users of the LHS, looking for VCMPo's that match. 12776 SDNode *VCMPoNode = nullptr; 12777 12778 SDNode *LHSN = N->getOperand(0).getNode(); 12779 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 12780 UI != E; ++UI) 12781 if (UI->getOpcode() == PPCISD::VCMPo && 12782 UI->getOperand(1) == N->getOperand(1) && 12783 UI->getOperand(2) == N->getOperand(2) && 12784 UI->getOperand(0) == N->getOperand(0)) { 12785 VCMPoNode = *UI; 12786 break; 12787 } 12788 12789 // If there is no VCMPo node, or if the flag value has a single use, don't 12790 // transform this. 12791 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 12792 break; 12793 12794 // Look at the (necessarily single) use of the flag value. If it has a 12795 // chain, this transformation is more complex. Note that multiple things 12796 // could use the value result, which we should ignore. 12797 SDNode *FlagUser = nullptr; 12798 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 12799 FlagUser == nullptr; ++UI) { 12800 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 12801 SDNode *User = *UI; 12802 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 12803 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 12804 FlagUser = User; 12805 break; 12806 } 12807 } 12808 } 12809 12810 // If the user is a MFOCRF instruction, we know this is safe. 12811 // Otherwise we give up for right now. 12812 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 12813 return SDValue(VCMPoNode, 0); 12814 } 12815 break; 12816 case ISD::BRCOND: { 12817 SDValue Cond = N->getOperand(1); 12818 SDValue Target = N->getOperand(2); 12819 12820 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 12821 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 12822 Intrinsic::ppc_is_decremented_ctr_nonzero) { 12823 12824 // We now need to make the intrinsic dead (it cannot be instruction 12825 // selected). 12826 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 12827 assert(Cond.getNode()->hasOneUse() && 12828 "Counter decrement has more than one use"); 12829 12830 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 12831 N->getOperand(0), Target); 12832 } 12833 } 12834 break; 12835 case ISD::BR_CC: { 12836 // If this is a branch on an altivec predicate comparison, lower this so 12837 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 12838 // lowering is done pre-legalize, because the legalizer lowers the predicate 12839 // compare down to code that is difficult to reassemble. 12840 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 12841 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 12842 12843 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 12844 // value. If so, pass-through the AND to get to the intrinsic. 12845 if (LHS.getOpcode() == ISD::AND && 12846 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 12847 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 12848 Intrinsic::ppc_is_decremented_ctr_nonzero && 12849 isa<ConstantSDNode>(LHS.getOperand(1)) && 12850 !isNullConstant(LHS.getOperand(1))) 12851 LHS = LHS.getOperand(0); 12852 12853 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 12854 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 12855 Intrinsic::ppc_is_decremented_ctr_nonzero && 12856 isa<ConstantSDNode>(RHS)) { 12857 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 12858 "Counter decrement comparison is not EQ or NE"); 12859 12860 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 12861 bool isBDNZ = (CC == ISD::SETEQ && Val) || 12862 (CC == ISD::SETNE && !Val); 12863 12864 // We now need to make the intrinsic dead (it cannot be instruction 12865 // selected). 12866 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 12867 assert(LHS.getNode()->hasOneUse() && 12868 "Counter decrement has more than one use"); 12869 12870 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 12871 N->getOperand(0), N->getOperand(4)); 12872 } 12873 12874 int CompareOpc; 12875 bool isDot; 12876 12877 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12878 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 12879 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 12880 assert(isDot && "Can't compare against a vector result!"); 12881 12882 // If this is a comparison against something other than 0/1, then we know 12883 // that the condition is never/always true. 12884 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 12885 if (Val != 0 && Val != 1) { 12886 if (CC == ISD::SETEQ) // Cond never true, remove branch. 12887 return N->getOperand(0); 12888 // Always !=, turn it into an unconditional branch. 12889 return DAG.getNode(ISD::BR, dl, MVT::Other, 12890 N->getOperand(0), N->getOperand(4)); 12891 } 12892 12893 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 12894 12895 // Create the PPCISD altivec 'dot' comparison node. 12896 SDValue Ops[] = { 12897 LHS.getOperand(2), // LHS of compare 12898 LHS.getOperand(3), // RHS of compare 12899 DAG.getConstant(CompareOpc, dl, MVT::i32) 12900 }; 12901 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 12902 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 12903 12904 // Unpack the result based on how the target uses it. 12905 PPC::Predicate CompOpc; 12906 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 12907 default: // Can't happen, don't crash on invalid number though. 12908 case 0: // Branch on the value of the EQ bit of CR6. 12909 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 12910 break; 12911 case 1: // Branch on the inverted value of the EQ bit of CR6. 12912 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 12913 break; 12914 case 2: // Branch on the value of the LT bit of CR6. 12915 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 12916 break; 12917 case 3: // Branch on the inverted value of the LT bit of CR6. 12918 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 12919 break; 12920 } 12921 12922 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 12923 DAG.getConstant(CompOpc, dl, MVT::i32), 12924 DAG.getRegister(PPC::CR6, MVT::i32), 12925 N->getOperand(4), CompNode.getValue(1)); 12926 } 12927 break; 12928 } 12929 case ISD::BUILD_VECTOR: 12930 return DAGCombineBuildVector(N, DCI); 12931 } 12932 12933 return SDValue(); 12934 } 12935 12936 SDValue 12937 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12938 SelectionDAG &DAG, 12939 std::vector<SDNode *> *Created) const { 12940 // fold (sdiv X, pow2) 12941 EVT VT = N->getValueType(0); 12942 if (VT == MVT::i64 && !Subtarget.isPPC64()) 12943 return SDValue(); 12944 if ((VT != MVT::i32 && VT != MVT::i64) || 12945 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 12946 return SDValue(); 12947 12948 SDLoc DL(N); 12949 SDValue N0 = N->getOperand(0); 12950 12951 bool IsNegPow2 = (-Divisor).isPowerOf2(); 12952 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 12953 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 12954 12955 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 12956 if (Created) 12957 Created->push_back(Op.getNode()); 12958 12959 if (IsNegPow2) { 12960 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 12961 if (Created) 12962 Created->push_back(Op.getNode()); 12963 } 12964 12965 return Op; 12966 } 12967 12968 //===----------------------------------------------------------------------===// 12969 // Inline Assembly Support 12970 //===----------------------------------------------------------------------===// 12971 12972 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12973 KnownBits &Known, 12974 const APInt &DemandedElts, 12975 const SelectionDAG &DAG, 12976 unsigned Depth) const { 12977 Known.resetAll(); 12978 switch (Op.getOpcode()) { 12979 default: break; 12980 case PPCISD::LBRX: { 12981 // lhbrx is known to have the top bits cleared out. 12982 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 12983 Known.Zero = 0xFFFF0000; 12984 break; 12985 } 12986 case ISD::INTRINSIC_WO_CHAIN: { 12987 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 12988 default: break; 12989 case Intrinsic::ppc_altivec_vcmpbfp_p: 12990 case Intrinsic::ppc_altivec_vcmpeqfp_p: 12991 case Intrinsic::ppc_altivec_vcmpequb_p: 12992 case Intrinsic::ppc_altivec_vcmpequh_p: 12993 case Intrinsic::ppc_altivec_vcmpequw_p: 12994 case Intrinsic::ppc_altivec_vcmpequd_p: 12995 case Intrinsic::ppc_altivec_vcmpgefp_p: 12996 case Intrinsic::ppc_altivec_vcmpgtfp_p: 12997 case Intrinsic::ppc_altivec_vcmpgtsb_p: 12998 case Intrinsic::ppc_altivec_vcmpgtsh_p: 12999 case Intrinsic::ppc_altivec_vcmpgtsw_p: 13000 case Intrinsic::ppc_altivec_vcmpgtsd_p: 13001 case Intrinsic::ppc_altivec_vcmpgtub_p: 13002 case Intrinsic::ppc_altivec_vcmpgtuh_p: 13003 case Intrinsic::ppc_altivec_vcmpgtuw_p: 13004 case Intrinsic::ppc_altivec_vcmpgtud_p: 13005 Known.Zero = ~1U; // All bits but the low one are known to be zero. 13006 break; 13007 } 13008 } 13009 } 13010 } 13011 13012 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 13013 switch (Subtarget.getDarwinDirective()) { 13014 default: break; 13015 case PPC::DIR_970: 13016 case PPC::DIR_PWR4: 13017 case PPC::DIR_PWR5: 13018 case PPC::DIR_PWR5X: 13019 case PPC::DIR_PWR6: 13020 case PPC::DIR_PWR6X: 13021 case PPC::DIR_PWR7: 13022 case PPC::DIR_PWR8: 13023 case PPC::DIR_PWR9: { 13024 if (!ML) 13025 break; 13026 13027 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 13028 13029 // For small loops (between 5 and 8 instructions), align to a 32-byte 13030 // boundary so that the entire loop fits in one instruction-cache line. 13031 uint64_t LoopSize = 0; 13032 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 13033 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 13034 LoopSize += TII->getInstSizeInBytes(*J); 13035 if (LoopSize > 32) 13036 break; 13037 } 13038 13039 if (LoopSize > 16 && LoopSize <= 32) 13040 return 5; 13041 13042 break; 13043 } 13044 } 13045 13046 return TargetLowering::getPrefLoopAlignment(ML); 13047 } 13048 13049 /// getConstraintType - Given a constraint, return the type of 13050 /// constraint it is for this target. 13051 PPCTargetLowering::ConstraintType 13052 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 13053 if (Constraint.size() == 1) { 13054 switch (Constraint[0]) { 13055 default: break; 13056 case 'b': 13057 case 'r': 13058 case 'f': 13059 case 'd': 13060 case 'v': 13061 case 'y': 13062 return C_RegisterClass; 13063 case 'Z': 13064 // FIXME: While Z does indicate a memory constraint, it specifically 13065 // indicates an r+r address (used in conjunction with the 'y' modifier 13066 // in the replacement string). Currently, we're forcing the base 13067 // register to be r0 in the asm printer (which is interpreted as zero) 13068 // and forming the complete address in the second register. This is 13069 // suboptimal. 13070 return C_Memory; 13071 } 13072 } else if (Constraint == "wc") { // individual CR bits. 13073 return C_RegisterClass; 13074 } else if (Constraint == "wa" || Constraint == "wd" || 13075 Constraint == "wf" || Constraint == "ws") { 13076 return C_RegisterClass; // VSX registers. 13077 } 13078 return TargetLowering::getConstraintType(Constraint); 13079 } 13080 13081 /// Examine constraint type and operand type and determine a weight value. 13082 /// This object must already have been set up with the operand type 13083 /// and the current alternative constraint selected. 13084 TargetLowering::ConstraintWeight 13085 PPCTargetLowering::getSingleConstraintMatchWeight( 13086 AsmOperandInfo &info, const char *constraint) const { 13087 ConstraintWeight weight = CW_Invalid; 13088 Value *CallOperandVal = info.CallOperandVal; 13089 // If we don't have a value, we can't do a match, 13090 // but allow it at the lowest weight. 13091 if (!CallOperandVal) 13092 return CW_Default; 13093 Type *type = CallOperandVal->getType(); 13094 13095 // Look at the constraint type. 13096 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 13097 return CW_Register; // an individual CR bit. 13098 else if ((StringRef(constraint) == "wa" || 13099 StringRef(constraint) == "wd" || 13100 StringRef(constraint) == "wf") && 13101 type->isVectorTy()) 13102 return CW_Register; 13103 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 13104 return CW_Register; 13105 13106 switch (*constraint) { 13107 default: 13108 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13109 break; 13110 case 'b': 13111 if (type->isIntegerTy()) 13112 weight = CW_Register; 13113 break; 13114 case 'f': 13115 if (type->isFloatTy()) 13116 weight = CW_Register; 13117 break; 13118 case 'd': 13119 if (type->isDoubleTy()) 13120 weight = CW_Register; 13121 break; 13122 case 'v': 13123 if (type->isVectorTy()) 13124 weight = CW_Register; 13125 break; 13126 case 'y': 13127 weight = CW_Register; 13128 break; 13129 case 'Z': 13130 weight = CW_Memory; 13131 break; 13132 } 13133 return weight; 13134 } 13135 13136 std::pair<unsigned, const TargetRegisterClass *> 13137 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 13138 StringRef Constraint, 13139 MVT VT) const { 13140 if (Constraint.size() == 1) { 13141 // GCC RS6000 Constraint Letters 13142 switch (Constraint[0]) { 13143 case 'b': // R1-R31 13144 if (VT == MVT::i64 && Subtarget.isPPC64()) 13145 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 13146 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 13147 case 'r': // R0-R31 13148 if (VT == MVT::i64 && Subtarget.isPPC64()) 13149 return std::make_pair(0U, &PPC::G8RCRegClass); 13150 return std::make_pair(0U, &PPC::GPRCRegClass); 13151 // 'd' and 'f' constraints are both defined to be "the floating point 13152 // registers", where one is for 32-bit and the other for 64-bit. We don't 13153 // really care overly much here so just give them all the same reg classes. 13154 case 'd': 13155 case 'f': 13156 if (VT == MVT::f32 || VT == MVT::i32) 13157 return std::make_pair(0U, &PPC::F4RCRegClass); 13158 if (VT == MVT::f64 || VT == MVT::i64) 13159 return std::make_pair(0U, &PPC::F8RCRegClass); 13160 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13161 return std::make_pair(0U, &PPC::QFRCRegClass); 13162 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13163 return std::make_pair(0U, &PPC::QSRCRegClass); 13164 break; 13165 case 'v': 13166 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13167 return std::make_pair(0U, &PPC::QFRCRegClass); 13168 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13169 return std::make_pair(0U, &PPC::QSRCRegClass); 13170 if (Subtarget.hasAltivec()) 13171 return std::make_pair(0U, &PPC::VRRCRegClass); 13172 break; 13173 case 'y': // crrc 13174 return std::make_pair(0U, &PPC::CRRCRegClass); 13175 } 13176 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 13177 // An individual CR bit. 13178 return std::make_pair(0U, &PPC::CRBITRCRegClass); 13179 } else if ((Constraint == "wa" || Constraint == "wd" || 13180 Constraint == "wf") && Subtarget.hasVSX()) { 13181 return std::make_pair(0U, &PPC::VSRCRegClass); 13182 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 13183 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 13184 return std::make_pair(0U, &PPC::VSSRCRegClass); 13185 else 13186 return std::make_pair(0U, &PPC::VSFRCRegClass); 13187 } 13188 13189 std::pair<unsigned, const TargetRegisterClass *> R = 13190 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13191 13192 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 13193 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 13194 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 13195 // register. 13196 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 13197 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 13198 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 13199 PPC::GPRCRegClass.contains(R.first)) 13200 return std::make_pair(TRI->getMatchingSuperReg(R.first, 13201 PPC::sub_32, &PPC::G8RCRegClass), 13202 &PPC::G8RCRegClass); 13203 13204 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 13205 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 13206 R.first = PPC::CR0; 13207 R.second = &PPC::CRRCRegClass; 13208 } 13209 13210 return R; 13211 } 13212 13213 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13214 /// vector. If it is invalid, don't add anything to Ops. 13215 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13216 std::string &Constraint, 13217 std::vector<SDValue>&Ops, 13218 SelectionDAG &DAG) const { 13219 SDValue Result; 13220 13221 // Only support length 1 constraints. 13222 if (Constraint.length() > 1) return; 13223 13224 char Letter = Constraint[0]; 13225 switch (Letter) { 13226 default: break; 13227 case 'I': 13228 case 'J': 13229 case 'K': 13230 case 'L': 13231 case 'M': 13232 case 'N': 13233 case 'O': 13234 case 'P': { 13235 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 13236 if (!CST) return; // Must be an immediate to match. 13237 SDLoc dl(Op); 13238 int64_t Value = CST->getSExtValue(); 13239 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 13240 // numbers are printed as such. 13241 switch (Letter) { 13242 default: llvm_unreachable("Unknown constraint letter!"); 13243 case 'I': // "I" is a signed 16-bit constant. 13244 if (isInt<16>(Value)) 13245 Result = DAG.getTargetConstant(Value, dl, TCVT); 13246 break; 13247 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 13248 if (isShiftedUInt<16, 16>(Value)) 13249 Result = DAG.getTargetConstant(Value, dl, TCVT); 13250 break; 13251 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 13252 if (isShiftedInt<16, 16>(Value)) 13253 Result = DAG.getTargetConstant(Value, dl, TCVT); 13254 break; 13255 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 13256 if (isUInt<16>(Value)) 13257 Result = DAG.getTargetConstant(Value, dl, TCVT); 13258 break; 13259 case 'M': // "M" is a constant that is greater than 31. 13260 if (Value > 31) 13261 Result = DAG.getTargetConstant(Value, dl, TCVT); 13262 break; 13263 case 'N': // "N" is a positive constant that is an exact power of two. 13264 if (Value > 0 && isPowerOf2_64(Value)) 13265 Result = DAG.getTargetConstant(Value, dl, TCVT); 13266 break; 13267 case 'O': // "O" is the constant zero. 13268 if (Value == 0) 13269 Result = DAG.getTargetConstant(Value, dl, TCVT); 13270 break; 13271 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 13272 if (isInt<16>(-Value)) 13273 Result = DAG.getTargetConstant(Value, dl, TCVT); 13274 break; 13275 } 13276 break; 13277 } 13278 } 13279 13280 if (Result.getNode()) { 13281 Ops.push_back(Result); 13282 return; 13283 } 13284 13285 // Handle standard constraint letters. 13286 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13287 } 13288 13289 // isLegalAddressingMode - Return true if the addressing mode represented 13290 // by AM is legal for this target, for a load/store of the specified type. 13291 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13292 const AddrMode &AM, Type *Ty, 13293 unsigned AS, Instruction *I) const { 13294 // PPC does not allow r+i addressing modes for vectors! 13295 if (Ty->isVectorTy() && AM.BaseOffs != 0) 13296 return false; 13297 13298 // PPC allows a sign-extended 16-bit immediate field. 13299 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 13300 return false; 13301 13302 // No global is ever allowed as a base. 13303 if (AM.BaseGV) 13304 return false; 13305 13306 // PPC only support r+r, 13307 switch (AM.Scale) { 13308 case 0: // "r+i" or just "i", depending on HasBaseReg. 13309 break; 13310 case 1: 13311 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 13312 return false; 13313 // Otherwise we have r+r or r+i. 13314 break; 13315 case 2: 13316 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 13317 return false; 13318 // Allow 2*r as r+r. 13319 break; 13320 default: 13321 // No other scales are supported. 13322 return false; 13323 } 13324 13325 return true; 13326 } 13327 13328 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 13329 SelectionDAG &DAG) const { 13330 MachineFunction &MF = DAG.getMachineFunction(); 13331 MachineFrameInfo &MFI = MF.getFrameInfo(); 13332 MFI.setReturnAddressIsTaken(true); 13333 13334 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 13335 return SDValue(); 13336 13337 SDLoc dl(Op); 13338 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13339 13340 // Make sure the function does not optimize away the store of the RA to 13341 // the stack. 13342 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 13343 FuncInfo->setLRStoreRequired(); 13344 bool isPPC64 = Subtarget.isPPC64(); 13345 auto PtrVT = getPointerTy(MF.getDataLayout()); 13346 13347 if (Depth > 0) { 13348 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 13349 SDValue Offset = 13350 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 13351 isPPC64 ? MVT::i64 : MVT::i32); 13352 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 13353 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 13354 MachinePointerInfo()); 13355 } 13356 13357 // Just load the return address off the stack. 13358 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 13359 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 13360 MachinePointerInfo()); 13361 } 13362 13363 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 13364 SelectionDAG &DAG) const { 13365 SDLoc dl(Op); 13366 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13367 13368 MachineFunction &MF = DAG.getMachineFunction(); 13369 MachineFrameInfo &MFI = MF.getFrameInfo(); 13370 MFI.setFrameAddressIsTaken(true); 13371 13372 EVT PtrVT = getPointerTy(MF.getDataLayout()); 13373 bool isPPC64 = PtrVT == MVT::i64; 13374 13375 // Naked functions never have a frame pointer, and so we use r1. For all 13376 // other functions, this decision must be delayed until during PEI. 13377 unsigned FrameReg; 13378 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 13379 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 13380 else 13381 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 13382 13383 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 13384 PtrVT); 13385 while (Depth--) 13386 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 13387 FrameAddr, MachinePointerInfo()); 13388 return FrameAddr; 13389 } 13390 13391 // FIXME? Maybe this could be a TableGen attribute on some registers and 13392 // this table could be generated automatically from RegInfo. 13393 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 13394 SelectionDAG &DAG) const { 13395 bool isPPC64 = Subtarget.isPPC64(); 13396 bool isDarwinABI = Subtarget.isDarwinABI(); 13397 13398 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 13399 (!isPPC64 && VT != MVT::i32)) 13400 report_fatal_error("Invalid register global variable type"); 13401 13402 bool is64Bit = isPPC64 && VT == MVT::i64; 13403 unsigned Reg = StringSwitch<unsigned>(RegName) 13404 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 13405 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 13406 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 13407 (is64Bit ? PPC::X13 : PPC::R13)) 13408 .Default(0); 13409 13410 if (Reg) 13411 return Reg; 13412 report_fatal_error("Invalid register name global variable"); 13413 } 13414 13415 bool 13416 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13417 // The PowerPC target isn't yet aware of offsets. 13418 return false; 13419 } 13420 13421 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13422 const CallInst &I, 13423 MachineFunction &MF, 13424 unsigned Intrinsic) const { 13425 switch (Intrinsic) { 13426 case Intrinsic::ppc_qpx_qvlfd: 13427 case Intrinsic::ppc_qpx_qvlfs: 13428 case Intrinsic::ppc_qpx_qvlfcd: 13429 case Intrinsic::ppc_qpx_qvlfcs: 13430 case Intrinsic::ppc_qpx_qvlfiwa: 13431 case Intrinsic::ppc_qpx_qvlfiwz: 13432 case Intrinsic::ppc_altivec_lvx: 13433 case Intrinsic::ppc_altivec_lvxl: 13434 case Intrinsic::ppc_altivec_lvebx: 13435 case Intrinsic::ppc_altivec_lvehx: 13436 case Intrinsic::ppc_altivec_lvewx: 13437 case Intrinsic::ppc_vsx_lxvd2x: 13438 case Intrinsic::ppc_vsx_lxvw4x: { 13439 EVT VT; 13440 switch (Intrinsic) { 13441 case Intrinsic::ppc_altivec_lvebx: 13442 VT = MVT::i8; 13443 break; 13444 case Intrinsic::ppc_altivec_lvehx: 13445 VT = MVT::i16; 13446 break; 13447 case Intrinsic::ppc_altivec_lvewx: 13448 VT = MVT::i32; 13449 break; 13450 case Intrinsic::ppc_vsx_lxvd2x: 13451 VT = MVT::v2f64; 13452 break; 13453 case Intrinsic::ppc_qpx_qvlfd: 13454 VT = MVT::v4f64; 13455 break; 13456 case Intrinsic::ppc_qpx_qvlfs: 13457 VT = MVT::v4f32; 13458 break; 13459 case Intrinsic::ppc_qpx_qvlfcd: 13460 VT = MVT::v2f64; 13461 break; 13462 case Intrinsic::ppc_qpx_qvlfcs: 13463 VT = MVT::v2f32; 13464 break; 13465 default: 13466 VT = MVT::v4i32; 13467 break; 13468 } 13469 13470 Info.opc = ISD::INTRINSIC_W_CHAIN; 13471 Info.memVT = VT; 13472 Info.ptrVal = I.getArgOperand(0); 13473 Info.offset = -VT.getStoreSize()+1; 13474 Info.size = 2*VT.getStoreSize()-1; 13475 Info.align = 1; 13476 Info.flags = MachineMemOperand::MOLoad; 13477 return true; 13478 } 13479 case Intrinsic::ppc_qpx_qvlfda: 13480 case Intrinsic::ppc_qpx_qvlfsa: 13481 case Intrinsic::ppc_qpx_qvlfcda: 13482 case Intrinsic::ppc_qpx_qvlfcsa: 13483 case Intrinsic::ppc_qpx_qvlfiwaa: 13484 case Intrinsic::ppc_qpx_qvlfiwza: { 13485 EVT VT; 13486 switch (Intrinsic) { 13487 case Intrinsic::ppc_qpx_qvlfda: 13488 VT = MVT::v4f64; 13489 break; 13490 case Intrinsic::ppc_qpx_qvlfsa: 13491 VT = MVT::v4f32; 13492 break; 13493 case Intrinsic::ppc_qpx_qvlfcda: 13494 VT = MVT::v2f64; 13495 break; 13496 case Intrinsic::ppc_qpx_qvlfcsa: 13497 VT = MVT::v2f32; 13498 break; 13499 default: 13500 VT = MVT::v4i32; 13501 break; 13502 } 13503 13504 Info.opc = ISD::INTRINSIC_W_CHAIN; 13505 Info.memVT = VT; 13506 Info.ptrVal = I.getArgOperand(0); 13507 Info.offset = 0; 13508 Info.size = VT.getStoreSize(); 13509 Info.align = 1; 13510 Info.flags = MachineMemOperand::MOLoad; 13511 return true; 13512 } 13513 case Intrinsic::ppc_qpx_qvstfd: 13514 case Intrinsic::ppc_qpx_qvstfs: 13515 case Intrinsic::ppc_qpx_qvstfcd: 13516 case Intrinsic::ppc_qpx_qvstfcs: 13517 case Intrinsic::ppc_qpx_qvstfiw: 13518 case Intrinsic::ppc_altivec_stvx: 13519 case Intrinsic::ppc_altivec_stvxl: 13520 case Intrinsic::ppc_altivec_stvebx: 13521 case Intrinsic::ppc_altivec_stvehx: 13522 case Intrinsic::ppc_altivec_stvewx: 13523 case Intrinsic::ppc_vsx_stxvd2x: 13524 case Intrinsic::ppc_vsx_stxvw4x: { 13525 EVT VT; 13526 switch (Intrinsic) { 13527 case Intrinsic::ppc_altivec_stvebx: 13528 VT = MVT::i8; 13529 break; 13530 case Intrinsic::ppc_altivec_stvehx: 13531 VT = MVT::i16; 13532 break; 13533 case Intrinsic::ppc_altivec_stvewx: 13534 VT = MVT::i32; 13535 break; 13536 case Intrinsic::ppc_vsx_stxvd2x: 13537 VT = MVT::v2f64; 13538 break; 13539 case Intrinsic::ppc_qpx_qvstfd: 13540 VT = MVT::v4f64; 13541 break; 13542 case Intrinsic::ppc_qpx_qvstfs: 13543 VT = MVT::v4f32; 13544 break; 13545 case Intrinsic::ppc_qpx_qvstfcd: 13546 VT = MVT::v2f64; 13547 break; 13548 case Intrinsic::ppc_qpx_qvstfcs: 13549 VT = MVT::v2f32; 13550 break; 13551 default: 13552 VT = MVT::v4i32; 13553 break; 13554 } 13555 13556 Info.opc = ISD::INTRINSIC_VOID; 13557 Info.memVT = VT; 13558 Info.ptrVal = I.getArgOperand(1); 13559 Info.offset = -VT.getStoreSize()+1; 13560 Info.size = 2*VT.getStoreSize()-1; 13561 Info.align = 1; 13562 Info.flags = MachineMemOperand::MOStore; 13563 return true; 13564 } 13565 case Intrinsic::ppc_qpx_qvstfda: 13566 case Intrinsic::ppc_qpx_qvstfsa: 13567 case Intrinsic::ppc_qpx_qvstfcda: 13568 case Intrinsic::ppc_qpx_qvstfcsa: 13569 case Intrinsic::ppc_qpx_qvstfiwa: { 13570 EVT VT; 13571 switch (Intrinsic) { 13572 case Intrinsic::ppc_qpx_qvstfda: 13573 VT = MVT::v4f64; 13574 break; 13575 case Intrinsic::ppc_qpx_qvstfsa: 13576 VT = MVT::v4f32; 13577 break; 13578 case Intrinsic::ppc_qpx_qvstfcda: 13579 VT = MVT::v2f64; 13580 break; 13581 case Intrinsic::ppc_qpx_qvstfcsa: 13582 VT = MVT::v2f32; 13583 break; 13584 default: 13585 VT = MVT::v4i32; 13586 break; 13587 } 13588 13589 Info.opc = ISD::INTRINSIC_VOID; 13590 Info.memVT = VT; 13591 Info.ptrVal = I.getArgOperand(1); 13592 Info.offset = 0; 13593 Info.size = VT.getStoreSize(); 13594 Info.align = 1; 13595 Info.flags = MachineMemOperand::MOStore; 13596 return true; 13597 } 13598 default: 13599 break; 13600 } 13601 13602 return false; 13603 } 13604 13605 /// getOptimalMemOpType - Returns the target specific optimal type for load 13606 /// and store operations as a result of memset, memcpy, and memmove 13607 /// lowering. If DstAlign is zero that means it's safe to destination 13608 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 13609 /// means there isn't a need to check it against alignment requirement, 13610 /// probably because the source does not need to be loaded. If 'IsMemset' is 13611 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 13612 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 13613 /// source is constant so it does not need to be loaded. 13614 /// It returns EVT::Other if the type should be determined using generic 13615 /// target-independent logic. 13616 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 13617 unsigned DstAlign, unsigned SrcAlign, 13618 bool IsMemset, bool ZeroMemset, 13619 bool MemcpyStrSrc, 13620 MachineFunction &MF) const { 13621 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 13622 const Function &F = MF.getFunction(); 13623 // When expanding a memset, require at least two QPX instructions to cover 13624 // the cost of loading the value to be stored from the constant pool. 13625 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 13626 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 13627 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 13628 return MVT::v4f64; 13629 } 13630 13631 // We should use Altivec/VSX loads and stores when available. For unaligned 13632 // addresses, unaligned VSX loads are only fast starting with the P8. 13633 if (Subtarget.hasAltivec() && Size >= 16 && 13634 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 13635 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 13636 return MVT::v4i32; 13637 } 13638 13639 if (Subtarget.isPPC64()) { 13640 return MVT::i64; 13641 } 13642 13643 return MVT::i32; 13644 } 13645 13646 /// Returns true if it is beneficial to convert a load of a constant 13647 /// to just the constant itself. 13648 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13649 Type *Ty) const { 13650 assert(Ty->isIntegerTy()); 13651 13652 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 13653 return !(BitSize == 0 || BitSize > 64); 13654 } 13655 13656 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 13657 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13658 return false; 13659 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 13660 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 13661 return NumBits1 == 64 && NumBits2 == 32; 13662 } 13663 13664 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 13665 if (!VT1.isInteger() || !VT2.isInteger()) 13666 return false; 13667 unsigned NumBits1 = VT1.getSizeInBits(); 13668 unsigned NumBits2 = VT2.getSizeInBits(); 13669 return NumBits1 == 64 && NumBits2 == 32; 13670 } 13671 13672 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13673 // Generally speaking, zexts are not free, but they are free when they can be 13674 // folded with other operations. 13675 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 13676 EVT MemVT = LD->getMemoryVT(); 13677 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 13678 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 13679 (LD->getExtensionType() == ISD::NON_EXTLOAD || 13680 LD->getExtensionType() == ISD::ZEXTLOAD)) 13681 return true; 13682 } 13683 13684 // FIXME: Add other cases... 13685 // - 32-bit shifts with a zext to i64 13686 // - zext after ctlz, bswap, etc. 13687 // - zext after and by a constant mask 13688 13689 return TargetLowering::isZExtFree(Val, VT2); 13690 } 13691 13692 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 13693 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 13694 "invalid fpext types"); 13695 return true; 13696 } 13697 13698 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13699 return isInt<16>(Imm) || isUInt<16>(Imm); 13700 } 13701 13702 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13703 return isInt<16>(Imm) || isUInt<16>(Imm); 13704 } 13705 13706 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 13707 unsigned, 13708 unsigned, 13709 bool *Fast) const { 13710 if (DisablePPCUnaligned) 13711 return false; 13712 13713 // PowerPC supports unaligned memory access for simple non-vector types. 13714 // Although accessing unaligned addresses is not as efficient as accessing 13715 // aligned addresses, it is generally more efficient than manual expansion, 13716 // and generally only traps for software emulation when crossing page 13717 // boundaries. 13718 13719 if (!VT.isSimple()) 13720 return false; 13721 13722 if (VT.getSimpleVT().isVector()) { 13723 if (Subtarget.hasVSX()) { 13724 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 13725 VT != MVT::v4f32 && VT != MVT::v4i32) 13726 return false; 13727 } else { 13728 return false; 13729 } 13730 } 13731 13732 if (VT == MVT::ppcf128) 13733 return false; 13734 13735 if (Fast) 13736 *Fast = true; 13737 13738 return true; 13739 } 13740 13741 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 13742 VT = VT.getScalarType(); 13743 13744 if (!VT.isSimple()) 13745 return false; 13746 13747 switch (VT.getSimpleVT().SimpleTy) { 13748 case MVT::f32: 13749 case MVT::f64: 13750 return true; 13751 case MVT::f128: 13752 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 13753 default: 13754 break; 13755 } 13756 13757 return false; 13758 } 13759 13760 const MCPhysReg * 13761 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 13762 // LR is a callee-save register, but we must treat it as clobbered by any call 13763 // site. Hence we include LR in the scratch registers, which are in turn added 13764 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 13765 // to CTR, which is used by any indirect call. 13766 static const MCPhysReg ScratchRegs[] = { 13767 PPC::X12, PPC::LR8, PPC::CTR8, 0 13768 }; 13769 13770 return ScratchRegs; 13771 } 13772 13773 unsigned PPCTargetLowering::getExceptionPointerRegister( 13774 const Constant *PersonalityFn) const { 13775 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 13776 } 13777 13778 unsigned PPCTargetLowering::getExceptionSelectorRegister( 13779 const Constant *PersonalityFn) const { 13780 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 13781 } 13782 13783 bool 13784 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 13785 EVT VT , unsigned DefinedValues) const { 13786 if (VT == MVT::v2i64) 13787 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 13788 13789 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 13790 return true; 13791 13792 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 13793 } 13794 13795 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 13796 if (DisableILPPref || Subtarget.enableMachineScheduler()) 13797 return TargetLowering::getSchedulingPreference(N); 13798 13799 return Sched::ILP; 13800 } 13801 13802 // Create a fast isel object. 13803 FastISel * 13804 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 13805 const TargetLibraryInfo *LibInfo) const { 13806 return PPC::createFastISel(FuncInfo, LibInfo); 13807 } 13808 13809 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13810 if (Subtarget.isDarwinABI()) return; 13811 if (!Subtarget.isPPC64()) return; 13812 13813 // Update IsSplitCSR in PPCFunctionInfo 13814 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 13815 PFI->setIsSplitCSR(true); 13816 } 13817 13818 void PPCTargetLowering::insertCopiesSplitCSR( 13819 MachineBasicBlock *Entry, 13820 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13821 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 13822 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13823 if (!IStart) 13824 return; 13825 13826 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 13827 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13828 MachineBasicBlock::iterator MBBI = Entry->begin(); 13829 for (const MCPhysReg *I = IStart; *I; ++I) { 13830 const TargetRegisterClass *RC = nullptr; 13831 if (PPC::G8RCRegClass.contains(*I)) 13832 RC = &PPC::G8RCRegClass; 13833 else if (PPC::F8RCRegClass.contains(*I)) 13834 RC = &PPC::F8RCRegClass; 13835 else if (PPC::CRRCRegClass.contains(*I)) 13836 RC = &PPC::CRRCRegClass; 13837 else if (PPC::VRRCRegClass.contains(*I)) 13838 RC = &PPC::VRRCRegClass; 13839 else 13840 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13841 13842 unsigned NewVR = MRI->createVirtualRegister(RC); 13843 // Create copy from CSR to a virtual register. 13844 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13845 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13846 // nounwind. If we want to generalize this later, we may need to emit 13847 // CFI pseudo-instructions. 13848 assert(Entry->getParent()->getFunction().hasFnAttribute( 13849 Attribute::NoUnwind) && 13850 "Function should be nounwind in insertCopiesSplitCSR!"); 13851 Entry->addLiveIn(*I); 13852 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 13853 .addReg(*I); 13854 13855 // Insert the copy-back instructions right before the terminator 13856 for (auto *Exit : Exits) 13857 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 13858 TII->get(TargetOpcode::COPY), *I) 13859 .addReg(NewVR); 13860 } 13861 } 13862 13863 // Override to enable LOAD_STACK_GUARD lowering on Linux. 13864 bool PPCTargetLowering::useLoadStackGuardNode() const { 13865 if (!Subtarget.isTargetLinux()) 13866 return TargetLowering::useLoadStackGuardNode(); 13867 return true; 13868 } 13869 13870 // Override to disable global variable loading on Linux. 13871 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 13872 if (!Subtarget.isTargetLinux()) 13873 return TargetLowering::insertSSPDeclarations(M); 13874 } 13875 13876 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 13877 if (!VT.isSimple() || !Subtarget.hasVSX()) 13878 return false; 13879 13880 switch(VT.getSimpleVT().SimpleTy) { 13881 default: 13882 // For FP types that are currently not supported by PPC backend, return 13883 // false. Examples: f16, f80. 13884 return false; 13885 case MVT::f32: 13886 case MVT::f64: 13887 case MVT::ppcf128: 13888 return Imm.isPosZero(); 13889 } 13890 } 13891 13892 // For vector shift operation op, fold 13893 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 13894 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 13895 SelectionDAG &DAG) { 13896 SDValue N0 = N->getOperand(0); 13897 SDValue N1 = N->getOperand(1); 13898 EVT VT = N0.getValueType(); 13899 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 13900 unsigned Opcode = N->getOpcode(); 13901 unsigned TargetOpcode; 13902 13903 switch (Opcode) { 13904 default: 13905 llvm_unreachable("Unexpected shift operation"); 13906 case ISD::SHL: 13907 TargetOpcode = PPCISD::SHL; 13908 break; 13909 case ISD::SRL: 13910 TargetOpcode = PPCISD::SRL; 13911 break; 13912 case ISD::SRA: 13913 TargetOpcode = PPCISD::SRA; 13914 break; 13915 } 13916 13917 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 13918 N1->getOpcode() == ISD::AND) 13919 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 13920 if (Mask->getZExtValue() == OpSizeInBits - 1) 13921 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 13922 13923 return SDValue(); 13924 } 13925 13926 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 13927 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13928 return Value; 13929 13930 return SDValue(); 13931 } 13932 13933 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 13934 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13935 return Value; 13936 13937 return SDValue(); 13938 } 13939 13940 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 13941 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13942 return Value; 13943 13944 return SDValue(); 13945 } 13946 13947 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 13948 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 13949 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 13950 return false; 13951 13952 // If not a tail call then no need to proceed. 13953 if (!CI->isTailCall()) 13954 return false; 13955 13956 // If tail calls are disabled for the caller then we are done. 13957 const Function *Caller = CI->getParent()->getParent(); 13958 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 13959 if (Attr.getValueAsString() == "true") 13960 return false; 13961 13962 // If sibling calls have been disabled and tail-calls aren't guaranteed 13963 // there is no reason to duplicate. 13964 auto &TM = getTargetMachine(); 13965 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 13966 return false; 13967 13968 // Can't tail call a function called indirectly, or if it has variadic args. 13969 const Function *Callee = CI->getCalledFunction(); 13970 if (!Callee || Callee->isVarArg()) 13971 return false; 13972 13973 // Make sure the callee and caller calling conventions are eligible for tco. 13974 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 13975 CI->getCallingConv())) 13976 return false; 13977 13978 // If the function is local then we have a good chance at tail-calling it 13979 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 13980 } 13981 13982 bool PPCTargetLowering:: 13983 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 13984 const Value *Mask = AndI.getOperand(1); 13985 // If the mask is suitable for andi. or andis. we should sink the and. 13986 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 13987 // Can't handle constants wider than 64-bits. 13988 if (CI->getBitWidth() > 64) 13989 return false; 13990 int64_t ConstVal = CI->getZExtValue(); 13991 return isUInt<16>(ConstVal) || 13992 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 13993 } 13994 13995 // For non-constant masks, we can always use the record-form and. 13996 return true; 13997 } 13998