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/MachineValueType.h" 51 #include "llvm/CodeGen/RuntimeLibcalls.h" 52 #include "llvm/CodeGen/SelectionDAG.h" 53 #include "llvm/CodeGen/SelectionDAGNodes.h" 54 #include "llvm/CodeGen/TargetInstrInfo.h" 55 #include "llvm/CodeGen/TargetLowering.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallSite.h" 59 #include "llvm/IR/CallingConv.h" 60 #include "llvm/IR/Constant.h" 61 #include "llvm/IR/Constants.h" 62 #include "llvm/IR/DataLayout.h" 63 #include "llvm/IR/DebugLoc.h" 64 #include "llvm/IR/DerivedTypes.h" 65 #include "llvm/IR/Function.h" 66 #include "llvm/IR/GlobalValue.h" 67 #include "llvm/IR/IRBuilder.h" 68 #include "llvm/IR/Instructions.h" 69 #include "llvm/IR/Intrinsics.h" 70 #include "llvm/IR/Module.h" 71 #include "llvm/IR/Type.h" 72 #include "llvm/IR/Use.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/MC/MCExpr.h" 75 #include "llvm/MC/MCRegisterInfo.h" 76 #include "llvm/Support/AtomicOrdering.h" 77 #include "llvm/Support/BranchProbability.h" 78 #include "llvm/Support/Casting.h" 79 #include "llvm/Support/CodeGen.h" 80 #include "llvm/Support/CommandLine.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/Debug.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/Format.h" 85 #include "llvm/Support/KnownBits.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 STATISTIC(NumTailCalls, "Number of tail calls"); 115 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 116 117 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 118 119 // FIXME: Remove this once the bug has been fixed! 120 extern cl::opt<bool> ANDIGlueBug; 121 122 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 123 const PPCSubtarget &STI) 124 : TargetLowering(TM), Subtarget(STI) { 125 // Use _setjmp/_longjmp instead of setjmp/longjmp. 126 setUseUnderscoreSetJmp(true); 127 setUseUnderscoreLongJmp(true); 128 129 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 130 // arguments are at least 4/8 bytes aligned. 131 bool isPPC64 = Subtarget.isPPC64(); 132 setMinStackArgumentAlignment(isPPC64 ? 8:4); 133 134 // Set up the register classes. 135 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 136 if (!useSoftFloat()) { 137 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 138 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 139 } 140 141 // Match BITREVERSE to customized fast code sequence in the td file. 142 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 143 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 144 145 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 146 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 147 148 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 149 for (MVT VT : MVT::integer_valuetypes()) { 150 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 151 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 152 } 153 154 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 155 156 // PowerPC has pre-inc load and store's. 157 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 158 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 159 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 160 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 161 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 162 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 163 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 164 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 165 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 166 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 167 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 168 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 169 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 170 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 171 172 if (Subtarget.useCRBits()) { 173 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 174 175 if (isPPC64 || Subtarget.hasFPCVT()) { 176 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 177 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 178 isPPC64 ? MVT::i64 : MVT::i32); 179 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 180 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 181 isPPC64 ? MVT::i64 : MVT::i32); 182 } else { 183 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 184 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 185 } 186 187 // PowerPC does not support direct load/store of condition registers. 188 setOperationAction(ISD::LOAD, MVT::i1, Custom); 189 setOperationAction(ISD::STORE, MVT::i1, Custom); 190 191 // FIXME: Remove this once the ANDI glue bug is fixed: 192 if (ANDIGlueBug) 193 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 194 195 for (MVT VT : MVT::integer_valuetypes()) { 196 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 197 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 198 setTruncStoreAction(VT, MVT::i1, Expand); 199 } 200 201 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 202 } 203 204 // This is used in the ppcf128->int sequence. Note it has different semantics 205 // from FP_ROUND: that rounds to nearest, this rounds to zero. 206 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom); 207 208 // We do not currently implement these libm ops for PowerPC. 209 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 210 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 211 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 212 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 213 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 214 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 215 216 // PowerPC has no SREM/UREM instructions unless we are on P9 217 // On P9 we may use a hardware instruction to compute the remainder. 218 // The instructions are not legalized directly because in the cases where the 219 // result of both the remainder and the division is required it is more 220 // efficient to compute the remainder from the result of the division rather 221 // than use the remainder instruction. 222 if (Subtarget.isISA3_0()) { 223 setOperationAction(ISD::SREM, MVT::i32, Custom); 224 setOperationAction(ISD::UREM, MVT::i32, Custom); 225 setOperationAction(ISD::SREM, MVT::i64, Custom); 226 setOperationAction(ISD::UREM, MVT::i64, Custom); 227 } else { 228 setOperationAction(ISD::SREM, MVT::i32, Expand); 229 setOperationAction(ISD::UREM, MVT::i32, Expand); 230 setOperationAction(ISD::SREM, MVT::i64, Expand); 231 setOperationAction(ISD::UREM, MVT::i64, Expand); 232 } 233 234 if (Subtarget.hasP9Vector()) { 235 setOperationAction(ISD::ABS, MVT::v4i32, Legal); 236 setOperationAction(ISD::ABS, MVT::v8i16, Legal); 237 setOperationAction(ISD::ABS, MVT::v16i8, Legal); 238 } 239 240 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 241 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 242 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 243 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 244 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 245 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 246 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 247 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 248 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 249 250 // We don't support sin/cos/sqrt/fmod/pow 251 setOperationAction(ISD::FSIN , MVT::f64, Expand); 252 setOperationAction(ISD::FCOS , MVT::f64, Expand); 253 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 254 setOperationAction(ISD::FREM , MVT::f64, Expand); 255 setOperationAction(ISD::FPOW , MVT::f64, Expand); 256 setOperationAction(ISD::FMA , MVT::f64, Legal); 257 setOperationAction(ISD::FSIN , MVT::f32, Expand); 258 setOperationAction(ISD::FCOS , MVT::f32, Expand); 259 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 260 setOperationAction(ISD::FREM , MVT::f32, Expand); 261 setOperationAction(ISD::FPOW , MVT::f32, Expand); 262 setOperationAction(ISD::FMA , MVT::f32, Legal); 263 264 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 265 266 // If we're enabling GP optimizations, use hardware square root 267 if (!Subtarget.hasFSQRT() && 268 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 269 Subtarget.hasFRE())) 270 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 271 272 if (!Subtarget.hasFSQRT() && 273 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 274 Subtarget.hasFRES())) 275 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 276 277 if (Subtarget.hasFCPSGN()) { 278 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 279 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 280 } else { 281 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 282 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 283 } 284 285 if (Subtarget.hasFPRND()) { 286 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 287 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 288 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 289 setOperationAction(ISD::FROUND, MVT::f64, Legal); 290 291 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 292 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 293 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 294 setOperationAction(ISD::FROUND, MVT::f32, Legal); 295 } 296 297 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 298 // to speed up scalar BSWAP64. 299 // CTPOP or CTTZ were introduced in P8/P9 respectivelly 300 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 301 if (Subtarget.isISA3_0()) { 302 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 303 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 304 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 305 } else { 306 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 307 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 308 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 309 } 310 311 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 312 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 313 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 314 } else { 315 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 316 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 317 } 318 319 // PowerPC does not have ROTR 320 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 321 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 322 323 if (!Subtarget.useCRBits()) { 324 // PowerPC does not have Select 325 setOperationAction(ISD::SELECT, MVT::i32, Expand); 326 setOperationAction(ISD::SELECT, MVT::i64, Expand); 327 setOperationAction(ISD::SELECT, MVT::f32, Expand); 328 setOperationAction(ISD::SELECT, MVT::f64, Expand); 329 } 330 331 // PowerPC wants to turn select_cc of FP into fsel when possible. 332 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 333 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 334 335 // PowerPC wants to optimize integer setcc a bit 336 if (!Subtarget.useCRBits()) 337 setOperationAction(ISD::SETCC, MVT::i32, Custom); 338 339 // PowerPC does not have BRCOND which requires SetCC 340 if (!Subtarget.useCRBits()) 341 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 342 343 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 344 345 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 346 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 347 348 // PowerPC does not have [U|S]INT_TO_FP 349 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 350 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 351 352 if (Subtarget.hasDirectMove() && isPPC64) { 353 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 354 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 355 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 356 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 357 } else { 358 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 359 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 360 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 361 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 362 } 363 364 // We cannot sextinreg(i1). Expand to shifts. 365 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 366 367 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 368 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 369 // support continuation, user-level threading, and etc.. As a result, no 370 // other SjLj exception interfaces are implemented and please don't build 371 // your own exception handling based on them. 372 // LLVM/Clang supports zero-cost DWARF exception handling. 373 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 374 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 375 376 // We want to legalize GlobalAddress and ConstantPool nodes into the 377 // appropriate instructions to materialize the address. 378 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 379 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 380 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 381 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 382 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 383 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 384 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 385 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 386 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 387 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 388 389 // TRAP is legal. 390 setOperationAction(ISD::TRAP, MVT::Other, Legal); 391 392 // TRAMPOLINE is custom lowered. 393 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 394 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 395 396 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 397 setOperationAction(ISD::VASTART , MVT::Other, Custom); 398 399 if (Subtarget.isSVR4ABI()) { 400 if (isPPC64) { 401 // VAARG always uses double-word chunks, so promote anything smaller. 402 setOperationAction(ISD::VAARG, MVT::i1, Promote); 403 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 404 setOperationAction(ISD::VAARG, MVT::i8, Promote); 405 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 406 setOperationAction(ISD::VAARG, MVT::i16, Promote); 407 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 408 setOperationAction(ISD::VAARG, MVT::i32, Promote); 409 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 410 setOperationAction(ISD::VAARG, MVT::Other, Expand); 411 } else { 412 // VAARG is custom lowered with the 32-bit SVR4 ABI. 413 setOperationAction(ISD::VAARG, MVT::Other, Custom); 414 setOperationAction(ISD::VAARG, MVT::i64, Custom); 415 } 416 } else 417 setOperationAction(ISD::VAARG, MVT::Other, Expand); 418 419 if (Subtarget.isSVR4ABI() && !isPPC64) 420 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 421 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 422 else 423 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 424 425 // Use the default implementation. 426 setOperationAction(ISD::VAEND , MVT::Other, Expand); 427 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 428 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 429 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 430 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 431 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 432 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 433 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 434 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 435 436 // We want to custom lower some of our intrinsics. 437 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 438 439 // To handle counter-based loop conditions. 440 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 441 442 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 443 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 444 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 445 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 446 447 // Comparisons that require checking two conditions. 448 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 449 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 450 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 451 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 452 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 453 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 454 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 455 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 456 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 457 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 458 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 459 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 460 461 if (Subtarget.has64BitSupport()) { 462 // They also have instructions for converting between i64 and fp. 463 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 464 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 465 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 466 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 467 // This is just the low 32 bits of a (signed) fp->i64 conversion. 468 // We cannot do this with Promote because i64 is not a legal type. 469 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 470 471 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 472 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 473 } else { 474 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 475 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 476 } 477 478 // With the instructions enabled under FPCVT, we can do everything. 479 if (Subtarget.hasFPCVT()) { 480 if (Subtarget.has64BitSupport()) { 481 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 482 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 483 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 484 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 485 } 486 487 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 488 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 489 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 490 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 491 } 492 493 if (Subtarget.use64BitRegs()) { 494 // 64-bit PowerPC implementations can support i64 types directly 495 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 496 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 497 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 498 // 64-bit PowerPC wants to expand i128 shifts itself. 499 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 500 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 501 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 502 } else { 503 // 32-bit PowerPC wants to expand i64 shifts itself. 504 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 505 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 506 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 507 } 508 509 if (Subtarget.hasAltivec()) { 510 // First set operation action for all vector types to expand. Then we 511 // will selectively turn on ones that can be effectively codegen'd. 512 for (MVT VT : MVT::vector_valuetypes()) { 513 // add/sub are legal for all supported vector VT's. 514 setOperationAction(ISD::ADD, VT, Legal); 515 setOperationAction(ISD::SUB, VT, Legal); 516 517 // Vector instructions introduced in P8 518 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 519 setOperationAction(ISD::CTPOP, VT, Legal); 520 setOperationAction(ISD::CTLZ, VT, Legal); 521 } 522 else { 523 setOperationAction(ISD::CTPOP, VT, Expand); 524 setOperationAction(ISD::CTLZ, VT, Expand); 525 } 526 527 // Vector instructions introduced in P9 528 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 529 setOperationAction(ISD::CTTZ, VT, Legal); 530 else 531 setOperationAction(ISD::CTTZ, VT, Expand); 532 533 // We promote all shuffles to v16i8. 534 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 535 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 536 537 // We promote all non-typed operations to v4i32. 538 setOperationAction(ISD::AND , VT, Promote); 539 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 540 setOperationAction(ISD::OR , VT, Promote); 541 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 542 setOperationAction(ISD::XOR , VT, Promote); 543 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 544 setOperationAction(ISD::LOAD , VT, Promote); 545 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 546 setOperationAction(ISD::SELECT, VT, Promote); 547 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 548 setOperationAction(ISD::SELECT_CC, VT, Promote); 549 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 550 setOperationAction(ISD::STORE, VT, Promote); 551 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 552 553 // No other operations are legal. 554 setOperationAction(ISD::MUL , VT, Expand); 555 setOperationAction(ISD::SDIV, VT, Expand); 556 setOperationAction(ISD::SREM, VT, Expand); 557 setOperationAction(ISD::UDIV, VT, Expand); 558 setOperationAction(ISD::UREM, VT, Expand); 559 setOperationAction(ISD::FDIV, VT, Expand); 560 setOperationAction(ISD::FREM, VT, Expand); 561 setOperationAction(ISD::FNEG, VT, Expand); 562 setOperationAction(ISD::FSQRT, VT, Expand); 563 setOperationAction(ISD::FLOG, VT, Expand); 564 setOperationAction(ISD::FLOG10, VT, Expand); 565 setOperationAction(ISD::FLOG2, VT, Expand); 566 setOperationAction(ISD::FEXP, VT, Expand); 567 setOperationAction(ISD::FEXP2, VT, Expand); 568 setOperationAction(ISD::FSIN, VT, Expand); 569 setOperationAction(ISD::FCOS, VT, Expand); 570 setOperationAction(ISD::FABS, VT, Expand); 571 setOperationAction(ISD::FFLOOR, VT, Expand); 572 setOperationAction(ISD::FCEIL, VT, Expand); 573 setOperationAction(ISD::FTRUNC, VT, Expand); 574 setOperationAction(ISD::FRINT, VT, Expand); 575 setOperationAction(ISD::FNEARBYINT, VT, Expand); 576 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 577 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 578 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 579 setOperationAction(ISD::MULHU, VT, Expand); 580 setOperationAction(ISD::MULHS, VT, Expand); 581 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 582 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 583 setOperationAction(ISD::UDIVREM, VT, Expand); 584 setOperationAction(ISD::SDIVREM, VT, Expand); 585 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 586 setOperationAction(ISD::FPOW, VT, Expand); 587 setOperationAction(ISD::BSWAP, VT, Expand); 588 setOperationAction(ISD::VSELECT, VT, Expand); 589 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 590 setOperationAction(ISD::ROTL, VT, Expand); 591 setOperationAction(ISD::ROTR, VT, Expand); 592 593 for (MVT InnerVT : MVT::vector_valuetypes()) { 594 setTruncStoreAction(VT, InnerVT, Expand); 595 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 596 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 597 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 598 } 599 } 600 601 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 602 // with merges, splats, etc. 603 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 604 605 setOperationAction(ISD::AND , MVT::v4i32, Legal); 606 setOperationAction(ISD::OR , MVT::v4i32, Legal); 607 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 608 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 609 setOperationAction(ISD::SELECT, MVT::v4i32, 610 Subtarget.useCRBits() ? Legal : Expand); 611 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 612 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 613 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 614 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 615 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 616 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 617 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 618 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 619 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 620 621 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 622 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 623 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 624 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 625 626 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 627 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 628 629 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 630 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 631 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 632 } 633 634 if (Subtarget.hasP8Altivec()) 635 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 636 else 637 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 638 639 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 640 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 641 642 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 643 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 644 645 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 646 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 647 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 648 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 649 650 // Altivec does not contain unordered floating-point compare instructions 651 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 652 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 653 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 654 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 655 656 if (Subtarget.hasVSX()) { 657 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 658 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 659 if (Subtarget.hasP8Vector()) { 660 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 661 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 662 } 663 if (Subtarget.hasDirectMove() && isPPC64) { 664 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 665 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 666 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 667 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 668 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 669 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 670 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 671 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 672 } 673 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 674 675 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 676 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 677 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 678 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 679 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 680 681 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 682 683 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 684 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 685 686 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 687 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 688 689 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 690 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal); 691 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 692 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 693 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 694 695 // Share the Altivec comparison restrictions. 696 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 697 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 698 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 699 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 700 701 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 702 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 703 704 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 705 706 if (Subtarget.hasP8Vector()) 707 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 708 709 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 710 711 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 712 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 713 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 714 715 if (Subtarget.hasP8Altivec()) { 716 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 717 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 718 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 719 720 // 128 bit shifts can be accomplished via 3 instructions for SHL and 721 // SRL, but not for SRA because of the instructions available: 722 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 723 // doing 724 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 725 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 726 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 727 728 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 729 } 730 else { 731 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 732 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 733 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 734 735 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 736 737 // VSX v2i64 only supports non-arithmetic operations. 738 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 739 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 740 } 741 742 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 743 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 744 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 745 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 746 747 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 748 749 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 750 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 751 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 752 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 753 754 // Vector operation legalization checks the result type of 755 // SIGN_EXTEND_INREG, overall legalization checks the inner type. 756 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 757 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 758 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 759 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 760 761 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 762 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 763 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 764 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 765 766 if (Subtarget.hasDirectMove()) 767 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 768 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 769 770 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 771 } 772 773 if (Subtarget.hasP8Altivec()) { 774 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 775 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 776 } 777 778 if (Subtarget.hasP9Vector()) { 779 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 780 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 781 782 // 128 bit shifts can be accomplished via 3 instructions for SHL and 783 // SRL, but not for SRA because of the instructions available: 784 // VS{RL} and VS{RL}O. 785 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 786 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 787 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 788 } 789 790 if (Subtarget.hasP9Altivec()) { 791 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 792 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 793 } 794 } 795 796 if (Subtarget.hasQPX()) { 797 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 798 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 799 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 800 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 801 802 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 803 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 804 805 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 806 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 807 808 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 809 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 810 811 if (!Subtarget.useCRBits()) 812 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 813 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 814 815 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 816 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 817 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 818 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 819 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 820 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 821 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 822 823 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 824 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 825 826 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 827 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 828 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 829 830 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 831 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 832 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 833 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 834 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 835 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 836 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 837 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 838 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 839 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 840 841 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 842 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 843 844 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 845 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 846 847 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 848 849 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 850 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 851 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 852 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 853 854 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 855 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 856 857 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 858 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 859 860 if (!Subtarget.useCRBits()) 861 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 862 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 863 864 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 865 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 866 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 867 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 868 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 869 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 870 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 871 872 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 873 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 874 875 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 876 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 877 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 878 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 879 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 880 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 881 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 882 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 883 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 884 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 885 886 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 887 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 888 889 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 890 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 891 892 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 893 894 setOperationAction(ISD::AND , MVT::v4i1, Legal); 895 setOperationAction(ISD::OR , MVT::v4i1, Legal); 896 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 897 898 if (!Subtarget.useCRBits()) 899 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 900 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 901 902 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 903 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 904 905 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 906 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 907 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 908 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 909 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 910 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 911 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 912 913 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 914 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 915 916 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 917 918 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 919 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 920 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 921 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 922 923 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 924 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 925 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 926 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 927 928 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 929 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 930 931 // These need to set FE_INEXACT, and so cannot be vectorized here. 932 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 933 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 934 935 if (TM.Options.UnsafeFPMath) { 936 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 937 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 938 939 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 940 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 941 } else { 942 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 943 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 944 945 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 946 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 947 } 948 } 949 950 if (Subtarget.has64BitSupport()) 951 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 952 953 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 954 955 if (!isPPC64) { 956 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 957 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 958 } 959 960 setBooleanContents(ZeroOrOneBooleanContent); 961 962 if (Subtarget.hasAltivec()) { 963 // Altivec instructions set fields to all zeros or all ones. 964 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 965 } 966 967 if (!isPPC64) { 968 // These libcalls are not available in 32-bit. 969 setLibcallName(RTLIB::SHL_I128, nullptr); 970 setLibcallName(RTLIB::SRL_I128, nullptr); 971 setLibcallName(RTLIB::SRA_I128, nullptr); 972 } 973 974 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 975 976 // We have target-specific dag combine patterns for the following nodes: 977 setTargetDAGCombine(ISD::SHL); 978 setTargetDAGCombine(ISD::SRA); 979 setTargetDAGCombine(ISD::SRL); 980 setTargetDAGCombine(ISD::SINT_TO_FP); 981 setTargetDAGCombine(ISD::BUILD_VECTOR); 982 if (Subtarget.hasFPCVT()) 983 setTargetDAGCombine(ISD::UINT_TO_FP); 984 setTargetDAGCombine(ISD::LOAD); 985 setTargetDAGCombine(ISD::STORE); 986 setTargetDAGCombine(ISD::BR_CC); 987 if (Subtarget.useCRBits()) 988 setTargetDAGCombine(ISD::BRCOND); 989 setTargetDAGCombine(ISD::BSWAP); 990 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 991 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 992 setTargetDAGCombine(ISD::INTRINSIC_VOID); 993 994 setTargetDAGCombine(ISD::SIGN_EXTEND); 995 setTargetDAGCombine(ISD::ZERO_EXTEND); 996 setTargetDAGCombine(ISD::ANY_EXTEND); 997 998 if (Subtarget.useCRBits()) { 999 setTargetDAGCombine(ISD::TRUNCATE); 1000 setTargetDAGCombine(ISD::SETCC); 1001 setTargetDAGCombine(ISD::SELECT_CC); 1002 } 1003 1004 // Use reciprocal estimates. 1005 if (TM.Options.UnsafeFPMath) { 1006 setTargetDAGCombine(ISD::FDIV); 1007 setTargetDAGCombine(ISD::FSQRT); 1008 } 1009 1010 // Darwin long double math library functions have $LDBL128 appended. 1011 if (Subtarget.isDarwin()) { 1012 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1013 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1014 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1015 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1016 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1017 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1018 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1019 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1020 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1021 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1022 } 1023 1024 // With 32 condition bits, we don't need to sink (and duplicate) compares 1025 // aggressively in CodeGenPrep. 1026 if (Subtarget.useCRBits()) { 1027 setHasMultipleConditionRegisters(); 1028 setJumpIsExpensive(); 1029 } 1030 1031 setMinFunctionAlignment(2); 1032 if (Subtarget.isDarwin()) 1033 setPrefFunctionAlignment(4); 1034 1035 switch (Subtarget.getDarwinDirective()) { 1036 default: break; 1037 case PPC::DIR_970: 1038 case PPC::DIR_A2: 1039 case PPC::DIR_E500mc: 1040 case PPC::DIR_E5500: 1041 case PPC::DIR_PWR4: 1042 case PPC::DIR_PWR5: 1043 case PPC::DIR_PWR5X: 1044 case PPC::DIR_PWR6: 1045 case PPC::DIR_PWR6X: 1046 case PPC::DIR_PWR7: 1047 case PPC::DIR_PWR8: 1048 case PPC::DIR_PWR9: 1049 setPrefFunctionAlignment(4); 1050 setPrefLoopAlignment(4); 1051 break; 1052 } 1053 1054 if (Subtarget.enableMachineScheduler()) 1055 setSchedulingPreference(Sched::Source); 1056 else 1057 setSchedulingPreference(Sched::Hybrid); 1058 1059 computeRegisterProperties(STI.getRegisterInfo()); 1060 1061 // The Freescale cores do better with aggressive inlining of memcpy and 1062 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1063 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1064 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1065 MaxStoresPerMemset = 32; 1066 MaxStoresPerMemsetOptSize = 16; 1067 MaxStoresPerMemcpy = 32; 1068 MaxStoresPerMemcpyOptSize = 8; 1069 MaxStoresPerMemmove = 32; 1070 MaxStoresPerMemmoveOptSize = 8; 1071 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1072 // The A2 also benefits from (very) aggressive inlining of memcpy and 1073 // friends. The overhead of a the function call, even when warm, can be 1074 // over one hundred cycles. 1075 MaxStoresPerMemset = 128; 1076 MaxStoresPerMemcpy = 128; 1077 MaxStoresPerMemmove = 128; 1078 MaxLoadsPerMemcmp = 128; 1079 } else { 1080 MaxLoadsPerMemcmp = 8; 1081 MaxLoadsPerMemcmpOptSize = 4; 1082 } 1083 } 1084 1085 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1086 /// the desired ByVal argument alignment. 1087 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1088 unsigned MaxMaxAlign) { 1089 if (MaxAlign == MaxMaxAlign) 1090 return; 1091 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1092 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1093 MaxAlign = 32; 1094 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1095 MaxAlign = 16; 1096 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1097 unsigned EltAlign = 0; 1098 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1099 if (EltAlign > MaxAlign) 1100 MaxAlign = EltAlign; 1101 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1102 for (auto *EltTy : STy->elements()) { 1103 unsigned EltAlign = 0; 1104 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1105 if (EltAlign > MaxAlign) 1106 MaxAlign = EltAlign; 1107 if (MaxAlign == MaxMaxAlign) 1108 break; 1109 } 1110 } 1111 } 1112 1113 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1114 /// function arguments in the caller parameter area. 1115 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1116 const DataLayout &DL) const { 1117 // Darwin passes everything on 4 byte boundary. 1118 if (Subtarget.isDarwin()) 1119 return 4; 1120 1121 // 16byte and wider vectors are passed on 16byte boundary. 1122 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1123 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1124 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1125 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1126 return Align; 1127 } 1128 1129 bool PPCTargetLowering::useSoftFloat() const { 1130 return Subtarget.useSoftFloat(); 1131 } 1132 1133 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1134 switch ((PPCISD::NodeType)Opcode) { 1135 case PPCISD::FIRST_NUMBER: break; 1136 case PPCISD::FSEL: return "PPCISD::FSEL"; 1137 case PPCISD::FCFID: return "PPCISD::FCFID"; 1138 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1139 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1140 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1141 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1142 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1143 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1144 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1145 case PPCISD::FRE: return "PPCISD::FRE"; 1146 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1147 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1148 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1149 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1150 case PPCISD::VPERM: return "PPCISD::VPERM"; 1151 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1152 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1153 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1154 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1155 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1156 case PPCISD::CMPB: return "PPCISD::CMPB"; 1157 case PPCISD::Hi: return "PPCISD::Hi"; 1158 case PPCISD::Lo: return "PPCISD::Lo"; 1159 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1160 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1161 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1162 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1163 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1164 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1165 case PPCISD::SRL: return "PPCISD::SRL"; 1166 case PPCISD::SRA: return "PPCISD::SRA"; 1167 case PPCISD::SHL: return "PPCISD::SHL"; 1168 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1169 case PPCISD::CALL: return "PPCISD::CALL"; 1170 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1171 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1172 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1173 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1174 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1175 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1176 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1177 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1178 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1179 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1180 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1181 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1182 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1183 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1184 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1185 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1186 case PPCISD::VCMP: return "PPCISD::VCMP"; 1187 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1188 case PPCISD::LBRX: return "PPCISD::LBRX"; 1189 case PPCISD::STBRX: return "PPCISD::STBRX"; 1190 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1191 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1192 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1193 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1194 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1195 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1196 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1197 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1198 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1199 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1200 case PPCISD::BDZ: return "PPCISD::BDZ"; 1201 case PPCISD::MFFS: return "PPCISD::MFFS"; 1202 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1203 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1204 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1205 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1206 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1207 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1208 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1209 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1210 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1211 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1212 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1213 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1214 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1215 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1216 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1217 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1218 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1219 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1220 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1221 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1222 case PPCISD::SC: return "PPCISD::SC"; 1223 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1224 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1225 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1226 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1227 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1228 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1229 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1230 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1231 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1232 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1233 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1234 } 1235 return nullptr; 1236 } 1237 1238 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1239 EVT VT) const { 1240 if (!VT.isVector()) 1241 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1242 1243 if (Subtarget.hasQPX()) 1244 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1245 1246 return VT.changeVectorElementTypeToInteger(); 1247 } 1248 1249 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1250 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1251 return true; 1252 } 1253 1254 //===----------------------------------------------------------------------===// 1255 // Node matching predicates, for use by the tblgen matching code. 1256 //===----------------------------------------------------------------------===// 1257 1258 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1259 static bool isFloatingPointZero(SDValue Op) { 1260 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1261 return CFP->getValueAPF().isZero(); 1262 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1263 // Maybe this has already been legalized into the constant pool? 1264 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1265 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1266 return CFP->getValueAPF().isZero(); 1267 } 1268 return false; 1269 } 1270 1271 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1272 /// true if Op is undef or if it matches the specified value. 1273 static bool isConstantOrUndef(int Op, int Val) { 1274 return Op < 0 || Op == Val; 1275 } 1276 1277 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1278 /// VPKUHUM instruction. 1279 /// The ShuffleKind distinguishes between big-endian operations with 1280 /// two different inputs (0), either-endian operations with two identical 1281 /// inputs (1), and little-endian operations with two different inputs (2). 1282 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1283 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1284 SelectionDAG &DAG) { 1285 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1286 if (ShuffleKind == 0) { 1287 if (IsLE) 1288 return false; 1289 for (unsigned i = 0; i != 16; ++i) 1290 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1291 return false; 1292 } else if (ShuffleKind == 2) { 1293 if (!IsLE) 1294 return false; 1295 for (unsigned i = 0; i != 16; ++i) 1296 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1297 return false; 1298 } else if (ShuffleKind == 1) { 1299 unsigned j = IsLE ? 0 : 1; 1300 for (unsigned i = 0; i != 8; ++i) 1301 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1302 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1303 return false; 1304 } 1305 return true; 1306 } 1307 1308 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1309 /// VPKUWUM instruction. 1310 /// The ShuffleKind distinguishes between big-endian operations with 1311 /// two different inputs (0), either-endian operations with two identical 1312 /// inputs (1), and little-endian operations with two different inputs (2). 1313 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1314 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1315 SelectionDAG &DAG) { 1316 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1317 if (ShuffleKind == 0) { 1318 if (IsLE) 1319 return false; 1320 for (unsigned i = 0; i != 16; i += 2) 1321 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1322 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1323 return false; 1324 } else if (ShuffleKind == 2) { 1325 if (!IsLE) 1326 return false; 1327 for (unsigned i = 0; i != 16; i += 2) 1328 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1329 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1330 return false; 1331 } else if (ShuffleKind == 1) { 1332 unsigned j = IsLE ? 0 : 2; 1333 for (unsigned i = 0; i != 8; i += 2) 1334 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1335 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1336 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1337 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1338 return false; 1339 } 1340 return true; 1341 } 1342 1343 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1344 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1345 /// current subtarget. 1346 /// 1347 /// The ShuffleKind distinguishes between big-endian operations with 1348 /// two different inputs (0), either-endian operations with two identical 1349 /// inputs (1), and little-endian operations with two different inputs (2). 1350 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1351 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1352 SelectionDAG &DAG) { 1353 const PPCSubtarget& Subtarget = 1354 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1355 if (!Subtarget.hasP8Vector()) 1356 return false; 1357 1358 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1359 if (ShuffleKind == 0) { 1360 if (IsLE) 1361 return false; 1362 for (unsigned i = 0; i != 16; i += 4) 1363 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1364 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1365 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1366 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1367 return false; 1368 } else if (ShuffleKind == 2) { 1369 if (!IsLE) 1370 return false; 1371 for (unsigned i = 0; i != 16; i += 4) 1372 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1373 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1374 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1375 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1376 return false; 1377 } else if (ShuffleKind == 1) { 1378 unsigned j = IsLE ? 0 : 4; 1379 for (unsigned i = 0; i != 8; i += 4) 1380 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1381 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1382 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1383 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1384 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1385 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1386 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1387 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1388 return false; 1389 } 1390 return true; 1391 } 1392 1393 /// isVMerge - Common function, used to match vmrg* shuffles. 1394 /// 1395 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1396 unsigned LHSStart, unsigned RHSStart) { 1397 if (N->getValueType(0) != MVT::v16i8) 1398 return false; 1399 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1400 "Unsupported merge size!"); 1401 1402 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1403 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1404 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1405 LHSStart+j+i*UnitSize) || 1406 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1407 RHSStart+j+i*UnitSize)) 1408 return false; 1409 } 1410 return true; 1411 } 1412 1413 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1414 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1415 /// The ShuffleKind distinguishes between big-endian merges with two 1416 /// different inputs (0), either-endian merges with two identical inputs (1), 1417 /// and little-endian merges with two different inputs (2). For the latter, 1418 /// the input operands are swapped (see PPCInstrAltivec.td). 1419 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1420 unsigned ShuffleKind, SelectionDAG &DAG) { 1421 if (DAG.getDataLayout().isLittleEndian()) { 1422 if (ShuffleKind == 1) // unary 1423 return isVMerge(N, UnitSize, 0, 0); 1424 else if (ShuffleKind == 2) // swapped 1425 return isVMerge(N, UnitSize, 0, 16); 1426 else 1427 return false; 1428 } else { 1429 if (ShuffleKind == 1) // unary 1430 return isVMerge(N, UnitSize, 8, 8); 1431 else if (ShuffleKind == 0) // normal 1432 return isVMerge(N, UnitSize, 8, 24); 1433 else 1434 return false; 1435 } 1436 } 1437 1438 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1439 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1440 /// The ShuffleKind distinguishes between big-endian merges with two 1441 /// different inputs (0), either-endian merges with two identical inputs (1), 1442 /// and little-endian merges with two different inputs (2). For the latter, 1443 /// the input operands are swapped (see PPCInstrAltivec.td). 1444 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1445 unsigned ShuffleKind, SelectionDAG &DAG) { 1446 if (DAG.getDataLayout().isLittleEndian()) { 1447 if (ShuffleKind == 1) // unary 1448 return isVMerge(N, UnitSize, 8, 8); 1449 else if (ShuffleKind == 2) // swapped 1450 return isVMerge(N, UnitSize, 8, 24); 1451 else 1452 return false; 1453 } else { 1454 if (ShuffleKind == 1) // unary 1455 return isVMerge(N, UnitSize, 0, 0); 1456 else if (ShuffleKind == 0) // normal 1457 return isVMerge(N, UnitSize, 0, 16); 1458 else 1459 return false; 1460 } 1461 } 1462 1463 /** 1464 * \brief Common function used to match vmrgew and vmrgow shuffles 1465 * 1466 * The indexOffset determines whether to look for even or odd words in 1467 * the shuffle mask. This is based on the of the endianness of the target 1468 * machine. 1469 * - Little Endian: 1470 * - Use offset of 0 to check for odd elements 1471 * - Use offset of 4 to check for even elements 1472 * - Big Endian: 1473 * - Use offset of 0 to check for even elements 1474 * - Use offset of 4 to check for odd elements 1475 * A detailed description of the vector element ordering for little endian and 1476 * big endian can be found at 1477 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1478 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1479 * compiler differences mean to you 1480 * 1481 * The mask to the shuffle vector instruction specifies the indices of the 1482 * elements from the two input vectors to place in the result. The elements are 1483 * numbered in array-access order, starting with the first vector. These vectors 1484 * are always of type v16i8, thus each vector will contain 16 elements of size 1485 * 8. More info on the shuffle vector can be found in the 1486 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1487 * Language Reference. 1488 * 1489 * The RHSStartValue indicates whether the same input vectors are used (unary) 1490 * or two different input vectors are used, based on the following: 1491 * - If the instruction uses the same vector for both inputs, the range of the 1492 * indices will be 0 to 15. In this case, the RHSStart value passed should 1493 * be 0. 1494 * - If the instruction has two different vectors then the range of the 1495 * indices will be 0 to 31. In this case, the RHSStart value passed should 1496 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1497 * to 31 specify elements in the second vector). 1498 * 1499 * \param[in] N The shuffle vector SD Node to analyze 1500 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1501 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1502 * vector to the shuffle_vector instruction 1503 * \return true iff this shuffle vector represents an even or odd word merge 1504 */ 1505 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1506 unsigned RHSStartValue) { 1507 if (N->getValueType(0) != MVT::v16i8) 1508 return false; 1509 1510 for (unsigned i = 0; i < 2; ++i) 1511 for (unsigned j = 0; j < 4; ++j) 1512 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1513 i*RHSStartValue+j+IndexOffset) || 1514 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1515 i*RHSStartValue+j+IndexOffset+8)) 1516 return false; 1517 return true; 1518 } 1519 1520 /** 1521 * \brief Determine if the specified shuffle mask is suitable for the vmrgew or 1522 * vmrgow instructions. 1523 * 1524 * \param[in] N The shuffle vector SD Node to analyze 1525 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1526 * \param[in] ShuffleKind Identify the type of merge: 1527 * - 0 = big-endian merge with two different inputs; 1528 * - 1 = either-endian merge with two identical inputs; 1529 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1530 * little-endian merges). 1531 * \param[in] DAG The current SelectionDAG 1532 * \return true iff this shuffle mask 1533 */ 1534 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1535 unsigned ShuffleKind, SelectionDAG &DAG) { 1536 if (DAG.getDataLayout().isLittleEndian()) { 1537 unsigned indexOffset = CheckEven ? 4 : 0; 1538 if (ShuffleKind == 1) // Unary 1539 return isVMerge(N, indexOffset, 0); 1540 else if (ShuffleKind == 2) // swapped 1541 return isVMerge(N, indexOffset, 16); 1542 else 1543 return false; 1544 } 1545 else { 1546 unsigned indexOffset = CheckEven ? 0 : 4; 1547 if (ShuffleKind == 1) // Unary 1548 return isVMerge(N, indexOffset, 0); 1549 else if (ShuffleKind == 0) // Normal 1550 return isVMerge(N, indexOffset, 16); 1551 else 1552 return false; 1553 } 1554 return false; 1555 } 1556 1557 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1558 /// amount, otherwise return -1. 1559 /// The ShuffleKind distinguishes between big-endian operations with two 1560 /// different inputs (0), either-endian operations with two identical inputs 1561 /// (1), and little-endian operations with two different inputs (2). For the 1562 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1563 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1564 SelectionDAG &DAG) { 1565 if (N->getValueType(0) != MVT::v16i8) 1566 return -1; 1567 1568 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1569 1570 // Find the first non-undef value in the shuffle mask. 1571 unsigned i; 1572 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1573 /*search*/; 1574 1575 if (i == 16) return -1; // all undef. 1576 1577 // Otherwise, check to see if the rest of the elements are consecutively 1578 // numbered from this value. 1579 unsigned ShiftAmt = SVOp->getMaskElt(i); 1580 if (ShiftAmt < i) return -1; 1581 1582 ShiftAmt -= i; 1583 bool isLE = DAG.getDataLayout().isLittleEndian(); 1584 1585 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1586 // Check the rest of the elements to see if they are consecutive. 1587 for (++i; i != 16; ++i) 1588 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1589 return -1; 1590 } else if (ShuffleKind == 1) { 1591 // Check the rest of the elements to see if they are consecutive. 1592 for (++i; i != 16; ++i) 1593 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1594 return -1; 1595 } else 1596 return -1; 1597 1598 if (isLE) 1599 ShiftAmt = 16 - ShiftAmt; 1600 1601 return ShiftAmt; 1602 } 1603 1604 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1605 /// specifies a splat of a single element that is suitable for input to 1606 /// VSPLTB/VSPLTH/VSPLTW. 1607 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1608 assert(N->getValueType(0) == MVT::v16i8 && 1609 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1610 1611 // The consecutive indices need to specify an element, not part of two 1612 // different elements. So abandon ship early if this isn't the case. 1613 if (N->getMaskElt(0) % EltSize != 0) 1614 return false; 1615 1616 // This is a splat operation if each element of the permute is the same, and 1617 // if the value doesn't reference the second vector. 1618 unsigned ElementBase = N->getMaskElt(0); 1619 1620 // FIXME: Handle UNDEF elements too! 1621 if (ElementBase >= 16) 1622 return false; 1623 1624 // Check that the indices are consecutive, in the case of a multi-byte element 1625 // splatted with a v16i8 mask. 1626 for (unsigned i = 1; i != EltSize; ++i) 1627 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1628 return false; 1629 1630 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1631 if (N->getMaskElt(i) < 0) continue; 1632 for (unsigned j = 0; j != EltSize; ++j) 1633 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1634 return false; 1635 } 1636 return true; 1637 } 1638 1639 /// Check that the mask is shuffling N byte elements. Within each N byte 1640 /// element of the mask, the indices could be either in increasing or 1641 /// decreasing order as long as they are consecutive. 1642 /// \param[in] N the shuffle vector SD Node to analyze 1643 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1644 /// Word/DoubleWord/QuadWord). 1645 /// \param[in] StepLen the delta indices number among the N byte element, if 1646 /// the mask is in increasing/decreasing order then it is 1/-1. 1647 /// \return true iff the mask is shuffling N byte elements. 1648 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1649 int StepLen) { 1650 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1651 "Unexpected element width."); 1652 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1653 1654 unsigned NumOfElem = 16 / Width; 1655 unsigned MaskVal[16]; // Width is never greater than 16 1656 for (unsigned i = 0; i < NumOfElem; ++i) { 1657 MaskVal[0] = N->getMaskElt(i * Width); 1658 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1659 return false; 1660 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1661 return false; 1662 } 1663 1664 for (unsigned int j = 1; j < Width; ++j) { 1665 MaskVal[j] = N->getMaskElt(i * Width + j); 1666 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1667 return false; 1668 } 1669 } 1670 } 1671 1672 return true; 1673 } 1674 1675 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1676 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1677 if (!isNByteElemShuffleMask(N, 4, 1)) 1678 return false; 1679 1680 // Now we look at mask elements 0,4,8,12 1681 unsigned M0 = N->getMaskElt(0) / 4; 1682 unsigned M1 = N->getMaskElt(4) / 4; 1683 unsigned M2 = N->getMaskElt(8) / 4; 1684 unsigned M3 = N->getMaskElt(12) / 4; 1685 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1686 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1687 1688 // Below, let H and L be arbitrary elements of the shuffle mask 1689 // where H is in the range [4,7] and L is in the range [0,3]. 1690 // H, 1, 2, 3 or L, 5, 6, 7 1691 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1692 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1693 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1694 InsertAtByte = IsLE ? 12 : 0; 1695 Swap = M0 < 4; 1696 return true; 1697 } 1698 // 0, H, 2, 3 or 4, L, 6, 7 1699 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1700 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1701 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1702 InsertAtByte = IsLE ? 8 : 4; 1703 Swap = M1 < 4; 1704 return true; 1705 } 1706 // 0, 1, H, 3 or 4, 5, L, 7 1707 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1708 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1709 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1710 InsertAtByte = IsLE ? 4 : 8; 1711 Swap = M2 < 4; 1712 return true; 1713 } 1714 // 0, 1, 2, H or 4, 5, 6, L 1715 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1716 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1717 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1718 InsertAtByte = IsLE ? 0 : 12; 1719 Swap = M3 < 4; 1720 return true; 1721 } 1722 1723 // If both vector operands for the shuffle are the same vector, the mask will 1724 // contain only elements from the first one and the second one will be undef. 1725 if (N->getOperand(1).isUndef()) { 1726 ShiftElts = 0; 1727 Swap = true; 1728 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1729 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1730 InsertAtByte = IsLE ? 12 : 0; 1731 return true; 1732 } 1733 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1734 InsertAtByte = IsLE ? 8 : 4; 1735 return true; 1736 } 1737 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1738 InsertAtByte = IsLE ? 4 : 8; 1739 return true; 1740 } 1741 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1742 InsertAtByte = IsLE ? 0 : 12; 1743 return true; 1744 } 1745 } 1746 1747 return false; 1748 } 1749 1750 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1751 bool &Swap, bool IsLE) { 1752 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1753 // Ensure each byte index of the word is consecutive. 1754 if (!isNByteElemShuffleMask(N, 4, 1)) 1755 return false; 1756 1757 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1758 unsigned M0 = N->getMaskElt(0) / 4; 1759 unsigned M1 = N->getMaskElt(4) / 4; 1760 unsigned M2 = N->getMaskElt(8) / 4; 1761 unsigned M3 = N->getMaskElt(12) / 4; 1762 1763 // If both vector operands for the shuffle are the same vector, the mask will 1764 // contain only elements from the first one and the second one will be undef. 1765 if (N->getOperand(1).isUndef()) { 1766 assert(M0 < 4 && "Indexing into an undef vector?"); 1767 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1768 return false; 1769 1770 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1771 Swap = false; 1772 return true; 1773 } 1774 1775 // Ensure each word index of the ShuffleVector Mask is consecutive. 1776 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1777 return false; 1778 1779 if (IsLE) { 1780 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1781 // Input vectors don't need to be swapped if the leading element 1782 // of the result is one of the 3 left elements of the second vector 1783 // (or if there is no shift to be done at all). 1784 Swap = false; 1785 ShiftElts = (8 - M0) % 8; 1786 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1787 // Input vectors need to be swapped if the leading element 1788 // of the result is one of the 3 left elements of the first vector 1789 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1790 Swap = true; 1791 ShiftElts = (4 - M0) % 4; 1792 } 1793 1794 return true; 1795 } else { // BE 1796 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1797 // Input vectors don't need to be swapped if the leading element 1798 // of the result is one of the 4 elements of the first vector. 1799 Swap = false; 1800 ShiftElts = M0; 1801 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1802 // Input vectors need to be swapped if the leading element 1803 // of the result is one of the 4 elements of the right vector. 1804 Swap = true; 1805 ShiftElts = M0 - 4; 1806 } 1807 1808 return true; 1809 } 1810 } 1811 1812 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1813 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1814 1815 if (!isNByteElemShuffleMask(N, Width, -1)) 1816 return false; 1817 1818 for (int i = 0; i < 16; i += Width) 1819 if (N->getMaskElt(i) != i + Width - 1) 1820 return false; 1821 1822 return true; 1823 } 1824 1825 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1826 return isXXBRShuffleMaskHelper(N, 2); 1827 } 1828 1829 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1830 return isXXBRShuffleMaskHelper(N, 4); 1831 } 1832 1833 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 1834 return isXXBRShuffleMaskHelper(N, 8); 1835 } 1836 1837 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 1838 return isXXBRShuffleMaskHelper(N, 16); 1839 } 1840 1841 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 1842 /// if the inputs to the instruction should be swapped and set \p DM to the 1843 /// value for the immediate. 1844 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 1845 /// AND element 0 of the result comes from the first input (LE) or second input 1846 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 1847 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 1848 /// mask. 1849 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 1850 bool &Swap, bool IsLE) { 1851 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1852 1853 // Ensure each byte index of the double word is consecutive. 1854 if (!isNByteElemShuffleMask(N, 8, 1)) 1855 return false; 1856 1857 unsigned M0 = N->getMaskElt(0) / 8; 1858 unsigned M1 = N->getMaskElt(8) / 8; 1859 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 1860 1861 // If both vector operands for the shuffle are the same vector, the mask will 1862 // contain only elements from the first one and the second one will be undef. 1863 if (N->getOperand(1).isUndef()) { 1864 if ((M0 | M1) < 2) { 1865 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 1866 Swap = false; 1867 return true; 1868 } else 1869 return false; 1870 } 1871 1872 if (IsLE) { 1873 if (M0 > 1 && M1 < 2) { 1874 Swap = false; 1875 } else if (M0 < 2 && M1 > 1) { 1876 M0 = (M0 + 2) % 4; 1877 M1 = (M1 + 2) % 4; 1878 Swap = true; 1879 } else 1880 return false; 1881 1882 // Note: if control flow comes here that means Swap is already set above 1883 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 1884 return true; 1885 } else { // BE 1886 if (M0 < 2 && M1 > 1) { 1887 Swap = false; 1888 } else if (M0 > 1 && M1 < 2) { 1889 M0 = (M0 + 2) % 4; 1890 M1 = (M1 + 2) % 4; 1891 Swap = true; 1892 } else 1893 return false; 1894 1895 // Note: if control flow comes here that means Swap is already set above 1896 DM = (M0 << 1) + (M1 & 1); 1897 return true; 1898 } 1899 } 1900 1901 1902 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 1903 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 1904 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 1905 SelectionDAG &DAG) { 1906 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1907 assert(isSplatShuffleMask(SVOp, EltSize)); 1908 if (DAG.getDataLayout().isLittleEndian()) 1909 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 1910 else 1911 return SVOp->getMaskElt(0) / EltSize; 1912 } 1913 1914 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 1915 /// by using a vspltis[bhw] instruction of the specified element size, return 1916 /// the constant being splatted. The ByteSize field indicates the number of 1917 /// bytes of each element [124] -> [bhw]. 1918 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 1919 SDValue OpVal(nullptr, 0); 1920 1921 // If ByteSize of the splat is bigger than the element size of the 1922 // build_vector, then we have a case where we are checking for a splat where 1923 // multiple elements of the buildvector are folded together into a single 1924 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 1925 unsigned EltSize = 16/N->getNumOperands(); 1926 if (EltSize < ByteSize) { 1927 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 1928 SDValue UniquedVals[4]; 1929 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 1930 1931 // See if all of the elements in the buildvector agree across. 1932 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1933 if (N->getOperand(i).isUndef()) continue; 1934 // If the element isn't a constant, bail fully out. 1935 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 1936 1937 if (!UniquedVals[i&(Multiple-1)].getNode()) 1938 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 1939 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 1940 return SDValue(); // no match. 1941 } 1942 1943 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 1944 // either constant or undef values that are identical for each chunk. See 1945 // if these chunks can form into a larger vspltis*. 1946 1947 // Check to see if all of the leading entries are either 0 or -1. If 1948 // neither, then this won't fit into the immediate field. 1949 bool LeadingZero = true; 1950 bool LeadingOnes = true; 1951 for (unsigned i = 0; i != Multiple-1; ++i) { 1952 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 1953 1954 LeadingZero &= isNullConstant(UniquedVals[i]); 1955 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 1956 } 1957 // Finally, check the least significant entry. 1958 if (LeadingZero) { 1959 if (!UniquedVals[Multiple-1].getNode()) 1960 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 1961 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 1962 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 1963 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1964 } 1965 if (LeadingOnes) { 1966 if (!UniquedVals[Multiple-1].getNode()) 1967 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 1968 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 1969 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 1970 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1971 } 1972 1973 return SDValue(); 1974 } 1975 1976 // Check to see if this buildvec has a single non-undef value in its elements. 1977 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1978 if (N->getOperand(i).isUndef()) continue; 1979 if (!OpVal.getNode()) 1980 OpVal = N->getOperand(i); 1981 else if (OpVal != N->getOperand(i)) 1982 return SDValue(); 1983 } 1984 1985 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 1986 1987 unsigned ValSizeInBytes = EltSize; 1988 uint64_t Value = 0; 1989 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 1990 Value = CN->getZExtValue(); 1991 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 1992 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 1993 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 1994 } 1995 1996 // If the splat value is larger than the element value, then we can never do 1997 // this splat. The only case that we could fit the replicated bits into our 1998 // immediate field for would be zero, and we prefer to use vxor for it. 1999 if (ValSizeInBytes < ByteSize) return SDValue(); 2000 2001 // If the element value is larger than the splat value, check if it consists 2002 // of a repeated bit pattern of size ByteSize. 2003 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2004 return SDValue(); 2005 2006 // Properly sign extend the value. 2007 int MaskVal = SignExtend32(Value, ByteSize * 8); 2008 2009 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2010 if (MaskVal == 0) return SDValue(); 2011 2012 // Finally, if this value fits in a 5 bit sext field, return it 2013 if (SignExtend32<5>(MaskVal) == MaskVal) 2014 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2015 return SDValue(); 2016 } 2017 2018 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2019 /// amount, otherwise return -1. 2020 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2021 EVT VT = N->getValueType(0); 2022 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2023 return -1; 2024 2025 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2026 2027 // Find the first non-undef value in the shuffle mask. 2028 unsigned i; 2029 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2030 /*search*/; 2031 2032 if (i == 4) return -1; // all undef. 2033 2034 // Otherwise, check to see if the rest of the elements are consecutively 2035 // numbered from this value. 2036 unsigned ShiftAmt = SVOp->getMaskElt(i); 2037 if (ShiftAmt < i) return -1; 2038 ShiftAmt -= i; 2039 2040 // Check the rest of the elements to see if they are consecutive. 2041 for (++i; i != 4; ++i) 2042 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2043 return -1; 2044 2045 return ShiftAmt; 2046 } 2047 2048 //===----------------------------------------------------------------------===// 2049 // Addressing Mode Selection 2050 //===----------------------------------------------------------------------===// 2051 2052 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2053 /// or 64-bit immediate, and if the value can be accurately represented as a 2054 /// sign extension from a 16-bit value. If so, this returns true and the 2055 /// immediate. 2056 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2057 if (!isa<ConstantSDNode>(N)) 2058 return false; 2059 2060 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2061 if (N->getValueType(0) == MVT::i32) 2062 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2063 else 2064 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2065 } 2066 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2067 return isIntS16Immediate(Op.getNode(), Imm); 2068 } 2069 2070 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2071 /// can be represented as an indexed [r+r] operation. Returns false if it 2072 /// can be more efficiently represented with [r+imm]. 2073 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2074 SDValue &Index, 2075 SelectionDAG &DAG) const { 2076 int16_t imm = 0; 2077 if (N.getOpcode() == ISD::ADD) { 2078 if (isIntS16Immediate(N.getOperand(1), imm)) 2079 return false; // r+i 2080 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2081 return false; // r+i 2082 2083 Base = N.getOperand(0); 2084 Index = N.getOperand(1); 2085 return true; 2086 } else if (N.getOpcode() == ISD::OR) { 2087 if (isIntS16Immediate(N.getOperand(1), imm)) 2088 return false; // r+i can fold it if we can. 2089 2090 // If this is an or of disjoint bitfields, we can codegen this as an add 2091 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2092 // disjoint. 2093 KnownBits LHSKnown, RHSKnown; 2094 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2095 2096 if (LHSKnown.Zero.getBoolValue()) { 2097 DAG.computeKnownBits(N.getOperand(1), RHSKnown); 2098 // If all of the bits are known zero on the LHS or RHS, the add won't 2099 // carry. 2100 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2101 Base = N.getOperand(0); 2102 Index = N.getOperand(1); 2103 return true; 2104 } 2105 } 2106 } 2107 2108 return false; 2109 } 2110 2111 // If we happen to be doing an i64 load or store into a stack slot that has 2112 // less than a 4-byte alignment, then the frame-index elimination may need to 2113 // use an indexed load or store instruction (because the offset may not be a 2114 // multiple of 4). The extra register needed to hold the offset comes from the 2115 // register scavenger, and it is possible that the scavenger will need to use 2116 // an emergency spill slot. As a result, we need to make sure that a spill slot 2117 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2118 // stack slot. 2119 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2120 // FIXME: This does not handle the LWA case. 2121 if (VT != MVT::i64) 2122 return; 2123 2124 // NOTE: We'll exclude negative FIs here, which come from argument 2125 // lowering, because there are no known test cases triggering this problem 2126 // using packed structures (or similar). We can remove this exclusion if 2127 // we find such a test case. The reason why this is so test-case driven is 2128 // because this entire 'fixup' is only to prevent crashes (from the 2129 // register scavenger) on not-really-valid inputs. For example, if we have: 2130 // %a = alloca i1 2131 // %b = bitcast i1* %a to i64* 2132 // store i64* a, i64 b 2133 // then the store should really be marked as 'align 1', but is not. If it 2134 // were marked as 'align 1' then the indexed form would have been 2135 // instruction-selected initially, and the problem this 'fixup' is preventing 2136 // won't happen regardless. 2137 if (FrameIdx < 0) 2138 return; 2139 2140 MachineFunction &MF = DAG.getMachineFunction(); 2141 MachineFrameInfo &MFI = MF.getFrameInfo(); 2142 2143 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2144 if (Align >= 4) 2145 return; 2146 2147 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2148 FuncInfo->setHasNonRISpills(); 2149 } 2150 2151 /// Returns true if the address N can be represented by a base register plus 2152 /// a signed 16-bit displacement [r+imm], and if it is not better 2153 /// represented as reg+reg. If \p Alignment is non-zero, only accept 2154 /// displacements that are multiples of that value. 2155 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2156 SDValue &Base, 2157 SelectionDAG &DAG, 2158 unsigned Alignment) const { 2159 // FIXME dl should come from parent load or store, not from address 2160 SDLoc dl(N); 2161 // If this can be more profitably realized as r+r, fail. 2162 if (SelectAddressRegReg(N, Disp, Base, DAG)) 2163 return false; 2164 2165 if (N.getOpcode() == ISD::ADD) { 2166 int16_t imm = 0; 2167 if (isIntS16Immediate(N.getOperand(1), imm) && 2168 (!Alignment || (imm % Alignment) == 0)) { 2169 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2170 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2171 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2172 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2173 } else { 2174 Base = N.getOperand(0); 2175 } 2176 return true; // [r+i] 2177 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2178 // Match LOAD (ADD (X, Lo(G))). 2179 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2180 && "Cannot handle constant offsets yet!"); 2181 Disp = N.getOperand(1).getOperand(0); // The global address. 2182 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2183 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2184 Disp.getOpcode() == ISD::TargetConstantPool || 2185 Disp.getOpcode() == ISD::TargetJumpTable); 2186 Base = N.getOperand(0); 2187 return true; // [&g+r] 2188 } 2189 } else if (N.getOpcode() == ISD::OR) { 2190 int16_t imm = 0; 2191 if (isIntS16Immediate(N.getOperand(1), imm) && 2192 (!Alignment || (imm % Alignment) == 0)) { 2193 // If this is an or of disjoint bitfields, we can codegen this as an add 2194 // (for better address arithmetic) if the LHS and RHS of the OR are 2195 // provably disjoint. 2196 KnownBits LHSKnown; 2197 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2198 2199 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2200 // If all of the bits are known zero on the LHS or RHS, the add won't 2201 // carry. 2202 if (FrameIndexSDNode *FI = 2203 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2204 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2205 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2206 } else { 2207 Base = N.getOperand(0); 2208 } 2209 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2210 return true; 2211 } 2212 } 2213 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2214 // Loading from a constant address. 2215 2216 // If this address fits entirely in a 16-bit sext immediate field, codegen 2217 // this as "d, 0" 2218 int16_t Imm; 2219 if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) { 2220 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2221 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2222 CN->getValueType(0)); 2223 return true; 2224 } 2225 2226 // Handle 32-bit sext immediates with LIS + addr mode. 2227 if ((CN->getValueType(0) == MVT::i32 || 2228 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2229 (!Alignment || (CN->getZExtValue() % Alignment) == 0)) { 2230 int Addr = (int)CN->getZExtValue(); 2231 2232 // Otherwise, break this down into an LIS + disp. 2233 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2234 2235 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2236 MVT::i32); 2237 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2238 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2239 return true; 2240 } 2241 } 2242 2243 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2244 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2245 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2246 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2247 } else 2248 Base = N; 2249 return true; // [r+0] 2250 } 2251 2252 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2253 /// represented as an indexed [r+r] operation. 2254 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2255 SDValue &Index, 2256 SelectionDAG &DAG) const { 2257 // Check to see if we can easily represent this as an [r+r] address. This 2258 // will fail if it thinks that the address is more profitably represented as 2259 // reg+imm, e.g. where imm = 0. 2260 if (SelectAddressRegReg(N, Base, Index, DAG)) 2261 return true; 2262 2263 // If the address is the result of an add, we will utilize the fact that the 2264 // address calculation includes an implicit add. However, we can reduce 2265 // register pressure if we do not materialize a constant just for use as the 2266 // index register. We only get rid of the add if it is not an add of a 2267 // value and a 16-bit signed constant and both have a single use. 2268 int16_t imm = 0; 2269 if (N.getOpcode() == ISD::ADD && 2270 (!isIntS16Immediate(N.getOperand(1), imm) || 2271 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2272 Base = N.getOperand(0); 2273 Index = N.getOperand(1); 2274 return true; 2275 } 2276 2277 // Otherwise, do it the hard way, using R0 as the base register. 2278 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2279 N.getValueType()); 2280 Index = N; 2281 return true; 2282 } 2283 2284 /// getPreIndexedAddressParts - returns true by value, base pointer and 2285 /// offset pointer and addressing mode by reference if the node's address 2286 /// can be legally represented as pre-indexed load / store address. 2287 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2288 SDValue &Offset, 2289 ISD::MemIndexedMode &AM, 2290 SelectionDAG &DAG) const { 2291 if (DisablePPCPreinc) return false; 2292 2293 bool isLoad = true; 2294 SDValue Ptr; 2295 EVT VT; 2296 unsigned Alignment; 2297 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2298 Ptr = LD->getBasePtr(); 2299 VT = LD->getMemoryVT(); 2300 Alignment = LD->getAlignment(); 2301 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2302 Ptr = ST->getBasePtr(); 2303 VT = ST->getMemoryVT(); 2304 Alignment = ST->getAlignment(); 2305 isLoad = false; 2306 } else 2307 return false; 2308 2309 // PowerPC doesn't have preinc load/store instructions for vectors (except 2310 // for QPX, which does have preinc r+r forms). 2311 if (VT.isVector()) { 2312 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2313 return false; 2314 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2315 AM = ISD::PRE_INC; 2316 return true; 2317 } 2318 } 2319 2320 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2321 // Common code will reject creating a pre-inc form if the base pointer 2322 // is a frame index, or if N is a store and the base pointer is either 2323 // the same as or a predecessor of the value being stored. Check for 2324 // those situations here, and try with swapped Base/Offset instead. 2325 bool Swap = false; 2326 2327 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2328 Swap = true; 2329 else if (!isLoad) { 2330 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2331 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2332 Swap = true; 2333 } 2334 2335 if (Swap) 2336 std::swap(Base, Offset); 2337 2338 AM = ISD::PRE_INC; 2339 return true; 2340 } 2341 2342 // LDU/STU can only handle immediates that are a multiple of 4. 2343 if (VT != MVT::i64) { 2344 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2345 return false; 2346 } else { 2347 // LDU/STU need an address with at least 4-byte alignment. 2348 if (Alignment < 4) 2349 return false; 2350 2351 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2352 return false; 2353 } 2354 2355 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2356 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2357 // sext i32 to i64 when addr mode is r+i. 2358 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2359 LD->getExtensionType() == ISD::SEXTLOAD && 2360 isa<ConstantSDNode>(Offset)) 2361 return false; 2362 } 2363 2364 AM = ISD::PRE_INC; 2365 return true; 2366 } 2367 2368 //===----------------------------------------------------------------------===// 2369 // LowerOperation implementation 2370 //===----------------------------------------------------------------------===// 2371 2372 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2373 /// and LoOpFlags to the target MO flags. 2374 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2375 unsigned &HiOpFlags, unsigned &LoOpFlags, 2376 const GlobalValue *GV = nullptr) { 2377 HiOpFlags = PPCII::MO_HA; 2378 LoOpFlags = PPCII::MO_LO; 2379 2380 // Don't use the pic base if not in PIC relocation model. 2381 if (IsPIC) { 2382 HiOpFlags |= PPCII::MO_PIC_FLAG; 2383 LoOpFlags |= PPCII::MO_PIC_FLAG; 2384 } 2385 2386 // If this is a reference to a global value that requires a non-lazy-ptr, make 2387 // sure that instruction lowering adds it. 2388 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2389 HiOpFlags |= PPCII::MO_NLP_FLAG; 2390 LoOpFlags |= PPCII::MO_NLP_FLAG; 2391 2392 if (GV->hasHiddenVisibility()) { 2393 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2394 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2395 } 2396 } 2397 } 2398 2399 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2400 SelectionDAG &DAG) { 2401 SDLoc DL(HiPart); 2402 EVT PtrVT = HiPart.getValueType(); 2403 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2404 2405 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2406 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2407 2408 // With PIC, the first instruction is actually "GR+hi(&G)". 2409 if (isPIC) 2410 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2411 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2412 2413 // Generate non-pic code that has direct accesses to the constant pool. 2414 // The address of the global is just (hi(&g)+lo(&g)). 2415 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2416 } 2417 2418 static void setUsesTOCBasePtr(MachineFunction &MF) { 2419 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2420 FuncInfo->setUsesTOCBasePtr(); 2421 } 2422 2423 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2424 setUsesTOCBasePtr(DAG.getMachineFunction()); 2425 } 2426 2427 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2428 SDValue GA) { 2429 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2430 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2431 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2432 2433 SDValue Ops[] = { GA, Reg }; 2434 return DAG.getMemIntrinsicNode( 2435 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2436 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2437 MachineMemOperand::MOLoad); 2438 } 2439 2440 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2441 SelectionDAG &DAG) const { 2442 EVT PtrVT = Op.getValueType(); 2443 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2444 const Constant *C = CP->getConstVal(); 2445 2446 // 64-bit SVR4 ABI code is always position-independent. 2447 // The actual address of the GlobalValue is stored in the TOC. 2448 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2449 setUsesTOCBasePtr(DAG); 2450 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2451 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2452 } 2453 2454 unsigned MOHiFlag, MOLoFlag; 2455 bool IsPIC = isPositionIndependent(); 2456 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2457 2458 if (IsPIC && Subtarget.isSVR4ABI()) { 2459 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2460 PPCII::MO_PIC_FLAG); 2461 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2462 } 2463 2464 SDValue CPIHi = 2465 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2466 SDValue CPILo = 2467 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2468 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2469 } 2470 2471 // For 64-bit PowerPC, prefer the more compact relative encodings. 2472 // This trades 32 bits per jump table entry for one or two instructions 2473 // on the jump site. 2474 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2475 if (isJumpTableRelative()) 2476 return MachineJumpTableInfo::EK_LabelDifference32; 2477 2478 return TargetLowering::getJumpTableEncoding(); 2479 } 2480 2481 bool PPCTargetLowering::isJumpTableRelative() const { 2482 if (Subtarget.isPPC64()) 2483 return true; 2484 return TargetLowering::isJumpTableRelative(); 2485 } 2486 2487 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2488 SelectionDAG &DAG) const { 2489 if (!Subtarget.isPPC64()) 2490 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2491 2492 switch (getTargetMachine().getCodeModel()) { 2493 case CodeModel::Small: 2494 case CodeModel::Medium: 2495 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2496 default: 2497 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2498 getPointerTy(DAG.getDataLayout())); 2499 } 2500 } 2501 2502 const MCExpr * 2503 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2504 unsigned JTI, 2505 MCContext &Ctx) const { 2506 if (!Subtarget.isPPC64()) 2507 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2508 2509 switch (getTargetMachine().getCodeModel()) { 2510 case CodeModel::Small: 2511 case CodeModel::Medium: 2512 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2513 default: 2514 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2515 } 2516 } 2517 2518 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2519 EVT PtrVT = Op.getValueType(); 2520 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2521 2522 // 64-bit SVR4 ABI code is always position-independent. 2523 // The actual address of the GlobalValue is stored in the TOC. 2524 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2525 setUsesTOCBasePtr(DAG); 2526 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2527 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2528 } 2529 2530 unsigned MOHiFlag, MOLoFlag; 2531 bool IsPIC = isPositionIndependent(); 2532 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2533 2534 if (IsPIC && Subtarget.isSVR4ABI()) { 2535 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2536 PPCII::MO_PIC_FLAG); 2537 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2538 } 2539 2540 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2541 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2542 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2543 } 2544 2545 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2546 SelectionDAG &DAG) const { 2547 EVT PtrVT = Op.getValueType(); 2548 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2549 const BlockAddress *BA = BASDN->getBlockAddress(); 2550 2551 // 64-bit SVR4 ABI code is always position-independent. 2552 // The actual BlockAddress is stored in the TOC. 2553 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2554 setUsesTOCBasePtr(DAG); 2555 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2556 return getTOCEntry(DAG, SDLoc(BASDN), true, GA); 2557 } 2558 2559 unsigned MOHiFlag, MOLoFlag; 2560 bool IsPIC = isPositionIndependent(); 2561 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2562 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2563 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2564 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2565 } 2566 2567 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2568 SelectionDAG &DAG) const { 2569 // FIXME: TLS addresses currently use medium model code sequences, 2570 // which is the most useful form. Eventually support for small and 2571 // large models could be added if users need it, at the cost of 2572 // additional complexity. 2573 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2574 if (DAG.getTarget().Options.EmulatedTLS) 2575 return LowerToTLSEmulatedModel(GA, DAG); 2576 2577 SDLoc dl(GA); 2578 const GlobalValue *GV = GA->getGlobal(); 2579 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2580 bool is64bit = Subtarget.isPPC64(); 2581 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2582 PICLevel::Level picLevel = M->getPICLevel(); 2583 2584 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 2585 2586 if (Model == TLSModel::LocalExec) { 2587 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2588 PPCII::MO_TPREL_HA); 2589 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2590 PPCII::MO_TPREL_LO); 2591 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2592 : DAG.getRegister(PPC::R2, MVT::i32); 2593 2594 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2595 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2596 } 2597 2598 if (Model == TLSModel::InitialExec) { 2599 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2600 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2601 PPCII::MO_TLS); 2602 SDValue GOTPtr; 2603 if (is64bit) { 2604 setUsesTOCBasePtr(DAG); 2605 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2606 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2607 PtrVT, GOTReg, TGA); 2608 } else 2609 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2610 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2611 PtrVT, TGA, GOTPtr); 2612 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2613 } 2614 2615 if (Model == TLSModel::GeneralDynamic) { 2616 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2617 SDValue GOTPtr; 2618 if (is64bit) { 2619 setUsesTOCBasePtr(DAG); 2620 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2621 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2622 GOTReg, TGA); 2623 } else { 2624 if (picLevel == PICLevel::SmallPIC) 2625 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2626 else 2627 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2628 } 2629 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2630 GOTPtr, TGA, TGA); 2631 } 2632 2633 if (Model == TLSModel::LocalDynamic) { 2634 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2635 SDValue GOTPtr; 2636 if (is64bit) { 2637 setUsesTOCBasePtr(DAG); 2638 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2639 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2640 GOTReg, TGA); 2641 } else { 2642 if (picLevel == PICLevel::SmallPIC) 2643 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2644 else 2645 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2646 } 2647 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2648 PtrVT, GOTPtr, TGA, TGA); 2649 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2650 PtrVT, TLSAddr, TGA); 2651 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2652 } 2653 2654 llvm_unreachable("Unknown TLS model!"); 2655 } 2656 2657 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2658 SelectionDAG &DAG) const { 2659 EVT PtrVT = Op.getValueType(); 2660 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2661 SDLoc DL(GSDN); 2662 const GlobalValue *GV = GSDN->getGlobal(); 2663 2664 // 64-bit SVR4 ABI code is always position-independent. 2665 // The actual address of the GlobalValue is stored in the TOC. 2666 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2667 setUsesTOCBasePtr(DAG); 2668 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2669 return getTOCEntry(DAG, DL, true, GA); 2670 } 2671 2672 unsigned MOHiFlag, MOLoFlag; 2673 bool IsPIC = isPositionIndependent(); 2674 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2675 2676 if (IsPIC && Subtarget.isSVR4ABI()) { 2677 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2678 GSDN->getOffset(), 2679 PPCII::MO_PIC_FLAG); 2680 return getTOCEntry(DAG, DL, false, GA); 2681 } 2682 2683 SDValue GAHi = 2684 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2685 SDValue GALo = 2686 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2687 2688 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2689 2690 // If the global reference is actually to a non-lazy-pointer, we have to do an 2691 // extra load to get the address of the global. 2692 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2693 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2694 return Ptr; 2695 } 2696 2697 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2698 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2699 SDLoc dl(Op); 2700 2701 if (Op.getValueType() == MVT::v2i64) { 2702 // When the operands themselves are v2i64 values, we need to do something 2703 // special because VSX has no underlying comparison operations for these. 2704 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2705 // Equality can be handled by casting to the legal type for Altivec 2706 // comparisons, everything else needs to be expanded. 2707 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2708 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2709 DAG.getSetCC(dl, MVT::v4i32, 2710 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2711 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2712 CC)); 2713 } 2714 2715 return SDValue(); 2716 } 2717 2718 // We handle most of these in the usual way. 2719 return Op; 2720 } 2721 2722 // If we're comparing for equality to zero, expose the fact that this is 2723 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2724 // fold the new nodes. 2725 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2726 return V; 2727 2728 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2729 // Leave comparisons against 0 and -1 alone for now, since they're usually 2730 // optimized. FIXME: revisit this when we can custom lower all setcc 2731 // optimizations. 2732 if (C->isAllOnesValue() || C->isNullValue()) 2733 return SDValue(); 2734 } 2735 2736 // If we have an integer seteq/setne, turn it into a compare against zero 2737 // by xor'ing the rhs with the lhs, which is faster than setting a 2738 // condition register, reading it back out, and masking the correct bit. The 2739 // normal approach here uses sub to do this instead of xor. Using xor exposes 2740 // the result to other bit-twiddling opportunities. 2741 EVT LHSVT = Op.getOperand(0).getValueType(); 2742 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2743 EVT VT = Op.getValueType(); 2744 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2745 Op.getOperand(1)); 2746 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2747 } 2748 return SDValue(); 2749 } 2750 2751 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2752 SDNode *Node = Op.getNode(); 2753 EVT VT = Node->getValueType(0); 2754 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2755 SDValue InChain = Node->getOperand(0); 2756 SDValue VAListPtr = Node->getOperand(1); 2757 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2758 SDLoc dl(Node); 2759 2760 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2761 2762 // gpr_index 2763 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2764 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2765 InChain = GprIndex.getValue(1); 2766 2767 if (VT == MVT::i64) { 2768 // Check if GprIndex is even 2769 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2770 DAG.getConstant(1, dl, MVT::i32)); 2771 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2772 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2773 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2774 DAG.getConstant(1, dl, MVT::i32)); 2775 // Align GprIndex to be even if it isn't 2776 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2777 GprIndex); 2778 } 2779 2780 // fpr index is 1 byte after gpr 2781 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2782 DAG.getConstant(1, dl, MVT::i32)); 2783 2784 // fpr 2785 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2786 FprPtr, MachinePointerInfo(SV), MVT::i8); 2787 InChain = FprIndex.getValue(1); 2788 2789 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2790 DAG.getConstant(8, dl, MVT::i32)); 2791 2792 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2793 DAG.getConstant(4, dl, MVT::i32)); 2794 2795 // areas 2796 SDValue OverflowArea = 2797 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 2798 InChain = OverflowArea.getValue(1); 2799 2800 SDValue RegSaveArea = 2801 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 2802 InChain = RegSaveArea.getValue(1); 2803 2804 // select overflow_area if index > 8 2805 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2806 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 2807 2808 // adjustment constant gpr_index * 4/8 2809 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2810 VT.isInteger() ? GprIndex : FprIndex, 2811 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 2812 MVT::i32)); 2813 2814 // OurReg = RegSaveArea + RegConstant 2815 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2816 RegConstant); 2817 2818 // Floating types are 32 bytes into RegSaveArea 2819 if (VT.isFloatingPoint()) 2820 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 2821 DAG.getConstant(32, dl, MVT::i32)); 2822 2823 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 2824 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 2825 VT.isInteger() ? GprIndex : FprIndex, 2826 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 2827 MVT::i32)); 2828 2829 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 2830 VT.isInteger() ? VAListPtr : FprPtr, 2831 MachinePointerInfo(SV), MVT::i8); 2832 2833 // determine if we should load from reg_save_area or overflow_area 2834 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 2835 2836 // increase overflow_area by 4/8 if gpr/fpr > 8 2837 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 2838 DAG.getConstant(VT.isInteger() ? 4 : 8, 2839 dl, MVT::i32)); 2840 2841 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 2842 OverflowAreaPlusN); 2843 2844 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 2845 MachinePointerInfo(), MVT::i32); 2846 2847 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 2848 } 2849 2850 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 2851 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 2852 2853 // We have to copy the entire va_list struct: 2854 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 2855 return DAG.getMemcpy(Op.getOperand(0), Op, 2856 Op.getOperand(1), Op.getOperand(2), 2857 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 2858 false, MachinePointerInfo(), MachinePointerInfo()); 2859 } 2860 2861 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 2862 SelectionDAG &DAG) const { 2863 return Op.getOperand(0); 2864 } 2865 2866 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 2867 SelectionDAG &DAG) const { 2868 SDValue Chain = Op.getOperand(0); 2869 SDValue Trmp = Op.getOperand(1); // trampoline 2870 SDValue FPtr = Op.getOperand(2); // nested function 2871 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 2872 SDLoc dl(Op); 2873 2874 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2875 bool isPPC64 = (PtrVT == MVT::i64); 2876 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 2877 2878 TargetLowering::ArgListTy Args; 2879 TargetLowering::ArgListEntry Entry; 2880 2881 Entry.Ty = IntPtrTy; 2882 Entry.Node = Trmp; Args.push_back(Entry); 2883 2884 // TrampSize == (isPPC64 ? 48 : 40); 2885 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 2886 isPPC64 ? MVT::i64 : MVT::i32); 2887 Args.push_back(Entry); 2888 2889 Entry.Node = FPtr; Args.push_back(Entry); 2890 Entry.Node = Nest; Args.push_back(Entry); 2891 2892 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 2893 TargetLowering::CallLoweringInfo CLI(DAG); 2894 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2895 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 2896 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 2897 2898 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2899 return CallResult.second; 2900 } 2901 2902 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 2903 MachineFunction &MF = DAG.getMachineFunction(); 2904 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2905 EVT PtrVT = getPointerTy(MF.getDataLayout()); 2906 2907 SDLoc dl(Op); 2908 2909 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 2910 // vastart just stores the address of the VarArgsFrameIndex slot into the 2911 // memory location argument. 2912 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2913 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2914 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2915 MachinePointerInfo(SV)); 2916 } 2917 2918 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 2919 // We suppose the given va_list is already allocated. 2920 // 2921 // typedef struct { 2922 // char gpr; /* index into the array of 8 GPRs 2923 // * stored in the register save area 2924 // * gpr=0 corresponds to r3, 2925 // * gpr=1 to r4, etc. 2926 // */ 2927 // char fpr; /* index into the array of 8 FPRs 2928 // * stored in the register save area 2929 // * fpr=0 corresponds to f1, 2930 // * fpr=1 to f2, etc. 2931 // */ 2932 // char *overflow_arg_area; 2933 // /* location on stack that holds 2934 // * the next overflow argument 2935 // */ 2936 // char *reg_save_area; 2937 // /* where r3:r10 and f1:f8 (if saved) 2938 // * are stored 2939 // */ 2940 // } va_list[1]; 2941 2942 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 2943 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 2944 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 2945 PtrVT); 2946 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 2947 PtrVT); 2948 2949 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 2950 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 2951 2952 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 2953 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 2954 2955 uint64_t FPROffset = 1; 2956 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 2957 2958 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2959 2960 // Store first byte : number of int regs 2961 SDValue firstStore = 2962 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 2963 MachinePointerInfo(SV), MVT::i8); 2964 uint64_t nextOffset = FPROffset; 2965 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 2966 ConstFPROffset); 2967 2968 // Store second byte : number of float regs 2969 SDValue secondStore = 2970 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 2971 MachinePointerInfo(SV, nextOffset), MVT::i8); 2972 nextOffset += StackOffset; 2973 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 2974 2975 // Store second word : arguments given on stack 2976 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 2977 MachinePointerInfo(SV, nextOffset)); 2978 nextOffset += FrameOffset; 2979 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 2980 2981 // Store third word : arguments given in registers 2982 return DAG.getStore(thirdStore, dl, FR, nextPtr, 2983 MachinePointerInfo(SV, nextOffset)); 2984 } 2985 2986 #include "PPCGenCallingConv.inc" 2987 2988 // Function whose sole purpose is to kill compiler warnings 2989 // stemming from unused functions included from PPCGenCallingConv.inc. 2990 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { 2991 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; 2992 } 2993 2994 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 2995 CCValAssign::LocInfo &LocInfo, 2996 ISD::ArgFlagsTy &ArgFlags, 2997 CCState &State) { 2998 return true; 2999 } 3000 3001 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 3002 MVT &LocVT, 3003 CCValAssign::LocInfo &LocInfo, 3004 ISD::ArgFlagsTy &ArgFlags, 3005 CCState &State) { 3006 static const MCPhysReg ArgRegs[] = { 3007 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3008 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3009 }; 3010 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3011 3012 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3013 3014 // Skip one register if the first unallocated register has an even register 3015 // number and there are still argument registers available which have not been 3016 // allocated yet. RegNum is actually an index into ArgRegs, which means we 3017 // need to skip a register if RegNum is odd. 3018 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 3019 State.AllocateReg(ArgRegs[RegNum]); 3020 } 3021 3022 // Always return false here, as this function only makes sure that the first 3023 // unallocated register has an odd register number and does not actually 3024 // allocate a register for the current argument. 3025 return false; 3026 } 3027 3028 bool 3029 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT, 3030 MVT &LocVT, 3031 CCValAssign::LocInfo &LocInfo, 3032 ISD::ArgFlagsTy &ArgFlags, 3033 CCState &State) { 3034 static const MCPhysReg ArgRegs[] = { 3035 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3036 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3037 }; 3038 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3039 3040 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3041 int RegsLeft = NumArgRegs - RegNum; 3042 3043 // Skip if there is not enough registers left for long double type (4 gpr regs 3044 // in soft float mode) and put long double argument on the stack. 3045 if (RegNum != NumArgRegs && RegsLeft < 4) { 3046 for (int i = 0; i < RegsLeft; i++) { 3047 State.AllocateReg(ArgRegs[RegNum + i]); 3048 } 3049 } 3050 3051 return false; 3052 } 3053 3054 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 3055 MVT &LocVT, 3056 CCValAssign::LocInfo &LocInfo, 3057 ISD::ArgFlagsTy &ArgFlags, 3058 CCState &State) { 3059 static const MCPhysReg ArgRegs[] = { 3060 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3061 PPC::F8 3062 }; 3063 3064 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3065 3066 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3067 3068 // If there is only one Floating-point register left we need to put both f64 3069 // values of a split ppc_fp128 value on the stack. 3070 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 3071 State.AllocateReg(ArgRegs[RegNum]); 3072 } 3073 3074 // Always return false here, as this function only makes sure that the two f64 3075 // values a ppc_fp128 value is split into are both passed in registers or both 3076 // passed on the stack and does not actually allocate a register for the 3077 // current argument. 3078 return false; 3079 } 3080 3081 /// FPR - The set of FP registers that should be allocated for arguments, 3082 /// on Darwin. 3083 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3084 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3085 PPC::F11, PPC::F12, PPC::F13}; 3086 3087 /// QFPR - The set of QPX registers that should be allocated for arguments. 3088 static const MCPhysReg QFPR[] = { 3089 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3090 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3091 3092 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3093 /// the stack. 3094 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3095 unsigned PtrByteSize) { 3096 unsigned ArgSize = ArgVT.getStoreSize(); 3097 if (Flags.isByVal()) 3098 ArgSize = Flags.getByValSize(); 3099 3100 // Round up to multiples of the pointer size, except for array members, 3101 // which are always packed. 3102 if (!Flags.isInConsecutiveRegs()) 3103 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3104 3105 return ArgSize; 3106 } 3107 3108 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3109 /// on the stack. 3110 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3111 ISD::ArgFlagsTy Flags, 3112 unsigned PtrByteSize) { 3113 unsigned Align = PtrByteSize; 3114 3115 // Altivec parameters are padded to a 16 byte boundary. 3116 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3117 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3118 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3119 ArgVT == MVT::v1i128) 3120 Align = 16; 3121 // QPX vector types stored in double-precision are padded to a 32 byte 3122 // boundary. 3123 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3124 Align = 32; 3125 3126 // ByVal parameters are aligned as requested. 3127 if (Flags.isByVal()) { 3128 unsigned BVAlign = Flags.getByValAlign(); 3129 if (BVAlign > PtrByteSize) { 3130 if (BVAlign % PtrByteSize != 0) 3131 llvm_unreachable( 3132 "ByVal alignment is not a multiple of the pointer size"); 3133 3134 Align = BVAlign; 3135 } 3136 } 3137 3138 // Array members are always packed to their original alignment. 3139 if (Flags.isInConsecutiveRegs()) { 3140 // If the array member was split into multiple registers, the first 3141 // needs to be aligned to the size of the full type. (Except for 3142 // ppcf128, which is only aligned as its f64 components.) 3143 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3144 Align = OrigVT.getStoreSize(); 3145 else 3146 Align = ArgVT.getStoreSize(); 3147 } 3148 3149 return Align; 3150 } 3151 3152 /// CalculateStackSlotUsed - Return whether this argument will use its 3153 /// stack slot (instead of being passed in registers). ArgOffset, 3154 /// AvailableFPRs, and AvailableVRs must hold the current argument 3155 /// position, and will be updated to account for this argument. 3156 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3157 ISD::ArgFlagsTy Flags, 3158 unsigned PtrByteSize, 3159 unsigned LinkageSize, 3160 unsigned ParamAreaSize, 3161 unsigned &ArgOffset, 3162 unsigned &AvailableFPRs, 3163 unsigned &AvailableVRs, bool HasQPX) { 3164 bool UseMemory = false; 3165 3166 // Respect alignment of argument on the stack. 3167 unsigned Align = 3168 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3169 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3170 // If there's no space left in the argument save area, we must 3171 // use memory (this check also catches zero-sized arguments). 3172 if (ArgOffset >= LinkageSize + ParamAreaSize) 3173 UseMemory = true; 3174 3175 // Allocate argument on the stack. 3176 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3177 if (Flags.isInConsecutiveRegsLast()) 3178 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3179 // If we overran the argument save area, we must use memory 3180 // (this check catches arguments passed partially in memory) 3181 if (ArgOffset > LinkageSize + ParamAreaSize) 3182 UseMemory = true; 3183 3184 // However, if the argument is actually passed in an FPR or a VR, 3185 // we don't use memory after all. 3186 if (!Flags.isByVal()) { 3187 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3188 // QPX registers overlap with the scalar FP registers. 3189 (HasQPX && (ArgVT == MVT::v4f32 || 3190 ArgVT == MVT::v4f64 || 3191 ArgVT == MVT::v4i1))) 3192 if (AvailableFPRs > 0) { 3193 --AvailableFPRs; 3194 return false; 3195 } 3196 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3197 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3198 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3199 ArgVT == MVT::v1i128) 3200 if (AvailableVRs > 0) { 3201 --AvailableVRs; 3202 return false; 3203 } 3204 } 3205 3206 return UseMemory; 3207 } 3208 3209 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3210 /// ensure minimum alignment required for target. 3211 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3212 unsigned NumBytes) { 3213 unsigned TargetAlign = Lowering->getStackAlignment(); 3214 unsigned AlignMask = TargetAlign - 1; 3215 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3216 return NumBytes; 3217 } 3218 3219 SDValue PPCTargetLowering::LowerFormalArguments( 3220 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3221 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3222 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3223 if (Subtarget.isSVR4ABI()) { 3224 if (Subtarget.isPPC64()) 3225 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3226 dl, DAG, InVals); 3227 else 3228 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3229 dl, DAG, InVals); 3230 } else { 3231 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3232 dl, DAG, InVals); 3233 } 3234 } 3235 3236 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3237 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3238 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3239 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3240 3241 // 32-bit SVR4 ABI Stack Frame Layout: 3242 // +-----------------------------------+ 3243 // +--> | Back chain | 3244 // | +-----------------------------------+ 3245 // | | Floating-point register save area | 3246 // | +-----------------------------------+ 3247 // | | General register save area | 3248 // | +-----------------------------------+ 3249 // | | CR save word | 3250 // | +-----------------------------------+ 3251 // | | VRSAVE save word | 3252 // | +-----------------------------------+ 3253 // | | Alignment padding | 3254 // | +-----------------------------------+ 3255 // | | Vector register save area | 3256 // | +-----------------------------------+ 3257 // | | Local variable space | 3258 // | +-----------------------------------+ 3259 // | | Parameter list area | 3260 // | +-----------------------------------+ 3261 // | | LR save word | 3262 // | +-----------------------------------+ 3263 // SP--> +--- | Back chain | 3264 // +-----------------------------------+ 3265 // 3266 // Specifications: 3267 // System V Application Binary Interface PowerPC Processor Supplement 3268 // AltiVec Technology Programming Interface Manual 3269 3270 MachineFunction &MF = DAG.getMachineFunction(); 3271 MachineFrameInfo &MFI = MF.getFrameInfo(); 3272 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3273 3274 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3275 // Potential tail calls could cause overwriting of argument stack slots. 3276 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3277 (CallConv == CallingConv::Fast)); 3278 unsigned PtrByteSize = 4; 3279 3280 // Assign locations to all of the incoming arguments. 3281 SmallVector<CCValAssign, 16> ArgLocs; 3282 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3283 *DAG.getContext()); 3284 3285 // Reserve space for the linkage area on the stack. 3286 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3287 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3288 if (useSoftFloat()) 3289 CCInfo.PreAnalyzeFormalArguments(Ins); 3290 3291 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3292 CCInfo.clearWasPPCF128(); 3293 3294 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3295 CCValAssign &VA = ArgLocs[i]; 3296 3297 // Arguments stored in registers. 3298 if (VA.isRegLoc()) { 3299 const TargetRegisterClass *RC; 3300 EVT ValVT = VA.getValVT(); 3301 3302 switch (ValVT.getSimpleVT().SimpleTy) { 3303 default: 3304 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3305 case MVT::i1: 3306 case MVT::i32: 3307 RC = &PPC::GPRCRegClass; 3308 break; 3309 case MVT::f32: 3310 if (Subtarget.hasP8Vector()) 3311 RC = &PPC::VSSRCRegClass; 3312 else 3313 RC = &PPC::F4RCRegClass; 3314 break; 3315 case MVT::f64: 3316 if (Subtarget.hasVSX()) 3317 RC = &PPC::VSFRCRegClass; 3318 else 3319 RC = &PPC::F8RCRegClass; 3320 break; 3321 case MVT::v16i8: 3322 case MVT::v8i16: 3323 case MVT::v4i32: 3324 RC = &PPC::VRRCRegClass; 3325 break; 3326 case MVT::v4f32: 3327 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3328 break; 3329 case MVT::v2f64: 3330 case MVT::v2i64: 3331 RC = &PPC::VRRCRegClass; 3332 break; 3333 case MVT::v4f64: 3334 RC = &PPC::QFRCRegClass; 3335 break; 3336 case MVT::v4i1: 3337 RC = &PPC::QBRCRegClass; 3338 break; 3339 } 3340 3341 // Transform the arguments stored in physical registers into virtual ones. 3342 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3343 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3344 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3345 3346 if (ValVT == MVT::i1) 3347 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3348 3349 InVals.push_back(ArgValue); 3350 } else { 3351 // Argument stored in memory. 3352 assert(VA.isMemLoc()); 3353 3354 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3355 int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(), 3356 isImmutable); 3357 3358 // Create load nodes to retrieve arguments from the stack. 3359 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3360 InVals.push_back( 3361 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3362 } 3363 } 3364 3365 // Assign locations to all of the incoming aggregate by value arguments. 3366 // Aggregates passed by value are stored in the local variable space of the 3367 // caller's stack frame, right above the parameter list area. 3368 SmallVector<CCValAssign, 16> ByValArgLocs; 3369 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3370 ByValArgLocs, *DAG.getContext()); 3371 3372 // Reserve stack space for the allocations in CCInfo. 3373 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3374 3375 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3376 3377 // Area that is at least reserved in the caller of this function. 3378 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3379 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3380 3381 // Set the size that is at least reserved in caller of this function. Tail 3382 // call optimized function's reserved stack space needs to be aligned so that 3383 // taking the difference between two stack areas will result in an aligned 3384 // stack. 3385 MinReservedArea = 3386 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3387 FuncInfo->setMinReservedArea(MinReservedArea); 3388 3389 SmallVector<SDValue, 8> MemOps; 3390 3391 // If the function takes variable number of arguments, make a frame index for 3392 // the start of the first vararg value... for expansion of llvm.va_start. 3393 if (isVarArg) { 3394 static const MCPhysReg GPArgRegs[] = { 3395 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3396 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3397 }; 3398 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3399 3400 static const MCPhysReg FPArgRegs[] = { 3401 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3402 PPC::F8 3403 }; 3404 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3405 3406 if (useSoftFloat()) 3407 NumFPArgRegs = 0; 3408 3409 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3410 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3411 3412 // Make room for NumGPArgRegs and NumFPArgRegs. 3413 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3414 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3415 3416 FuncInfo->setVarArgsStackOffset( 3417 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3418 CCInfo.getNextStackOffset(), true)); 3419 3420 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3421 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3422 3423 // The fixed integer arguments of a variadic function are stored to the 3424 // VarArgsFrameIndex on the stack so that they may be loaded by 3425 // dereferencing the result of va_next. 3426 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3427 // Get an existing live-in vreg, or add a new one. 3428 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3429 if (!VReg) 3430 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3431 3432 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3433 SDValue Store = 3434 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3435 MemOps.push_back(Store); 3436 // Increment the address by four for the next argument to store 3437 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3438 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3439 } 3440 3441 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3442 // is set. 3443 // The double arguments are stored to the VarArgsFrameIndex 3444 // on the stack. 3445 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3446 // Get an existing live-in vreg, or add a new one. 3447 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3448 if (!VReg) 3449 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3450 3451 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3452 SDValue Store = 3453 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3454 MemOps.push_back(Store); 3455 // Increment the address by eight for the next argument to store 3456 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3457 PtrVT); 3458 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3459 } 3460 } 3461 3462 if (!MemOps.empty()) 3463 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3464 3465 return Chain; 3466 } 3467 3468 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3469 // value to MVT::i64 and then truncate to the correct register size. 3470 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3471 EVT ObjectVT, SelectionDAG &DAG, 3472 SDValue ArgVal, 3473 const SDLoc &dl) const { 3474 if (Flags.isSExt()) 3475 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3476 DAG.getValueType(ObjectVT)); 3477 else if (Flags.isZExt()) 3478 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3479 DAG.getValueType(ObjectVT)); 3480 3481 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3482 } 3483 3484 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3485 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3486 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3487 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3488 // TODO: add description of PPC stack frame format, or at least some docs. 3489 // 3490 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3491 bool isLittleEndian = Subtarget.isLittleEndian(); 3492 MachineFunction &MF = DAG.getMachineFunction(); 3493 MachineFrameInfo &MFI = MF.getFrameInfo(); 3494 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3495 3496 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3497 "fastcc not supported on varargs functions"); 3498 3499 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3500 // Potential tail calls could cause overwriting of argument stack slots. 3501 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3502 (CallConv == CallingConv::Fast)); 3503 unsigned PtrByteSize = 8; 3504 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3505 3506 static const MCPhysReg GPR[] = { 3507 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3508 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3509 }; 3510 static const MCPhysReg VR[] = { 3511 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3512 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3513 }; 3514 3515 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3516 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3517 const unsigned Num_VR_Regs = array_lengthof(VR); 3518 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3519 3520 // Do a first pass over the arguments to determine whether the ABI 3521 // guarantees that our caller has allocated the parameter save area 3522 // on its stack frame. In the ELFv1 ABI, this is always the case; 3523 // in the ELFv2 ABI, it is true if this is a vararg function or if 3524 // any parameter is located in a stack slot. 3525 3526 bool HasParameterArea = !isELFv2ABI || isVarArg; 3527 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3528 unsigned NumBytes = LinkageSize; 3529 unsigned AvailableFPRs = Num_FPR_Regs; 3530 unsigned AvailableVRs = Num_VR_Regs; 3531 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3532 if (Ins[i].Flags.isNest()) 3533 continue; 3534 3535 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3536 PtrByteSize, LinkageSize, ParamAreaSize, 3537 NumBytes, AvailableFPRs, AvailableVRs, 3538 Subtarget.hasQPX())) 3539 HasParameterArea = true; 3540 } 3541 3542 // Add DAG nodes to load the arguments or copy them out of registers. On 3543 // entry to a function on PPC, the arguments start after the linkage area, 3544 // although the first ones are often in registers. 3545 3546 unsigned ArgOffset = LinkageSize; 3547 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3548 unsigned &QFPR_idx = FPR_idx; 3549 SmallVector<SDValue, 8> MemOps; 3550 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3551 unsigned CurArgIdx = 0; 3552 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3553 SDValue ArgVal; 3554 bool needsLoad = false; 3555 EVT ObjectVT = Ins[ArgNo].VT; 3556 EVT OrigVT = Ins[ArgNo].ArgVT; 3557 unsigned ObjSize = ObjectVT.getStoreSize(); 3558 unsigned ArgSize = ObjSize; 3559 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3560 if (Ins[ArgNo].isOrigArg()) { 3561 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3562 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3563 } 3564 // We re-align the argument offset for each argument, except when using the 3565 // fast calling convention, when we need to make sure we do that only when 3566 // we'll actually use a stack slot. 3567 unsigned CurArgOffset, Align; 3568 auto ComputeArgOffset = [&]() { 3569 /* Respect alignment of argument on the stack. */ 3570 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3571 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3572 CurArgOffset = ArgOffset; 3573 }; 3574 3575 if (CallConv != CallingConv::Fast) { 3576 ComputeArgOffset(); 3577 3578 /* Compute GPR index associated with argument offset. */ 3579 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3580 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3581 } 3582 3583 // FIXME the codegen can be much improved in some cases. 3584 // We do not have to keep everything in memory. 3585 if (Flags.isByVal()) { 3586 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3587 3588 if (CallConv == CallingConv::Fast) 3589 ComputeArgOffset(); 3590 3591 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3592 ObjSize = Flags.getByValSize(); 3593 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3594 // Empty aggregate parameters do not take up registers. Examples: 3595 // struct { } a; 3596 // union { } b; 3597 // int c[0]; 3598 // etc. However, we have to provide a place-holder in InVals, so 3599 // pretend we have an 8-byte item at the current address for that 3600 // purpose. 3601 if (!ObjSize) { 3602 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3603 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3604 InVals.push_back(FIN); 3605 continue; 3606 } 3607 3608 // Create a stack object covering all stack doublewords occupied 3609 // by the argument. If the argument is (fully or partially) on 3610 // the stack, or if the argument is fully in registers but the 3611 // caller has allocated the parameter save anyway, we can refer 3612 // directly to the caller's stack frame. Otherwise, create a 3613 // local copy in our own frame. 3614 int FI; 3615 if (HasParameterArea || 3616 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3617 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3618 else 3619 FI = MFI.CreateStackObject(ArgSize, Align, false); 3620 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3621 3622 // Handle aggregates smaller than 8 bytes. 3623 if (ObjSize < PtrByteSize) { 3624 // The value of the object is its address, which differs from the 3625 // address of the enclosing doubleword on big-endian systems. 3626 SDValue Arg = FIN; 3627 if (!isLittleEndian) { 3628 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3629 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3630 } 3631 InVals.push_back(Arg); 3632 3633 if (GPR_idx != Num_GPR_Regs) { 3634 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3635 FuncInfo->addLiveInAttr(VReg, Flags); 3636 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3637 SDValue Store; 3638 3639 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3640 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3641 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3642 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3643 MachinePointerInfo(&*FuncArg), ObjType); 3644 } else { 3645 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3646 // store the whole register as-is to the parameter save area 3647 // slot. 3648 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3649 MachinePointerInfo(&*FuncArg)); 3650 } 3651 3652 MemOps.push_back(Store); 3653 } 3654 // Whether we copied from a register or not, advance the offset 3655 // into the parameter save area by a full doubleword. 3656 ArgOffset += PtrByteSize; 3657 continue; 3658 } 3659 3660 // The value of the object is its address, which is the address of 3661 // its first stack doubleword. 3662 InVals.push_back(FIN); 3663 3664 // Store whatever pieces of the object are in registers to memory. 3665 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3666 if (GPR_idx == Num_GPR_Regs) 3667 break; 3668 3669 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3670 FuncInfo->addLiveInAttr(VReg, Flags); 3671 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3672 SDValue Addr = FIN; 3673 if (j) { 3674 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3675 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3676 } 3677 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3678 MachinePointerInfo(&*FuncArg, j)); 3679 MemOps.push_back(Store); 3680 ++GPR_idx; 3681 } 3682 ArgOffset += ArgSize; 3683 continue; 3684 } 3685 3686 switch (ObjectVT.getSimpleVT().SimpleTy) { 3687 default: llvm_unreachable("Unhandled argument type!"); 3688 case MVT::i1: 3689 case MVT::i32: 3690 case MVT::i64: 3691 if (Flags.isNest()) { 3692 // The 'nest' parameter, if any, is passed in R11. 3693 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3694 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3695 3696 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3697 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3698 3699 break; 3700 } 3701 3702 // These can be scalar arguments or elements of an integer array type 3703 // passed directly. Clang may use those instead of "byval" aggregate 3704 // types to avoid forcing arguments to memory unnecessarily. 3705 if (GPR_idx != Num_GPR_Regs) { 3706 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3707 FuncInfo->addLiveInAttr(VReg, Flags); 3708 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3709 3710 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3711 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3712 // value to MVT::i64 and then truncate to the correct register size. 3713 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3714 } else { 3715 if (CallConv == CallingConv::Fast) 3716 ComputeArgOffset(); 3717 3718 needsLoad = true; 3719 ArgSize = PtrByteSize; 3720 } 3721 if (CallConv != CallingConv::Fast || needsLoad) 3722 ArgOffset += 8; 3723 break; 3724 3725 case MVT::f32: 3726 case MVT::f64: 3727 // These can be scalar arguments or elements of a float array type 3728 // passed directly. The latter are used to implement ELFv2 homogenous 3729 // float aggregates. 3730 if (FPR_idx != Num_FPR_Regs) { 3731 unsigned VReg; 3732 3733 if (ObjectVT == MVT::f32) 3734 VReg = MF.addLiveIn(FPR[FPR_idx], 3735 Subtarget.hasP8Vector() 3736 ? &PPC::VSSRCRegClass 3737 : &PPC::F4RCRegClass); 3738 else 3739 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3740 ? &PPC::VSFRCRegClass 3741 : &PPC::F8RCRegClass); 3742 3743 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3744 ++FPR_idx; 3745 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3746 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3747 // once we support fp <-> gpr moves. 3748 3749 // This can only ever happen in the presence of f32 array types, 3750 // since otherwise we never run out of FPRs before running out 3751 // of GPRs. 3752 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3753 FuncInfo->addLiveInAttr(VReg, Flags); 3754 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3755 3756 if (ObjectVT == MVT::f32) { 3757 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3758 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3759 DAG.getConstant(32, dl, MVT::i32)); 3760 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3761 } 3762 3763 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3764 } else { 3765 if (CallConv == CallingConv::Fast) 3766 ComputeArgOffset(); 3767 3768 needsLoad = true; 3769 } 3770 3771 // When passing an array of floats, the array occupies consecutive 3772 // space in the argument area; only round up to the next doubleword 3773 // at the end of the array. Otherwise, each float takes 8 bytes. 3774 if (CallConv != CallingConv::Fast || needsLoad) { 3775 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3776 ArgOffset += ArgSize; 3777 if (Flags.isInConsecutiveRegsLast()) 3778 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3779 } 3780 break; 3781 case MVT::v4f32: 3782 case MVT::v4i32: 3783 case MVT::v8i16: 3784 case MVT::v16i8: 3785 case MVT::v2f64: 3786 case MVT::v2i64: 3787 case MVT::v1i128: 3788 if (!Subtarget.hasQPX()) { 3789 // These can be scalar arguments or elements of a vector array type 3790 // passed directly. The latter are used to implement ELFv2 homogenous 3791 // vector aggregates. 3792 if (VR_idx != Num_VR_Regs) { 3793 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3794 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3795 ++VR_idx; 3796 } else { 3797 if (CallConv == CallingConv::Fast) 3798 ComputeArgOffset(); 3799 3800 needsLoad = true; 3801 } 3802 if (CallConv != CallingConv::Fast || needsLoad) 3803 ArgOffset += 16; 3804 break; 3805 } // not QPX 3806 3807 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3808 "Invalid QPX parameter type"); 3809 /* fall through */ 3810 3811 case MVT::v4f64: 3812 case MVT::v4i1: 3813 // QPX vectors are treated like their scalar floating-point subregisters 3814 // (except that they're larger). 3815 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3816 if (QFPR_idx != Num_QFPR_Regs) { 3817 const TargetRegisterClass *RC; 3818 switch (ObjectVT.getSimpleVT().SimpleTy) { 3819 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3820 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3821 default: RC = &PPC::QBRCRegClass; break; 3822 } 3823 3824 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3825 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3826 ++QFPR_idx; 3827 } else { 3828 if (CallConv == CallingConv::Fast) 3829 ComputeArgOffset(); 3830 needsLoad = true; 3831 } 3832 if (CallConv != CallingConv::Fast || needsLoad) 3833 ArgOffset += Sz; 3834 break; 3835 } 3836 3837 // We need to load the argument to a virtual register if we determined 3838 // above that we ran out of physical registers of the appropriate type. 3839 if (needsLoad) { 3840 if (ObjSize < ArgSize && !isLittleEndian) 3841 CurArgOffset += ArgSize - ObjSize; 3842 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3843 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3844 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3845 } 3846 3847 InVals.push_back(ArgVal); 3848 } 3849 3850 // Area that is at least reserved in the caller of this function. 3851 unsigned MinReservedArea; 3852 if (HasParameterArea) 3853 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 3854 else 3855 MinReservedArea = LinkageSize; 3856 3857 // Set the size that is at least reserved in caller of this function. Tail 3858 // call optimized functions' reserved stack space needs to be aligned so that 3859 // taking the difference between two stack areas will result in an aligned 3860 // stack. 3861 MinReservedArea = 3862 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3863 FuncInfo->setMinReservedArea(MinReservedArea); 3864 3865 // If the function takes variable number of arguments, make a frame index for 3866 // the start of the first vararg value... for expansion of llvm.va_start. 3867 if (isVarArg) { 3868 int Depth = ArgOffset; 3869 3870 FuncInfo->setVarArgsFrameIndex( 3871 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 3872 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3873 3874 // If this function is vararg, store any remaining integer argument regs 3875 // to their spots on the stack so that they may be loaded by dereferencing 3876 // the result of va_next. 3877 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3878 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 3879 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3880 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3881 SDValue Store = 3882 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3883 MemOps.push_back(Store); 3884 // Increment the address by four for the next argument to store 3885 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 3886 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3887 } 3888 } 3889 3890 if (!MemOps.empty()) 3891 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3892 3893 return Chain; 3894 } 3895 3896 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 3897 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3898 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3899 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3900 // TODO: add description of PPC stack frame format, or at least some docs. 3901 // 3902 MachineFunction &MF = DAG.getMachineFunction(); 3903 MachineFrameInfo &MFI = MF.getFrameInfo(); 3904 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3905 3906 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3907 bool isPPC64 = PtrVT == MVT::i64; 3908 // Potential tail calls could cause overwriting of argument stack slots. 3909 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3910 (CallConv == CallingConv::Fast)); 3911 unsigned PtrByteSize = isPPC64 ? 8 : 4; 3912 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3913 unsigned ArgOffset = LinkageSize; 3914 // Area that is at least reserved in caller of this function. 3915 unsigned MinReservedArea = ArgOffset; 3916 3917 static const MCPhysReg GPR_32[] = { // 32-bit registers. 3918 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3919 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3920 }; 3921 static const MCPhysReg GPR_64[] = { // 64-bit registers. 3922 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3923 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3924 }; 3925 static const MCPhysReg VR[] = { 3926 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3927 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3928 }; 3929 3930 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 3931 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3932 const unsigned Num_VR_Regs = array_lengthof( VR); 3933 3934 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3935 3936 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 3937 3938 // In 32-bit non-varargs functions, the stack space for vectors is after the 3939 // stack space for non-vectors. We do not use this space unless we have 3940 // too many vectors to fit in registers, something that only occurs in 3941 // constructed examples:), but we have to walk the arglist to figure 3942 // that out...for the pathological case, compute VecArgOffset as the 3943 // start of the vector parameter area. Computing VecArgOffset is the 3944 // entire point of the following loop. 3945 unsigned VecArgOffset = ArgOffset; 3946 if (!isVarArg && !isPPC64) { 3947 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 3948 ++ArgNo) { 3949 EVT ObjectVT = Ins[ArgNo].VT; 3950 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3951 3952 if (Flags.isByVal()) { 3953 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 3954 unsigned ObjSize = Flags.getByValSize(); 3955 unsigned ArgSize = 3956 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3957 VecArgOffset += ArgSize; 3958 continue; 3959 } 3960 3961 switch(ObjectVT.getSimpleVT().SimpleTy) { 3962 default: llvm_unreachable("Unhandled argument type!"); 3963 case MVT::i1: 3964 case MVT::i32: 3965 case MVT::f32: 3966 VecArgOffset += 4; 3967 break; 3968 case MVT::i64: // PPC64 3969 case MVT::f64: 3970 // FIXME: We are guaranteed to be !isPPC64 at this point. 3971 // Does MVT::i64 apply? 3972 VecArgOffset += 8; 3973 break; 3974 case MVT::v4f32: 3975 case MVT::v4i32: 3976 case MVT::v8i16: 3977 case MVT::v16i8: 3978 // Nothing to do, we're only looking at Nonvector args here. 3979 break; 3980 } 3981 } 3982 } 3983 // We've found where the vector parameter area in memory is. Skip the 3984 // first 12 parameters; these don't use that memory. 3985 VecArgOffset = ((VecArgOffset+15)/16)*16; 3986 VecArgOffset += 12*16; 3987 3988 // Add DAG nodes to load the arguments or copy them out of registers. On 3989 // entry to a function on PPC, the arguments start after the linkage area, 3990 // although the first ones are often in registers. 3991 3992 SmallVector<SDValue, 8> MemOps; 3993 unsigned nAltivecParamsAtEnd = 0; 3994 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3995 unsigned CurArgIdx = 0; 3996 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3997 SDValue ArgVal; 3998 bool needsLoad = false; 3999 EVT ObjectVT = Ins[ArgNo].VT; 4000 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4001 unsigned ArgSize = ObjSize; 4002 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4003 if (Ins[ArgNo].isOrigArg()) { 4004 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4005 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4006 } 4007 unsigned CurArgOffset = ArgOffset; 4008 4009 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4010 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4011 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4012 if (isVarArg || isPPC64) { 4013 MinReservedArea = ((MinReservedArea+15)/16)*16; 4014 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4015 Flags, 4016 PtrByteSize); 4017 } else nAltivecParamsAtEnd++; 4018 } else 4019 // Calculate min reserved area. 4020 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4021 Flags, 4022 PtrByteSize); 4023 4024 // FIXME the codegen can be much improved in some cases. 4025 // We do not have to keep everything in memory. 4026 if (Flags.isByVal()) { 4027 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4028 4029 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4030 ObjSize = Flags.getByValSize(); 4031 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4032 // Objects of size 1 and 2 are right justified, everything else is 4033 // left justified. This means the memory address is adjusted forwards. 4034 if (ObjSize==1 || ObjSize==2) { 4035 CurArgOffset = CurArgOffset + (4 - ObjSize); 4036 } 4037 // The value of the object is its address. 4038 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4039 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4040 InVals.push_back(FIN); 4041 if (ObjSize==1 || ObjSize==2) { 4042 if (GPR_idx != Num_GPR_Regs) { 4043 unsigned VReg; 4044 if (isPPC64) 4045 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4046 else 4047 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4048 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4049 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4050 SDValue Store = 4051 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4052 MachinePointerInfo(&*FuncArg), ObjType); 4053 MemOps.push_back(Store); 4054 ++GPR_idx; 4055 } 4056 4057 ArgOffset += PtrByteSize; 4058 4059 continue; 4060 } 4061 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4062 // Store whatever pieces of the object are in registers 4063 // to memory. ArgOffset will be the address of the beginning 4064 // of the object. 4065 if (GPR_idx != Num_GPR_Regs) { 4066 unsigned VReg; 4067 if (isPPC64) 4068 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4069 else 4070 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4071 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4072 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4073 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4074 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4075 MachinePointerInfo(&*FuncArg, j)); 4076 MemOps.push_back(Store); 4077 ++GPR_idx; 4078 ArgOffset += PtrByteSize; 4079 } else { 4080 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4081 break; 4082 } 4083 } 4084 continue; 4085 } 4086 4087 switch (ObjectVT.getSimpleVT().SimpleTy) { 4088 default: llvm_unreachable("Unhandled argument type!"); 4089 case MVT::i1: 4090 case MVT::i32: 4091 if (!isPPC64) { 4092 if (GPR_idx != Num_GPR_Regs) { 4093 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4094 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4095 4096 if (ObjectVT == MVT::i1) 4097 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4098 4099 ++GPR_idx; 4100 } else { 4101 needsLoad = true; 4102 ArgSize = PtrByteSize; 4103 } 4104 // All int arguments reserve stack space in the Darwin ABI. 4105 ArgOffset += PtrByteSize; 4106 break; 4107 } 4108 LLVM_FALLTHROUGH; 4109 case MVT::i64: // PPC64 4110 if (GPR_idx != Num_GPR_Regs) { 4111 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4112 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4113 4114 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4115 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4116 // value to MVT::i64 and then truncate to the correct register size. 4117 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4118 4119 ++GPR_idx; 4120 } else { 4121 needsLoad = true; 4122 ArgSize = PtrByteSize; 4123 } 4124 // All int arguments reserve stack space in the Darwin ABI. 4125 ArgOffset += 8; 4126 break; 4127 4128 case MVT::f32: 4129 case MVT::f64: 4130 // Every 4 bytes of argument space consumes one of the GPRs available for 4131 // argument passing. 4132 if (GPR_idx != Num_GPR_Regs) { 4133 ++GPR_idx; 4134 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4135 ++GPR_idx; 4136 } 4137 if (FPR_idx != Num_FPR_Regs) { 4138 unsigned VReg; 4139 4140 if (ObjectVT == MVT::f32) 4141 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4142 else 4143 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4144 4145 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4146 ++FPR_idx; 4147 } else { 4148 needsLoad = true; 4149 } 4150 4151 // All FP arguments reserve stack space in the Darwin ABI. 4152 ArgOffset += isPPC64 ? 8 : ObjSize; 4153 break; 4154 case MVT::v4f32: 4155 case MVT::v4i32: 4156 case MVT::v8i16: 4157 case MVT::v16i8: 4158 // Note that vector arguments in registers don't reserve stack space, 4159 // except in varargs functions. 4160 if (VR_idx != Num_VR_Regs) { 4161 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4162 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4163 if (isVarArg) { 4164 while ((ArgOffset % 16) != 0) { 4165 ArgOffset += PtrByteSize; 4166 if (GPR_idx != Num_GPR_Regs) 4167 GPR_idx++; 4168 } 4169 ArgOffset += 16; 4170 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4171 } 4172 ++VR_idx; 4173 } else { 4174 if (!isVarArg && !isPPC64) { 4175 // Vectors go after all the nonvectors. 4176 CurArgOffset = VecArgOffset; 4177 VecArgOffset += 16; 4178 } else { 4179 // Vectors are aligned. 4180 ArgOffset = ((ArgOffset+15)/16)*16; 4181 CurArgOffset = ArgOffset; 4182 ArgOffset += 16; 4183 } 4184 needsLoad = true; 4185 } 4186 break; 4187 } 4188 4189 // We need to load the argument to a virtual register if we determined above 4190 // that we ran out of physical registers of the appropriate type. 4191 if (needsLoad) { 4192 int FI = MFI.CreateFixedObject(ObjSize, 4193 CurArgOffset + (ArgSize - ObjSize), 4194 isImmutable); 4195 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4196 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4197 } 4198 4199 InVals.push_back(ArgVal); 4200 } 4201 4202 // Allow for Altivec parameters at the end, if needed. 4203 if (nAltivecParamsAtEnd) { 4204 MinReservedArea = ((MinReservedArea+15)/16)*16; 4205 MinReservedArea += 16*nAltivecParamsAtEnd; 4206 } 4207 4208 // Area that is at least reserved in the caller of this function. 4209 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4210 4211 // Set the size that is at least reserved in caller of this function. Tail 4212 // call optimized functions' reserved stack space needs to be aligned so that 4213 // taking the difference between two stack areas will result in an aligned 4214 // stack. 4215 MinReservedArea = 4216 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4217 FuncInfo->setMinReservedArea(MinReservedArea); 4218 4219 // If the function takes variable number of arguments, make a frame index for 4220 // the start of the first vararg value... for expansion of llvm.va_start. 4221 if (isVarArg) { 4222 int Depth = ArgOffset; 4223 4224 FuncInfo->setVarArgsFrameIndex( 4225 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4226 Depth, true)); 4227 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4228 4229 // If this function is vararg, store any remaining integer argument regs 4230 // to their spots on the stack so that they may be loaded by dereferencing 4231 // the result of va_next. 4232 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4233 unsigned VReg; 4234 4235 if (isPPC64) 4236 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4237 else 4238 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4239 4240 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4241 SDValue Store = 4242 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4243 MemOps.push_back(Store); 4244 // Increment the address by four for the next argument to store 4245 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4246 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4247 } 4248 } 4249 4250 if (!MemOps.empty()) 4251 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4252 4253 return Chain; 4254 } 4255 4256 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4257 /// adjusted to accommodate the arguments for the tailcall. 4258 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4259 unsigned ParamSize) { 4260 4261 if (!isTailCall) return 0; 4262 4263 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4264 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4265 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4266 // Remember only if the new adjustement is bigger. 4267 if (SPDiff < FI->getTailCallSPDelta()) 4268 FI->setTailCallSPDelta(SPDiff); 4269 4270 return SPDiff; 4271 } 4272 4273 static bool isFunctionGlobalAddress(SDValue Callee); 4274 4275 static bool 4276 callsShareTOCBase(const Function *Caller, SDValue Callee, 4277 const TargetMachine &TM) { 4278 // If !G, Callee can be an external symbol. 4279 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4280 if (!G) 4281 return false; 4282 4283 // The medium and large code models are expected to provide a sufficiently 4284 // large TOC to provide all data addressing needs of a module with a 4285 // single TOC. Since each module will be addressed with a single TOC then we 4286 // only need to check that caller and callee don't cross dso boundaries. 4287 if (CodeModel::Medium == TM.getCodeModel() || 4288 CodeModel::Large == TM.getCodeModel()) 4289 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal()); 4290 4291 // Otherwise we need to ensure callee and caller are in the same section, 4292 // since the linker may allocate multiple TOCs, and we don't know which 4293 // sections will belong to the same TOC base. 4294 4295 const GlobalValue *GV = G->getGlobal(); 4296 if (!GV->isStrongDefinitionForLinker()) 4297 return false; 4298 4299 // Any explicitly-specified sections and section prefixes must also match. 4300 // Also, if we're using -ffunction-sections, then each function is always in 4301 // a different section (the same is true for COMDAT functions). 4302 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4303 GV->getSection() != Caller->getSection()) 4304 return false; 4305 if (const auto *F = dyn_cast<Function>(GV)) { 4306 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4307 return false; 4308 } 4309 4310 // If the callee might be interposed, then we can't assume the ultimate call 4311 // target will be in the same section. Even in cases where we can assume that 4312 // interposition won't happen, in any case where the linker might insert a 4313 // stub to allow for interposition, we must generate code as though 4314 // interposition might occur. To understand why this matters, consider a 4315 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4316 // in the same section, but a is in a different module (i.e. has a different 4317 // TOC base pointer). If the linker allows for interposition between b and c, 4318 // then it will generate a stub for the call edge between b and c which will 4319 // save the TOC pointer into the designated stack slot allocated by b. If we 4320 // return true here, and therefore allow a tail call between b and c, that 4321 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4322 // pointer into the stack slot allocated by a (where the a -> b stub saved 4323 // a's TOC base pointer). If we're not considering a tail call, but rather, 4324 // whether a nop is needed after the call instruction in b, because the linker 4325 // will insert a stub, it might complain about a missing nop if we omit it 4326 // (although many don't complain in this case). 4327 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4328 return false; 4329 4330 return true; 4331 } 4332 4333 static bool 4334 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4335 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4336 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4337 4338 const unsigned PtrByteSize = 8; 4339 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4340 4341 static const MCPhysReg GPR[] = { 4342 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4343 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4344 }; 4345 static const MCPhysReg VR[] = { 4346 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4347 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4348 }; 4349 4350 const unsigned NumGPRs = array_lengthof(GPR); 4351 const unsigned NumFPRs = 13; 4352 const unsigned NumVRs = array_lengthof(VR); 4353 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4354 4355 unsigned NumBytes = LinkageSize; 4356 unsigned AvailableFPRs = NumFPRs; 4357 unsigned AvailableVRs = NumVRs; 4358 4359 for (const ISD::OutputArg& Param : Outs) { 4360 if (Param.Flags.isNest()) continue; 4361 4362 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4363 PtrByteSize, LinkageSize, ParamAreaSize, 4364 NumBytes, AvailableFPRs, AvailableVRs, 4365 Subtarget.hasQPX())) 4366 return true; 4367 } 4368 return false; 4369 } 4370 4371 static bool 4372 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4373 if (CS.arg_size() != CallerFn->arg_size()) 4374 return false; 4375 4376 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4377 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4378 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4379 4380 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4381 const Value* CalleeArg = *CalleeArgIter; 4382 const Value* CallerArg = &(*CallerArgIter); 4383 if (CalleeArg == CallerArg) 4384 continue; 4385 4386 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4387 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4388 // } 4389 // 1st argument of callee is undef and has the same type as caller. 4390 if (CalleeArg->getType() == CallerArg->getType() && 4391 isa<UndefValue>(CalleeArg)) 4392 continue; 4393 4394 return false; 4395 } 4396 4397 return true; 4398 } 4399 4400 // Returns true if TCO is possible between the callers and callees 4401 // calling conventions. 4402 static bool 4403 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4404 CallingConv::ID CalleeCC) { 4405 // Tail calls are possible with fastcc and ccc. 4406 auto isTailCallableCC = [] (CallingConv::ID CC){ 4407 return CC == CallingConv::C || CC == CallingConv::Fast; 4408 }; 4409 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4410 return false; 4411 4412 // We can safely tail call both fastcc and ccc callees from a c calling 4413 // convention caller. If the caller is fastcc, we may have less stack space 4414 // than a non-fastcc caller with the same signature so disable tail-calls in 4415 // that case. 4416 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4417 } 4418 4419 bool 4420 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4421 SDValue Callee, 4422 CallingConv::ID CalleeCC, 4423 ImmutableCallSite CS, 4424 bool isVarArg, 4425 const SmallVectorImpl<ISD::OutputArg> &Outs, 4426 const SmallVectorImpl<ISD::InputArg> &Ins, 4427 SelectionDAG& DAG) const { 4428 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4429 4430 if (DisableSCO && !TailCallOpt) return false; 4431 4432 // Variadic argument functions are not supported. 4433 if (isVarArg) return false; 4434 4435 auto &Caller = DAG.getMachineFunction().getFunction(); 4436 // Check that the calling conventions are compatible for tco. 4437 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4438 return false; 4439 4440 // Caller contains any byval parameter is not supported. 4441 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4442 return false; 4443 4444 // Callee contains any byval parameter is not supported, too. 4445 // Note: This is a quick work around, because in some cases, e.g. 4446 // caller's stack size > callee's stack size, we are still able to apply 4447 // sibling call optimization. For example, gcc is able to do SCO for caller1 4448 // in the following example, but not for caller2. 4449 // struct test { 4450 // long int a; 4451 // char ary[56]; 4452 // } gTest; 4453 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4454 // b->a = v.a; 4455 // return 0; 4456 // } 4457 // void caller1(struct test a, struct test c, struct test *b) { 4458 // callee(gTest, b); } 4459 // void caller2(struct test *b) { callee(gTest, b); } 4460 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4461 return false; 4462 4463 // If callee and caller use different calling conventions, we cannot pass 4464 // parameters on stack since offsets for the parameter area may be different. 4465 if (Caller.getCallingConv() != CalleeCC && 4466 needStackSlotPassParameters(Subtarget, Outs)) 4467 return false; 4468 4469 // No TCO/SCO on indirect call because Caller have to restore its TOC 4470 if (!isFunctionGlobalAddress(Callee) && 4471 !isa<ExternalSymbolSDNode>(Callee)) 4472 return false; 4473 4474 // If the caller and callee potentially have different TOC bases then we 4475 // cannot tail call since we need to restore the TOC pointer after the call. 4476 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4477 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4478 return false; 4479 4480 // TCO allows altering callee ABI, so we don't have to check further. 4481 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4482 return true; 4483 4484 if (DisableSCO) return false; 4485 4486 // If callee use the same argument list that caller is using, then we can 4487 // apply SCO on this case. If it is not, then we need to check if callee needs 4488 // stack for passing arguments. 4489 if (!hasSameArgumentList(&Caller, CS) && 4490 needStackSlotPassParameters(Subtarget, Outs)) { 4491 return false; 4492 } 4493 4494 return true; 4495 } 4496 4497 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4498 /// for tail call optimization. Targets which want to do tail call 4499 /// optimization should implement this function. 4500 bool 4501 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4502 CallingConv::ID CalleeCC, 4503 bool isVarArg, 4504 const SmallVectorImpl<ISD::InputArg> &Ins, 4505 SelectionDAG& DAG) const { 4506 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4507 return false; 4508 4509 // Variable argument functions are not supported. 4510 if (isVarArg) 4511 return false; 4512 4513 MachineFunction &MF = DAG.getMachineFunction(); 4514 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4515 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4516 // Functions containing by val parameters are not supported. 4517 for (unsigned i = 0; i != Ins.size(); i++) { 4518 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4519 if (Flags.isByVal()) return false; 4520 } 4521 4522 // Non-PIC/GOT tail calls are supported. 4523 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4524 return true; 4525 4526 // At the moment we can only do local tail calls (in same module, hidden 4527 // or protected) if we are generating PIC. 4528 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4529 return G->getGlobal()->hasHiddenVisibility() 4530 || G->getGlobal()->hasProtectedVisibility(); 4531 } 4532 4533 return false; 4534 } 4535 4536 /// isCallCompatibleAddress - Return the immediate to use if the specified 4537 /// 32-bit value is representable in the immediate field of a BxA instruction. 4538 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4539 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4540 if (!C) return nullptr; 4541 4542 int Addr = C->getZExtValue(); 4543 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4544 SignExtend32<26>(Addr) != Addr) 4545 return nullptr; // Top 6 bits have to be sext of immediate. 4546 4547 return DAG 4548 .getConstant( 4549 (int)C->getZExtValue() >> 2, SDLoc(Op), 4550 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4551 .getNode(); 4552 } 4553 4554 namespace { 4555 4556 struct TailCallArgumentInfo { 4557 SDValue Arg; 4558 SDValue FrameIdxOp; 4559 int FrameIdx = 0; 4560 4561 TailCallArgumentInfo() = default; 4562 }; 4563 4564 } // end anonymous namespace 4565 4566 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4567 static void StoreTailCallArgumentsToStackSlot( 4568 SelectionDAG &DAG, SDValue Chain, 4569 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4570 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4571 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4572 SDValue Arg = TailCallArgs[i].Arg; 4573 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4574 int FI = TailCallArgs[i].FrameIdx; 4575 // Store relative to framepointer. 4576 MemOpChains.push_back(DAG.getStore( 4577 Chain, dl, Arg, FIN, 4578 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4579 } 4580 } 4581 4582 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4583 /// the appropriate stack slot for the tail call optimized function call. 4584 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4585 SDValue OldRetAddr, SDValue OldFP, 4586 int SPDiff, const SDLoc &dl) { 4587 if (SPDiff) { 4588 // Calculate the new stack slot for the return address. 4589 MachineFunction &MF = DAG.getMachineFunction(); 4590 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4591 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4592 bool isPPC64 = Subtarget.isPPC64(); 4593 int SlotSize = isPPC64 ? 8 : 4; 4594 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4595 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4596 NewRetAddrLoc, true); 4597 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4598 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4599 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4600 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4601 4602 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4603 // slot as the FP is never overwritten. 4604 if (Subtarget.isDarwinABI()) { 4605 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4606 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4607 true); 4608 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4609 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4610 MachinePointerInfo::getFixedStack( 4611 DAG.getMachineFunction(), NewFPIdx)); 4612 } 4613 } 4614 return Chain; 4615 } 4616 4617 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4618 /// the position of the argument. 4619 static void 4620 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4621 SDValue Arg, int SPDiff, unsigned ArgOffset, 4622 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4623 int Offset = ArgOffset + SPDiff; 4624 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4625 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4626 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4627 SDValue FIN = DAG.getFrameIndex(FI, VT); 4628 TailCallArgumentInfo Info; 4629 Info.Arg = Arg; 4630 Info.FrameIdxOp = FIN; 4631 Info.FrameIdx = FI; 4632 TailCallArguments.push_back(Info); 4633 } 4634 4635 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4636 /// stack slot. Returns the chain as result and the loaded frame pointers in 4637 /// LROpOut/FPOpout. Used when tail calling. 4638 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4639 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4640 SDValue &FPOpOut, const SDLoc &dl) const { 4641 if (SPDiff) { 4642 // Load the LR and FP stack slot for later adjusting. 4643 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4644 LROpOut = getReturnAddrFrameIndex(DAG); 4645 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4646 Chain = SDValue(LROpOut.getNode(), 1); 4647 4648 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4649 // slot as the FP is never overwritten. 4650 if (Subtarget.isDarwinABI()) { 4651 FPOpOut = getFramePointerFrameIndex(DAG); 4652 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4653 Chain = SDValue(FPOpOut.getNode(), 1); 4654 } 4655 } 4656 return Chain; 4657 } 4658 4659 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4660 /// by "Src" to address "Dst" of size "Size". Alignment information is 4661 /// specified by the specific parameter attribute. The copy will be passed as 4662 /// a byval function parameter. 4663 /// Sometimes what we are copying is the end of a larger object, the part that 4664 /// does not fit in registers. 4665 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4666 SDValue Chain, ISD::ArgFlagsTy Flags, 4667 SelectionDAG &DAG, const SDLoc &dl) { 4668 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4669 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4670 false, false, false, MachinePointerInfo(), 4671 MachinePointerInfo()); 4672 } 4673 4674 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4675 /// tail calls. 4676 static void LowerMemOpCallTo( 4677 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4678 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4679 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4680 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4681 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4682 if (!isTailCall) { 4683 if (isVector) { 4684 SDValue StackPtr; 4685 if (isPPC64) 4686 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4687 else 4688 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4689 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4690 DAG.getConstant(ArgOffset, dl, PtrVT)); 4691 } 4692 MemOpChains.push_back( 4693 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4694 // Calculate and remember argument location. 4695 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4696 TailCallArguments); 4697 } 4698 4699 static void 4700 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4701 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4702 SDValue FPOp, 4703 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4704 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4705 // might overwrite each other in case of tail call optimization. 4706 SmallVector<SDValue, 8> MemOpChains2; 4707 // Do not flag preceding copytoreg stuff together with the following stuff. 4708 InFlag = SDValue(); 4709 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4710 MemOpChains2, dl); 4711 if (!MemOpChains2.empty()) 4712 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4713 4714 // Store the return address to the appropriate stack slot. 4715 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4716 4717 // Emit callseq_end just before tailcall node. 4718 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4719 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4720 InFlag = Chain.getValue(1); 4721 } 4722 4723 // Is this global address that of a function that can be called by name? (as 4724 // opposed to something that must hold a descriptor for an indirect call). 4725 static bool isFunctionGlobalAddress(SDValue Callee) { 4726 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4727 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4728 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4729 return false; 4730 4731 return G->getGlobal()->getValueType()->isFunctionTy(); 4732 } 4733 4734 return false; 4735 } 4736 4737 static unsigned 4738 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4739 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4740 bool isPatchPoint, bool hasNest, 4741 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4742 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4743 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4744 bool isPPC64 = Subtarget.isPPC64(); 4745 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4746 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4747 4748 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4749 NodeTys.push_back(MVT::Other); // Returns a chain 4750 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4751 4752 unsigned CallOpc = PPCISD::CALL; 4753 4754 bool needIndirectCall = true; 4755 if (!isSVR4ABI || !isPPC64) 4756 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4757 // If this is an absolute destination address, use the munged value. 4758 Callee = SDValue(Dest, 0); 4759 needIndirectCall = false; 4760 } 4761 4762 // PC-relative references to external symbols should go through $stub, unless 4763 // we're building with the leopard linker or later, which automatically 4764 // synthesizes these stubs. 4765 const TargetMachine &TM = DAG.getTarget(); 4766 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4767 const GlobalValue *GV = nullptr; 4768 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4769 GV = G->getGlobal(); 4770 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4771 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4772 4773 if (isFunctionGlobalAddress(Callee)) { 4774 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4775 // A call to a TLS address is actually an indirect call to a 4776 // thread-specific pointer. 4777 unsigned OpFlags = 0; 4778 if (UsePlt) 4779 OpFlags = PPCII::MO_PLT; 4780 4781 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4782 // every direct call is) turn it into a TargetGlobalAddress / 4783 // TargetExternalSymbol node so that legalize doesn't hack it. 4784 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4785 Callee.getValueType(), 0, OpFlags); 4786 needIndirectCall = false; 4787 } 4788 4789 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4790 unsigned char OpFlags = 0; 4791 4792 if (UsePlt) 4793 OpFlags = PPCII::MO_PLT; 4794 4795 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4796 OpFlags); 4797 needIndirectCall = false; 4798 } 4799 4800 if (isPatchPoint) { 4801 // We'll form an invalid direct call when lowering a patchpoint; the full 4802 // sequence for an indirect call is complicated, and many of the 4803 // instructions introduced might have side effects (and, thus, can't be 4804 // removed later). The call itself will be removed as soon as the 4805 // argument/return lowering is complete, so the fact that it has the wrong 4806 // kind of operands should not really matter. 4807 needIndirectCall = false; 4808 } 4809 4810 if (needIndirectCall) { 4811 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4812 // to do the call, we can't use PPCISD::CALL. 4813 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4814 4815 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4816 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4817 // entry point, but to the function descriptor (the function entry point 4818 // address is part of the function descriptor though). 4819 // The function descriptor is a three doubleword structure with the 4820 // following fields: function entry point, TOC base address and 4821 // environment pointer. 4822 // Thus for a call through a function pointer, the following actions need 4823 // to be performed: 4824 // 1. Save the TOC of the caller in the TOC save area of its stack 4825 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4826 // 2. Load the address of the function entry point from the function 4827 // descriptor. 4828 // 3. Load the TOC of the callee from the function descriptor into r2. 4829 // 4. Load the environment pointer from the function descriptor into 4830 // r11. 4831 // 5. Branch to the function entry point address. 4832 // 6. On return of the callee, the TOC of the caller needs to be 4833 // restored (this is done in FinishCall()). 4834 // 4835 // The loads are scheduled at the beginning of the call sequence, and the 4836 // register copies are flagged together to ensure that no other 4837 // operations can be scheduled in between. E.g. without flagging the 4838 // copies together, a TOC access in the caller could be scheduled between 4839 // the assignment of the callee TOC and the branch to the callee, which 4840 // results in the TOC access going through the TOC of the callee instead 4841 // of going through the TOC of the caller, which leads to incorrect code. 4842 4843 // Load the address of the function entry point from the function 4844 // descriptor. 4845 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 4846 if (LDChain.getValueType() == MVT::Glue) 4847 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 4848 4849 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 4850 ? (MachineMemOperand::MODereferenceable | 4851 MachineMemOperand::MOInvariant) 4852 : MachineMemOperand::MONone; 4853 4854 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 4855 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 4856 /* Alignment = */ 8, MMOFlags); 4857 4858 // Load environment pointer into r11. 4859 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 4860 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 4861 SDValue LoadEnvPtr = 4862 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 4863 /* Alignment = */ 8, MMOFlags); 4864 4865 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 4866 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 4867 SDValue TOCPtr = 4868 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 4869 /* Alignment = */ 8, MMOFlags); 4870 4871 setUsesTOCBasePtr(DAG); 4872 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 4873 InFlag); 4874 Chain = TOCVal.getValue(0); 4875 InFlag = TOCVal.getValue(1); 4876 4877 // If the function call has an explicit 'nest' parameter, it takes the 4878 // place of the environment pointer. 4879 if (!hasNest) { 4880 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 4881 InFlag); 4882 4883 Chain = EnvVal.getValue(0); 4884 InFlag = EnvVal.getValue(1); 4885 } 4886 4887 MTCTROps[0] = Chain; 4888 MTCTROps[1] = LoadFuncPtr; 4889 MTCTROps[2] = InFlag; 4890 } 4891 4892 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 4893 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 4894 InFlag = Chain.getValue(1); 4895 4896 NodeTys.clear(); 4897 NodeTys.push_back(MVT::Other); 4898 NodeTys.push_back(MVT::Glue); 4899 Ops.push_back(Chain); 4900 CallOpc = PPCISD::BCTRL; 4901 Callee.setNode(nullptr); 4902 // Add use of X11 (holding environment pointer) 4903 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 4904 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 4905 // Add CTR register as callee so a bctr can be emitted later. 4906 if (isTailCall) 4907 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 4908 } 4909 4910 // If this is a direct call, pass the chain and the callee. 4911 if (Callee.getNode()) { 4912 Ops.push_back(Chain); 4913 Ops.push_back(Callee); 4914 } 4915 // If this is a tail call add stack pointer delta. 4916 if (isTailCall) 4917 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 4918 4919 // Add argument registers to the end of the list so that they are known live 4920 // into the call. 4921 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 4922 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 4923 RegsToPass[i].second.getValueType())); 4924 4925 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 4926 // into the call. 4927 if (isSVR4ABI && isPPC64 && !isPatchPoint) { 4928 setUsesTOCBasePtr(DAG); 4929 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 4930 } 4931 4932 return CallOpc; 4933 } 4934 4935 SDValue PPCTargetLowering::LowerCallResult( 4936 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4937 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4938 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4939 SmallVector<CCValAssign, 16> RVLocs; 4940 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4941 *DAG.getContext()); 4942 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC); 4943 4944 // Copy all of the result registers out of their specified physreg. 4945 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4946 CCValAssign &VA = RVLocs[i]; 4947 assert(VA.isRegLoc() && "Can only return in registers!"); 4948 4949 SDValue Val = DAG.getCopyFromReg(Chain, dl, 4950 VA.getLocReg(), VA.getLocVT(), InFlag); 4951 Chain = Val.getValue(1); 4952 InFlag = Val.getValue(2); 4953 4954 switch (VA.getLocInfo()) { 4955 default: llvm_unreachable("Unknown loc info!"); 4956 case CCValAssign::Full: break; 4957 case CCValAssign::AExt: 4958 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4959 break; 4960 case CCValAssign::ZExt: 4961 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4962 DAG.getValueType(VA.getValVT())); 4963 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4964 break; 4965 case CCValAssign::SExt: 4966 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 4967 DAG.getValueType(VA.getValVT())); 4968 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4969 break; 4970 } 4971 4972 InVals.push_back(Val); 4973 } 4974 4975 return Chain; 4976 } 4977 4978 SDValue PPCTargetLowering::FinishCall( 4979 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 4980 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 4981 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 4982 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 4983 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 4984 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 4985 std::vector<EVT> NodeTys; 4986 SmallVector<SDValue, 8> Ops; 4987 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 4988 SPDiff, isTailCall, isPatchPoint, hasNest, 4989 RegsToPass, Ops, NodeTys, CS, Subtarget); 4990 4991 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 4992 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 4993 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 4994 4995 // When performing tail call optimization the callee pops its arguments off 4996 // the stack. Account for this here so these bytes can be pushed back on in 4997 // PPCFrameLowering::eliminateCallFramePseudoInstr. 4998 int BytesCalleePops = 4999 (CallConv == CallingConv::Fast && 5000 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5001 5002 // Add a register mask operand representing the call-preserved registers. 5003 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5004 const uint32_t *Mask = 5005 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5006 assert(Mask && "Missing call preserved mask for calling convention"); 5007 Ops.push_back(DAG.getRegisterMask(Mask)); 5008 5009 if (InFlag.getNode()) 5010 Ops.push_back(InFlag); 5011 5012 // Emit tail call. 5013 if (isTailCall) { 5014 assert(((Callee.getOpcode() == ISD::Register && 5015 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5016 Callee.getOpcode() == ISD::TargetExternalSymbol || 5017 Callee.getOpcode() == ISD::TargetGlobalAddress || 5018 isa<ConstantSDNode>(Callee)) && 5019 "Expecting an global address, external symbol, absolute value or register"); 5020 5021 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5022 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5023 } 5024 5025 // Add a NOP immediately after the branch instruction when using the 64-bit 5026 // SVR4 ABI. At link time, if caller and callee are in a different module and 5027 // thus have a different TOC, the call will be replaced with a call to a stub 5028 // function which saves the current TOC, loads the TOC of the callee and 5029 // branches to the callee. The NOP will be replaced with a load instruction 5030 // which restores the TOC of the caller from the TOC save slot of the current 5031 // stack frame. If caller and callee belong to the same module (and have the 5032 // same TOC), the NOP will remain unchanged. 5033 5034 MachineFunction &MF = DAG.getMachineFunction(); 5035 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 5036 !isPatchPoint) { 5037 if (CallOpc == PPCISD::BCTRL) { 5038 // This is a call through a function pointer. 5039 // Restore the caller TOC from the save area into R2. 5040 // See PrepareCall() for more information about calls through function 5041 // pointers in the 64-bit SVR4 ABI. 5042 // We are using a target-specific load with r2 hard coded, because the 5043 // result of a target-independent load would never go directly into r2, 5044 // since r2 is a reserved register (which prevents the register allocator 5045 // from allocating it), resulting in an additional register being 5046 // allocated and an unnecessary move instruction being generated. 5047 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5048 5049 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5050 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5051 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5052 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5053 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5054 5055 // The address needs to go after the chain input but before the flag (or 5056 // any other variadic arguments). 5057 Ops.insert(std::next(Ops.begin()), AddTOC); 5058 } else if (CallOpc == PPCISD::CALL && 5059 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5060 // Otherwise insert NOP for non-local calls. 5061 CallOpc = PPCISD::CALL_NOP; 5062 } 5063 } 5064 5065 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5066 InFlag = Chain.getValue(1); 5067 5068 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5069 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5070 InFlag, dl); 5071 if (!Ins.empty()) 5072 InFlag = Chain.getValue(1); 5073 5074 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5075 Ins, dl, DAG, InVals); 5076 } 5077 5078 SDValue 5079 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5080 SmallVectorImpl<SDValue> &InVals) const { 5081 SelectionDAG &DAG = CLI.DAG; 5082 SDLoc &dl = CLI.DL; 5083 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5084 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5085 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5086 SDValue Chain = CLI.Chain; 5087 SDValue Callee = CLI.Callee; 5088 bool &isTailCall = CLI.IsTailCall; 5089 CallingConv::ID CallConv = CLI.CallConv; 5090 bool isVarArg = CLI.IsVarArg; 5091 bool isPatchPoint = CLI.IsPatchPoint; 5092 ImmutableCallSite CS = CLI.CS; 5093 5094 if (isTailCall) { 5095 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5096 isTailCall = false; 5097 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5098 isTailCall = 5099 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5100 isVarArg, Outs, Ins, DAG); 5101 else 5102 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5103 Ins, DAG); 5104 if (isTailCall) { 5105 ++NumTailCalls; 5106 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5107 ++NumSiblingCalls; 5108 5109 assert(isa<GlobalAddressSDNode>(Callee) && 5110 "Callee should be an llvm::Function object."); 5111 DEBUG( 5112 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5113 const unsigned Width = 80 - strlen("TCO caller: ") 5114 - strlen(", callee linkage: 0, 0"); 5115 dbgs() << "TCO caller: " 5116 << left_justify(DAG.getMachineFunction().getName(), Width) 5117 << ", callee linkage: " 5118 << GV->getVisibility() << ", " << GV->getLinkage() << "\n" 5119 ); 5120 } 5121 } 5122 5123 if (!isTailCall && CS && CS.isMustTailCall()) 5124 report_fatal_error("failed to perform tail call elimination on a call " 5125 "site marked musttail"); 5126 5127 // When long calls (i.e. indirect calls) are always used, calls are always 5128 // made via function pointer. If we have a function name, first translate it 5129 // into a pointer. 5130 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5131 !isTailCall) 5132 Callee = LowerGlobalAddress(Callee, DAG); 5133 5134 if (Subtarget.isSVR4ABI()) { 5135 if (Subtarget.isPPC64()) 5136 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5137 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5138 dl, DAG, InVals, CS); 5139 else 5140 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5141 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5142 dl, DAG, InVals, CS); 5143 } 5144 5145 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5146 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5147 dl, DAG, InVals, CS); 5148 } 5149 5150 SDValue PPCTargetLowering::LowerCall_32SVR4( 5151 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5152 bool isTailCall, bool isPatchPoint, 5153 const SmallVectorImpl<ISD::OutputArg> &Outs, 5154 const SmallVectorImpl<SDValue> &OutVals, 5155 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5156 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5157 ImmutableCallSite CS) const { 5158 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5159 // of the 32-bit SVR4 ABI stack frame layout. 5160 5161 assert((CallConv == CallingConv::C || 5162 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5163 5164 unsigned PtrByteSize = 4; 5165 5166 MachineFunction &MF = DAG.getMachineFunction(); 5167 5168 // Mark this function as potentially containing a function that contains a 5169 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5170 // and restoring the callers stack pointer in this functions epilog. This is 5171 // done because by tail calling the called function might overwrite the value 5172 // in this function's (MF) stack pointer stack slot 0(SP). 5173 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5174 CallConv == CallingConv::Fast) 5175 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5176 5177 // Count how many bytes are to be pushed on the stack, including the linkage 5178 // area, parameter list area and the part of the local variable space which 5179 // contains copies of aggregates which are passed by value. 5180 5181 // Assign locations to all of the outgoing arguments. 5182 SmallVector<CCValAssign, 16> ArgLocs; 5183 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5184 5185 // Reserve space for the linkage area on the stack. 5186 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5187 PtrByteSize); 5188 if (useSoftFloat()) 5189 CCInfo.PreAnalyzeCallOperands(Outs); 5190 5191 if (isVarArg) { 5192 // Handle fixed and variable vector arguments differently. 5193 // Fixed vector arguments go into registers as long as registers are 5194 // available. Variable vector arguments always go into memory. 5195 unsigned NumArgs = Outs.size(); 5196 5197 for (unsigned i = 0; i != NumArgs; ++i) { 5198 MVT ArgVT = Outs[i].VT; 5199 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5200 bool Result; 5201 5202 if (Outs[i].IsFixed) { 5203 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5204 CCInfo); 5205 } else { 5206 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5207 ArgFlags, CCInfo); 5208 } 5209 5210 if (Result) { 5211 #ifndef NDEBUG 5212 errs() << "Call operand #" << i << " has unhandled type " 5213 << EVT(ArgVT).getEVTString() << "\n"; 5214 #endif 5215 llvm_unreachable(nullptr); 5216 } 5217 } 5218 } else { 5219 // All arguments are treated the same. 5220 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5221 } 5222 CCInfo.clearWasPPCF128(); 5223 5224 // Assign locations to all of the outgoing aggregate by value arguments. 5225 SmallVector<CCValAssign, 16> ByValArgLocs; 5226 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5227 5228 // Reserve stack space for the allocations in CCInfo. 5229 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5230 5231 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5232 5233 // Size of the linkage area, parameter list area and the part of the local 5234 // space variable where copies of aggregates which are passed by value are 5235 // stored. 5236 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5237 5238 // Calculate by how many bytes the stack has to be adjusted in case of tail 5239 // call optimization. 5240 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5241 5242 // Adjust the stack pointer for the new arguments... 5243 // These operations are automatically eliminated by the prolog/epilog pass 5244 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5245 SDValue CallSeqStart = Chain; 5246 5247 // Load the return address and frame pointer so it can be moved somewhere else 5248 // later. 5249 SDValue LROp, FPOp; 5250 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5251 5252 // Set up a copy of the stack pointer for use loading and storing any 5253 // arguments that may not fit in the registers available for argument 5254 // passing. 5255 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5256 5257 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5258 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5259 SmallVector<SDValue, 8> MemOpChains; 5260 5261 bool seenFloatArg = false; 5262 // Walk the register/memloc assignments, inserting copies/loads. 5263 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 5264 i != e; 5265 ++i) { 5266 CCValAssign &VA = ArgLocs[i]; 5267 SDValue Arg = OutVals[i]; 5268 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5269 5270 if (Flags.isByVal()) { 5271 // Argument is an aggregate which is passed by value, thus we need to 5272 // create a copy of it in the local variable space of the current stack 5273 // frame (which is the stack frame of the caller) and pass the address of 5274 // this copy to the callee. 5275 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5276 CCValAssign &ByValVA = ByValArgLocs[j++]; 5277 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5278 5279 // Memory reserved in the local variable space of the callers stack frame. 5280 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5281 5282 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5283 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5284 StackPtr, PtrOff); 5285 5286 // Create a copy of the argument in the local area of the current 5287 // stack frame. 5288 SDValue MemcpyCall = 5289 CreateCopyOfByValArgument(Arg, PtrOff, 5290 CallSeqStart.getNode()->getOperand(0), 5291 Flags, DAG, dl); 5292 5293 // This must go outside the CALLSEQ_START..END. 5294 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5295 SDLoc(MemcpyCall)); 5296 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5297 NewCallSeqStart.getNode()); 5298 Chain = CallSeqStart = NewCallSeqStart; 5299 5300 // Pass the address of the aggregate copy on the stack either in a 5301 // physical register or in the parameter list area of the current stack 5302 // frame to the callee. 5303 Arg = PtrOff; 5304 } 5305 5306 if (VA.isRegLoc()) { 5307 if (Arg.getValueType() == MVT::i1) 5308 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg); 5309 5310 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5311 // Put argument in a physical register. 5312 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5313 } else { 5314 // Put argument in the parameter list area of the current stack frame. 5315 assert(VA.isMemLoc()); 5316 unsigned LocMemOffset = VA.getLocMemOffset(); 5317 5318 if (!isTailCall) { 5319 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5320 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5321 StackPtr, PtrOff); 5322 5323 MemOpChains.push_back( 5324 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5325 } else { 5326 // Calculate and remember argument location. 5327 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5328 TailCallArguments); 5329 } 5330 } 5331 } 5332 5333 if (!MemOpChains.empty()) 5334 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5335 5336 // Build a sequence of copy-to-reg nodes chained together with token chain 5337 // and flag operands which copy the outgoing args into the appropriate regs. 5338 SDValue InFlag; 5339 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5340 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5341 RegsToPass[i].second, InFlag); 5342 InFlag = Chain.getValue(1); 5343 } 5344 5345 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5346 // registers. 5347 if (isVarArg) { 5348 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5349 SDValue Ops[] = { Chain, InFlag }; 5350 5351 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5352 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5353 5354 InFlag = Chain.getValue(1); 5355 } 5356 5357 if (isTailCall) 5358 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5359 TailCallArguments); 5360 5361 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5362 /* unused except on PPC64 ELFv1 */ false, DAG, 5363 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5364 NumBytes, Ins, InVals, CS); 5365 } 5366 5367 // Copy an argument into memory, being careful to do this outside the 5368 // call sequence for the call to which the argument belongs. 5369 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5370 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5371 SelectionDAG &DAG, const SDLoc &dl) const { 5372 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5373 CallSeqStart.getNode()->getOperand(0), 5374 Flags, DAG, dl); 5375 // The MEMCPY must go outside the CALLSEQ_START..END. 5376 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5377 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5378 SDLoc(MemcpyCall)); 5379 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5380 NewCallSeqStart.getNode()); 5381 return NewCallSeqStart; 5382 } 5383 5384 SDValue PPCTargetLowering::LowerCall_64SVR4( 5385 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5386 bool isTailCall, bool isPatchPoint, 5387 const SmallVectorImpl<ISD::OutputArg> &Outs, 5388 const SmallVectorImpl<SDValue> &OutVals, 5389 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5390 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5391 ImmutableCallSite CS) const { 5392 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5393 bool isLittleEndian = Subtarget.isLittleEndian(); 5394 unsigned NumOps = Outs.size(); 5395 bool hasNest = false; 5396 bool IsSibCall = false; 5397 5398 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5399 unsigned PtrByteSize = 8; 5400 5401 MachineFunction &MF = DAG.getMachineFunction(); 5402 5403 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5404 IsSibCall = true; 5405 5406 // Mark this function as potentially containing a function that contains a 5407 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5408 // and restoring the callers stack pointer in this functions epilog. This is 5409 // done because by tail calling the called function might overwrite the value 5410 // in this function's (MF) stack pointer stack slot 0(SP). 5411 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5412 CallConv == CallingConv::Fast) 5413 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5414 5415 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5416 "fastcc not supported on varargs functions"); 5417 5418 // Count how many bytes are to be pushed on the stack, including the linkage 5419 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5420 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5421 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5422 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5423 unsigned NumBytes = LinkageSize; 5424 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5425 unsigned &QFPR_idx = FPR_idx; 5426 5427 static const MCPhysReg GPR[] = { 5428 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5429 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5430 }; 5431 static const MCPhysReg VR[] = { 5432 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5433 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5434 }; 5435 5436 const unsigned NumGPRs = array_lengthof(GPR); 5437 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5438 const unsigned NumVRs = array_lengthof(VR); 5439 const unsigned NumQFPRs = NumFPRs; 5440 5441 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5442 // can be passed to the callee in registers. 5443 // For the fast calling convention, there is another check below. 5444 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5445 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5446 if (!HasParameterArea) { 5447 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5448 unsigned AvailableFPRs = NumFPRs; 5449 unsigned AvailableVRs = NumVRs; 5450 unsigned NumBytesTmp = NumBytes; 5451 for (unsigned i = 0; i != NumOps; ++i) { 5452 if (Outs[i].Flags.isNest()) continue; 5453 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5454 PtrByteSize, LinkageSize, ParamAreaSize, 5455 NumBytesTmp, AvailableFPRs, AvailableVRs, 5456 Subtarget.hasQPX())) 5457 HasParameterArea = true; 5458 } 5459 } 5460 5461 // When using the fast calling convention, we don't provide backing for 5462 // arguments that will be in registers. 5463 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5464 5465 // Add up all the space actually used. 5466 for (unsigned i = 0; i != NumOps; ++i) { 5467 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5468 EVT ArgVT = Outs[i].VT; 5469 EVT OrigVT = Outs[i].ArgVT; 5470 5471 if (Flags.isNest()) 5472 continue; 5473 5474 if (CallConv == CallingConv::Fast) { 5475 if (Flags.isByVal()) 5476 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5477 else 5478 switch (ArgVT.getSimpleVT().SimpleTy) { 5479 default: llvm_unreachable("Unexpected ValueType for argument!"); 5480 case MVT::i1: 5481 case MVT::i32: 5482 case MVT::i64: 5483 if (++NumGPRsUsed <= NumGPRs) 5484 continue; 5485 break; 5486 case MVT::v4i32: 5487 case MVT::v8i16: 5488 case MVT::v16i8: 5489 case MVT::v2f64: 5490 case MVT::v2i64: 5491 case MVT::v1i128: 5492 if (++NumVRsUsed <= NumVRs) 5493 continue; 5494 break; 5495 case MVT::v4f32: 5496 // When using QPX, this is handled like a FP register, otherwise, it 5497 // is an Altivec register. 5498 if (Subtarget.hasQPX()) { 5499 if (++NumFPRsUsed <= NumFPRs) 5500 continue; 5501 } else { 5502 if (++NumVRsUsed <= NumVRs) 5503 continue; 5504 } 5505 break; 5506 case MVT::f32: 5507 case MVT::f64: 5508 case MVT::v4f64: // QPX 5509 case MVT::v4i1: // QPX 5510 if (++NumFPRsUsed <= NumFPRs) 5511 continue; 5512 break; 5513 } 5514 } 5515 5516 /* Respect alignment of argument on the stack. */ 5517 unsigned Align = 5518 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5519 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5520 5521 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5522 if (Flags.isInConsecutiveRegsLast()) 5523 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5524 } 5525 5526 unsigned NumBytesActuallyUsed = NumBytes; 5527 5528 // In the old ELFv1 ABI, 5529 // the prolog code of the callee may store up to 8 GPR argument registers to 5530 // the stack, allowing va_start to index over them in memory if its varargs. 5531 // Because we cannot tell if this is needed on the caller side, we have to 5532 // conservatively assume that it is needed. As such, make sure we have at 5533 // least enough stack space for the caller to store the 8 GPRs. 5534 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5535 // really requires memory operands, e.g. a vararg function. 5536 if (HasParameterArea) 5537 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5538 else 5539 NumBytes = LinkageSize; 5540 5541 // Tail call needs the stack to be aligned. 5542 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5543 CallConv == CallingConv::Fast) 5544 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5545 5546 int SPDiff = 0; 5547 5548 // Calculate by how many bytes the stack has to be adjusted in case of tail 5549 // call optimization. 5550 if (!IsSibCall) 5551 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5552 5553 // To protect arguments on the stack from being clobbered in a tail call, 5554 // force all the loads to happen before doing any other lowering. 5555 if (isTailCall) 5556 Chain = DAG.getStackArgumentTokenFactor(Chain); 5557 5558 // Adjust the stack pointer for the new arguments... 5559 // These operations are automatically eliminated by the prolog/epilog pass 5560 if (!IsSibCall) 5561 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5562 SDValue CallSeqStart = Chain; 5563 5564 // Load the return address and frame pointer so it can be move somewhere else 5565 // later. 5566 SDValue LROp, FPOp; 5567 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5568 5569 // Set up a copy of the stack pointer for use loading and storing any 5570 // arguments that may not fit in the registers available for argument 5571 // passing. 5572 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5573 5574 // Figure out which arguments are going to go in registers, and which in 5575 // memory. Also, if this is a vararg function, floating point operations 5576 // must be stored to our stack, and loaded into integer regs as well, if 5577 // any integer regs are available for argument passing. 5578 unsigned ArgOffset = LinkageSize; 5579 5580 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5581 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5582 5583 SmallVector<SDValue, 8> MemOpChains; 5584 for (unsigned i = 0; i != NumOps; ++i) { 5585 SDValue Arg = OutVals[i]; 5586 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5587 EVT ArgVT = Outs[i].VT; 5588 EVT OrigVT = Outs[i].ArgVT; 5589 5590 // PtrOff will be used to store the current argument to the stack if a 5591 // register cannot be found for it. 5592 SDValue PtrOff; 5593 5594 // We re-align the argument offset for each argument, except when using the 5595 // fast calling convention, when we need to make sure we do that only when 5596 // we'll actually use a stack slot. 5597 auto ComputePtrOff = [&]() { 5598 /* Respect alignment of argument on the stack. */ 5599 unsigned Align = 5600 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5601 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5602 5603 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5604 5605 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5606 }; 5607 5608 if (CallConv != CallingConv::Fast) { 5609 ComputePtrOff(); 5610 5611 /* Compute GPR index associated with argument offset. */ 5612 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5613 GPR_idx = std::min(GPR_idx, NumGPRs); 5614 } 5615 5616 // Promote integers to 64-bit values. 5617 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5618 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5619 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5620 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5621 } 5622 5623 // FIXME memcpy is used way more than necessary. Correctness first. 5624 // Note: "by value" is code for passing a structure by value, not 5625 // basic types. 5626 if (Flags.isByVal()) { 5627 // Note: Size includes alignment padding, so 5628 // struct x { short a; char b; } 5629 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5630 // These are the proper values we need for right-justifying the 5631 // aggregate in a parameter register. 5632 unsigned Size = Flags.getByValSize(); 5633 5634 // An empty aggregate parameter takes up no storage and no 5635 // registers. 5636 if (Size == 0) 5637 continue; 5638 5639 if (CallConv == CallingConv::Fast) 5640 ComputePtrOff(); 5641 5642 // All aggregates smaller than 8 bytes must be passed right-justified. 5643 if (Size==1 || Size==2 || Size==4) { 5644 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5645 if (GPR_idx != NumGPRs) { 5646 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5647 MachinePointerInfo(), VT); 5648 MemOpChains.push_back(Load.getValue(1)); 5649 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5650 5651 ArgOffset += PtrByteSize; 5652 continue; 5653 } 5654 } 5655 5656 if (GPR_idx == NumGPRs && Size < 8) { 5657 SDValue AddPtr = PtrOff; 5658 if (!isLittleEndian) { 5659 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5660 PtrOff.getValueType()); 5661 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5662 } 5663 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5664 CallSeqStart, 5665 Flags, DAG, dl); 5666 ArgOffset += PtrByteSize; 5667 continue; 5668 } 5669 // Copy entire object into memory. There are cases where gcc-generated 5670 // code assumes it is there, even if it could be put entirely into 5671 // registers. (This is not what the doc says.) 5672 5673 // FIXME: The above statement is likely due to a misunderstanding of the 5674 // documents. All arguments must be copied into the parameter area BY 5675 // THE CALLEE in the event that the callee takes the address of any 5676 // formal argument. That has not yet been implemented. However, it is 5677 // reasonable to use the stack area as a staging area for the register 5678 // load. 5679 5680 // Skip this for small aggregates, as we will use the same slot for a 5681 // right-justified copy, below. 5682 if (Size >= 8) 5683 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5684 CallSeqStart, 5685 Flags, DAG, dl); 5686 5687 // When a register is available, pass a small aggregate right-justified. 5688 if (Size < 8 && GPR_idx != NumGPRs) { 5689 // The easiest way to get this right-justified in a register 5690 // is to copy the structure into the rightmost portion of a 5691 // local variable slot, then load the whole slot into the 5692 // register. 5693 // FIXME: The memcpy seems to produce pretty awful code for 5694 // small aggregates, particularly for packed ones. 5695 // FIXME: It would be preferable to use the slot in the 5696 // parameter save area instead of a new local variable. 5697 SDValue AddPtr = PtrOff; 5698 if (!isLittleEndian) { 5699 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5700 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5701 } 5702 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5703 CallSeqStart, 5704 Flags, DAG, dl); 5705 5706 // Load the slot into the register. 5707 SDValue Load = 5708 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5709 MemOpChains.push_back(Load.getValue(1)); 5710 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5711 5712 // Done with this argument. 5713 ArgOffset += PtrByteSize; 5714 continue; 5715 } 5716 5717 // For aggregates larger than PtrByteSize, copy the pieces of the 5718 // object that fit into registers from the parameter save area. 5719 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5720 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5721 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5722 if (GPR_idx != NumGPRs) { 5723 SDValue Load = 5724 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5725 MemOpChains.push_back(Load.getValue(1)); 5726 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5727 ArgOffset += PtrByteSize; 5728 } else { 5729 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5730 break; 5731 } 5732 } 5733 continue; 5734 } 5735 5736 switch (Arg.getSimpleValueType().SimpleTy) { 5737 default: llvm_unreachable("Unexpected ValueType for argument!"); 5738 case MVT::i1: 5739 case MVT::i32: 5740 case MVT::i64: 5741 if (Flags.isNest()) { 5742 // The 'nest' parameter, if any, is passed in R11. 5743 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5744 hasNest = true; 5745 break; 5746 } 5747 5748 // These can be scalar arguments or elements of an integer array type 5749 // passed directly. Clang may use those instead of "byval" aggregate 5750 // types to avoid forcing arguments to memory unnecessarily. 5751 if (GPR_idx != NumGPRs) { 5752 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5753 } else { 5754 if (CallConv == CallingConv::Fast) 5755 ComputePtrOff(); 5756 5757 assert(HasParameterArea && 5758 "Parameter area must exist to pass an argument in memory."); 5759 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5760 true, isTailCall, false, MemOpChains, 5761 TailCallArguments, dl); 5762 if (CallConv == CallingConv::Fast) 5763 ArgOffset += PtrByteSize; 5764 } 5765 if (CallConv != CallingConv::Fast) 5766 ArgOffset += PtrByteSize; 5767 break; 5768 case MVT::f32: 5769 case MVT::f64: { 5770 // These can be scalar arguments or elements of a float array type 5771 // passed directly. The latter are used to implement ELFv2 homogenous 5772 // float aggregates. 5773 5774 // Named arguments go into FPRs first, and once they overflow, the 5775 // remaining arguments go into GPRs and then the parameter save area. 5776 // Unnamed arguments for vararg functions always go to GPRs and 5777 // then the parameter save area. For now, put all arguments to vararg 5778 // routines always in both locations (FPR *and* GPR or stack slot). 5779 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5780 bool NeededLoad = false; 5781 5782 // First load the argument into the next available FPR. 5783 if (FPR_idx != NumFPRs) 5784 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5785 5786 // Next, load the argument into GPR or stack slot if needed. 5787 if (!NeedGPROrStack) 5788 ; 5789 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5790 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5791 // once we support fp <-> gpr moves. 5792 5793 // In the non-vararg case, this can only ever happen in the 5794 // presence of f32 array types, since otherwise we never run 5795 // out of FPRs before running out of GPRs. 5796 SDValue ArgVal; 5797 5798 // Double values are always passed in a single GPR. 5799 if (Arg.getValueType() != MVT::f32) { 5800 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5801 5802 // Non-array float values are extended and passed in a GPR. 5803 } else if (!Flags.isInConsecutiveRegs()) { 5804 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5805 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5806 5807 // If we have an array of floats, we collect every odd element 5808 // together with its predecessor into one GPR. 5809 } else if (ArgOffset % PtrByteSize != 0) { 5810 SDValue Lo, Hi; 5811 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5812 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5813 if (!isLittleEndian) 5814 std::swap(Lo, Hi); 5815 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5816 5817 // The final element, if even, goes into the first half of a GPR. 5818 } else if (Flags.isInConsecutiveRegsLast()) { 5819 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5820 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5821 if (!isLittleEndian) 5822 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 5823 DAG.getConstant(32, dl, MVT::i32)); 5824 5825 // Non-final even elements are skipped; they will be handled 5826 // together the with subsequent argument on the next go-around. 5827 } else 5828 ArgVal = SDValue(); 5829 5830 if (ArgVal.getNode()) 5831 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 5832 } else { 5833 if (CallConv == CallingConv::Fast) 5834 ComputePtrOff(); 5835 5836 // Single-precision floating-point values are mapped to the 5837 // second (rightmost) word of the stack doubleword. 5838 if (Arg.getValueType() == MVT::f32 && 5839 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 5840 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5841 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5842 } 5843 5844 assert(HasParameterArea && 5845 "Parameter area must exist to pass an argument in memory."); 5846 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5847 true, isTailCall, false, MemOpChains, 5848 TailCallArguments, dl); 5849 5850 NeededLoad = true; 5851 } 5852 // When passing an array of floats, the array occupies consecutive 5853 // space in the argument area; only round up to the next doubleword 5854 // at the end of the array. Otherwise, each float takes 8 bytes. 5855 if (CallConv != CallingConv::Fast || NeededLoad) { 5856 ArgOffset += (Arg.getValueType() == MVT::f32 && 5857 Flags.isInConsecutiveRegs()) ? 4 : 8; 5858 if (Flags.isInConsecutiveRegsLast()) 5859 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5860 } 5861 break; 5862 } 5863 case MVT::v4f32: 5864 case MVT::v4i32: 5865 case MVT::v8i16: 5866 case MVT::v16i8: 5867 case MVT::v2f64: 5868 case MVT::v2i64: 5869 case MVT::v1i128: 5870 if (!Subtarget.hasQPX()) { 5871 // These can be scalar arguments or elements of a vector array type 5872 // passed directly. The latter are used to implement ELFv2 homogenous 5873 // vector aggregates. 5874 5875 // For a varargs call, named arguments go into VRs or on the stack as 5876 // usual; unnamed arguments always go to the stack or the corresponding 5877 // GPRs when within range. For now, we always put the value in both 5878 // locations (or even all three). 5879 if (isVarArg) { 5880 assert(HasParameterArea && 5881 "Parameter area must exist if we have a varargs call."); 5882 // We could elide this store in the case where the object fits 5883 // entirely in R registers. Maybe later. 5884 SDValue Store = 5885 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5886 MemOpChains.push_back(Store); 5887 if (VR_idx != NumVRs) { 5888 SDValue Load = 5889 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 5890 MemOpChains.push_back(Load.getValue(1)); 5891 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 5892 } 5893 ArgOffset += 16; 5894 for (unsigned i=0; i<16; i+=PtrByteSize) { 5895 if (GPR_idx == NumGPRs) 5896 break; 5897 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5898 DAG.getConstant(i, dl, PtrVT)); 5899 SDValue Load = 5900 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5901 MemOpChains.push_back(Load.getValue(1)); 5902 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5903 } 5904 break; 5905 } 5906 5907 // Non-varargs Altivec params go into VRs or on the stack. 5908 if (VR_idx != NumVRs) { 5909 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 5910 } else { 5911 if (CallConv == CallingConv::Fast) 5912 ComputePtrOff(); 5913 5914 assert(HasParameterArea && 5915 "Parameter area must exist to pass an argument in memory."); 5916 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5917 true, isTailCall, true, MemOpChains, 5918 TailCallArguments, dl); 5919 if (CallConv == CallingConv::Fast) 5920 ArgOffset += 16; 5921 } 5922 5923 if (CallConv != CallingConv::Fast) 5924 ArgOffset += 16; 5925 break; 5926 } // not QPX 5927 5928 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 5929 "Invalid QPX parameter type"); 5930 5931 /* fall through */ 5932 case MVT::v4f64: 5933 case MVT::v4i1: { 5934 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 5935 if (isVarArg) { 5936 assert(HasParameterArea && 5937 "Parameter area must exist if we have a varargs call."); 5938 // We could elide this store in the case where the object fits 5939 // entirely in R registers. Maybe later. 5940 SDValue Store = 5941 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5942 MemOpChains.push_back(Store); 5943 if (QFPR_idx != NumQFPRs) { 5944 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 5945 PtrOff, MachinePointerInfo()); 5946 MemOpChains.push_back(Load.getValue(1)); 5947 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 5948 } 5949 ArgOffset += (IsF32 ? 16 : 32); 5950 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 5951 if (GPR_idx == NumGPRs) 5952 break; 5953 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5954 DAG.getConstant(i, dl, PtrVT)); 5955 SDValue Load = 5956 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5957 MemOpChains.push_back(Load.getValue(1)); 5958 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5959 } 5960 break; 5961 } 5962 5963 // Non-varargs QPX params go into registers or on the stack. 5964 if (QFPR_idx != NumQFPRs) { 5965 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 5966 } else { 5967 if (CallConv == CallingConv::Fast) 5968 ComputePtrOff(); 5969 5970 assert(HasParameterArea && 5971 "Parameter area must exist to pass an argument in memory."); 5972 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5973 true, isTailCall, true, MemOpChains, 5974 TailCallArguments, dl); 5975 if (CallConv == CallingConv::Fast) 5976 ArgOffset += (IsF32 ? 16 : 32); 5977 } 5978 5979 if (CallConv != CallingConv::Fast) 5980 ArgOffset += (IsF32 ? 16 : 32); 5981 break; 5982 } 5983 } 5984 } 5985 5986 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 5987 "mismatch in size of parameter area"); 5988 (void)NumBytesActuallyUsed; 5989 5990 if (!MemOpChains.empty()) 5991 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5992 5993 // Check if this is an indirect call (MTCTR/BCTRL). 5994 // See PrepareCall() for more information about calls through function 5995 // pointers in the 64-bit SVR4 ABI. 5996 if (!isTailCall && !isPatchPoint && 5997 !isFunctionGlobalAddress(Callee) && 5998 !isa<ExternalSymbolSDNode>(Callee)) { 5999 // Load r2 into a virtual register and store it to the TOC save area. 6000 setUsesTOCBasePtr(DAG); 6001 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6002 // TOC save area offset. 6003 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6004 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6005 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6006 Chain = DAG.getStore( 6007 Val.getValue(1), dl, Val, AddPtr, 6008 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6009 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6010 // This does not mean the MTCTR instruction must use R12; it's easier 6011 // to model this as an extra parameter, so do that. 6012 if (isELFv2ABI && !isPatchPoint) 6013 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6014 } 6015 6016 // Build a sequence of copy-to-reg nodes chained together with token chain 6017 // and flag operands which copy the outgoing args into the appropriate regs. 6018 SDValue InFlag; 6019 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6020 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6021 RegsToPass[i].second, InFlag); 6022 InFlag = Chain.getValue(1); 6023 } 6024 6025 if (isTailCall && !IsSibCall) 6026 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6027 TailCallArguments); 6028 6029 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6030 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6031 SPDiff, NumBytes, Ins, InVals, CS); 6032 } 6033 6034 SDValue PPCTargetLowering::LowerCall_Darwin( 6035 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6036 bool isTailCall, bool isPatchPoint, 6037 const SmallVectorImpl<ISD::OutputArg> &Outs, 6038 const SmallVectorImpl<SDValue> &OutVals, 6039 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6040 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6041 ImmutableCallSite CS) const { 6042 unsigned NumOps = Outs.size(); 6043 6044 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6045 bool isPPC64 = PtrVT == MVT::i64; 6046 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6047 6048 MachineFunction &MF = DAG.getMachineFunction(); 6049 6050 // Mark this function as potentially containing a function that contains a 6051 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6052 // and restoring the callers stack pointer in this functions epilog. This is 6053 // done because by tail calling the called function might overwrite the value 6054 // in this function's (MF) stack pointer stack slot 0(SP). 6055 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6056 CallConv == CallingConv::Fast) 6057 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6058 6059 // Count how many bytes are to be pushed on the stack, including the linkage 6060 // area, and parameter passing area. We start with 24/48 bytes, which is 6061 // prereserved space for [SP][CR][LR][3 x unused]. 6062 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6063 unsigned NumBytes = LinkageSize; 6064 6065 // Add up all the space actually used. 6066 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6067 // they all go in registers, but we must reserve stack space for them for 6068 // possible use by the caller. In varargs or 64-bit calls, parameters are 6069 // assigned stack space in order, with padding so Altivec parameters are 6070 // 16-byte aligned. 6071 unsigned nAltivecParamsAtEnd = 0; 6072 for (unsigned i = 0; i != NumOps; ++i) { 6073 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6074 EVT ArgVT = Outs[i].VT; 6075 // Varargs Altivec parameters are padded to a 16 byte boundary. 6076 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6077 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6078 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6079 if (!isVarArg && !isPPC64) { 6080 // Non-varargs Altivec parameters go after all the non-Altivec 6081 // parameters; handle those later so we know how much padding we need. 6082 nAltivecParamsAtEnd++; 6083 continue; 6084 } 6085 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6086 NumBytes = ((NumBytes+15)/16)*16; 6087 } 6088 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6089 } 6090 6091 // Allow for Altivec parameters at the end, if needed. 6092 if (nAltivecParamsAtEnd) { 6093 NumBytes = ((NumBytes+15)/16)*16; 6094 NumBytes += 16*nAltivecParamsAtEnd; 6095 } 6096 6097 // The prolog code of the callee may store up to 8 GPR argument registers to 6098 // the stack, allowing va_start to index over them in memory if its varargs. 6099 // Because we cannot tell if this is needed on the caller side, we have to 6100 // conservatively assume that it is needed. As such, make sure we have at 6101 // least enough stack space for the caller to store the 8 GPRs. 6102 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6103 6104 // Tail call needs the stack to be aligned. 6105 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6106 CallConv == CallingConv::Fast) 6107 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6108 6109 // Calculate by how many bytes the stack has to be adjusted in case of tail 6110 // call optimization. 6111 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6112 6113 // To protect arguments on the stack from being clobbered in a tail call, 6114 // force all the loads to happen before doing any other lowering. 6115 if (isTailCall) 6116 Chain = DAG.getStackArgumentTokenFactor(Chain); 6117 6118 // Adjust the stack pointer for the new arguments... 6119 // These operations are automatically eliminated by the prolog/epilog pass 6120 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6121 SDValue CallSeqStart = Chain; 6122 6123 // Load the return address and frame pointer so it can be move somewhere else 6124 // later. 6125 SDValue LROp, FPOp; 6126 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6127 6128 // Set up a copy of the stack pointer for use loading and storing any 6129 // arguments that may not fit in the registers available for argument 6130 // passing. 6131 SDValue StackPtr; 6132 if (isPPC64) 6133 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6134 else 6135 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6136 6137 // Figure out which arguments are going to go in registers, and which in 6138 // memory. Also, if this is a vararg function, floating point operations 6139 // must be stored to our stack, and loaded into integer regs as well, if 6140 // any integer regs are available for argument passing. 6141 unsigned ArgOffset = LinkageSize; 6142 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6143 6144 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6145 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6146 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6147 }; 6148 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6149 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6150 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6151 }; 6152 static const MCPhysReg VR[] = { 6153 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6154 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6155 }; 6156 const unsigned NumGPRs = array_lengthof(GPR_32); 6157 const unsigned NumFPRs = 13; 6158 const unsigned NumVRs = array_lengthof(VR); 6159 6160 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6161 6162 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6163 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6164 6165 SmallVector<SDValue, 8> MemOpChains; 6166 for (unsigned i = 0; i != NumOps; ++i) { 6167 SDValue Arg = OutVals[i]; 6168 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6169 6170 // PtrOff will be used to store the current argument to the stack if a 6171 // register cannot be found for it. 6172 SDValue PtrOff; 6173 6174 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6175 6176 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6177 6178 // On PPC64, promote integers to 64-bit values. 6179 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6180 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6181 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6182 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6183 } 6184 6185 // FIXME memcpy is used way more than necessary. Correctness first. 6186 // Note: "by value" is code for passing a structure by value, not 6187 // basic types. 6188 if (Flags.isByVal()) { 6189 unsigned Size = Flags.getByValSize(); 6190 // Very small objects are passed right-justified. Everything else is 6191 // passed left-justified. 6192 if (Size==1 || Size==2) { 6193 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6194 if (GPR_idx != NumGPRs) { 6195 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6196 MachinePointerInfo(), VT); 6197 MemOpChains.push_back(Load.getValue(1)); 6198 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6199 6200 ArgOffset += PtrByteSize; 6201 } else { 6202 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6203 PtrOff.getValueType()); 6204 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6205 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6206 CallSeqStart, 6207 Flags, DAG, dl); 6208 ArgOffset += PtrByteSize; 6209 } 6210 continue; 6211 } 6212 // Copy entire object into memory. There are cases where gcc-generated 6213 // code assumes it is there, even if it could be put entirely into 6214 // registers. (This is not what the doc says.) 6215 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6216 CallSeqStart, 6217 Flags, DAG, dl); 6218 6219 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6220 // copy the pieces of the object that fit into registers from the 6221 // parameter save area. 6222 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6223 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6224 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6225 if (GPR_idx != NumGPRs) { 6226 SDValue Load = 6227 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6228 MemOpChains.push_back(Load.getValue(1)); 6229 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6230 ArgOffset += PtrByteSize; 6231 } else { 6232 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6233 break; 6234 } 6235 } 6236 continue; 6237 } 6238 6239 switch (Arg.getSimpleValueType().SimpleTy) { 6240 default: llvm_unreachable("Unexpected ValueType for argument!"); 6241 case MVT::i1: 6242 case MVT::i32: 6243 case MVT::i64: 6244 if (GPR_idx != NumGPRs) { 6245 if (Arg.getValueType() == MVT::i1) 6246 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6247 6248 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6249 } else { 6250 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6251 isPPC64, isTailCall, false, MemOpChains, 6252 TailCallArguments, dl); 6253 } 6254 ArgOffset += PtrByteSize; 6255 break; 6256 case MVT::f32: 6257 case MVT::f64: 6258 if (FPR_idx != NumFPRs) { 6259 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6260 6261 if (isVarArg) { 6262 SDValue Store = 6263 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6264 MemOpChains.push_back(Store); 6265 6266 // Float varargs are always shadowed in available integer registers 6267 if (GPR_idx != NumGPRs) { 6268 SDValue Load = 6269 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6270 MemOpChains.push_back(Load.getValue(1)); 6271 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6272 } 6273 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6274 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6275 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6276 SDValue Load = 6277 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6278 MemOpChains.push_back(Load.getValue(1)); 6279 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6280 } 6281 } else { 6282 // If we have any FPRs remaining, we may also have GPRs remaining. 6283 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6284 // GPRs. 6285 if (GPR_idx != NumGPRs) 6286 ++GPR_idx; 6287 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6288 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6289 ++GPR_idx; 6290 } 6291 } else 6292 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6293 isPPC64, isTailCall, false, MemOpChains, 6294 TailCallArguments, dl); 6295 if (isPPC64) 6296 ArgOffset += 8; 6297 else 6298 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6299 break; 6300 case MVT::v4f32: 6301 case MVT::v4i32: 6302 case MVT::v8i16: 6303 case MVT::v16i8: 6304 if (isVarArg) { 6305 // These go aligned on the stack, or in the corresponding R registers 6306 // when within range. The Darwin PPC ABI doc claims they also go in 6307 // V registers; in fact gcc does this only for arguments that are 6308 // prototyped, not for those that match the ... We do it for all 6309 // arguments, seems to work. 6310 while (ArgOffset % 16 !=0) { 6311 ArgOffset += PtrByteSize; 6312 if (GPR_idx != NumGPRs) 6313 GPR_idx++; 6314 } 6315 // We could elide this store in the case where the object fits 6316 // entirely in R registers. Maybe later. 6317 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6318 DAG.getConstant(ArgOffset, dl, PtrVT)); 6319 SDValue Store = 6320 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6321 MemOpChains.push_back(Store); 6322 if (VR_idx != NumVRs) { 6323 SDValue Load = 6324 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6325 MemOpChains.push_back(Load.getValue(1)); 6326 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6327 } 6328 ArgOffset += 16; 6329 for (unsigned i=0; i<16; i+=PtrByteSize) { 6330 if (GPR_idx == NumGPRs) 6331 break; 6332 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6333 DAG.getConstant(i, dl, PtrVT)); 6334 SDValue Load = 6335 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6336 MemOpChains.push_back(Load.getValue(1)); 6337 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6338 } 6339 break; 6340 } 6341 6342 // Non-varargs Altivec params generally go in registers, but have 6343 // stack space allocated at the end. 6344 if (VR_idx != NumVRs) { 6345 // Doesn't have GPR space allocated. 6346 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6347 } else if (nAltivecParamsAtEnd==0) { 6348 // We are emitting Altivec params in order. 6349 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6350 isPPC64, isTailCall, true, MemOpChains, 6351 TailCallArguments, dl); 6352 ArgOffset += 16; 6353 } 6354 break; 6355 } 6356 } 6357 // If all Altivec parameters fit in registers, as they usually do, 6358 // they get stack space following the non-Altivec parameters. We 6359 // don't track this here because nobody below needs it. 6360 // If there are more Altivec parameters than fit in registers emit 6361 // the stores here. 6362 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6363 unsigned j = 0; 6364 // Offset is aligned; skip 1st 12 params which go in V registers. 6365 ArgOffset = ((ArgOffset+15)/16)*16; 6366 ArgOffset += 12*16; 6367 for (unsigned i = 0; i != NumOps; ++i) { 6368 SDValue Arg = OutVals[i]; 6369 EVT ArgType = Outs[i].VT; 6370 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6371 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6372 if (++j > NumVRs) { 6373 SDValue PtrOff; 6374 // We are emitting Altivec params in order. 6375 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6376 isPPC64, isTailCall, true, MemOpChains, 6377 TailCallArguments, dl); 6378 ArgOffset += 16; 6379 } 6380 } 6381 } 6382 } 6383 6384 if (!MemOpChains.empty()) 6385 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6386 6387 // On Darwin, R12 must contain the address of an indirect callee. This does 6388 // not mean the MTCTR instruction must use R12; it's easier to model this as 6389 // an extra parameter, so do that. 6390 if (!isTailCall && 6391 !isFunctionGlobalAddress(Callee) && 6392 !isa<ExternalSymbolSDNode>(Callee) && 6393 !isBLACompatibleAddress(Callee, DAG)) 6394 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6395 PPC::R12), Callee)); 6396 6397 // Build a sequence of copy-to-reg nodes chained together with token chain 6398 // and flag operands which copy the outgoing args into the appropriate regs. 6399 SDValue InFlag; 6400 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6401 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6402 RegsToPass[i].second, InFlag); 6403 InFlag = Chain.getValue(1); 6404 } 6405 6406 if (isTailCall) 6407 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6408 TailCallArguments); 6409 6410 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6411 /* unused except on PPC64 ELFv1 */ false, DAG, 6412 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6413 NumBytes, Ins, InVals, CS); 6414 } 6415 6416 bool 6417 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6418 MachineFunction &MF, bool isVarArg, 6419 const SmallVectorImpl<ISD::OutputArg> &Outs, 6420 LLVMContext &Context) const { 6421 SmallVector<CCValAssign, 16> RVLocs; 6422 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6423 return CCInfo.CheckReturn(Outs, RetCC_PPC); 6424 } 6425 6426 SDValue 6427 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6428 bool isVarArg, 6429 const SmallVectorImpl<ISD::OutputArg> &Outs, 6430 const SmallVectorImpl<SDValue> &OutVals, 6431 const SDLoc &dl, SelectionDAG &DAG) const { 6432 SmallVector<CCValAssign, 16> RVLocs; 6433 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6434 *DAG.getContext()); 6435 CCInfo.AnalyzeReturn(Outs, RetCC_PPC); 6436 6437 SDValue Flag; 6438 SmallVector<SDValue, 4> RetOps(1, Chain); 6439 6440 // Copy the result values into the output registers. 6441 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6442 CCValAssign &VA = RVLocs[i]; 6443 assert(VA.isRegLoc() && "Can only return in registers!"); 6444 6445 SDValue Arg = OutVals[i]; 6446 6447 switch (VA.getLocInfo()) { 6448 default: llvm_unreachable("Unknown loc info!"); 6449 case CCValAssign::Full: break; 6450 case CCValAssign::AExt: 6451 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6452 break; 6453 case CCValAssign::ZExt: 6454 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6455 break; 6456 case CCValAssign::SExt: 6457 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6458 break; 6459 } 6460 6461 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6462 Flag = Chain.getValue(1); 6463 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6464 } 6465 6466 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6467 const MCPhysReg *I = 6468 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6469 if (I) { 6470 for (; *I; ++I) { 6471 6472 if (PPC::G8RCRegClass.contains(*I)) 6473 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6474 else if (PPC::F8RCRegClass.contains(*I)) 6475 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6476 else if (PPC::CRRCRegClass.contains(*I)) 6477 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6478 else if (PPC::VRRCRegClass.contains(*I)) 6479 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6480 else 6481 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6482 } 6483 } 6484 6485 RetOps[0] = Chain; // Update chain. 6486 6487 // Add the flag if we have it. 6488 if (Flag.getNode()) 6489 RetOps.push_back(Flag); 6490 6491 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6492 } 6493 6494 SDValue 6495 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6496 SelectionDAG &DAG) const { 6497 SDLoc dl(Op); 6498 6499 // Get the correct type for integers. 6500 EVT IntVT = Op.getValueType(); 6501 6502 // Get the inputs. 6503 SDValue Chain = Op.getOperand(0); 6504 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6505 // Build a DYNAREAOFFSET node. 6506 SDValue Ops[2] = {Chain, FPSIdx}; 6507 SDVTList VTs = DAG.getVTList(IntVT); 6508 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6509 } 6510 6511 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6512 SelectionDAG &DAG) const { 6513 // When we pop the dynamic allocation we need to restore the SP link. 6514 SDLoc dl(Op); 6515 6516 // Get the correct type for pointers. 6517 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6518 6519 // Construct the stack pointer operand. 6520 bool isPPC64 = Subtarget.isPPC64(); 6521 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6522 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6523 6524 // Get the operands for the STACKRESTORE. 6525 SDValue Chain = Op.getOperand(0); 6526 SDValue SaveSP = Op.getOperand(1); 6527 6528 // Load the old link SP. 6529 SDValue LoadLinkSP = 6530 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6531 6532 // Restore the stack pointer. 6533 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6534 6535 // Store the old link SP. 6536 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6537 } 6538 6539 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6540 MachineFunction &MF = DAG.getMachineFunction(); 6541 bool isPPC64 = Subtarget.isPPC64(); 6542 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6543 6544 // Get current frame pointer save index. The users of this index will be 6545 // primarily DYNALLOC instructions. 6546 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6547 int RASI = FI->getReturnAddrSaveIndex(); 6548 6549 // If the frame pointer save index hasn't been defined yet. 6550 if (!RASI) { 6551 // Find out what the fix offset of the frame pointer save area. 6552 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6553 // Allocate the frame index for frame pointer save area. 6554 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6555 // Save the result. 6556 FI->setReturnAddrSaveIndex(RASI); 6557 } 6558 return DAG.getFrameIndex(RASI, PtrVT); 6559 } 6560 6561 SDValue 6562 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6563 MachineFunction &MF = DAG.getMachineFunction(); 6564 bool isPPC64 = Subtarget.isPPC64(); 6565 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6566 6567 // Get current frame pointer save index. The users of this index will be 6568 // primarily DYNALLOC instructions. 6569 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6570 int FPSI = FI->getFramePointerSaveIndex(); 6571 6572 // If the frame pointer save index hasn't been defined yet. 6573 if (!FPSI) { 6574 // Find out what the fix offset of the frame pointer save area. 6575 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6576 // Allocate the frame index for frame pointer save area. 6577 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6578 // Save the result. 6579 FI->setFramePointerSaveIndex(FPSI); 6580 } 6581 return DAG.getFrameIndex(FPSI, PtrVT); 6582 } 6583 6584 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6585 SelectionDAG &DAG) const { 6586 // Get the inputs. 6587 SDValue Chain = Op.getOperand(0); 6588 SDValue Size = Op.getOperand(1); 6589 SDLoc dl(Op); 6590 6591 // Get the correct type for pointers. 6592 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6593 // Negate the size. 6594 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6595 DAG.getConstant(0, dl, PtrVT), Size); 6596 // Construct a node for the frame pointer save index. 6597 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6598 // Build a DYNALLOC node. 6599 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6600 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6601 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6602 } 6603 6604 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6605 SelectionDAG &DAG) const { 6606 MachineFunction &MF = DAG.getMachineFunction(); 6607 6608 bool isPPC64 = Subtarget.isPPC64(); 6609 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6610 6611 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6612 return DAG.getFrameIndex(FI, PtrVT); 6613 } 6614 6615 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6616 SelectionDAG &DAG) const { 6617 SDLoc DL(Op); 6618 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6619 DAG.getVTList(MVT::i32, MVT::Other), 6620 Op.getOperand(0), Op.getOperand(1)); 6621 } 6622 6623 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6624 SelectionDAG &DAG) const { 6625 SDLoc DL(Op); 6626 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6627 Op.getOperand(0), Op.getOperand(1)); 6628 } 6629 6630 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6631 if (Op.getValueType().isVector()) 6632 return LowerVectorLoad(Op, DAG); 6633 6634 assert(Op.getValueType() == MVT::i1 && 6635 "Custom lowering only for i1 loads"); 6636 6637 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6638 6639 SDLoc dl(Op); 6640 LoadSDNode *LD = cast<LoadSDNode>(Op); 6641 6642 SDValue Chain = LD->getChain(); 6643 SDValue BasePtr = LD->getBasePtr(); 6644 MachineMemOperand *MMO = LD->getMemOperand(); 6645 6646 SDValue NewLD = 6647 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6648 BasePtr, MVT::i8, MMO); 6649 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6650 6651 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6652 return DAG.getMergeValues(Ops, dl); 6653 } 6654 6655 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6656 if (Op.getOperand(1).getValueType().isVector()) 6657 return LowerVectorStore(Op, DAG); 6658 6659 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6660 "Custom lowering only for i1 stores"); 6661 6662 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6663 6664 SDLoc dl(Op); 6665 StoreSDNode *ST = cast<StoreSDNode>(Op); 6666 6667 SDValue Chain = ST->getChain(); 6668 SDValue BasePtr = ST->getBasePtr(); 6669 SDValue Value = ST->getValue(); 6670 MachineMemOperand *MMO = ST->getMemOperand(); 6671 6672 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6673 Value); 6674 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6675 } 6676 6677 // FIXME: Remove this once the ANDI glue bug is fixed: 6678 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6679 assert(Op.getValueType() == MVT::i1 && 6680 "Custom lowering only for i1 results"); 6681 6682 SDLoc DL(Op); 6683 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6684 Op.getOperand(0)); 6685 } 6686 6687 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6688 /// possible. 6689 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6690 // Not FP? Not a fsel. 6691 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6692 !Op.getOperand(2).getValueType().isFloatingPoint()) 6693 return Op; 6694 6695 // We might be able to do better than this under some circumstances, but in 6696 // general, fsel-based lowering of select is a finite-math-only optimization. 6697 // For more information, see section F.3 of the 2.06 ISA specification. 6698 if (!DAG.getTarget().Options.NoInfsFPMath || 6699 !DAG.getTarget().Options.NoNaNsFPMath) 6700 return Op; 6701 // TODO: Propagate flags from the select rather than global settings. 6702 SDNodeFlags Flags; 6703 Flags.setNoInfs(true); 6704 Flags.setNoNaNs(true); 6705 6706 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6707 6708 EVT ResVT = Op.getValueType(); 6709 EVT CmpVT = Op.getOperand(0).getValueType(); 6710 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6711 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6712 SDLoc dl(Op); 6713 6714 // If the RHS of the comparison is a 0.0, we don't need to do the 6715 // subtraction at all. 6716 SDValue Sel1; 6717 if (isFloatingPointZero(RHS)) 6718 switch (CC) { 6719 default: break; // SETUO etc aren't handled by fsel. 6720 case ISD::SETNE: 6721 std::swap(TV, FV); 6722 LLVM_FALLTHROUGH; 6723 case ISD::SETEQ: 6724 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6725 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6726 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6727 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6728 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6729 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6730 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6731 case ISD::SETULT: 6732 case ISD::SETLT: 6733 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6734 LLVM_FALLTHROUGH; 6735 case ISD::SETOGE: 6736 case ISD::SETGE: 6737 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6738 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6739 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6740 case ISD::SETUGT: 6741 case ISD::SETGT: 6742 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6743 LLVM_FALLTHROUGH; 6744 case ISD::SETOLE: 6745 case ISD::SETLE: 6746 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6747 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6748 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6749 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6750 } 6751 6752 SDValue Cmp; 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 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6760 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6761 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6762 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6763 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6764 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6765 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6766 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6767 case ISD::SETULT: 6768 case ISD::SETLT: 6769 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6770 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6771 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6772 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6773 case ISD::SETOGE: 6774 case ISD::SETGE: 6775 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6776 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6777 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6778 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6779 case ISD::SETUGT: 6780 case ISD::SETGT: 6781 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6782 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6783 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6784 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6785 case ISD::SETOLE: 6786 case ISD::SETLE: 6787 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6788 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6789 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6790 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6791 } 6792 return Op; 6793 } 6794 6795 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 6796 SelectionDAG &DAG, 6797 const SDLoc &dl) const { 6798 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6799 SDValue Src = Op.getOperand(0); 6800 if (Src.getValueType() == MVT::f32) 6801 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6802 6803 SDValue Tmp; 6804 switch (Op.getSimpleValueType().SimpleTy) { 6805 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6806 case MVT::i32: 6807 Tmp = DAG.getNode( 6808 Op.getOpcode() == ISD::FP_TO_SINT 6809 ? PPCISD::FCTIWZ 6810 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6811 dl, MVT::f64, Src); 6812 break; 6813 case MVT::i64: 6814 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6815 "i64 FP_TO_UINT is supported only with FPCVT"); 6816 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6817 PPCISD::FCTIDUZ, 6818 dl, MVT::f64, Src); 6819 break; 6820 } 6821 6822 // Convert the FP value to an int value through memory. 6823 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 6824 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 6825 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 6826 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 6827 MachinePointerInfo MPI = 6828 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 6829 6830 // Emit a store to the stack slot. 6831 SDValue Chain; 6832 if (i32Stack) { 6833 MachineFunction &MF = DAG.getMachineFunction(); 6834 MachineMemOperand *MMO = 6835 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 6836 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 6837 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 6838 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 6839 } else 6840 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 6841 6842 // Result is a load from the stack slot. If loading 4 bytes, make sure to 6843 // add in a bias on big endian. 6844 if (Op.getValueType() == MVT::i32 && !i32Stack) { 6845 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 6846 DAG.getConstant(4, dl, FIPtr.getValueType())); 6847 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 6848 } 6849 6850 RLI.Chain = Chain; 6851 RLI.Ptr = FIPtr; 6852 RLI.MPI = MPI; 6853 } 6854 6855 /// \brief Custom lowers floating point to integer conversions to use 6856 /// the direct move instructions available in ISA 2.07 to avoid the 6857 /// need for load/store combinations. 6858 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 6859 SelectionDAG &DAG, 6860 const SDLoc &dl) const { 6861 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6862 SDValue Src = Op.getOperand(0); 6863 6864 if (Src.getValueType() == MVT::f32) 6865 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6866 6867 SDValue Tmp; 6868 switch (Op.getSimpleValueType().SimpleTy) { 6869 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6870 case MVT::i32: 6871 Tmp = DAG.getNode( 6872 Op.getOpcode() == ISD::FP_TO_SINT 6873 ? PPCISD::FCTIWZ 6874 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6875 dl, MVT::f64, Src); 6876 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 6877 break; 6878 case MVT::i64: 6879 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6880 "i64 FP_TO_UINT is supported only with FPCVT"); 6881 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6882 PPCISD::FCTIDUZ, 6883 dl, MVT::f64, Src); 6884 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 6885 break; 6886 } 6887 return Tmp; 6888 } 6889 6890 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 6891 const SDLoc &dl) const { 6892 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 6893 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 6894 6895 ReuseLoadInfo RLI; 6896 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6897 6898 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 6899 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 6900 } 6901 6902 // We're trying to insert a regular store, S, and then a load, L. If the 6903 // incoming value, O, is a load, we might just be able to have our load use the 6904 // address used by O. However, we don't know if anything else will store to 6905 // that address before we can load from it. To prevent this situation, we need 6906 // to insert our load, L, into the chain as a peer of O. To do this, we give L 6907 // the same chain operand as O, we create a token factor from the chain results 6908 // of O and L, and we replace all uses of O's chain result with that token 6909 // factor (see spliceIntoChain below for this last part). 6910 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 6911 ReuseLoadInfo &RLI, 6912 SelectionDAG &DAG, 6913 ISD::LoadExtType ET) const { 6914 SDLoc dl(Op); 6915 if (ET == ISD::NON_EXTLOAD && 6916 (Op.getOpcode() == ISD::FP_TO_UINT || 6917 Op.getOpcode() == ISD::FP_TO_SINT) && 6918 isOperationLegalOrCustom(Op.getOpcode(), 6919 Op.getOperand(0).getValueType())) { 6920 6921 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6922 return true; 6923 } 6924 6925 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 6926 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 6927 LD->isNonTemporal()) 6928 return false; 6929 if (LD->getMemoryVT() != MemVT) 6930 return false; 6931 6932 RLI.Ptr = LD->getBasePtr(); 6933 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 6934 assert(LD->getAddressingMode() == ISD::PRE_INC && 6935 "Non-pre-inc AM on PPC?"); 6936 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 6937 LD->getOffset()); 6938 } 6939 6940 RLI.Chain = LD->getChain(); 6941 RLI.MPI = LD->getPointerInfo(); 6942 RLI.IsDereferenceable = LD->isDereferenceable(); 6943 RLI.IsInvariant = LD->isInvariant(); 6944 RLI.Alignment = LD->getAlignment(); 6945 RLI.AAInfo = LD->getAAInfo(); 6946 RLI.Ranges = LD->getRanges(); 6947 6948 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 6949 return true; 6950 } 6951 6952 // Given the head of the old chain, ResChain, insert a token factor containing 6953 // it and NewResChain, and make users of ResChain now be users of that token 6954 // factor. 6955 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 6956 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 6957 SDValue NewResChain, 6958 SelectionDAG &DAG) const { 6959 if (!ResChain) 6960 return; 6961 6962 SDLoc dl(NewResChain); 6963 6964 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6965 NewResChain, DAG.getUNDEF(MVT::Other)); 6966 assert(TF.getNode() != NewResChain.getNode() && 6967 "A new TF really is required here"); 6968 6969 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 6970 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 6971 } 6972 6973 /// \brief Analyze profitability of direct move 6974 /// prefer float load to int load plus direct move 6975 /// when there is no integer use of int load 6976 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 6977 SDNode *Origin = Op.getOperand(0).getNode(); 6978 if (Origin->getOpcode() != ISD::LOAD) 6979 return true; 6980 6981 // If there is no LXSIBZX/LXSIHZX, like Power8, 6982 // prefer direct move if the memory size is 1 or 2 bytes. 6983 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 6984 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 6985 return true; 6986 6987 for (SDNode::use_iterator UI = Origin->use_begin(), 6988 UE = Origin->use_end(); 6989 UI != UE; ++UI) { 6990 6991 // Only look at the users of the loaded value. 6992 if (UI.getUse().get().getResNo() != 0) 6993 continue; 6994 6995 if (UI->getOpcode() != ISD::SINT_TO_FP && 6996 UI->getOpcode() != ISD::UINT_TO_FP) 6997 return true; 6998 } 6999 7000 return false; 7001 } 7002 7003 /// \brief Custom lowers integer to floating point conversions to use 7004 /// the direct move instructions available in ISA 2.07 to avoid the 7005 /// need for load/store combinations. 7006 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7007 SelectionDAG &DAG, 7008 const SDLoc &dl) const { 7009 assert((Op.getValueType() == MVT::f32 || 7010 Op.getValueType() == MVT::f64) && 7011 "Invalid floating point type as target of conversion"); 7012 assert(Subtarget.hasFPCVT() && 7013 "Int to FP conversions with direct moves require FPCVT"); 7014 SDValue FP; 7015 SDValue Src = Op.getOperand(0); 7016 bool SinglePrec = Op.getValueType() == MVT::f32; 7017 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7018 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7019 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7020 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7021 7022 if (WordInt) { 7023 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7024 dl, MVT::f64, Src); 7025 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7026 } 7027 else { 7028 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7029 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7030 } 7031 7032 return FP; 7033 } 7034 7035 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7036 SelectionDAG &DAG) const { 7037 SDLoc dl(Op); 7038 7039 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7040 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7041 return SDValue(); 7042 7043 SDValue Value = Op.getOperand(0); 7044 // The values are now known to be -1 (false) or 1 (true). To convert this 7045 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7046 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7047 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7048 7049 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7050 7051 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7052 7053 if (Op.getValueType() != MVT::v4f64) 7054 Value = DAG.getNode(ISD::FP_ROUND, dl, 7055 Op.getValueType(), Value, 7056 DAG.getIntPtrConstant(1, dl)); 7057 return Value; 7058 } 7059 7060 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7061 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7062 return SDValue(); 7063 7064 if (Op.getOperand(0).getValueType() == MVT::i1) 7065 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7066 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7067 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7068 7069 // If we have direct moves, we can do all the conversion, skip the store/load 7070 // however, without FPCVT we can't do most conversions. 7071 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7072 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7073 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7074 7075 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7076 "UINT_TO_FP is supported only with FPCVT"); 7077 7078 // If we have FCFIDS, then use it when converting to single-precision. 7079 // Otherwise, convert to double-precision and then round. 7080 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7081 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7082 : PPCISD::FCFIDS) 7083 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7084 : PPCISD::FCFID); 7085 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7086 ? MVT::f32 7087 : MVT::f64; 7088 7089 if (Op.getOperand(0).getValueType() == MVT::i64) { 7090 SDValue SINT = Op.getOperand(0); 7091 // When converting to single-precision, we actually need to convert 7092 // to double-precision first and then round to single-precision. 7093 // To avoid double-rounding effects during that operation, we have 7094 // to prepare the input operand. Bits that might be truncated when 7095 // converting to double-precision are replaced by a bit that won't 7096 // be lost at this stage, but is below the single-precision rounding 7097 // position. 7098 // 7099 // However, if -enable-unsafe-fp-math is in effect, accept double 7100 // rounding to avoid the extra overhead. 7101 if (Op.getValueType() == MVT::f32 && 7102 !Subtarget.hasFPCVT() && 7103 !DAG.getTarget().Options.UnsafeFPMath) { 7104 7105 // Twiddle input to make sure the low 11 bits are zero. (If this 7106 // is the case, we are guaranteed the value will fit into the 53 bit 7107 // mantissa of an IEEE double-precision value without rounding.) 7108 // If any of those low 11 bits were not zero originally, make sure 7109 // bit 12 (value 2048) is set instead, so that the final rounding 7110 // to single-precision gets the correct result. 7111 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7112 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7113 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7114 Round, DAG.getConstant(2047, dl, MVT::i64)); 7115 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7116 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7117 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7118 7119 // However, we cannot use that value unconditionally: if the magnitude 7120 // of the input value is small, the bit-twiddling we did above might 7121 // end up visibly changing the output. Fortunately, in that case, we 7122 // don't need to twiddle bits since the original input will convert 7123 // exactly to double-precision floating-point already. Therefore, 7124 // construct a conditional to use the original value if the top 11 7125 // bits are all sign-bit copies, and use the rounded value computed 7126 // above otherwise. 7127 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7128 SINT, DAG.getConstant(53, dl, MVT::i32)); 7129 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7130 Cond, DAG.getConstant(1, dl, MVT::i64)); 7131 Cond = DAG.getSetCC(dl, MVT::i32, 7132 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7133 7134 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7135 } 7136 7137 ReuseLoadInfo RLI; 7138 SDValue Bits; 7139 7140 MachineFunction &MF = DAG.getMachineFunction(); 7141 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7142 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7143 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7144 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7145 } else if (Subtarget.hasLFIWAX() && 7146 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7147 MachineMemOperand *MMO = 7148 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7149 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7150 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7151 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7152 DAG.getVTList(MVT::f64, MVT::Other), 7153 Ops, MVT::i32, MMO); 7154 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7155 } else if (Subtarget.hasFPCVT() && 7156 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7157 MachineMemOperand *MMO = 7158 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7159 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7160 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7161 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7162 DAG.getVTList(MVT::f64, MVT::Other), 7163 Ops, MVT::i32, MMO); 7164 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7165 } else if (((Subtarget.hasLFIWAX() && 7166 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7167 (Subtarget.hasFPCVT() && 7168 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7169 SINT.getOperand(0).getValueType() == MVT::i32) { 7170 MachineFrameInfo &MFI = MF.getFrameInfo(); 7171 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7172 7173 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7174 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7175 7176 SDValue Store = 7177 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7178 MachinePointerInfo::getFixedStack( 7179 DAG.getMachineFunction(), FrameIdx)); 7180 7181 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7182 "Expected an i32 store"); 7183 7184 RLI.Ptr = FIdx; 7185 RLI.Chain = Store; 7186 RLI.MPI = 7187 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7188 RLI.Alignment = 4; 7189 7190 MachineMemOperand *MMO = 7191 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7192 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7193 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7194 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7195 PPCISD::LFIWZX : PPCISD::LFIWAX, 7196 dl, DAG.getVTList(MVT::f64, MVT::Other), 7197 Ops, MVT::i32, MMO); 7198 } else 7199 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7200 7201 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7202 7203 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7204 FP = DAG.getNode(ISD::FP_ROUND, dl, 7205 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7206 return FP; 7207 } 7208 7209 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7210 "Unhandled INT_TO_FP type in custom expander!"); 7211 // Since we only generate this in 64-bit mode, we can take advantage of 7212 // 64-bit registers. In particular, sign extend the input value into the 7213 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7214 // then lfd it and fcfid it. 7215 MachineFunction &MF = DAG.getMachineFunction(); 7216 MachineFrameInfo &MFI = MF.getFrameInfo(); 7217 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7218 7219 SDValue Ld; 7220 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7221 ReuseLoadInfo RLI; 7222 bool ReusingLoad; 7223 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7224 DAG))) { 7225 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7226 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7227 7228 SDValue Store = 7229 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7230 MachinePointerInfo::getFixedStack( 7231 DAG.getMachineFunction(), FrameIdx)); 7232 7233 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7234 "Expected an i32 store"); 7235 7236 RLI.Ptr = FIdx; 7237 RLI.Chain = Store; 7238 RLI.MPI = 7239 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7240 RLI.Alignment = 4; 7241 } 7242 7243 MachineMemOperand *MMO = 7244 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7245 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7246 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7247 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7248 PPCISD::LFIWZX : PPCISD::LFIWAX, 7249 dl, DAG.getVTList(MVT::f64, MVT::Other), 7250 Ops, MVT::i32, MMO); 7251 if (ReusingLoad) 7252 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7253 } else { 7254 assert(Subtarget.isPPC64() && 7255 "i32->FP without LFIWAX supported only on PPC64"); 7256 7257 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7258 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7259 7260 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7261 Op.getOperand(0)); 7262 7263 // STD the extended value into the stack slot. 7264 SDValue Store = DAG.getStore( 7265 DAG.getEntryNode(), dl, Ext64, FIdx, 7266 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7267 7268 // Load the value as a double. 7269 Ld = DAG.getLoad( 7270 MVT::f64, dl, Store, FIdx, 7271 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7272 } 7273 7274 // FCFID it and return it. 7275 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7276 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7277 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7278 DAG.getIntPtrConstant(0, dl)); 7279 return FP; 7280 } 7281 7282 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7283 SelectionDAG &DAG) const { 7284 SDLoc dl(Op); 7285 /* 7286 The rounding mode is in bits 30:31 of FPSR, and has the following 7287 settings: 7288 00 Round to nearest 7289 01 Round to 0 7290 10 Round to +inf 7291 11 Round to -inf 7292 7293 FLT_ROUNDS, on the other hand, expects the following: 7294 -1 Undefined 7295 0 Round to 0 7296 1 Round to nearest 7297 2 Round to +inf 7298 3 Round to -inf 7299 7300 To perform the conversion, we do: 7301 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7302 */ 7303 7304 MachineFunction &MF = DAG.getMachineFunction(); 7305 EVT VT = Op.getValueType(); 7306 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7307 7308 // Save FP Control Word to register 7309 EVT NodeTys[] = { 7310 MVT::f64, // return register 7311 MVT::Glue // unused in this context 7312 }; 7313 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7314 7315 // Save FP register to stack slot 7316 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7317 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7318 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7319 MachinePointerInfo()); 7320 7321 // Load FP Control Word from low 32 bits of stack slot. 7322 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7323 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7324 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7325 7326 // Transform as necessary 7327 SDValue CWD1 = 7328 DAG.getNode(ISD::AND, dl, MVT::i32, 7329 CWD, DAG.getConstant(3, dl, MVT::i32)); 7330 SDValue CWD2 = 7331 DAG.getNode(ISD::SRL, dl, MVT::i32, 7332 DAG.getNode(ISD::AND, dl, MVT::i32, 7333 DAG.getNode(ISD::XOR, dl, MVT::i32, 7334 CWD, DAG.getConstant(3, dl, MVT::i32)), 7335 DAG.getConstant(3, dl, MVT::i32)), 7336 DAG.getConstant(1, dl, MVT::i32)); 7337 7338 SDValue RetVal = 7339 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7340 7341 return DAG.getNode((VT.getSizeInBits() < 16 ? 7342 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7343 } 7344 7345 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7346 EVT VT = Op.getValueType(); 7347 unsigned BitWidth = VT.getSizeInBits(); 7348 SDLoc dl(Op); 7349 assert(Op.getNumOperands() == 3 && 7350 VT == Op.getOperand(1).getValueType() && 7351 "Unexpected SHL!"); 7352 7353 // Expand into a bunch of logical ops. Note that these ops 7354 // depend on the PPC behavior for oversized shift amounts. 7355 SDValue Lo = Op.getOperand(0); 7356 SDValue Hi = Op.getOperand(1); 7357 SDValue Amt = Op.getOperand(2); 7358 EVT AmtVT = Amt.getValueType(); 7359 7360 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7361 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7362 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7363 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7364 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7365 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7366 DAG.getConstant(-BitWidth, dl, AmtVT)); 7367 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7368 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7369 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7370 SDValue OutOps[] = { OutLo, OutHi }; 7371 return DAG.getMergeValues(OutOps, dl); 7372 } 7373 7374 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7375 EVT VT = Op.getValueType(); 7376 SDLoc dl(Op); 7377 unsigned BitWidth = VT.getSizeInBits(); 7378 assert(Op.getNumOperands() == 3 && 7379 VT == Op.getOperand(1).getValueType() && 7380 "Unexpected SRL!"); 7381 7382 // Expand into a bunch of logical ops. Note that these ops 7383 // depend on the PPC behavior for oversized shift amounts. 7384 SDValue Lo = Op.getOperand(0); 7385 SDValue Hi = Op.getOperand(1); 7386 SDValue Amt = Op.getOperand(2); 7387 EVT AmtVT = Amt.getValueType(); 7388 7389 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7390 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7391 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7392 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7393 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7394 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7395 DAG.getConstant(-BitWidth, dl, AmtVT)); 7396 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7397 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7398 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7399 SDValue OutOps[] = { OutLo, OutHi }; 7400 return DAG.getMergeValues(OutOps, dl); 7401 } 7402 7403 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7404 SDLoc dl(Op); 7405 EVT VT = Op.getValueType(); 7406 unsigned BitWidth = VT.getSizeInBits(); 7407 assert(Op.getNumOperands() == 3 && 7408 VT == Op.getOperand(1).getValueType() && 7409 "Unexpected SRA!"); 7410 7411 // Expand into a bunch of logical ops, followed by a select_cc. 7412 SDValue Lo = Op.getOperand(0); 7413 SDValue Hi = Op.getOperand(1); 7414 SDValue Amt = Op.getOperand(2); 7415 EVT AmtVT = Amt.getValueType(); 7416 7417 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7418 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7419 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7420 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7421 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7422 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7423 DAG.getConstant(-BitWidth, dl, AmtVT)); 7424 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7425 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7426 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7427 Tmp4, Tmp6, ISD::SETLE); 7428 SDValue OutOps[] = { OutLo, OutHi }; 7429 return DAG.getMergeValues(OutOps, dl); 7430 } 7431 7432 //===----------------------------------------------------------------------===// 7433 // Vector related lowering. 7434 // 7435 7436 /// BuildSplatI - Build a canonical splati of Val with an element size of 7437 /// SplatSize. Cast the result to VT. 7438 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7439 SelectionDAG &DAG, const SDLoc &dl) { 7440 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7441 7442 static const MVT VTys[] = { // canonical VT to use for each size. 7443 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7444 }; 7445 7446 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7447 7448 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7449 if (Val == -1) 7450 SplatSize = 1; 7451 7452 EVT CanonicalVT = VTys[SplatSize-1]; 7453 7454 // Build a canonical splat for this value. 7455 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7456 } 7457 7458 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7459 /// specified intrinsic ID. 7460 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7461 const SDLoc &dl, EVT DestVT = MVT::Other) { 7462 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7463 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7464 DAG.getConstant(IID, dl, MVT::i32), Op); 7465 } 7466 7467 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7468 /// specified intrinsic ID. 7469 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7470 SelectionDAG &DAG, const SDLoc &dl, 7471 EVT DestVT = MVT::Other) { 7472 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7473 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7474 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7475 } 7476 7477 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7478 /// specified intrinsic ID. 7479 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7480 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7481 EVT DestVT = MVT::Other) { 7482 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7483 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7484 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7485 } 7486 7487 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7488 /// amount. The result has the specified value type. 7489 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7490 SelectionDAG &DAG, const SDLoc &dl) { 7491 // Force LHS/RHS to be the right type. 7492 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7493 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7494 7495 int Ops[16]; 7496 for (unsigned i = 0; i != 16; ++i) 7497 Ops[i] = i + Amt; 7498 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7499 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7500 } 7501 7502 /// Do we have an efficient pattern in a .td file for this node? 7503 /// 7504 /// \param V - pointer to the BuildVectorSDNode being matched 7505 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7506 /// 7507 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7508 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7509 /// the opposite is true (expansion is beneficial) are: 7510 /// - The node builds a vector out of integers that are not 32 or 64-bits 7511 /// - The node builds a vector out of constants 7512 /// - The node is a "load-and-splat" 7513 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7514 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7515 bool HasDirectMove, 7516 bool HasP8Vector) { 7517 EVT VecVT = V->getValueType(0); 7518 bool RightType = VecVT == MVT::v2f64 || 7519 (HasP8Vector && VecVT == MVT::v4f32) || 7520 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7521 if (!RightType) 7522 return false; 7523 7524 bool IsSplat = true; 7525 bool IsLoad = false; 7526 SDValue Op0 = V->getOperand(0); 7527 7528 // This function is called in a block that confirms the node is not a constant 7529 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7530 // different constants. 7531 if (V->isConstant()) 7532 return false; 7533 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7534 if (V->getOperand(i).isUndef()) 7535 return false; 7536 // We want to expand nodes that represent load-and-splat even if the 7537 // loaded value is a floating point truncation or conversion to int. 7538 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7539 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7540 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7541 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7542 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7543 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7544 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7545 IsLoad = true; 7546 // If the operands are different or the input is not a load and has more 7547 // uses than just this BV node, then it isn't a splat. 7548 if (V->getOperand(i) != Op0 || 7549 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7550 IsSplat = false; 7551 } 7552 return !(IsSplat && IsLoad); 7553 } 7554 7555 // If this is a case we can't handle, return null and let the default 7556 // expansion code take care of it. If we CAN select this case, and if it 7557 // selects to a single instruction, return Op. Otherwise, if we can codegen 7558 // this case more efficiently than a constant pool load, lower it to the 7559 // sequence of ops that should be used. 7560 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7561 SelectionDAG &DAG) const { 7562 SDLoc dl(Op); 7563 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7564 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7565 7566 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7567 // We first build an i32 vector, load it into a QPX register, 7568 // then convert it to a floating-point vector and compare it 7569 // to a zero vector to get the boolean result. 7570 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7571 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7572 MachinePointerInfo PtrInfo = 7573 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7574 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7575 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7576 7577 assert(BVN->getNumOperands() == 4 && 7578 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7579 7580 bool IsConst = true; 7581 for (unsigned i = 0; i < 4; ++i) { 7582 if (BVN->getOperand(i).isUndef()) continue; 7583 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7584 IsConst = false; 7585 break; 7586 } 7587 } 7588 7589 if (IsConst) { 7590 Constant *One = 7591 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7592 Constant *NegOne = 7593 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7594 7595 Constant *CV[4]; 7596 for (unsigned i = 0; i < 4; ++i) { 7597 if (BVN->getOperand(i).isUndef()) 7598 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7599 else if (isNullConstant(BVN->getOperand(i))) 7600 CV[i] = NegOne; 7601 else 7602 CV[i] = One; 7603 } 7604 7605 Constant *CP = ConstantVector::get(CV); 7606 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7607 16 /* alignment */); 7608 7609 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7610 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7611 return DAG.getMemIntrinsicNode( 7612 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7613 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7614 } 7615 7616 SmallVector<SDValue, 4> Stores; 7617 for (unsigned i = 0; i < 4; ++i) { 7618 if (BVN->getOperand(i).isUndef()) continue; 7619 7620 unsigned Offset = 4*i; 7621 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7622 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7623 7624 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7625 if (StoreSize > 4) { 7626 Stores.push_back( 7627 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7628 PtrInfo.getWithOffset(Offset), MVT::i32)); 7629 } else { 7630 SDValue StoreValue = BVN->getOperand(i); 7631 if (StoreSize < 4) 7632 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7633 7634 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7635 PtrInfo.getWithOffset(Offset))); 7636 } 7637 } 7638 7639 SDValue StoreChain; 7640 if (!Stores.empty()) 7641 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7642 else 7643 StoreChain = DAG.getEntryNode(); 7644 7645 // Now load from v4i32 into the QPX register; this will extend it to 7646 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7647 // is typed as v4f64 because the QPX register integer states are not 7648 // explicitly represented. 7649 7650 SDValue Ops[] = {StoreChain, 7651 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7652 FIdx}; 7653 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7654 7655 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 7656 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7657 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7658 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 7659 LoadedVect); 7660 7661 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 7662 7663 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 7664 } 7665 7666 // All other QPX vectors are handled by generic code. 7667 if (Subtarget.hasQPX()) 7668 return SDValue(); 7669 7670 // Check if this is a splat of a constant value. 7671 APInt APSplatBits, APSplatUndef; 7672 unsigned SplatBitSize; 7673 bool HasAnyUndefs; 7674 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 7675 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 7676 SplatBitSize > 32) { 7677 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 7678 // lowered to VSX instructions under certain conditions. 7679 // Without VSX, there is no pattern more efficient than expanding the node. 7680 if (Subtarget.hasVSX() && 7681 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 7682 Subtarget.hasP8Vector())) 7683 return Op; 7684 return SDValue(); 7685 } 7686 7687 unsigned SplatBits = APSplatBits.getZExtValue(); 7688 unsigned SplatUndef = APSplatUndef.getZExtValue(); 7689 unsigned SplatSize = SplatBitSize / 8; 7690 7691 // First, handle single instruction cases. 7692 7693 // All zeros? 7694 if (SplatBits == 0) { 7695 // Canonicalize all zero vectors to be v4i32. 7696 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 7697 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 7698 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 7699 } 7700 return Op; 7701 } 7702 7703 // We have XXSPLTIB for constant splats one byte wide 7704 if (Subtarget.hasP9Vector() && SplatSize == 1) { 7705 // This is a splat of 1-byte elements with some elements potentially undef. 7706 // Rather than trying to match undef in the SDAG patterns, ensure that all 7707 // elements are the same constant. 7708 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 7709 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 7710 dl, MVT::i32)); 7711 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 7712 if (Op.getValueType() != MVT::v16i8) 7713 return DAG.getBitcast(Op.getValueType(), NewBV); 7714 return NewBV; 7715 } 7716 7717 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 7718 // detect that constant splats like v8i16: 0xABAB are really just splats 7719 // of a 1-byte constant. In this case, we need to convert the node to a 7720 // splat of v16i8 and a bitcast. 7721 if (Op.getValueType() != MVT::v16i8) 7722 return DAG.getBitcast(Op.getValueType(), 7723 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 7724 7725 return Op; 7726 } 7727 7728 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 7729 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 7730 (32-SplatBitSize)); 7731 if (SextVal >= -16 && SextVal <= 15) 7732 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 7733 7734 // Two instruction sequences. 7735 7736 // If this value is in the range [-32,30] and is even, use: 7737 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 7738 // If this value is in the range [17,31] and is odd, use: 7739 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 7740 // If this value is in the range [-31,-17] and is odd, use: 7741 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 7742 // Note the last two are three-instruction sequences. 7743 if (SextVal >= -32 && SextVal <= 31) { 7744 // To avoid having these optimizations undone by constant folding, 7745 // we convert to a pseudo that will be expanded later into one of 7746 // the above forms. 7747 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 7748 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 7749 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 7750 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 7751 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 7752 if (VT == Op.getValueType()) 7753 return RetVal; 7754 else 7755 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 7756 } 7757 7758 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 7759 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 7760 // for fneg/fabs. 7761 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 7762 // Make -1 and vspltisw -1: 7763 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 7764 7765 // Make the VSLW intrinsic, computing 0x8000_0000. 7766 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 7767 OnesV, DAG, dl); 7768 7769 // xor by OnesV to invert it. 7770 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 7771 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7772 } 7773 7774 // Check to see if this is a wide variety of vsplti*, binop self cases. 7775 static const signed char SplatCsts[] = { 7776 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 7777 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 7778 }; 7779 7780 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 7781 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 7782 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 7783 int i = SplatCsts[idx]; 7784 7785 // Figure out what shift amount will be used by altivec if shifted by i in 7786 // this splat size. 7787 unsigned TypeShiftAmt = i & (SplatBitSize-1); 7788 7789 // vsplti + shl self. 7790 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 7791 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7792 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7793 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 7794 Intrinsic::ppc_altivec_vslw 7795 }; 7796 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7797 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7798 } 7799 7800 // vsplti + srl self. 7801 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7802 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7803 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7804 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 7805 Intrinsic::ppc_altivec_vsrw 7806 }; 7807 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7808 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7809 } 7810 7811 // vsplti + sra self. 7812 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7813 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7814 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7815 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 7816 Intrinsic::ppc_altivec_vsraw 7817 }; 7818 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7819 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7820 } 7821 7822 // vsplti + rol self. 7823 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 7824 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 7825 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7826 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7827 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 7828 Intrinsic::ppc_altivec_vrlw 7829 }; 7830 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7831 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7832 } 7833 7834 // t = vsplti c, result = vsldoi t, t, 1 7835 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 7836 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7837 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 7838 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7839 } 7840 // t = vsplti c, result = vsldoi t, t, 2 7841 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 7842 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7843 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 7844 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7845 } 7846 // t = vsplti c, result = vsldoi t, t, 3 7847 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 7848 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7849 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 7850 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7851 } 7852 } 7853 7854 return SDValue(); 7855 } 7856 7857 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7858 /// the specified operations to build the shuffle. 7859 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7860 SDValue RHS, SelectionDAG &DAG, 7861 const SDLoc &dl) { 7862 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7863 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7864 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7865 7866 enum { 7867 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7868 OP_VMRGHW, 7869 OP_VMRGLW, 7870 OP_VSPLTISW0, 7871 OP_VSPLTISW1, 7872 OP_VSPLTISW2, 7873 OP_VSPLTISW3, 7874 OP_VSLDOI4, 7875 OP_VSLDOI8, 7876 OP_VSLDOI12 7877 }; 7878 7879 if (OpNum == OP_COPY) { 7880 if (LHSID == (1*9+2)*9+3) return LHS; 7881 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7882 return RHS; 7883 } 7884 7885 SDValue OpLHS, OpRHS; 7886 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7887 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7888 7889 int ShufIdxs[16]; 7890 switch (OpNum) { 7891 default: llvm_unreachable("Unknown i32 permute!"); 7892 case OP_VMRGHW: 7893 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 7894 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 7895 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 7896 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 7897 break; 7898 case OP_VMRGLW: 7899 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 7900 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 7901 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 7902 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 7903 break; 7904 case OP_VSPLTISW0: 7905 for (unsigned i = 0; i != 16; ++i) 7906 ShufIdxs[i] = (i&3)+0; 7907 break; 7908 case OP_VSPLTISW1: 7909 for (unsigned i = 0; i != 16; ++i) 7910 ShufIdxs[i] = (i&3)+4; 7911 break; 7912 case OP_VSPLTISW2: 7913 for (unsigned i = 0; i != 16; ++i) 7914 ShufIdxs[i] = (i&3)+8; 7915 break; 7916 case OP_VSPLTISW3: 7917 for (unsigned i = 0; i != 16; ++i) 7918 ShufIdxs[i] = (i&3)+12; 7919 break; 7920 case OP_VSLDOI4: 7921 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 7922 case OP_VSLDOI8: 7923 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 7924 case OP_VSLDOI12: 7925 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 7926 } 7927 EVT VT = OpLHS.getValueType(); 7928 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 7929 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 7930 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 7931 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7932 } 7933 7934 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 7935 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 7936 /// SDValue. 7937 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 7938 SelectionDAG &DAG) const { 7939 const unsigned BytesInVector = 16; 7940 bool IsLE = Subtarget.isLittleEndian(); 7941 SDLoc dl(N); 7942 SDValue V1 = N->getOperand(0); 7943 SDValue V2 = N->getOperand(1); 7944 unsigned ShiftElts = 0, InsertAtByte = 0; 7945 bool Swap = false; 7946 7947 // Shifts required to get the byte we want at element 7. 7948 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 7949 0, 15, 14, 13, 12, 11, 10, 9}; 7950 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 7951 1, 2, 3, 4, 5, 6, 7, 8}; 7952 7953 ArrayRef<int> Mask = N->getMask(); 7954 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 7955 7956 // For each mask element, find out if we're just inserting something 7957 // from V2 into V1 or vice versa. 7958 // Possible permutations inserting an element from V2 into V1: 7959 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 7960 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 7961 // ... 7962 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 7963 // Inserting from V1 into V2 will be similar, except mask range will be 7964 // [16,31]. 7965 7966 bool FoundCandidate = false; 7967 // If both vector operands for the shuffle are the same vector, the mask 7968 // will contain only elements from the first one and the second one will be 7969 // undef. 7970 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 7971 // Go through the mask of half-words to find an element that's being moved 7972 // from one vector to the other. 7973 for (unsigned i = 0; i < BytesInVector; ++i) { 7974 unsigned CurrentElement = Mask[i]; 7975 // If 2nd operand is undefined, we should only look for element 7 in the 7976 // Mask. 7977 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 7978 continue; 7979 7980 bool OtherElementsInOrder = true; 7981 // Examine the other elements in the Mask to see if they're in original 7982 // order. 7983 for (unsigned j = 0; j < BytesInVector; ++j) { 7984 if (j == i) 7985 continue; 7986 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 7987 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 7988 // in which we always assume we're always picking from the 1st operand. 7989 int MaskOffset = 7990 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 7991 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 7992 OtherElementsInOrder = false; 7993 break; 7994 } 7995 } 7996 // If other elements are in original order, we record the number of shifts 7997 // we need to get the element we want into element 7. Also record which byte 7998 // in the vector we should insert into. 7999 if (OtherElementsInOrder) { 8000 // If 2nd operand is undefined, we assume no shifts and no swapping. 8001 if (V2.isUndef()) { 8002 ShiftElts = 0; 8003 Swap = false; 8004 } else { 8005 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8006 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8007 : BigEndianShifts[CurrentElement & 0xF]; 8008 Swap = CurrentElement < BytesInVector; 8009 } 8010 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8011 FoundCandidate = true; 8012 break; 8013 } 8014 } 8015 8016 if (!FoundCandidate) 8017 return SDValue(); 8018 8019 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8020 // optionally with VECSHL if shift is required. 8021 if (Swap) 8022 std::swap(V1, V2); 8023 if (V2.isUndef()) 8024 V2 = V1; 8025 if (ShiftElts) { 8026 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8027 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8028 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8029 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8030 } 8031 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8032 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8033 } 8034 8035 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8036 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8037 /// SDValue. 8038 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8039 SelectionDAG &DAG) const { 8040 const unsigned NumHalfWords = 8; 8041 const unsigned BytesInVector = NumHalfWords * 2; 8042 // Check that the shuffle is on half-words. 8043 if (!isNByteElemShuffleMask(N, 2, 1)) 8044 return SDValue(); 8045 8046 bool IsLE = Subtarget.isLittleEndian(); 8047 SDLoc dl(N); 8048 SDValue V1 = N->getOperand(0); 8049 SDValue V2 = N->getOperand(1); 8050 unsigned ShiftElts = 0, InsertAtByte = 0; 8051 bool Swap = false; 8052 8053 // Shifts required to get the half-word we want at element 3. 8054 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8055 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8056 8057 uint32_t Mask = 0; 8058 uint32_t OriginalOrderLow = 0x1234567; 8059 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8060 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8061 // 32-bit space, only need 4-bit nibbles per element. 8062 for (unsigned i = 0; i < NumHalfWords; ++i) { 8063 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8064 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8065 } 8066 8067 // For each mask element, find out if we're just inserting something 8068 // from V2 into V1 or vice versa. Possible permutations inserting an element 8069 // from V2 into V1: 8070 // X, 1, 2, 3, 4, 5, 6, 7 8071 // 0, X, 2, 3, 4, 5, 6, 7 8072 // 0, 1, X, 3, 4, 5, 6, 7 8073 // 0, 1, 2, X, 4, 5, 6, 7 8074 // 0, 1, 2, 3, X, 5, 6, 7 8075 // 0, 1, 2, 3, 4, X, 6, 7 8076 // 0, 1, 2, 3, 4, 5, X, 7 8077 // 0, 1, 2, 3, 4, 5, 6, X 8078 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8079 8080 bool FoundCandidate = false; 8081 // Go through the mask of half-words to find an element that's being moved 8082 // from one vector to the other. 8083 for (unsigned i = 0; i < NumHalfWords; ++i) { 8084 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8085 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8086 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8087 uint32_t TargetOrder = 0x0; 8088 8089 // If both vector operands for the shuffle are the same vector, the mask 8090 // will contain only elements from the first one and the second one will be 8091 // undef. 8092 if (V2.isUndef()) { 8093 ShiftElts = 0; 8094 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8095 TargetOrder = OriginalOrderLow; 8096 Swap = false; 8097 // Skip if not the correct element or mask of other elements don't equal 8098 // to our expected order. 8099 if (MaskOneElt == VINSERTHSrcElem && 8100 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8101 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8102 FoundCandidate = true; 8103 break; 8104 } 8105 } else { // If both operands are defined. 8106 // Target order is [8,15] if the current mask is between [0,7]. 8107 TargetOrder = 8108 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8109 // Skip if mask of other elements don't equal our expected order. 8110 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8111 // We only need the last 3 bits for the number of shifts. 8112 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8113 : BigEndianShifts[MaskOneElt & 0x7]; 8114 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8115 Swap = MaskOneElt < NumHalfWords; 8116 FoundCandidate = true; 8117 break; 8118 } 8119 } 8120 } 8121 8122 if (!FoundCandidate) 8123 return SDValue(); 8124 8125 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8126 // optionally with VECSHL if shift is required. 8127 if (Swap) 8128 std::swap(V1, V2); 8129 if (V2.isUndef()) 8130 V2 = V1; 8131 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8132 if (ShiftElts) { 8133 // Double ShiftElts because we're left shifting on v16i8 type. 8134 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8135 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8136 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8137 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8138 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8139 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8140 } 8141 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8142 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8143 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8144 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8145 } 8146 8147 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8148 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8149 /// return the code it can be lowered into. Worst case, it can always be 8150 /// lowered into a vperm. 8151 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8152 SelectionDAG &DAG) const { 8153 SDLoc dl(Op); 8154 SDValue V1 = Op.getOperand(0); 8155 SDValue V2 = Op.getOperand(1); 8156 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8157 EVT VT = Op.getValueType(); 8158 bool isLittleEndian = Subtarget.isLittleEndian(); 8159 8160 unsigned ShiftElts, InsertAtByte; 8161 bool Swap = false; 8162 if (Subtarget.hasP9Vector() && 8163 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8164 isLittleEndian)) { 8165 if (Swap) 8166 std::swap(V1, V2); 8167 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8168 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8169 if (ShiftElts) { 8170 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8171 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8172 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8173 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8174 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8175 } 8176 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8177 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8178 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8179 } 8180 8181 if (Subtarget.hasP9Altivec()) { 8182 SDValue NewISDNode; 8183 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8184 return NewISDNode; 8185 8186 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8187 return NewISDNode; 8188 } 8189 8190 if (Subtarget.hasVSX() && 8191 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8192 if (Swap) 8193 std::swap(V1, V2); 8194 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8195 SDValue Conv2 = 8196 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8197 8198 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8199 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8200 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8201 } 8202 8203 if (Subtarget.hasVSX() && 8204 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8205 if (Swap) 8206 std::swap(V1, V2); 8207 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8208 SDValue Conv2 = 8209 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8210 8211 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8212 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8213 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8214 } 8215 8216 if (Subtarget.hasP9Vector()) { 8217 if (PPC::isXXBRHShuffleMask(SVOp)) { 8218 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8219 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8220 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8221 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8222 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8223 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8224 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8225 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8226 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8227 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8228 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8229 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8230 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8231 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8232 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8233 } 8234 } 8235 8236 if (Subtarget.hasVSX()) { 8237 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8238 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8239 8240 // If the source for the shuffle is a scalar_to_vector that came from a 8241 // 32-bit load, it will have used LXVWSX so we don't need to splat again. 8242 if (Subtarget.hasP9Vector() && 8243 ((isLittleEndian && SplatIdx == 3) || 8244 (!isLittleEndian && SplatIdx == 0))) { 8245 SDValue Src = V1.getOperand(0); 8246 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR && 8247 Src.getOperand(0).getOpcode() == ISD::LOAD && 8248 Src.getOperand(0).hasOneUse()) 8249 return V1; 8250 } 8251 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8252 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8253 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8254 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8255 } 8256 8257 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8258 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8259 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8260 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8261 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8262 } 8263 } 8264 8265 if (Subtarget.hasQPX()) { 8266 if (VT.getVectorNumElements() != 4) 8267 return SDValue(); 8268 8269 if (V2.isUndef()) V2 = V1; 8270 8271 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8272 if (AlignIdx != -1) { 8273 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8274 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8275 } else if (SVOp->isSplat()) { 8276 int SplatIdx = SVOp->getSplatIndex(); 8277 if (SplatIdx >= 4) { 8278 std::swap(V1, V2); 8279 SplatIdx -= 4; 8280 } 8281 8282 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8283 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8284 } 8285 8286 // Lower this into a qvgpci/qvfperm pair. 8287 8288 // Compute the qvgpci literal 8289 unsigned idx = 0; 8290 for (unsigned i = 0; i < 4; ++i) { 8291 int m = SVOp->getMaskElt(i); 8292 unsigned mm = m >= 0 ? (unsigned) m : i; 8293 idx |= mm << (3-i)*3; 8294 } 8295 8296 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8297 DAG.getConstant(idx, dl, MVT::i32)); 8298 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8299 } 8300 8301 // Cases that are handled by instructions that take permute immediates 8302 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8303 // selected by the instruction selector. 8304 if (V2.isUndef()) { 8305 if (PPC::isSplatShuffleMask(SVOp, 1) || 8306 PPC::isSplatShuffleMask(SVOp, 2) || 8307 PPC::isSplatShuffleMask(SVOp, 4) || 8308 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8309 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8310 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8311 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8312 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8313 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8314 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8315 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8316 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8317 (Subtarget.hasP8Altivec() && ( 8318 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8319 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8320 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8321 return Op; 8322 } 8323 } 8324 8325 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8326 // and produce a fixed permutation. If any of these match, do not lower to 8327 // VPERM. 8328 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8329 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8330 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8331 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8332 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8333 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8334 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8335 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8336 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8337 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8338 (Subtarget.hasP8Altivec() && ( 8339 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8340 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8341 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8342 return Op; 8343 8344 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8345 // perfect shuffle table to emit an optimal matching sequence. 8346 ArrayRef<int> PermMask = SVOp->getMask(); 8347 8348 unsigned PFIndexes[4]; 8349 bool isFourElementShuffle = true; 8350 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8351 unsigned EltNo = 8; // Start out undef. 8352 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8353 if (PermMask[i*4+j] < 0) 8354 continue; // Undef, ignore it. 8355 8356 unsigned ByteSource = PermMask[i*4+j]; 8357 if ((ByteSource & 3) != j) { 8358 isFourElementShuffle = false; 8359 break; 8360 } 8361 8362 if (EltNo == 8) { 8363 EltNo = ByteSource/4; 8364 } else if (EltNo != ByteSource/4) { 8365 isFourElementShuffle = false; 8366 break; 8367 } 8368 } 8369 PFIndexes[i] = EltNo; 8370 } 8371 8372 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8373 // perfect shuffle vector to determine if it is cost effective to do this as 8374 // discrete instructions, or whether we should use a vperm. 8375 // For now, we skip this for little endian until such time as we have a 8376 // little-endian perfect shuffle table. 8377 if (isFourElementShuffle && !isLittleEndian) { 8378 // Compute the index in the perfect shuffle table. 8379 unsigned PFTableIndex = 8380 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8381 8382 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8383 unsigned Cost = (PFEntry >> 30); 8384 8385 // Determining when to avoid vperm is tricky. Many things affect the cost 8386 // of vperm, particularly how many times the perm mask needs to be computed. 8387 // For example, if the perm mask can be hoisted out of a loop or is already 8388 // used (perhaps because there are multiple permutes with the same shuffle 8389 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8390 // the loop requires an extra register. 8391 // 8392 // As a compromise, we only emit discrete instructions if the shuffle can be 8393 // generated in 3 or fewer operations. When we have loop information 8394 // available, if this block is within a loop, we should avoid using vperm 8395 // for 3-operation perms and use a constant pool load instead. 8396 if (Cost < 3) 8397 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8398 } 8399 8400 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8401 // vector that will get spilled to the constant pool. 8402 if (V2.isUndef()) V2 = V1; 8403 8404 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8405 // that it is in input element units, not in bytes. Convert now. 8406 8407 // For little endian, the order of the input vectors is reversed, and 8408 // the permutation mask is complemented with respect to 31. This is 8409 // necessary to produce proper semantics with the big-endian-biased vperm 8410 // instruction. 8411 EVT EltVT = V1.getValueType().getVectorElementType(); 8412 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8413 8414 SmallVector<SDValue, 16> ResultMask; 8415 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8416 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8417 8418 for (unsigned j = 0; j != BytesPerElement; ++j) 8419 if (isLittleEndian) 8420 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8421 dl, MVT::i32)); 8422 else 8423 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8424 MVT::i32)); 8425 } 8426 8427 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8428 if (isLittleEndian) 8429 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8430 V2, V1, VPermMask); 8431 else 8432 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8433 V1, V2, VPermMask); 8434 } 8435 8436 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 8437 /// vector comparison. If it is, return true and fill in Opc/isDot with 8438 /// information about the intrinsic. 8439 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 8440 bool &isDot, const PPCSubtarget &Subtarget) { 8441 unsigned IntrinsicID = 8442 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 8443 CompareOpc = -1; 8444 isDot = false; 8445 switch (IntrinsicID) { 8446 default: 8447 return false; 8448 // Comparison predicates. 8449 case Intrinsic::ppc_altivec_vcmpbfp_p: 8450 CompareOpc = 966; 8451 isDot = true; 8452 break; 8453 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8454 CompareOpc = 198; 8455 isDot = true; 8456 break; 8457 case Intrinsic::ppc_altivec_vcmpequb_p: 8458 CompareOpc = 6; 8459 isDot = true; 8460 break; 8461 case Intrinsic::ppc_altivec_vcmpequh_p: 8462 CompareOpc = 70; 8463 isDot = true; 8464 break; 8465 case Intrinsic::ppc_altivec_vcmpequw_p: 8466 CompareOpc = 134; 8467 isDot = true; 8468 break; 8469 case Intrinsic::ppc_altivec_vcmpequd_p: 8470 if (Subtarget.hasP8Altivec()) { 8471 CompareOpc = 199; 8472 isDot = true; 8473 } else 8474 return false; 8475 break; 8476 case Intrinsic::ppc_altivec_vcmpneb_p: 8477 case Intrinsic::ppc_altivec_vcmpneh_p: 8478 case Intrinsic::ppc_altivec_vcmpnew_p: 8479 case Intrinsic::ppc_altivec_vcmpnezb_p: 8480 case Intrinsic::ppc_altivec_vcmpnezh_p: 8481 case Intrinsic::ppc_altivec_vcmpnezw_p: 8482 if (Subtarget.hasP9Altivec()) { 8483 switch (IntrinsicID) { 8484 default: 8485 llvm_unreachable("Unknown comparison intrinsic."); 8486 case Intrinsic::ppc_altivec_vcmpneb_p: 8487 CompareOpc = 7; 8488 break; 8489 case Intrinsic::ppc_altivec_vcmpneh_p: 8490 CompareOpc = 71; 8491 break; 8492 case Intrinsic::ppc_altivec_vcmpnew_p: 8493 CompareOpc = 135; 8494 break; 8495 case Intrinsic::ppc_altivec_vcmpnezb_p: 8496 CompareOpc = 263; 8497 break; 8498 case Intrinsic::ppc_altivec_vcmpnezh_p: 8499 CompareOpc = 327; 8500 break; 8501 case Intrinsic::ppc_altivec_vcmpnezw_p: 8502 CompareOpc = 391; 8503 break; 8504 } 8505 isDot = true; 8506 } else 8507 return false; 8508 break; 8509 case Intrinsic::ppc_altivec_vcmpgefp_p: 8510 CompareOpc = 454; 8511 isDot = true; 8512 break; 8513 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8514 CompareOpc = 710; 8515 isDot = true; 8516 break; 8517 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8518 CompareOpc = 774; 8519 isDot = true; 8520 break; 8521 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8522 CompareOpc = 838; 8523 isDot = true; 8524 break; 8525 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8526 CompareOpc = 902; 8527 isDot = true; 8528 break; 8529 case Intrinsic::ppc_altivec_vcmpgtsd_p: 8530 if (Subtarget.hasP8Altivec()) { 8531 CompareOpc = 967; 8532 isDot = true; 8533 } else 8534 return false; 8535 break; 8536 case Intrinsic::ppc_altivec_vcmpgtub_p: 8537 CompareOpc = 518; 8538 isDot = true; 8539 break; 8540 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8541 CompareOpc = 582; 8542 isDot = true; 8543 break; 8544 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8545 CompareOpc = 646; 8546 isDot = true; 8547 break; 8548 case Intrinsic::ppc_altivec_vcmpgtud_p: 8549 if (Subtarget.hasP8Altivec()) { 8550 CompareOpc = 711; 8551 isDot = true; 8552 } else 8553 return false; 8554 break; 8555 8556 // VSX predicate comparisons use the same infrastructure 8557 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8558 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8559 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8560 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8561 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8562 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8563 if (Subtarget.hasVSX()) { 8564 switch (IntrinsicID) { 8565 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8566 CompareOpc = 99; 8567 break; 8568 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8569 CompareOpc = 115; 8570 break; 8571 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8572 CompareOpc = 107; 8573 break; 8574 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8575 CompareOpc = 67; 8576 break; 8577 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8578 CompareOpc = 83; 8579 break; 8580 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8581 CompareOpc = 75; 8582 break; 8583 } 8584 isDot = true; 8585 } else 8586 return false; 8587 break; 8588 8589 // Normal Comparisons. 8590 case Intrinsic::ppc_altivec_vcmpbfp: 8591 CompareOpc = 966; 8592 break; 8593 case Intrinsic::ppc_altivec_vcmpeqfp: 8594 CompareOpc = 198; 8595 break; 8596 case Intrinsic::ppc_altivec_vcmpequb: 8597 CompareOpc = 6; 8598 break; 8599 case Intrinsic::ppc_altivec_vcmpequh: 8600 CompareOpc = 70; 8601 break; 8602 case Intrinsic::ppc_altivec_vcmpequw: 8603 CompareOpc = 134; 8604 break; 8605 case Intrinsic::ppc_altivec_vcmpequd: 8606 if (Subtarget.hasP8Altivec()) 8607 CompareOpc = 199; 8608 else 8609 return false; 8610 break; 8611 case Intrinsic::ppc_altivec_vcmpneb: 8612 case Intrinsic::ppc_altivec_vcmpneh: 8613 case Intrinsic::ppc_altivec_vcmpnew: 8614 case Intrinsic::ppc_altivec_vcmpnezb: 8615 case Intrinsic::ppc_altivec_vcmpnezh: 8616 case Intrinsic::ppc_altivec_vcmpnezw: 8617 if (Subtarget.hasP9Altivec()) 8618 switch (IntrinsicID) { 8619 default: 8620 llvm_unreachable("Unknown comparison intrinsic."); 8621 case Intrinsic::ppc_altivec_vcmpneb: 8622 CompareOpc = 7; 8623 break; 8624 case Intrinsic::ppc_altivec_vcmpneh: 8625 CompareOpc = 71; 8626 break; 8627 case Intrinsic::ppc_altivec_vcmpnew: 8628 CompareOpc = 135; 8629 break; 8630 case Intrinsic::ppc_altivec_vcmpnezb: 8631 CompareOpc = 263; 8632 break; 8633 case Intrinsic::ppc_altivec_vcmpnezh: 8634 CompareOpc = 327; 8635 break; 8636 case Intrinsic::ppc_altivec_vcmpnezw: 8637 CompareOpc = 391; 8638 break; 8639 } 8640 else 8641 return false; 8642 break; 8643 case Intrinsic::ppc_altivec_vcmpgefp: 8644 CompareOpc = 454; 8645 break; 8646 case Intrinsic::ppc_altivec_vcmpgtfp: 8647 CompareOpc = 710; 8648 break; 8649 case Intrinsic::ppc_altivec_vcmpgtsb: 8650 CompareOpc = 774; 8651 break; 8652 case Intrinsic::ppc_altivec_vcmpgtsh: 8653 CompareOpc = 838; 8654 break; 8655 case Intrinsic::ppc_altivec_vcmpgtsw: 8656 CompareOpc = 902; 8657 break; 8658 case Intrinsic::ppc_altivec_vcmpgtsd: 8659 if (Subtarget.hasP8Altivec()) 8660 CompareOpc = 967; 8661 else 8662 return false; 8663 break; 8664 case Intrinsic::ppc_altivec_vcmpgtub: 8665 CompareOpc = 518; 8666 break; 8667 case Intrinsic::ppc_altivec_vcmpgtuh: 8668 CompareOpc = 582; 8669 break; 8670 case Intrinsic::ppc_altivec_vcmpgtuw: 8671 CompareOpc = 646; 8672 break; 8673 case Intrinsic::ppc_altivec_vcmpgtud: 8674 if (Subtarget.hasP8Altivec()) 8675 CompareOpc = 711; 8676 else 8677 return false; 8678 break; 8679 } 8680 return true; 8681 } 8682 8683 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 8684 /// lower, do it, otherwise return null. 8685 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 8686 SelectionDAG &DAG) const { 8687 unsigned IntrinsicID = 8688 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8689 8690 SDLoc dl(Op); 8691 8692 if (IntrinsicID == Intrinsic::thread_pointer) { 8693 // Reads the thread pointer register, used for __builtin_thread_pointer. 8694 if (Subtarget.isPPC64()) 8695 return DAG.getRegister(PPC::X13, MVT::i64); 8696 return DAG.getRegister(PPC::R2, MVT::i32); 8697 } 8698 8699 // We are looking for absolute values here. 8700 // The idea is to try to fit one of two patterns: 8701 // max (a, (0-a)) OR max ((0-a), a) 8702 if (Subtarget.hasP9Vector() && 8703 (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw || 8704 IntrinsicID == Intrinsic::ppc_altivec_vmaxsh || 8705 IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) { 8706 SDValue V1 = Op.getOperand(1); 8707 SDValue V2 = Op.getOperand(2); 8708 if (V1.getSimpleValueType() == V2.getSimpleValueType() && 8709 (V1.getSimpleValueType() == MVT::v4i32 || 8710 V1.getSimpleValueType() == MVT::v8i16 || 8711 V1.getSimpleValueType() == MVT::v16i8)) { 8712 if ( V1.getOpcode() == ISD::SUB && 8713 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 8714 V1.getOperand(1) == V2 ) { 8715 // Generate the abs instruction with the operands 8716 return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2); 8717 } 8718 8719 if ( V2.getOpcode() == ISD::SUB && 8720 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 8721 V2.getOperand(1) == V1 ) { 8722 // Generate the abs instruction with the operands 8723 return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1); 8724 } 8725 } 8726 } 8727 8728 // If this is a lowered altivec predicate compare, CompareOpc is set to the 8729 // opcode number of the comparison. 8730 int CompareOpc; 8731 bool isDot; 8732 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 8733 return SDValue(); // Don't custom lower most intrinsics. 8734 8735 // If this is a non-dot comparison, make the VCMP node and we are done. 8736 if (!isDot) { 8737 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 8738 Op.getOperand(1), Op.getOperand(2), 8739 DAG.getConstant(CompareOpc, dl, MVT::i32)); 8740 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 8741 } 8742 8743 // Create the PPCISD altivec 'dot' comparison node. 8744 SDValue Ops[] = { 8745 Op.getOperand(2), // LHS 8746 Op.getOperand(3), // RHS 8747 DAG.getConstant(CompareOpc, dl, MVT::i32) 8748 }; 8749 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 8750 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 8751 8752 // Now that we have the comparison, emit a copy from the CR to a GPR. 8753 // This is flagged to the above dot comparison. 8754 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 8755 DAG.getRegister(PPC::CR6, MVT::i32), 8756 CompNode.getValue(1)); 8757 8758 // Unpack the result based on how the target uses it. 8759 unsigned BitNo; // Bit # of CR6. 8760 bool InvertBit; // Invert result? 8761 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 8762 default: // Can't happen, don't crash on invalid number though. 8763 case 0: // Return the value of the EQ bit of CR6. 8764 BitNo = 0; InvertBit = false; 8765 break; 8766 case 1: // Return the inverted value of the EQ bit of CR6. 8767 BitNo = 0; InvertBit = true; 8768 break; 8769 case 2: // Return the value of the LT bit of CR6. 8770 BitNo = 2; InvertBit = false; 8771 break; 8772 case 3: // Return the inverted value of the LT bit of CR6. 8773 BitNo = 2; InvertBit = true; 8774 break; 8775 } 8776 8777 // Shift the bit into the low position. 8778 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 8779 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 8780 // Isolate the bit. 8781 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 8782 DAG.getConstant(1, dl, MVT::i32)); 8783 8784 // If we are supposed to, toggle the bit. 8785 if (InvertBit) 8786 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 8787 DAG.getConstant(1, dl, MVT::i32)); 8788 return Flags; 8789 } 8790 8791 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 8792 SelectionDAG &DAG) const { 8793 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 8794 // the beginning of the argument list. 8795 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 8796 SDLoc DL(Op); 8797 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 8798 case Intrinsic::ppc_cfence: { 8799 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 8800 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 8801 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 8802 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 8803 Op.getOperand(ArgStart + 1)), 8804 Op.getOperand(0)), 8805 0); 8806 } 8807 default: 8808 break; 8809 } 8810 return SDValue(); 8811 } 8812 8813 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 8814 // Check for a DIV with the same operands as this REM. 8815 for (auto UI : Op.getOperand(1)->uses()) { 8816 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 8817 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 8818 if (UI->getOperand(0) == Op.getOperand(0) && 8819 UI->getOperand(1) == Op.getOperand(1)) 8820 return SDValue(); 8821 } 8822 return Op; 8823 } 8824 8825 // Lower scalar BSWAP64 to xxbrd. 8826 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 8827 SDLoc dl(Op); 8828 // MTVSRDD 8829 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 8830 Op.getOperand(0)); 8831 // XXBRD 8832 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 8833 // MFVSRD 8834 int VectorIndex = 0; 8835 if (Subtarget.isLittleEndian()) 8836 VectorIndex = 1; 8837 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 8838 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 8839 return Op; 8840 } 8841 8842 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 8843 // compared to a value that is atomically loaded (atomic loads zero-extend). 8844 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 8845 SelectionDAG &DAG) const { 8846 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 8847 "Expecting an atomic compare-and-swap here."); 8848 SDLoc dl(Op); 8849 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 8850 EVT MemVT = AtomicNode->getMemoryVT(); 8851 if (MemVT.getSizeInBits() >= 32) 8852 return Op; 8853 8854 SDValue CmpOp = Op.getOperand(2); 8855 // If this is already correctly zero-extended, leave it alone. 8856 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 8857 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 8858 return Op; 8859 8860 // Clear the high bits of the compare operand. 8861 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 8862 SDValue NewCmpOp = 8863 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 8864 DAG.getConstant(MaskVal, dl, MVT::i32)); 8865 8866 // Replace the existing compare operand with the properly zero-extended one. 8867 SmallVector<SDValue, 4> Ops; 8868 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 8869 Ops.push_back(AtomicNode->getOperand(i)); 8870 Ops[2] = NewCmpOp; 8871 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 8872 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 8873 auto NodeTy = 8874 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 8875 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 8876 } 8877 8878 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 8879 SelectionDAG &DAG) const { 8880 SDLoc dl(Op); 8881 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int 8882 // instructions), but for smaller types, we need to first extend up to v2i32 8883 // before doing going farther. 8884 if (Op.getValueType() == MVT::v2i64) { 8885 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 8886 if (ExtVT != MVT::v2i32) { 8887 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)); 8888 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op, 8889 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(), 8890 ExtVT.getVectorElementType(), 4))); 8891 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op); 8892 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op, 8893 DAG.getValueType(MVT::v2i32)); 8894 } 8895 8896 return Op; 8897 } 8898 8899 return SDValue(); 8900 } 8901 8902 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 8903 SelectionDAG &DAG) const { 8904 SDLoc dl(Op); 8905 // Create a stack slot that is 16-byte aligned. 8906 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8907 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8908 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8909 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8910 8911 // Store the input value into Value#0 of the stack slot. 8912 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8913 MachinePointerInfo()); 8914 // Load it out. 8915 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 8916 } 8917 8918 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8919 SelectionDAG &DAG) const { 8920 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 8921 "Should only be called for ISD::INSERT_VECTOR_ELT"); 8922 8923 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 8924 // We have legal lowering for constant indices but not for variable ones. 8925 if (!C) 8926 return SDValue(); 8927 8928 EVT VT = Op.getValueType(); 8929 SDLoc dl(Op); 8930 SDValue V1 = Op.getOperand(0); 8931 SDValue V2 = Op.getOperand(1); 8932 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 8933 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 8934 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 8935 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 8936 unsigned InsertAtElement = C->getZExtValue(); 8937 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 8938 if (Subtarget.isLittleEndian()) { 8939 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 8940 } 8941 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 8942 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8943 } 8944 return Op; 8945 } 8946 8947 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 8948 SelectionDAG &DAG) const { 8949 SDLoc dl(Op); 8950 SDNode *N = Op.getNode(); 8951 8952 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 8953 "Unknown extract_vector_elt type"); 8954 8955 SDValue Value = N->getOperand(0); 8956 8957 // The first part of this is like the store lowering except that we don't 8958 // need to track the chain. 8959 8960 // The values are now known to be -1 (false) or 1 (true). To convert this 8961 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8962 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8963 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8964 8965 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 8966 // understand how to form the extending load. 8967 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8968 8969 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8970 8971 // Now convert to an integer and store. 8972 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8973 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 8974 Value); 8975 8976 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8977 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8978 MachinePointerInfo PtrInfo = 8979 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8980 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8981 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8982 8983 SDValue StoreChain = DAG.getEntryNode(); 8984 SDValue Ops[] = {StoreChain, 8985 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 8986 Value, FIdx}; 8987 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 8988 8989 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 8990 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8991 8992 // Extract the value requested. 8993 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 8994 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8995 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8996 8997 SDValue IntVal = 8998 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 8999 9000 if (!Subtarget.useCRBits()) 9001 return IntVal; 9002 9003 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9004 } 9005 9006 /// Lowering for QPX v4i1 loads 9007 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9008 SelectionDAG &DAG) const { 9009 SDLoc dl(Op); 9010 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9011 SDValue LoadChain = LN->getChain(); 9012 SDValue BasePtr = LN->getBasePtr(); 9013 9014 if (Op.getValueType() == MVT::v4f64 || 9015 Op.getValueType() == MVT::v4f32) { 9016 EVT MemVT = LN->getMemoryVT(); 9017 unsigned Alignment = LN->getAlignment(); 9018 9019 // If this load is properly aligned, then it is legal. 9020 if (Alignment >= MemVT.getStoreSize()) 9021 return Op; 9022 9023 EVT ScalarVT = Op.getValueType().getScalarType(), 9024 ScalarMemVT = MemVT.getScalarType(); 9025 unsigned Stride = ScalarMemVT.getStoreSize(); 9026 9027 SDValue Vals[4], LoadChains[4]; 9028 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9029 SDValue Load; 9030 if (ScalarVT != ScalarMemVT) 9031 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9032 BasePtr, 9033 LN->getPointerInfo().getWithOffset(Idx * Stride), 9034 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9035 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9036 else 9037 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9038 LN->getPointerInfo().getWithOffset(Idx * Stride), 9039 MinAlign(Alignment, Idx * Stride), 9040 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9041 9042 if (Idx == 0 && LN->isIndexed()) { 9043 assert(LN->getAddressingMode() == ISD::PRE_INC && 9044 "Unknown addressing mode on vector load"); 9045 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9046 LN->getAddressingMode()); 9047 } 9048 9049 Vals[Idx] = Load; 9050 LoadChains[Idx] = Load.getValue(1); 9051 9052 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9053 DAG.getConstant(Stride, dl, 9054 BasePtr.getValueType())); 9055 } 9056 9057 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9058 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9059 9060 if (LN->isIndexed()) { 9061 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9062 return DAG.getMergeValues(RetOps, dl); 9063 } 9064 9065 SDValue RetOps[] = { Value, TF }; 9066 return DAG.getMergeValues(RetOps, dl); 9067 } 9068 9069 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9070 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9071 9072 // To lower v4i1 from a byte array, we load the byte elements of the 9073 // vector and then reuse the BUILD_VECTOR logic. 9074 9075 SDValue VectElmts[4], VectElmtChains[4]; 9076 for (unsigned i = 0; i < 4; ++i) { 9077 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9078 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9079 9080 VectElmts[i] = DAG.getExtLoad( 9081 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9082 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9083 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9084 VectElmtChains[i] = VectElmts[i].getValue(1); 9085 } 9086 9087 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9088 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9089 9090 SDValue RVals[] = { Value, LoadChain }; 9091 return DAG.getMergeValues(RVals, dl); 9092 } 9093 9094 /// Lowering for QPX v4i1 stores 9095 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9096 SelectionDAG &DAG) const { 9097 SDLoc dl(Op); 9098 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9099 SDValue StoreChain = SN->getChain(); 9100 SDValue BasePtr = SN->getBasePtr(); 9101 SDValue Value = SN->getValue(); 9102 9103 if (Value.getValueType() == MVT::v4f64 || 9104 Value.getValueType() == MVT::v4f32) { 9105 EVT MemVT = SN->getMemoryVT(); 9106 unsigned Alignment = SN->getAlignment(); 9107 9108 // If this store is properly aligned, then it is legal. 9109 if (Alignment >= MemVT.getStoreSize()) 9110 return Op; 9111 9112 EVT ScalarVT = Value.getValueType().getScalarType(), 9113 ScalarMemVT = MemVT.getScalarType(); 9114 unsigned Stride = ScalarMemVT.getStoreSize(); 9115 9116 SDValue Stores[4]; 9117 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9118 SDValue Ex = DAG.getNode( 9119 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9120 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9121 SDValue Store; 9122 if (ScalarVT != ScalarMemVT) 9123 Store = 9124 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9125 SN->getPointerInfo().getWithOffset(Idx * Stride), 9126 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9127 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9128 else 9129 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9130 SN->getPointerInfo().getWithOffset(Idx * Stride), 9131 MinAlign(Alignment, Idx * Stride), 9132 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9133 9134 if (Idx == 0 && SN->isIndexed()) { 9135 assert(SN->getAddressingMode() == ISD::PRE_INC && 9136 "Unknown addressing mode on vector store"); 9137 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9138 SN->getAddressingMode()); 9139 } 9140 9141 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9142 DAG.getConstant(Stride, dl, 9143 BasePtr.getValueType())); 9144 Stores[Idx] = Store; 9145 } 9146 9147 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9148 9149 if (SN->isIndexed()) { 9150 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9151 return DAG.getMergeValues(RetOps, dl); 9152 } 9153 9154 return TF; 9155 } 9156 9157 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9158 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9159 9160 // The values are now known to be -1 (false) or 1 (true). To convert this 9161 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9162 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9163 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9164 9165 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9166 // understand how to form the extending load. 9167 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9168 9169 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9170 9171 // Now convert to an integer and store. 9172 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9173 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9174 Value); 9175 9176 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9177 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9178 MachinePointerInfo PtrInfo = 9179 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9180 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9181 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9182 9183 SDValue Ops[] = {StoreChain, 9184 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9185 Value, FIdx}; 9186 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9187 9188 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9189 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9190 9191 // Move data into the byte array. 9192 SDValue Loads[4], LoadChains[4]; 9193 for (unsigned i = 0; i < 4; ++i) { 9194 unsigned Offset = 4*i; 9195 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9196 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9197 9198 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9199 PtrInfo.getWithOffset(Offset)); 9200 LoadChains[i] = Loads[i].getValue(1); 9201 } 9202 9203 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9204 9205 SDValue Stores[4]; 9206 for (unsigned i = 0; i < 4; ++i) { 9207 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9208 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9209 9210 Stores[i] = DAG.getTruncStore( 9211 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9212 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9213 SN->getAAInfo()); 9214 } 9215 9216 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9217 9218 return StoreChain; 9219 } 9220 9221 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9222 SDLoc dl(Op); 9223 if (Op.getValueType() == MVT::v4i32) { 9224 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9225 9226 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9227 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9228 9229 SDValue RHSSwap = // = vrlw RHS, 16 9230 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9231 9232 // Shrinkify inputs to v8i16. 9233 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9234 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9235 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9236 9237 // Low parts multiplied together, generating 32-bit results (we ignore the 9238 // top parts). 9239 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9240 LHS, RHS, DAG, dl, MVT::v4i32); 9241 9242 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9243 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9244 // Shift the high parts up 16 bits. 9245 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9246 Neg16, DAG, dl); 9247 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9248 } else if (Op.getValueType() == MVT::v8i16) { 9249 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9250 9251 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9252 9253 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9254 LHS, RHS, Zero, DAG, dl); 9255 } else if (Op.getValueType() == MVT::v16i8) { 9256 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9257 bool isLittleEndian = Subtarget.isLittleEndian(); 9258 9259 // Multiply the even 8-bit parts, producing 16-bit sums. 9260 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9261 LHS, RHS, DAG, dl, MVT::v8i16); 9262 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9263 9264 // Multiply the odd 8-bit parts, producing 16-bit sums. 9265 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9266 LHS, RHS, DAG, dl, MVT::v8i16); 9267 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9268 9269 // Merge the results together. Because vmuleub and vmuloub are 9270 // instructions with a big-endian bias, we must reverse the 9271 // element numbering and reverse the meaning of "odd" and "even" 9272 // when generating little endian code. 9273 int Ops[16]; 9274 for (unsigned i = 0; i != 8; ++i) { 9275 if (isLittleEndian) { 9276 Ops[i*2 ] = 2*i; 9277 Ops[i*2+1] = 2*i+16; 9278 } else { 9279 Ops[i*2 ] = 2*i+1; 9280 Ops[i*2+1] = 2*i+1+16; 9281 } 9282 } 9283 if (isLittleEndian) 9284 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9285 else 9286 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9287 } else { 9288 llvm_unreachable("Unknown mul to lower!"); 9289 } 9290 } 9291 9292 /// LowerOperation - Provide custom lowering hooks for some operations. 9293 /// 9294 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9295 switch (Op.getOpcode()) { 9296 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9297 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9298 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9299 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9300 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9301 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9302 case ISD::SETCC: return LowerSETCC(Op, DAG); 9303 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9304 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9305 case ISD::VASTART: 9306 return LowerVASTART(Op, DAG); 9307 9308 case ISD::VAARG: 9309 return LowerVAARG(Op, DAG); 9310 9311 case ISD::VACOPY: 9312 return LowerVACOPY(Op, DAG); 9313 9314 case ISD::STACKRESTORE: 9315 return LowerSTACKRESTORE(Op, DAG); 9316 9317 case ISD::DYNAMIC_STACKALLOC: 9318 return LowerDYNAMIC_STACKALLOC(Op, DAG); 9319 9320 case ISD::GET_DYNAMIC_AREA_OFFSET: 9321 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9322 9323 case ISD::EH_DWARF_CFA: 9324 return LowerEH_DWARF_CFA(Op, DAG); 9325 9326 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9327 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9328 9329 case ISD::LOAD: return LowerLOAD(Op, DAG); 9330 case ISD::STORE: return LowerSTORE(Op, DAG); 9331 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9332 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9333 case ISD::FP_TO_UINT: 9334 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, 9335 SDLoc(Op)); 9336 case ISD::UINT_TO_FP: 9337 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9338 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9339 9340 // Lower 64-bit shifts. 9341 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9342 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9343 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9344 9345 // Vector-related lowering. 9346 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9347 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9348 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9349 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9350 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG); 9351 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9352 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9353 case ISD::MUL: return LowerMUL(Op, DAG); 9354 9355 // For counter-based loop handling. 9356 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9357 9358 // Frame & Return address. 9359 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9360 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9361 9362 case ISD::INTRINSIC_VOID: 9363 return LowerINTRINSIC_VOID(Op, DAG); 9364 case ISD::SREM: 9365 case ISD::UREM: 9366 return LowerREM(Op, DAG); 9367 case ISD::BSWAP: 9368 return LowerBSWAP(Op, DAG); 9369 case ISD::ATOMIC_CMP_SWAP: 9370 return LowerATOMIC_CMP_SWAP(Op, DAG); 9371 } 9372 } 9373 9374 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9375 SmallVectorImpl<SDValue>&Results, 9376 SelectionDAG &DAG) const { 9377 SDLoc dl(N); 9378 switch (N->getOpcode()) { 9379 default: 9380 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9381 case ISD::READCYCLECOUNTER: { 9382 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9383 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9384 9385 Results.push_back(RTB); 9386 Results.push_back(RTB.getValue(1)); 9387 Results.push_back(RTB.getValue(2)); 9388 break; 9389 } 9390 case ISD::INTRINSIC_W_CHAIN: { 9391 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9392 Intrinsic::ppc_is_decremented_ctr_nonzero) 9393 break; 9394 9395 assert(N->getValueType(0) == MVT::i1 && 9396 "Unexpected result type for CTR decrement intrinsic"); 9397 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9398 N->getValueType(0)); 9399 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9400 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9401 N->getOperand(1)); 9402 9403 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 9404 Results.push_back(NewInt.getValue(1)); 9405 break; 9406 } 9407 case ISD::VAARG: { 9408 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 9409 return; 9410 9411 EVT VT = N->getValueType(0); 9412 9413 if (VT == MVT::i64) { 9414 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 9415 9416 Results.push_back(NewNode); 9417 Results.push_back(NewNode.getValue(1)); 9418 } 9419 return; 9420 } 9421 case ISD::FP_ROUND_INREG: { 9422 assert(N->getValueType(0) == MVT::ppcf128); 9423 assert(N->getOperand(0).getValueType() == MVT::ppcf128); 9424 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 9425 MVT::f64, N->getOperand(0), 9426 DAG.getIntPtrConstant(0, dl)); 9427 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 9428 MVT::f64, N->getOperand(0), 9429 DAG.getIntPtrConstant(1, dl)); 9430 9431 // Add the two halves of the long double in round-to-zero mode. 9432 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 9433 9434 // We know the low half is about to be thrown away, so just use something 9435 // convenient. 9436 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 9437 FPreg, FPreg)); 9438 return; 9439 } 9440 case ISD::FP_TO_SINT: 9441 case ISD::FP_TO_UINT: 9442 // LowerFP_TO_INT() can only handle f32 and f64. 9443 if (N->getOperand(0).getValueType() == MVT::ppcf128) 9444 return; 9445 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 9446 return; 9447 } 9448 } 9449 9450 //===----------------------------------------------------------------------===// 9451 // Other Lowering Code 9452 //===----------------------------------------------------------------------===// 9453 9454 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 9455 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9456 Function *Func = Intrinsic::getDeclaration(M, Id); 9457 return Builder.CreateCall(Func, {}); 9458 } 9459 9460 // The mappings for emitLeading/TrailingFence is taken from 9461 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 9462 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 9463 Instruction *Inst, 9464 AtomicOrdering Ord) const { 9465 if (Ord == AtomicOrdering::SequentiallyConsistent) 9466 return callIntrinsic(Builder, Intrinsic::ppc_sync); 9467 if (isReleaseOrStronger(Ord)) 9468 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9469 return nullptr; 9470 } 9471 9472 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 9473 Instruction *Inst, 9474 AtomicOrdering Ord) const { 9475 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 9476 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 9477 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 9478 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 9479 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 9480 return Builder.CreateCall( 9481 Intrinsic::getDeclaration( 9482 Builder.GetInsertBlock()->getParent()->getParent(), 9483 Intrinsic::ppc_cfence, {Inst->getType()}), 9484 {Inst}); 9485 // FIXME: Can use isync for rmw operation. 9486 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9487 } 9488 return nullptr; 9489 } 9490 9491 MachineBasicBlock * 9492 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 9493 unsigned AtomicSize, 9494 unsigned BinOpcode, 9495 unsigned CmpOpcode, 9496 unsigned CmpPred) const { 9497 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9498 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9499 9500 auto LoadMnemonic = PPC::LDARX; 9501 auto StoreMnemonic = PPC::STDCX; 9502 switch (AtomicSize) { 9503 default: 9504 llvm_unreachable("Unexpected size of atomic entity"); 9505 case 1: 9506 LoadMnemonic = PPC::LBARX; 9507 StoreMnemonic = PPC::STBCX; 9508 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9509 break; 9510 case 2: 9511 LoadMnemonic = PPC::LHARX; 9512 StoreMnemonic = PPC::STHCX; 9513 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9514 break; 9515 case 4: 9516 LoadMnemonic = PPC::LWARX; 9517 StoreMnemonic = PPC::STWCX; 9518 break; 9519 case 8: 9520 LoadMnemonic = PPC::LDARX; 9521 StoreMnemonic = PPC::STDCX; 9522 break; 9523 } 9524 9525 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9526 MachineFunction *F = BB->getParent(); 9527 MachineFunction::iterator It = ++BB->getIterator(); 9528 9529 unsigned dest = MI.getOperand(0).getReg(); 9530 unsigned ptrA = MI.getOperand(1).getReg(); 9531 unsigned ptrB = MI.getOperand(2).getReg(); 9532 unsigned incr = MI.getOperand(3).getReg(); 9533 DebugLoc dl = MI.getDebugLoc(); 9534 9535 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9536 MachineBasicBlock *loop2MBB = 9537 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9538 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9539 F->insert(It, loopMBB); 9540 if (CmpOpcode) 9541 F->insert(It, loop2MBB); 9542 F->insert(It, exitMBB); 9543 exitMBB->splice(exitMBB->begin(), BB, 9544 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9545 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9546 9547 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9548 unsigned TmpReg = (!BinOpcode) ? incr : 9549 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 9550 : &PPC::GPRCRegClass); 9551 9552 // thisMBB: 9553 // ... 9554 // fallthrough --> loopMBB 9555 BB->addSuccessor(loopMBB); 9556 9557 // loopMBB: 9558 // l[wd]arx dest, ptr 9559 // add r0, dest, incr 9560 // st[wd]cx. r0, ptr 9561 // bne- loopMBB 9562 // fallthrough --> exitMBB 9563 9564 // For max/min... 9565 // loopMBB: 9566 // l[wd]arx dest, ptr 9567 // cmpl?[wd] incr, dest 9568 // bgt exitMBB 9569 // loop2MBB: 9570 // st[wd]cx. dest, ptr 9571 // bne- loopMBB 9572 // fallthrough --> exitMBB 9573 9574 BB = loopMBB; 9575 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9576 .addReg(ptrA).addReg(ptrB); 9577 if (BinOpcode) 9578 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 9579 if (CmpOpcode) { 9580 // Signed comparisons of byte or halfword values must be sign-extended. 9581 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 9582 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9583 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 9584 ExtReg).addReg(dest); 9585 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9586 .addReg(incr).addReg(ExtReg); 9587 } else 9588 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9589 .addReg(incr).addReg(dest); 9590 9591 BuildMI(BB, dl, TII->get(PPC::BCC)) 9592 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9593 BB->addSuccessor(loop2MBB); 9594 BB->addSuccessor(exitMBB); 9595 BB = loop2MBB; 9596 } 9597 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9598 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 9599 BuildMI(BB, dl, TII->get(PPC::BCC)) 9600 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9601 BB->addSuccessor(loopMBB); 9602 BB->addSuccessor(exitMBB); 9603 9604 // exitMBB: 9605 // ... 9606 BB = exitMBB; 9607 return BB; 9608 } 9609 9610 MachineBasicBlock * 9611 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI, 9612 MachineBasicBlock *BB, 9613 bool is8bit, // operation 9614 unsigned BinOpcode, 9615 unsigned CmpOpcode, 9616 unsigned CmpPred) const { 9617 // If we support part-word atomic mnemonics, just use them 9618 if (Subtarget.hasPartwordAtomics()) 9619 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, 9620 CmpOpcode, CmpPred); 9621 9622 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9623 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9624 // In 64 bit mode we have to use 64 bits for addresses, even though the 9625 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 9626 // registers without caring whether they're 32 or 64, but here we're 9627 // doing actual arithmetic on the addresses. 9628 bool is64bit = Subtarget.isPPC64(); 9629 bool isLittleEndian = Subtarget.isLittleEndian(); 9630 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9631 9632 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9633 MachineFunction *F = BB->getParent(); 9634 MachineFunction::iterator It = ++BB->getIterator(); 9635 9636 unsigned dest = MI.getOperand(0).getReg(); 9637 unsigned ptrA = MI.getOperand(1).getReg(); 9638 unsigned ptrB = MI.getOperand(2).getReg(); 9639 unsigned incr = MI.getOperand(3).getReg(); 9640 DebugLoc dl = MI.getDebugLoc(); 9641 9642 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9643 MachineBasicBlock *loop2MBB = 9644 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9645 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9646 F->insert(It, loopMBB); 9647 if (CmpOpcode) 9648 F->insert(It, loop2MBB); 9649 F->insert(It, exitMBB); 9650 exitMBB->splice(exitMBB->begin(), BB, 9651 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9652 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9653 9654 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9655 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 9656 : &PPC::GPRCRegClass; 9657 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9658 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 9659 unsigned ShiftReg = 9660 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 9661 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 9662 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 9663 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 9664 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 9665 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 9666 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 9667 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 9668 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 9669 unsigned Ptr1Reg; 9670 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 9671 9672 // thisMBB: 9673 // ... 9674 // fallthrough --> loopMBB 9675 BB->addSuccessor(loopMBB); 9676 9677 // The 4-byte load must be aligned, while a char or short may be 9678 // anywhere in the word. Hence all this nasty bookkeeping code. 9679 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9680 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9681 // xori shift, shift1, 24 [16] 9682 // rlwinm ptr, ptr1, 0, 0, 29 9683 // slw incr2, incr, shift 9684 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9685 // slw mask, mask2, shift 9686 // loopMBB: 9687 // lwarx tmpDest, ptr 9688 // add tmp, tmpDest, incr2 9689 // andc tmp2, tmpDest, mask 9690 // and tmp3, tmp, mask 9691 // or tmp4, tmp3, tmp2 9692 // stwcx. tmp4, ptr 9693 // bne- loopMBB 9694 // fallthrough --> exitMBB 9695 // srw dest, tmpDest, shift 9696 if (ptrA != ZeroReg) { 9697 Ptr1Reg = RegInfo.createVirtualRegister(RC); 9698 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 9699 .addReg(ptrA).addReg(ptrB); 9700 } else { 9701 Ptr1Reg = ptrB; 9702 } 9703 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 9704 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 9705 if (!isLittleEndian) 9706 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 9707 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 9708 if (is64bit) 9709 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 9710 .addReg(Ptr1Reg).addImm(0).addImm(61); 9711 else 9712 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 9713 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 9714 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 9715 .addReg(incr).addReg(ShiftReg); 9716 if (is8bit) 9717 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 9718 else { 9719 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 9720 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 9721 } 9722 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 9723 .addReg(Mask2Reg).addReg(ShiftReg); 9724 9725 BB = loopMBB; 9726 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 9727 .addReg(ZeroReg).addReg(PtrReg); 9728 if (BinOpcode) 9729 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 9730 .addReg(Incr2Reg).addReg(TmpDestReg); 9731 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 9732 .addReg(TmpDestReg).addReg(MaskReg); 9733 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 9734 .addReg(TmpReg).addReg(MaskReg); 9735 if (CmpOpcode) { 9736 // For unsigned comparisons, we can directly compare the shifted values. 9737 // For signed comparisons we shift and sign extend. 9738 unsigned SReg = RegInfo.createVirtualRegister(RC); 9739 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg) 9740 .addReg(TmpDestReg).addReg(MaskReg); 9741 unsigned ValueReg = SReg; 9742 unsigned CmpReg = Incr2Reg; 9743 if (CmpOpcode == PPC::CMPW) { 9744 ValueReg = RegInfo.createVirtualRegister(RC); 9745 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 9746 .addReg(SReg).addReg(ShiftReg); 9747 unsigned ValueSReg = RegInfo.createVirtualRegister(RC); 9748 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 9749 .addReg(ValueReg); 9750 ValueReg = ValueSReg; 9751 CmpReg = incr; 9752 } 9753 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9754 .addReg(CmpReg).addReg(ValueReg); 9755 BuildMI(BB, dl, TII->get(PPC::BCC)) 9756 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9757 BB->addSuccessor(loop2MBB); 9758 BB->addSuccessor(exitMBB); 9759 BB = loop2MBB; 9760 } 9761 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 9762 .addReg(Tmp3Reg).addReg(Tmp2Reg); 9763 BuildMI(BB, dl, TII->get(PPC::STWCX)) 9764 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 9765 BuildMI(BB, dl, TII->get(PPC::BCC)) 9766 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9767 BB->addSuccessor(loopMBB); 9768 BB->addSuccessor(exitMBB); 9769 9770 // exitMBB: 9771 // ... 9772 BB = exitMBB; 9773 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 9774 .addReg(ShiftReg); 9775 return BB; 9776 } 9777 9778 llvm::MachineBasicBlock * 9779 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 9780 MachineBasicBlock *MBB) const { 9781 DebugLoc DL = MI.getDebugLoc(); 9782 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9783 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9784 9785 MachineFunction *MF = MBB->getParent(); 9786 MachineRegisterInfo &MRI = MF->getRegInfo(); 9787 9788 const BasicBlock *BB = MBB->getBasicBlock(); 9789 MachineFunction::iterator I = ++MBB->getIterator(); 9790 9791 // Memory Reference 9792 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9793 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9794 9795 unsigned DstReg = MI.getOperand(0).getReg(); 9796 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 9797 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 9798 unsigned mainDstReg = MRI.createVirtualRegister(RC); 9799 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 9800 9801 MVT PVT = getPointerTy(MF->getDataLayout()); 9802 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9803 "Invalid Pointer Size!"); 9804 // For v = setjmp(buf), we generate 9805 // 9806 // thisMBB: 9807 // SjLjSetup mainMBB 9808 // bl mainMBB 9809 // v_restore = 1 9810 // b sinkMBB 9811 // 9812 // mainMBB: 9813 // buf[LabelOffset] = LR 9814 // v_main = 0 9815 // 9816 // sinkMBB: 9817 // v = phi(main, restore) 9818 // 9819 9820 MachineBasicBlock *thisMBB = MBB; 9821 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 9822 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 9823 MF->insert(I, mainMBB); 9824 MF->insert(I, sinkMBB); 9825 9826 MachineInstrBuilder MIB; 9827 9828 // Transfer the remainder of BB and its successor edges to sinkMBB. 9829 sinkMBB->splice(sinkMBB->begin(), MBB, 9830 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9831 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 9832 9833 // Note that the structure of the jmp_buf used here is not compatible 9834 // with that used by libc, and is not designed to be. Specifically, it 9835 // stores only those 'reserved' registers that LLVM does not otherwise 9836 // understand how to spill. Also, by convention, by the time this 9837 // intrinsic is called, Clang has already stored the frame address in the 9838 // first slot of the buffer and stack address in the third. Following the 9839 // X86 target code, we'll store the jump address in the second slot. We also 9840 // need to save the TOC pointer (R2) to handle jumps between shared 9841 // libraries, and that will be stored in the fourth slot. The thread 9842 // identifier (R13) is not affected. 9843 9844 // thisMBB: 9845 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9846 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9847 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9848 9849 // Prepare IP either in reg. 9850 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 9851 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 9852 unsigned BufReg = MI.getOperand(1).getReg(); 9853 9854 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 9855 setUsesTOCBasePtr(*MBB->getParent()); 9856 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 9857 .addReg(PPC::X2) 9858 .addImm(TOCOffset) 9859 .addReg(BufReg); 9860 MIB.setMemRefs(MMOBegin, MMOEnd); 9861 } 9862 9863 // Naked functions never have a base pointer, and so we use r1. For all 9864 // other functions, this decision must be delayed until during PEI. 9865 unsigned BaseReg; 9866 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 9867 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 9868 else 9869 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 9870 9871 MIB = BuildMI(*thisMBB, MI, DL, 9872 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 9873 .addReg(BaseReg) 9874 .addImm(BPOffset) 9875 .addReg(BufReg); 9876 MIB.setMemRefs(MMOBegin, MMOEnd); 9877 9878 // Setup 9879 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 9880 MIB.addRegMask(TRI->getNoPreservedMask()); 9881 9882 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 9883 9884 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 9885 .addMBB(mainMBB); 9886 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 9887 9888 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 9889 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 9890 9891 // mainMBB: 9892 // mainDstReg = 0 9893 MIB = 9894 BuildMI(mainMBB, DL, 9895 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 9896 9897 // Store IP 9898 if (Subtarget.isPPC64()) { 9899 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 9900 .addReg(LabelReg) 9901 .addImm(LabelOffset) 9902 .addReg(BufReg); 9903 } else { 9904 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 9905 .addReg(LabelReg) 9906 .addImm(LabelOffset) 9907 .addReg(BufReg); 9908 } 9909 9910 MIB.setMemRefs(MMOBegin, MMOEnd); 9911 9912 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 9913 mainMBB->addSuccessor(sinkMBB); 9914 9915 // sinkMBB: 9916 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 9917 TII->get(PPC::PHI), DstReg) 9918 .addReg(mainDstReg).addMBB(mainMBB) 9919 .addReg(restoreDstReg).addMBB(thisMBB); 9920 9921 MI.eraseFromParent(); 9922 return sinkMBB; 9923 } 9924 9925 MachineBasicBlock * 9926 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 9927 MachineBasicBlock *MBB) const { 9928 DebugLoc DL = MI.getDebugLoc(); 9929 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9930 9931 MachineFunction *MF = MBB->getParent(); 9932 MachineRegisterInfo &MRI = MF->getRegInfo(); 9933 9934 // Memory Reference 9935 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9936 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9937 9938 MVT PVT = getPointerTy(MF->getDataLayout()); 9939 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9940 "Invalid Pointer Size!"); 9941 9942 const TargetRegisterClass *RC = 9943 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 9944 unsigned Tmp = MRI.createVirtualRegister(RC); 9945 // Since FP is only updated here but NOT referenced, it's treated as GPR. 9946 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 9947 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 9948 unsigned BP = 9949 (PVT == MVT::i64) 9950 ? PPC::X30 9951 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 9952 : PPC::R30); 9953 9954 MachineInstrBuilder MIB; 9955 9956 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9957 const int64_t SPOffset = 2 * PVT.getStoreSize(); 9958 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9959 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9960 9961 unsigned BufReg = MI.getOperand(0).getReg(); 9962 9963 // Reload FP (the jumped-to function may not have had a 9964 // frame pointer, and if so, then its r31 will be restored 9965 // as necessary). 9966 if (PVT == MVT::i64) { 9967 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 9968 .addImm(0) 9969 .addReg(BufReg); 9970 } else { 9971 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 9972 .addImm(0) 9973 .addReg(BufReg); 9974 } 9975 MIB.setMemRefs(MMOBegin, MMOEnd); 9976 9977 // Reload IP 9978 if (PVT == MVT::i64) { 9979 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 9980 .addImm(LabelOffset) 9981 .addReg(BufReg); 9982 } else { 9983 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 9984 .addImm(LabelOffset) 9985 .addReg(BufReg); 9986 } 9987 MIB.setMemRefs(MMOBegin, MMOEnd); 9988 9989 // Reload SP 9990 if (PVT == MVT::i64) { 9991 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 9992 .addImm(SPOffset) 9993 .addReg(BufReg); 9994 } else { 9995 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 9996 .addImm(SPOffset) 9997 .addReg(BufReg); 9998 } 9999 MIB.setMemRefs(MMOBegin, MMOEnd); 10000 10001 // Reload BP 10002 if (PVT == MVT::i64) { 10003 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10004 .addImm(BPOffset) 10005 .addReg(BufReg); 10006 } else { 10007 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10008 .addImm(BPOffset) 10009 .addReg(BufReg); 10010 } 10011 MIB.setMemRefs(MMOBegin, MMOEnd); 10012 10013 // Reload TOC 10014 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10015 setUsesTOCBasePtr(*MBB->getParent()); 10016 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10017 .addImm(TOCOffset) 10018 .addReg(BufReg); 10019 10020 MIB.setMemRefs(MMOBegin, MMOEnd); 10021 } 10022 10023 // Jump 10024 BuildMI(*MBB, MI, DL, 10025 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10026 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10027 10028 MI.eraseFromParent(); 10029 return MBB; 10030 } 10031 10032 MachineBasicBlock * 10033 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10034 MachineBasicBlock *BB) const { 10035 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10036 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10037 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10038 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10039 // Call lowering should have added an r2 operand to indicate a dependence 10040 // on the TOC base pointer value. It can't however, because there is no 10041 // way to mark the dependence as implicit there, and so the stackmap code 10042 // will confuse it with a regular operand. Instead, add the dependence 10043 // here. 10044 setUsesTOCBasePtr(*BB->getParent()); 10045 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10046 } 10047 10048 return emitPatchPoint(MI, BB); 10049 } 10050 10051 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10052 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10053 return emitEHSjLjSetJmp(MI, BB); 10054 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10055 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10056 return emitEHSjLjLongJmp(MI, BB); 10057 } 10058 10059 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10060 10061 // To "insert" these instructions we actually have to insert their 10062 // control-flow patterns. 10063 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10064 MachineFunction::iterator It = ++BB->getIterator(); 10065 10066 MachineFunction *F = BB->getParent(); 10067 10068 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10069 MI.getOpcode() == PPC::SELECT_CC_I8 || 10070 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) { 10071 SmallVector<MachineOperand, 2> Cond; 10072 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10073 MI.getOpcode() == PPC::SELECT_CC_I8) 10074 Cond.push_back(MI.getOperand(4)); 10075 else 10076 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10077 Cond.push_back(MI.getOperand(1)); 10078 10079 DebugLoc dl = MI.getDebugLoc(); 10080 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10081 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10082 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10083 MI.getOpcode() == PPC::SELECT_CC_I8 || 10084 MI.getOpcode() == PPC::SELECT_CC_F4 || 10085 MI.getOpcode() == PPC::SELECT_CC_F8 || 10086 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10087 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10088 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10089 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10090 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10091 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10092 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10093 MI.getOpcode() == PPC::SELECT_I4 || 10094 MI.getOpcode() == PPC::SELECT_I8 || 10095 MI.getOpcode() == PPC::SELECT_F4 || 10096 MI.getOpcode() == PPC::SELECT_F8 || 10097 MI.getOpcode() == PPC::SELECT_QFRC || 10098 MI.getOpcode() == PPC::SELECT_QSRC || 10099 MI.getOpcode() == PPC::SELECT_QBRC || 10100 MI.getOpcode() == PPC::SELECT_VRRC || 10101 MI.getOpcode() == PPC::SELECT_VSFRC || 10102 MI.getOpcode() == PPC::SELECT_VSSRC || 10103 MI.getOpcode() == PPC::SELECT_VSRC) { 10104 // The incoming instruction knows the destination vreg to set, the 10105 // condition code register to branch on, the true/false values to 10106 // select between, and a branch opcode to use. 10107 10108 // thisMBB: 10109 // ... 10110 // TrueVal = ... 10111 // cmpTY ccX, r1, r2 10112 // bCC copy1MBB 10113 // fallthrough --> copy0MBB 10114 MachineBasicBlock *thisMBB = BB; 10115 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10116 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10117 DebugLoc dl = MI.getDebugLoc(); 10118 F->insert(It, copy0MBB); 10119 F->insert(It, sinkMBB); 10120 10121 // Transfer the remainder of BB and its successor edges to sinkMBB. 10122 sinkMBB->splice(sinkMBB->begin(), BB, 10123 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10124 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10125 10126 // Next, add the true and fallthrough blocks as its successors. 10127 BB->addSuccessor(copy0MBB); 10128 BB->addSuccessor(sinkMBB); 10129 10130 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10131 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10132 MI.getOpcode() == PPC::SELECT_QFRC || 10133 MI.getOpcode() == PPC::SELECT_QSRC || 10134 MI.getOpcode() == PPC::SELECT_QBRC || 10135 MI.getOpcode() == PPC::SELECT_VRRC || 10136 MI.getOpcode() == PPC::SELECT_VSFRC || 10137 MI.getOpcode() == PPC::SELECT_VSSRC || 10138 MI.getOpcode() == PPC::SELECT_VSRC) { 10139 BuildMI(BB, dl, TII->get(PPC::BC)) 10140 .addReg(MI.getOperand(1).getReg()) 10141 .addMBB(sinkMBB); 10142 } else { 10143 unsigned SelectPred = MI.getOperand(4).getImm(); 10144 BuildMI(BB, dl, TII->get(PPC::BCC)) 10145 .addImm(SelectPred) 10146 .addReg(MI.getOperand(1).getReg()) 10147 .addMBB(sinkMBB); 10148 } 10149 10150 // copy0MBB: 10151 // %FalseValue = ... 10152 // # fallthrough to sinkMBB 10153 BB = copy0MBB; 10154 10155 // Update machine-CFG edges 10156 BB->addSuccessor(sinkMBB); 10157 10158 // sinkMBB: 10159 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10160 // ... 10161 BB = sinkMBB; 10162 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10163 .addReg(MI.getOperand(3).getReg()) 10164 .addMBB(copy0MBB) 10165 .addReg(MI.getOperand(2).getReg()) 10166 .addMBB(thisMBB); 10167 } else if (MI.getOpcode() == PPC::ReadTB) { 10168 // To read the 64-bit time-base register on a 32-bit target, we read the 10169 // two halves. Should the counter have wrapped while it was being read, we 10170 // need to try again. 10171 // ... 10172 // readLoop: 10173 // mfspr Rx,TBU # load from TBU 10174 // mfspr Ry,TB # load from TB 10175 // mfspr Rz,TBU # load from TBU 10176 // cmpw crX,Rx,Rz # check if 'old'='new' 10177 // bne readLoop # branch if they're not equal 10178 // ... 10179 10180 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10181 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10182 DebugLoc dl = MI.getDebugLoc(); 10183 F->insert(It, readMBB); 10184 F->insert(It, sinkMBB); 10185 10186 // Transfer the remainder of BB and its successor edges to sinkMBB. 10187 sinkMBB->splice(sinkMBB->begin(), BB, 10188 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10189 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10190 10191 BB->addSuccessor(readMBB); 10192 BB = readMBB; 10193 10194 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10195 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10196 unsigned LoReg = MI.getOperand(0).getReg(); 10197 unsigned HiReg = MI.getOperand(1).getReg(); 10198 10199 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10200 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10201 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10202 10203 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10204 10205 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10206 .addReg(HiReg).addReg(ReadAgainReg); 10207 BuildMI(BB, dl, TII->get(PPC::BCC)) 10208 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB); 10209 10210 BB->addSuccessor(readMBB); 10211 BB->addSuccessor(sinkMBB); 10212 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10213 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10214 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10215 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10216 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10217 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10218 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10219 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10220 10221 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10222 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10223 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10224 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10225 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10226 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10227 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10228 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10229 10230 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10231 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10232 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10233 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10234 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10235 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10236 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10237 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10238 10239 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10240 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10241 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10242 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10243 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10244 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10245 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10246 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10247 10248 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10249 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10250 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10251 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10252 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10253 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10254 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10255 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10256 10257 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10258 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10259 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10260 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10261 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10262 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10263 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10264 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10265 10266 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10267 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10268 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10269 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10270 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10271 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10272 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10273 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10274 10275 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10276 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10277 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10278 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10279 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10280 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10281 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10282 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10283 10284 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10285 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10286 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10287 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10288 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10289 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10290 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10291 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10292 10293 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10294 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10295 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10296 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10297 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10298 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10299 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10300 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10301 10302 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10303 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10304 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10305 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10306 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10307 BB = EmitAtomicBinary(MI, BB, 4, 0); 10308 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10309 BB = EmitAtomicBinary(MI, BB, 8, 0); 10310 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10311 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10312 (Subtarget.hasPartwordAtomics() && 10313 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10314 (Subtarget.hasPartwordAtomics() && 10315 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10316 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10317 10318 auto LoadMnemonic = PPC::LDARX; 10319 auto StoreMnemonic = PPC::STDCX; 10320 switch (MI.getOpcode()) { 10321 default: 10322 llvm_unreachable("Compare and swap of unknown size"); 10323 case PPC::ATOMIC_CMP_SWAP_I8: 10324 LoadMnemonic = PPC::LBARX; 10325 StoreMnemonic = PPC::STBCX; 10326 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10327 break; 10328 case PPC::ATOMIC_CMP_SWAP_I16: 10329 LoadMnemonic = PPC::LHARX; 10330 StoreMnemonic = PPC::STHCX; 10331 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10332 break; 10333 case PPC::ATOMIC_CMP_SWAP_I32: 10334 LoadMnemonic = PPC::LWARX; 10335 StoreMnemonic = PPC::STWCX; 10336 break; 10337 case PPC::ATOMIC_CMP_SWAP_I64: 10338 LoadMnemonic = PPC::LDARX; 10339 StoreMnemonic = PPC::STDCX; 10340 break; 10341 } 10342 unsigned dest = MI.getOperand(0).getReg(); 10343 unsigned ptrA = MI.getOperand(1).getReg(); 10344 unsigned ptrB = MI.getOperand(2).getReg(); 10345 unsigned oldval = MI.getOperand(3).getReg(); 10346 unsigned newval = MI.getOperand(4).getReg(); 10347 DebugLoc dl = MI.getDebugLoc(); 10348 10349 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10350 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10351 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10352 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10353 F->insert(It, loop1MBB); 10354 F->insert(It, loop2MBB); 10355 F->insert(It, midMBB); 10356 F->insert(It, exitMBB); 10357 exitMBB->splice(exitMBB->begin(), BB, 10358 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10359 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10360 10361 // thisMBB: 10362 // ... 10363 // fallthrough --> loopMBB 10364 BB->addSuccessor(loop1MBB); 10365 10366 // loop1MBB: 10367 // l[bhwd]arx dest, ptr 10368 // cmp[wd] dest, oldval 10369 // bne- midMBB 10370 // loop2MBB: 10371 // st[bhwd]cx. newval, ptr 10372 // bne- loopMBB 10373 // b exitBB 10374 // midMBB: 10375 // st[bhwd]cx. dest, ptr 10376 // exitBB: 10377 BB = loop1MBB; 10378 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10379 .addReg(ptrA).addReg(ptrB); 10380 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10381 .addReg(oldval).addReg(dest); 10382 BuildMI(BB, dl, TII->get(PPC::BCC)) 10383 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10384 BB->addSuccessor(loop2MBB); 10385 BB->addSuccessor(midMBB); 10386 10387 BB = loop2MBB; 10388 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10389 .addReg(newval).addReg(ptrA).addReg(ptrB); 10390 BuildMI(BB, dl, TII->get(PPC::BCC)) 10391 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10392 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10393 BB->addSuccessor(loop1MBB); 10394 BB->addSuccessor(exitMBB); 10395 10396 BB = midMBB; 10397 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10398 .addReg(dest).addReg(ptrA).addReg(ptrB); 10399 BB->addSuccessor(exitMBB); 10400 10401 // exitMBB: 10402 // ... 10403 BB = exitMBB; 10404 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 10405 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 10406 // We must use 64-bit registers for addresses when targeting 64-bit, 10407 // since we're actually doing arithmetic on them. Other registers 10408 // can be 32-bit. 10409 bool is64bit = Subtarget.isPPC64(); 10410 bool isLittleEndian = Subtarget.isLittleEndian(); 10411 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 10412 10413 unsigned dest = MI.getOperand(0).getReg(); 10414 unsigned ptrA = MI.getOperand(1).getReg(); 10415 unsigned ptrB = MI.getOperand(2).getReg(); 10416 unsigned oldval = MI.getOperand(3).getReg(); 10417 unsigned newval = MI.getOperand(4).getReg(); 10418 DebugLoc dl = MI.getDebugLoc(); 10419 10420 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10421 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10422 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10423 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10424 F->insert(It, loop1MBB); 10425 F->insert(It, loop2MBB); 10426 F->insert(It, midMBB); 10427 F->insert(It, exitMBB); 10428 exitMBB->splice(exitMBB->begin(), BB, 10429 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10430 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10431 10432 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10433 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 10434 : &PPC::GPRCRegClass; 10435 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10436 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 10437 unsigned ShiftReg = 10438 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 10439 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 10440 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 10441 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 10442 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 10443 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 10444 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 10445 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 10446 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 10447 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 10448 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 10449 unsigned Ptr1Reg; 10450 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 10451 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10452 // thisMBB: 10453 // ... 10454 // fallthrough --> loopMBB 10455 BB->addSuccessor(loop1MBB); 10456 10457 // The 4-byte load must be aligned, while a char or short may be 10458 // anywhere in the word. Hence all this nasty bookkeeping code. 10459 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10460 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10461 // xori shift, shift1, 24 [16] 10462 // rlwinm ptr, ptr1, 0, 0, 29 10463 // slw newval2, newval, shift 10464 // slw oldval2, oldval,shift 10465 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10466 // slw mask, mask2, shift 10467 // and newval3, newval2, mask 10468 // and oldval3, oldval2, mask 10469 // loop1MBB: 10470 // lwarx tmpDest, ptr 10471 // and tmp, tmpDest, mask 10472 // cmpw tmp, oldval3 10473 // bne- midMBB 10474 // loop2MBB: 10475 // andc tmp2, tmpDest, mask 10476 // or tmp4, tmp2, newval3 10477 // stwcx. tmp4, ptr 10478 // bne- loop1MBB 10479 // b exitBB 10480 // midMBB: 10481 // stwcx. tmpDest, ptr 10482 // exitBB: 10483 // srw dest, tmpDest, shift 10484 if (ptrA != ZeroReg) { 10485 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10486 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10487 .addReg(ptrA).addReg(ptrB); 10488 } else { 10489 Ptr1Reg = ptrB; 10490 } 10491 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 10492 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 10493 if (!isLittleEndian) 10494 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 10495 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 10496 if (is64bit) 10497 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10498 .addReg(Ptr1Reg).addImm(0).addImm(61); 10499 else 10500 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10501 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 10502 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 10503 .addReg(newval).addReg(ShiftReg); 10504 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 10505 .addReg(oldval).addReg(ShiftReg); 10506 if (is8bit) 10507 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10508 else { 10509 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10510 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10511 .addReg(Mask3Reg).addImm(65535); 10512 } 10513 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10514 .addReg(Mask2Reg).addReg(ShiftReg); 10515 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 10516 .addReg(NewVal2Reg).addReg(MaskReg); 10517 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 10518 .addReg(OldVal2Reg).addReg(MaskReg); 10519 10520 BB = loop1MBB; 10521 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10522 .addReg(ZeroReg).addReg(PtrReg); 10523 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 10524 .addReg(TmpDestReg).addReg(MaskReg); 10525 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 10526 .addReg(TmpReg).addReg(OldVal3Reg); 10527 BuildMI(BB, dl, TII->get(PPC::BCC)) 10528 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10529 BB->addSuccessor(loop2MBB); 10530 BB->addSuccessor(midMBB); 10531 10532 BB = loop2MBB; 10533 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 10534 .addReg(TmpDestReg).addReg(MaskReg); 10535 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 10536 .addReg(Tmp2Reg).addReg(NewVal3Reg); 10537 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 10538 .addReg(ZeroReg).addReg(PtrReg); 10539 BuildMI(BB, dl, TII->get(PPC::BCC)) 10540 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10541 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10542 BB->addSuccessor(loop1MBB); 10543 BB->addSuccessor(exitMBB); 10544 10545 BB = midMBB; 10546 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 10547 .addReg(ZeroReg).addReg(PtrReg); 10548 BB->addSuccessor(exitMBB); 10549 10550 // exitMBB: 10551 // ... 10552 BB = exitMBB; 10553 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 10554 .addReg(ShiftReg); 10555 } else if (MI.getOpcode() == PPC::FADDrtz) { 10556 // This pseudo performs an FADD with rounding mode temporarily forced 10557 // to round-to-zero. We emit this via custom inserter since the FPSCR 10558 // is not modeled at the SelectionDAG level. 10559 unsigned Dest = MI.getOperand(0).getReg(); 10560 unsigned Src1 = MI.getOperand(1).getReg(); 10561 unsigned Src2 = MI.getOperand(2).getReg(); 10562 DebugLoc dl = MI.getDebugLoc(); 10563 10564 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10565 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 10566 10567 // Save FPSCR value. 10568 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 10569 10570 // Set rounding mode to round-to-zero. 10571 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 10572 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 10573 10574 // Perform addition. 10575 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 10576 10577 // Restore FPSCR value. 10578 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 10579 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10580 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 10581 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10582 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 10583 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10584 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 10585 ? PPC::ANDIo8 10586 : PPC::ANDIo; 10587 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10588 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 10589 10590 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10591 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? 10592 &PPC::GPRCRegClass : 10593 &PPC::G8RCRegClass); 10594 10595 DebugLoc dl = MI.getDebugLoc(); 10596 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 10597 .addReg(MI.getOperand(1).getReg()) 10598 .addImm(1); 10599 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 10600 MI.getOperand(0).getReg()) 10601 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 10602 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 10603 DebugLoc Dl = MI.getDebugLoc(); 10604 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10605 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10606 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 10607 return BB; 10608 } else { 10609 llvm_unreachable("Unexpected instr type to insert"); 10610 } 10611 10612 MI.eraseFromParent(); // The pseudo instruction is gone now. 10613 return BB; 10614 } 10615 10616 //===----------------------------------------------------------------------===// 10617 // Target Optimization Hooks 10618 //===----------------------------------------------------------------------===// 10619 10620 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 10621 // For the estimates, convergence is quadratic, so we essentially double the 10622 // number of digits correct after every iteration. For both FRE and FRSQRTE, 10623 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 10624 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 10625 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 10626 if (VT.getScalarType() == MVT::f64) 10627 RefinementSteps++; 10628 return RefinementSteps; 10629 } 10630 10631 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 10632 int Enabled, int &RefinementSteps, 10633 bool &UseOneConstNR, 10634 bool Reciprocal) const { 10635 EVT VT = Operand.getValueType(); 10636 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 10637 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 10638 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10639 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10640 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10641 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10642 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10643 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10644 10645 UseOneConstNR = true; 10646 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 10647 } 10648 return SDValue(); 10649 } 10650 10651 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 10652 int Enabled, 10653 int &RefinementSteps) const { 10654 EVT VT = Operand.getValueType(); 10655 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 10656 (VT == MVT::f64 && Subtarget.hasFRE()) || 10657 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10658 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10659 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10660 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10661 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10662 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10663 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 10664 } 10665 return SDValue(); 10666 } 10667 10668 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 10669 // Note: This functionality is used only when unsafe-fp-math is enabled, and 10670 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 10671 // enabled for division), this functionality is redundant with the default 10672 // combiner logic (once the division -> reciprocal/multiply transformation 10673 // has taken place). As a result, this matters more for older cores than for 10674 // newer ones. 10675 10676 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10677 // reciprocal if there are two or more FDIVs (for embedded cores with only 10678 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 10679 switch (Subtarget.getDarwinDirective()) { 10680 default: 10681 return 3; 10682 case PPC::DIR_440: 10683 case PPC::DIR_A2: 10684 case PPC::DIR_E500mc: 10685 case PPC::DIR_E5500: 10686 return 2; 10687 } 10688 } 10689 10690 // isConsecutiveLSLoc needs to work even if all adds have not yet been 10691 // collapsed, and so we need to look through chains of them. 10692 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 10693 int64_t& Offset, SelectionDAG &DAG) { 10694 if (DAG.isBaseWithConstantOffset(Loc)) { 10695 Base = Loc.getOperand(0); 10696 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 10697 10698 // The base might itself be a base plus an offset, and if so, accumulate 10699 // that as well. 10700 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 10701 } 10702 } 10703 10704 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 10705 unsigned Bytes, int Dist, 10706 SelectionDAG &DAG) { 10707 if (VT.getSizeInBits() / 8 != Bytes) 10708 return false; 10709 10710 SDValue BaseLoc = Base->getBasePtr(); 10711 if (Loc.getOpcode() == ISD::FrameIndex) { 10712 if (BaseLoc.getOpcode() != ISD::FrameIndex) 10713 return false; 10714 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10715 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 10716 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 10717 int FS = MFI.getObjectSize(FI); 10718 int BFS = MFI.getObjectSize(BFI); 10719 if (FS != BFS || FS != (int)Bytes) return false; 10720 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 10721 } 10722 10723 SDValue Base1 = Loc, Base2 = BaseLoc; 10724 int64_t Offset1 = 0, Offset2 = 0; 10725 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 10726 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 10727 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 10728 return true; 10729 10730 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10731 const GlobalValue *GV1 = nullptr; 10732 const GlobalValue *GV2 = nullptr; 10733 Offset1 = 0; 10734 Offset2 = 0; 10735 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 10736 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 10737 if (isGA1 && isGA2 && GV1 == GV2) 10738 return Offset1 == (Offset2 + Dist*Bytes); 10739 return false; 10740 } 10741 10742 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 10743 // not enforce equality of the chain operands. 10744 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 10745 unsigned Bytes, int Dist, 10746 SelectionDAG &DAG) { 10747 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 10748 EVT VT = LS->getMemoryVT(); 10749 SDValue Loc = LS->getBasePtr(); 10750 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 10751 } 10752 10753 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 10754 EVT VT; 10755 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10756 default: return false; 10757 case Intrinsic::ppc_qpx_qvlfd: 10758 case Intrinsic::ppc_qpx_qvlfda: 10759 VT = MVT::v4f64; 10760 break; 10761 case Intrinsic::ppc_qpx_qvlfs: 10762 case Intrinsic::ppc_qpx_qvlfsa: 10763 VT = MVT::v4f32; 10764 break; 10765 case Intrinsic::ppc_qpx_qvlfcd: 10766 case Intrinsic::ppc_qpx_qvlfcda: 10767 VT = MVT::v2f64; 10768 break; 10769 case Intrinsic::ppc_qpx_qvlfcs: 10770 case Intrinsic::ppc_qpx_qvlfcsa: 10771 VT = MVT::v2f32; 10772 break; 10773 case Intrinsic::ppc_qpx_qvlfiwa: 10774 case Intrinsic::ppc_qpx_qvlfiwz: 10775 case Intrinsic::ppc_altivec_lvx: 10776 case Intrinsic::ppc_altivec_lvxl: 10777 case Intrinsic::ppc_vsx_lxvw4x: 10778 case Intrinsic::ppc_vsx_lxvw4x_be: 10779 VT = MVT::v4i32; 10780 break; 10781 case Intrinsic::ppc_vsx_lxvd2x: 10782 case Intrinsic::ppc_vsx_lxvd2x_be: 10783 VT = MVT::v2f64; 10784 break; 10785 case Intrinsic::ppc_altivec_lvebx: 10786 VT = MVT::i8; 10787 break; 10788 case Intrinsic::ppc_altivec_lvehx: 10789 VT = MVT::i16; 10790 break; 10791 case Intrinsic::ppc_altivec_lvewx: 10792 VT = MVT::i32; 10793 break; 10794 } 10795 10796 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 10797 } 10798 10799 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 10800 EVT VT; 10801 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10802 default: return false; 10803 case Intrinsic::ppc_qpx_qvstfd: 10804 case Intrinsic::ppc_qpx_qvstfda: 10805 VT = MVT::v4f64; 10806 break; 10807 case Intrinsic::ppc_qpx_qvstfs: 10808 case Intrinsic::ppc_qpx_qvstfsa: 10809 VT = MVT::v4f32; 10810 break; 10811 case Intrinsic::ppc_qpx_qvstfcd: 10812 case Intrinsic::ppc_qpx_qvstfcda: 10813 VT = MVT::v2f64; 10814 break; 10815 case Intrinsic::ppc_qpx_qvstfcs: 10816 case Intrinsic::ppc_qpx_qvstfcsa: 10817 VT = MVT::v2f32; 10818 break; 10819 case Intrinsic::ppc_qpx_qvstfiw: 10820 case Intrinsic::ppc_qpx_qvstfiwa: 10821 case Intrinsic::ppc_altivec_stvx: 10822 case Intrinsic::ppc_altivec_stvxl: 10823 case Intrinsic::ppc_vsx_stxvw4x: 10824 VT = MVT::v4i32; 10825 break; 10826 case Intrinsic::ppc_vsx_stxvd2x: 10827 VT = MVT::v2f64; 10828 break; 10829 case Intrinsic::ppc_vsx_stxvw4x_be: 10830 VT = MVT::v4i32; 10831 break; 10832 case Intrinsic::ppc_vsx_stxvd2x_be: 10833 VT = MVT::v2f64; 10834 break; 10835 case Intrinsic::ppc_altivec_stvebx: 10836 VT = MVT::i8; 10837 break; 10838 case Intrinsic::ppc_altivec_stvehx: 10839 VT = MVT::i16; 10840 break; 10841 case Intrinsic::ppc_altivec_stvewx: 10842 VT = MVT::i32; 10843 break; 10844 } 10845 10846 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 10847 } 10848 10849 return false; 10850 } 10851 10852 // Return true is there is a nearyby consecutive load to the one provided 10853 // (regardless of alignment). We search up and down the chain, looking though 10854 // token factors and other loads (but nothing else). As a result, a true result 10855 // indicates that it is safe to create a new consecutive load adjacent to the 10856 // load provided. 10857 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 10858 SDValue Chain = LD->getChain(); 10859 EVT VT = LD->getMemoryVT(); 10860 10861 SmallSet<SDNode *, 16> LoadRoots; 10862 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 10863 SmallSet<SDNode *, 16> Visited; 10864 10865 // First, search up the chain, branching to follow all token-factor operands. 10866 // If we find a consecutive load, then we're done, otherwise, record all 10867 // nodes just above the top-level loads and token factors. 10868 while (!Queue.empty()) { 10869 SDNode *ChainNext = Queue.pop_back_val(); 10870 if (!Visited.insert(ChainNext).second) 10871 continue; 10872 10873 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 10874 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10875 return true; 10876 10877 if (!Visited.count(ChainLD->getChain().getNode())) 10878 Queue.push_back(ChainLD->getChain().getNode()); 10879 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 10880 for (const SDUse &O : ChainNext->ops()) 10881 if (!Visited.count(O.getNode())) 10882 Queue.push_back(O.getNode()); 10883 } else 10884 LoadRoots.insert(ChainNext); 10885 } 10886 10887 // Second, search down the chain, starting from the top-level nodes recorded 10888 // in the first phase. These top-level nodes are the nodes just above all 10889 // loads and token factors. Starting with their uses, recursively look though 10890 // all loads (just the chain uses) and token factors to find a consecutive 10891 // load. 10892 Visited.clear(); 10893 Queue.clear(); 10894 10895 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 10896 IE = LoadRoots.end(); I != IE; ++I) { 10897 Queue.push_back(*I); 10898 10899 while (!Queue.empty()) { 10900 SDNode *LoadRoot = Queue.pop_back_val(); 10901 if (!Visited.insert(LoadRoot).second) 10902 continue; 10903 10904 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 10905 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10906 return true; 10907 10908 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 10909 UE = LoadRoot->use_end(); UI != UE; ++UI) 10910 if (((isa<MemSDNode>(*UI) && 10911 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 10912 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 10913 Queue.push_back(*UI); 10914 } 10915 } 10916 10917 return false; 10918 } 10919 10920 /// This function is called when we have proved that a SETCC node can be replaced 10921 /// by subtraction (and other supporting instructions) so that the result of 10922 /// comparison is kept in a GPR instead of CR. This function is purely for 10923 /// codegen purposes and has some flags to guide the codegen process. 10924 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 10925 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 10926 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10927 10928 // Zero extend the operands to the largest legal integer. Originally, they 10929 // must be of a strictly smaller size. 10930 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 10931 DAG.getConstant(Size, DL, MVT::i32)); 10932 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 10933 DAG.getConstant(Size, DL, MVT::i32)); 10934 10935 // Swap if needed. Depends on the condition code. 10936 if (Swap) 10937 std::swap(Op0, Op1); 10938 10939 // Subtract extended integers. 10940 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 10941 10942 // Move the sign bit to the least significant position and zero out the rest. 10943 // Now the least significant bit carries the result of original comparison. 10944 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 10945 DAG.getConstant(Size - 1, DL, MVT::i32)); 10946 auto Final = Shifted; 10947 10948 // Complement the result if needed. Based on the condition code. 10949 if (Complement) 10950 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 10951 DAG.getConstant(1, DL, MVT::i64)); 10952 10953 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 10954 } 10955 10956 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 10957 DAGCombinerInfo &DCI) const { 10958 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10959 10960 SelectionDAG &DAG = DCI.DAG; 10961 SDLoc DL(N); 10962 10963 // Size of integers being compared has a critical role in the following 10964 // analysis, so we prefer to do this when all types are legal. 10965 if (!DCI.isAfterLegalizeVectorOps()) 10966 return SDValue(); 10967 10968 // If all users of SETCC extend its value to a legal integer type 10969 // then we replace SETCC with a subtraction 10970 for (SDNode::use_iterator UI = N->use_begin(), 10971 UE = N->use_end(); UI != UE; ++UI) { 10972 if (UI->getOpcode() != ISD::ZERO_EXTEND) 10973 return SDValue(); 10974 } 10975 10976 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10977 auto OpSize = N->getOperand(0).getValueSizeInBits(); 10978 10979 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 10980 10981 if (OpSize < Size) { 10982 switch (CC) { 10983 default: break; 10984 case ISD::SETULT: 10985 return generateEquivalentSub(N, Size, false, false, DL, DAG); 10986 case ISD::SETULE: 10987 return generateEquivalentSub(N, Size, true, true, DL, DAG); 10988 case ISD::SETUGT: 10989 return generateEquivalentSub(N, Size, false, true, DL, DAG); 10990 case ISD::SETUGE: 10991 return generateEquivalentSub(N, Size, true, false, DL, DAG); 10992 } 10993 } 10994 10995 return SDValue(); 10996 } 10997 10998 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 10999 DAGCombinerInfo &DCI) const { 11000 SelectionDAG &DAG = DCI.DAG; 11001 SDLoc dl(N); 11002 11003 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11004 // If we're tracking CR bits, we need to be careful that we don't have: 11005 // trunc(binary-ops(zext(x), zext(y))) 11006 // or 11007 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11008 // such that we're unnecessarily moving things into GPRs when it would be 11009 // better to keep them in CR bits. 11010 11011 // Note that trunc here can be an actual i1 trunc, or can be the effective 11012 // truncation that comes from a setcc or select_cc. 11013 if (N->getOpcode() == ISD::TRUNCATE && 11014 N->getValueType(0) != MVT::i1) 11015 return SDValue(); 11016 11017 if (N->getOperand(0).getValueType() != MVT::i32 && 11018 N->getOperand(0).getValueType() != MVT::i64) 11019 return SDValue(); 11020 11021 if (N->getOpcode() == ISD::SETCC || 11022 N->getOpcode() == ISD::SELECT_CC) { 11023 // If we're looking at a comparison, then we need to make sure that the 11024 // high bits (all except for the first) don't matter the result. 11025 ISD::CondCode CC = 11026 cast<CondCodeSDNode>(N->getOperand( 11027 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11028 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11029 11030 if (ISD::isSignedIntSetCC(CC)) { 11031 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11032 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11033 return SDValue(); 11034 } else if (ISD::isUnsignedIntSetCC(CC)) { 11035 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11036 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11037 !DAG.MaskedValueIsZero(N->getOperand(1), 11038 APInt::getHighBitsSet(OpBits, OpBits-1))) 11039 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11040 : SDValue()); 11041 } else { 11042 // This is neither a signed nor an unsigned comparison, just make sure 11043 // that the high bits are equal. 11044 KnownBits Op1Known, Op2Known; 11045 DAG.computeKnownBits(N->getOperand(0), Op1Known); 11046 DAG.computeKnownBits(N->getOperand(1), Op2Known); 11047 11048 // We don't really care about what is known about the first bit (if 11049 // anything), so clear it in all masks prior to comparing them. 11050 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11051 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11052 11053 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11054 return SDValue(); 11055 } 11056 } 11057 11058 // We now know that the higher-order bits are irrelevant, we just need to 11059 // make sure that all of the intermediate operations are bit operations, and 11060 // all inputs are extensions. 11061 if (N->getOperand(0).getOpcode() != ISD::AND && 11062 N->getOperand(0).getOpcode() != ISD::OR && 11063 N->getOperand(0).getOpcode() != ISD::XOR && 11064 N->getOperand(0).getOpcode() != ISD::SELECT && 11065 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11066 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11067 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11068 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11069 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11070 return SDValue(); 11071 11072 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11073 N->getOperand(1).getOpcode() != ISD::AND && 11074 N->getOperand(1).getOpcode() != ISD::OR && 11075 N->getOperand(1).getOpcode() != ISD::XOR && 11076 N->getOperand(1).getOpcode() != ISD::SELECT && 11077 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11078 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11079 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11080 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11081 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11082 return SDValue(); 11083 11084 SmallVector<SDValue, 4> Inputs; 11085 SmallVector<SDValue, 8> BinOps, PromOps; 11086 SmallPtrSet<SDNode *, 16> Visited; 11087 11088 for (unsigned i = 0; i < 2; ++i) { 11089 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11090 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11091 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11092 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11093 isa<ConstantSDNode>(N->getOperand(i))) 11094 Inputs.push_back(N->getOperand(i)); 11095 else 11096 BinOps.push_back(N->getOperand(i)); 11097 11098 if (N->getOpcode() == ISD::TRUNCATE) 11099 break; 11100 } 11101 11102 // Visit all inputs, collect all binary operations (and, or, xor and 11103 // select) that are all fed by extensions. 11104 while (!BinOps.empty()) { 11105 SDValue BinOp = BinOps.back(); 11106 BinOps.pop_back(); 11107 11108 if (!Visited.insert(BinOp.getNode()).second) 11109 continue; 11110 11111 PromOps.push_back(BinOp); 11112 11113 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11114 // The condition of the select is not promoted. 11115 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11116 continue; 11117 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11118 continue; 11119 11120 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11121 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11122 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11123 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11124 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11125 Inputs.push_back(BinOp.getOperand(i)); 11126 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11127 BinOp.getOperand(i).getOpcode() == ISD::OR || 11128 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11129 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11130 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11131 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11132 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11133 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11134 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11135 BinOps.push_back(BinOp.getOperand(i)); 11136 } else { 11137 // We have an input that is not an extension or another binary 11138 // operation; we'll abort this transformation. 11139 return SDValue(); 11140 } 11141 } 11142 } 11143 11144 // Make sure that this is a self-contained cluster of operations (which 11145 // is not quite the same thing as saying that everything has only one 11146 // use). 11147 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11148 if (isa<ConstantSDNode>(Inputs[i])) 11149 continue; 11150 11151 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11152 UE = Inputs[i].getNode()->use_end(); 11153 UI != UE; ++UI) { 11154 SDNode *User = *UI; 11155 if (User != N && !Visited.count(User)) 11156 return SDValue(); 11157 11158 // Make sure that we're not going to promote the non-output-value 11159 // operand(s) or SELECT or SELECT_CC. 11160 // FIXME: Although we could sometimes handle this, and it does occur in 11161 // practice that one of the condition inputs to the select is also one of 11162 // the outputs, we currently can't deal with this. 11163 if (User->getOpcode() == ISD::SELECT) { 11164 if (User->getOperand(0) == Inputs[i]) 11165 return SDValue(); 11166 } else if (User->getOpcode() == ISD::SELECT_CC) { 11167 if (User->getOperand(0) == Inputs[i] || 11168 User->getOperand(1) == Inputs[i]) 11169 return SDValue(); 11170 } 11171 } 11172 } 11173 11174 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11175 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11176 UE = PromOps[i].getNode()->use_end(); 11177 UI != UE; ++UI) { 11178 SDNode *User = *UI; 11179 if (User != N && !Visited.count(User)) 11180 return SDValue(); 11181 11182 // Make sure that we're not going to promote the non-output-value 11183 // operand(s) or SELECT or SELECT_CC. 11184 // FIXME: Although we could sometimes handle this, and it does occur in 11185 // practice that one of the condition inputs to the select is also one of 11186 // the outputs, we currently can't deal with this. 11187 if (User->getOpcode() == ISD::SELECT) { 11188 if (User->getOperand(0) == PromOps[i]) 11189 return SDValue(); 11190 } else if (User->getOpcode() == ISD::SELECT_CC) { 11191 if (User->getOperand(0) == PromOps[i] || 11192 User->getOperand(1) == PromOps[i]) 11193 return SDValue(); 11194 } 11195 } 11196 } 11197 11198 // Replace all inputs with the extension operand. 11199 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11200 // Constants may have users outside the cluster of to-be-promoted nodes, 11201 // and so we need to replace those as we do the promotions. 11202 if (isa<ConstantSDNode>(Inputs[i])) 11203 continue; 11204 else 11205 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 11206 } 11207 11208 std::list<HandleSDNode> PromOpHandles; 11209 for (auto &PromOp : PromOps) 11210 PromOpHandles.emplace_back(PromOp); 11211 11212 // Replace all operations (these are all the same, but have a different 11213 // (i1) return type). DAG.getNode will validate that the types of 11214 // a binary operator match, so go through the list in reverse so that 11215 // we've likely promoted both operands first. Any intermediate truncations or 11216 // extensions disappear. 11217 while (!PromOpHandles.empty()) { 11218 SDValue PromOp = PromOpHandles.back().getValue(); 11219 PromOpHandles.pop_back(); 11220 11221 if (PromOp.getOpcode() == ISD::TRUNCATE || 11222 PromOp.getOpcode() == ISD::SIGN_EXTEND || 11223 PromOp.getOpcode() == ISD::ZERO_EXTEND || 11224 PromOp.getOpcode() == ISD::ANY_EXTEND) { 11225 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 11226 PromOp.getOperand(0).getValueType() != MVT::i1) { 11227 // The operand is not yet ready (see comment below). 11228 PromOpHandles.emplace_front(PromOp); 11229 continue; 11230 } 11231 11232 SDValue RepValue = PromOp.getOperand(0); 11233 if (isa<ConstantSDNode>(RepValue)) 11234 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 11235 11236 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 11237 continue; 11238 } 11239 11240 unsigned C; 11241 switch (PromOp.getOpcode()) { 11242 default: C = 0; break; 11243 case ISD::SELECT: C = 1; break; 11244 case ISD::SELECT_CC: C = 2; break; 11245 } 11246 11247 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11248 PromOp.getOperand(C).getValueType() != MVT::i1) || 11249 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11250 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 11251 // The to-be-promoted operands of this node have not yet been 11252 // promoted (this should be rare because we're going through the 11253 // list backward, but if one of the operands has several users in 11254 // this cluster of to-be-promoted nodes, it is possible). 11255 PromOpHandles.emplace_front(PromOp); 11256 continue; 11257 } 11258 11259 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11260 PromOp.getNode()->op_end()); 11261 11262 // If there are any constant inputs, make sure they're replaced now. 11263 for (unsigned i = 0; i < 2; ++i) 11264 if (isa<ConstantSDNode>(Ops[C+i])) 11265 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 11266 11267 DAG.ReplaceAllUsesOfValueWith(PromOp, 11268 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 11269 } 11270 11271 // Now we're left with the initial truncation itself. 11272 if (N->getOpcode() == ISD::TRUNCATE) 11273 return N->getOperand(0); 11274 11275 // Otherwise, this is a comparison. The operands to be compared have just 11276 // changed type (to i1), but everything else is the same. 11277 return SDValue(N, 0); 11278 } 11279 11280 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 11281 DAGCombinerInfo &DCI) const { 11282 SelectionDAG &DAG = DCI.DAG; 11283 SDLoc dl(N); 11284 11285 // If we're tracking CR bits, we need to be careful that we don't have: 11286 // zext(binary-ops(trunc(x), trunc(y))) 11287 // or 11288 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 11289 // such that we're unnecessarily moving things into CR bits that can more 11290 // efficiently stay in GPRs. Note that if we're not certain that the high 11291 // bits are set as required by the final extension, we still may need to do 11292 // some masking to get the proper behavior. 11293 11294 // This same functionality is important on PPC64 when dealing with 11295 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 11296 // the return values of functions. Because it is so similar, it is handled 11297 // here as well. 11298 11299 if (N->getValueType(0) != MVT::i32 && 11300 N->getValueType(0) != MVT::i64) 11301 return SDValue(); 11302 11303 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 11304 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 11305 return SDValue(); 11306 11307 if (N->getOperand(0).getOpcode() != ISD::AND && 11308 N->getOperand(0).getOpcode() != ISD::OR && 11309 N->getOperand(0).getOpcode() != ISD::XOR && 11310 N->getOperand(0).getOpcode() != ISD::SELECT && 11311 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 11312 return SDValue(); 11313 11314 SmallVector<SDValue, 4> Inputs; 11315 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 11316 SmallPtrSet<SDNode *, 16> Visited; 11317 11318 // Visit all inputs, collect all binary operations (and, or, xor and 11319 // select) that are all fed by truncations. 11320 while (!BinOps.empty()) { 11321 SDValue BinOp = BinOps.back(); 11322 BinOps.pop_back(); 11323 11324 if (!Visited.insert(BinOp.getNode()).second) 11325 continue; 11326 11327 PromOps.push_back(BinOp); 11328 11329 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11330 // The condition of the select is not promoted. 11331 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11332 continue; 11333 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11334 continue; 11335 11336 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11337 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11338 Inputs.push_back(BinOp.getOperand(i)); 11339 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11340 BinOp.getOperand(i).getOpcode() == ISD::OR || 11341 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11342 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11343 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 11344 BinOps.push_back(BinOp.getOperand(i)); 11345 } else { 11346 // We have an input that is not a truncation or another binary 11347 // operation; we'll abort this transformation. 11348 return SDValue(); 11349 } 11350 } 11351 } 11352 11353 // The operands of a select that must be truncated when the select is 11354 // promoted because the operand is actually part of the to-be-promoted set. 11355 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 11356 11357 // Make sure that this is a self-contained cluster of operations (which 11358 // is not quite the same thing as saying that everything has only one 11359 // use). 11360 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11361 if (isa<ConstantSDNode>(Inputs[i])) 11362 continue; 11363 11364 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11365 UE = Inputs[i].getNode()->use_end(); 11366 UI != UE; ++UI) { 11367 SDNode *User = *UI; 11368 if (User != N && !Visited.count(User)) 11369 return SDValue(); 11370 11371 // If we're going to promote the non-output-value operand(s) or SELECT or 11372 // SELECT_CC, record them for truncation. 11373 if (User->getOpcode() == ISD::SELECT) { 11374 if (User->getOperand(0) == Inputs[i]) 11375 SelectTruncOp[0].insert(std::make_pair(User, 11376 User->getOperand(0).getValueType())); 11377 } else if (User->getOpcode() == ISD::SELECT_CC) { 11378 if (User->getOperand(0) == Inputs[i]) 11379 SelectTruncOp[0].insert(std::make_pair(User, 11380 User->getOperand(0).getValueType())); 11381 if (User->getOperand(1) == Inputs[i]) 11382 SelectTruncOp[1].insert(std::make_pair(User, 11383 User->getOperand(1).getValueType())); 11384 } 11385 } 11386 } 11387 11388 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11389 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11390 UE = PromOps[i].getNode()->use_end(); 11391 UI != UE; ++UI) { 11392 SDNode *User = *UI; 11393 if (User != N && !Visited.count(User)) 11394 return SDValue(); 11395 11396 // If we're going to promote the non-output-value operand(s) or SELECT or 11397 // SELECT_CC, record them for truncation. 11398 if (User->getOpcode() == ISD::SELECT) { 11399 if (User->getOperand(0) == PromOps[i]) 11400 SelectTruncOp[0].insert(std::make_pair(User, 11401 User->getOperand(0).getValueType())); 11402 } else if (User->getOpcode() == ISD::SELECT_CC) { 11403 if (User->getOperand(0) == PromOps[i]) 11404 SelectTruncOp[0].insert(std::make_pair(User, 11405 User->getOperand(0).getValueType())); 11406 if (User->getOperand(1) == PromOps[i]) 11407 SelectTruncOp[1].insert(std::make_pair(User, 11408 User->getOperand(1).getValueType())); 11409 } 11410 } 11411 } 11412 11413 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 11414 bool ReallyNeedsExt = false; 11415 if (N->getOpcode() != ISD::ANY_EXTEND) { 11416 // If all of the inputs are not already sign/zero extended, then 11417 // we'll still need to do that at the end. 11418 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11419 if (isa<ConstantSDNode>(Inputs[i])) 11420 continue; 11421 11422 unsigned OpBits = 11423 Inputs[i].getOperand(0).getValueSizeInBits(); 11424 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 11425 11426 if ((N->getOpcode() == ISD::ZERO_EXTEND && 11427 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 11428 APInt::getHighBitsSet(OpBits, 11429 OpBits-PromBits))) || 11430 (N->getOpcode() == ISD::SIGN_EXTEND && 11431 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 11432 (OpBits-(PromBits-1)))) { 11433 ReallyNeedsExt = true; 11434 break; 11435 } 11436 } 11437 } 11438 11439 // Replace all inputs, either with the truncation operand, or a 11440 // truncation or extension to the final output type. 11441 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11442 // Constant inputs need to be replaced with the to-be-promoted nodes that 11443 // use them because they might have users outside of the cluster of 11444 // promoted nodes. 11445 if (isa<ConstantSDNode>(Inputs[i])) 11446 continue; 11447 11448 SDValue InSrc = Inputs[i].getOperand(0); 11449 if (Inputs[i].getValueType() == N->getValueType(0)) 11450 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 11451 else if (N->getOpcode() == ISD::SIGN_EXTEND) 11452 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11453 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 11454 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11455 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11456 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 11457 else 11458 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11459 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 11460 } 11461 11462 std::list<HandleSDNode> PromOpHandles; 11463 for (auto &PromOp : PromOps) 11464 PromOpHandles.emplace_back(PromOp); 11465 11466 // Replace all operations (these are all the same, but have a different 11467 // (promoted) return type). DAG.getNode will validate that the types of 11468 // a binary operator match, so go through the list in reverse so that 11469 // we've likely promoted both operands first. 11470 while (!PromOpHandles.empty()) { 11471 SDValue PromOp = PromOpHandles.back().getValue(); 11472 PromOpHandles.pop_back(); 11473 11474 unsigned C; 11475 switch (PromOp.getOpcode()) { 11476 default: C = 0; break; 11477 case ISD::SELECT: C = 1; break; 11478 case ISD::SELECT_CC: C = 2; break; 11479 } 11480 11481 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11482 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 11483 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11484 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 11485 // The to-be-promoted operands of this node have not yet been 11486 // promoted (this should be rare because we're going through the 11487 // list backward, but if one of the operands has several users in 11488 // this cluster of to-be-promoted nodes, it is possible). 11489 PromOpHandles.emplace_front(PromOp); 11490 continue; 11491 } 11492 11493 // For SELECT and SELECT_CC nodes, we do a similar check for any 11494 // to-be-promoted comparison inputs. 11495 if (PromOp.getOpcode() == ISD::SELECT || 11496 PromOp.getOpcode() == ISD::SELECT_CC) { 11497 if ((SelectTruncOp[0].count(PromOp.getNode()) && 11498 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 11499 (SelectTruncOp[1].count(PromOp.getNode()) && 11500 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 11501 PromOpHandles.emplace_front(PromOp); 11502 continue; 11503 } 11504 } 11505 11506 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11507 PromOp.getNode()->op_end()); 11508 11509 // If this node has constant inputs, then they'll need to be promoted here. 11510 for (unsigned i = 0; i < 2; ++i) { 11511 if (!isa<ConstantSDNode>(Ops[C+i])) 11512 continue; 11513 if (Ops[C+i].getValueType() == N->getValueType(0)) 11514 continue; 11515 11516 if (N->getOpcode() == ISD::SIGN_EXTEND) 11517 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11518 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11519 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11520 else 11521 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11522 } 11523 11524 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 11525 // truncate them again to the original value type. 11526 if (PromOp.getOpcode() == ISD::SELECT || 11527 PromOp.getOpcode() == ISD::SELECT_CC) { 11528 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 11529 if (SI0 != SelectTruncOp[0].end()) 11530 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 11531 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 11532 if (SI1 != SelectTruncOp[1].end()) 11533 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 11534 } 11535 11536 DAG.ReplaceAllUsesOfValueWith(PromOp, 11537 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 11538 } 11539 11540 // Now we're left with the initial extension itself. 11541 if (!ReallyNeedsExt) 11542 return N->getOperand(0); 11543 11544 // To zero extend, just mask off everything except for the first bit (in the 11545 // i1 case). 11546 if (N->getOpcode() == ISD::ZERO_EXTEND) 11547 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 11548 DAG.getConstant(APInt::getLowBitsSet( 11549 N->getValueSizeInBits(0), PromBits), 11550 dl, N->getValueType(0))); 11551 11552 assert(N->getOpcode() == ISD::SIGN_EXTEND && 11553 "Invalid extension type"); 11554 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 11555 SDValue ShiftCst = 11556 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 11557 return DAG.getNode( 11558 ISD::SRA, dl, N->getValueType(0), 11559 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 11560 ShiftCst); 11561 } 11562 11563 /// \brief Reduces the number of fp-to-int conversion when building a vector. 11564 /// 11565 /// If this vector is built out of floating to integer conversions, 11566 /// transform it to a vector built out of floating point values followed by a 11567 /// single floating to integer conversion of the vector. 11568 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 11569 /// becomes (fptosi (build_vector ($A, $B, ...))) 11570 SDValue PPCTargetLowering:: 11571 combineElementTruncationToVectorTruncation(SDNode *N, 11572 DAGCombinerInfo &DCI) const { 11573 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11574 "Should be called with a BUILD_VECTOR node"); 11575 11576 SelectionDAG &DAG = DCI.DAG; 11577 SDLoc dl(N); 11578 11579 SDValue FirstInput = N->getOperand(0); 11580 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 11581 "The input operand must be an fp-to-int conversion."); 11582 11583 // This combine happens after legalization so the fp_to_[su]i nodes are 11584 // already converted to PPCSISD nodes. 11585 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 11586 if (FirstConversion == PPCISD::FCTIDZ || 11587 FirstConversion == PPCISD::FCTIDUZ || 11588 FirstConversion == PPCISD::FCTIWZ || 11589 FirstConversion == PPCISD::FCTIWUZ) { 11590 bool IsSplat = true; 11591 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 11592 FirstConversion == PPCISD::FCTIWUZ; 11593 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 11594 SmallVector<SDValue, 4> Ops; 11595 EVT TargetVT = N->getValueType(0); 11596 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11597 if (N->getOperand(i).getOpcode() != PPCISD::MFVSR) 11598 return SDValue(); 11599 unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode(); 11600 if (NextConversion != FirstConversion) 11601 return SDValue(); 11602 if (N->getOperand(i) != FirstInput) 11603 IsSplat = false; 11604 } 11605 11606 // If this is a splat, we leave it as-is since there will be only a single 11607 // fp-to-int conversion followed by a splat of the integer. This is better 11608 // for 32-bit and smaller ints and neutral for 64-bit ints. 11609 if (IsSplat) 11610 return SDValue(); 11611 11612 // Now that we know we have the right type of node, get its operands 11613 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11614 SDValue In = N->getOperand(i).getOperand(0); 11615 // For 32-bit values, we need to add an FP_ROUND node. 11616 if (Is32Bit) { 11617 if (In.isUndef()) 11618 Ops.push_back(DAG.getUNDEF(SrcVT)); 11619 else { 11620 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 11621 MVT::f32, In.getOperand(0), 11622 DAG.getIntPtrConstant(1, dl)); 11623 Ops.push_back(Trunc); 11624 } 11625 } else 11626 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 11627 } 11628 11629 unsigned Opcode; 11630 if (FirstConversion == PPCISD::FCTIDZ || 11631 FirstConversion == PPCISD::FCTIWZ) 11632 Opcode = ISD::FP_TO_SINT; 11633 else 11634 Opcode = ISD::FP_TO_UINT; 11635 11636 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 11637 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 11638 return DAG.getNode(Opcode, dl, TargetVT, BV); 11639 } 11640 return SDValue(); 11641 } 11642 11643 /// \brief Reduce the number of loads when building a vector. 11644 /// 11645 /// Building a vector out of multiple loads can be converted to a load 11646 /// of the vector type if the loads are consecutive. If the loads are 11647 /// consecutive but in descending order, a shuffle is added at the end 11648 /// to reorder the vector. 11649 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 11650 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11651 "Should be called with a BUILD_VECTOR node"); 11652 11653 SDLoc dl(N); 11654 bool InputsAreConsecutiveLoads = true; 11655 bool InputsAreReverseConsecutive = true; 11656 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8; 11657 SDValue FirstInput = N->getOperand(0); 11658 bool IsRoundOfExtLoad = false; 11659 11660 if (FirstInput.getOpcode() == ISD::FP_ROUND && 11661 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 11662 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 11663 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 11664 } 11665 // Not a build vector of (possibly fp_rounded) loads. 11666 if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) 11667 return SDValue(); 11668 11669 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 11670 // If any inputs are fp_round(extload), they all must be. 11671 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 11672 return SDValue(); 11673 11674 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 11675 N->getOperand(i); 11676 if (NextInput.getOpcode() != ISD::LOAD) 11677 return SDValue(); 11678 11679 SDValue PreviousInput = 11680 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 11681 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 11682 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 11683 11684 // If any inputs are fp_round(extload), they all must be. 11685 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 11686 return SDValue(); 11687 11688 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 11689 InputsAreConsecutiveLoads = false; 11690 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 11691 InputsAreReverseConsecutive = false; 11692 11693 // Exit early if the loads are neither consecutive nor reverse consecutive. 11694 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 11695 return SDValue(); 11696 } 11697 11698 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 11699 "The loads cannot be both consecutive and reverse consecutive."); 11700 11701 SDValue FirstLoadOp = 11702 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 11703 SDValue LastLoadOp = 11704 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 11705 N->getOperand(N->getNumOperands()-1); 11706 11707 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 11708 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 11709 if (InputsAreConsecutiveLoads) { 11710 assert(LD1 && "Input needs to be a LoadSDNode."); 11711 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 11712 LD1->getBasePtr(), LD1->getPointerInfo(), 11713 LD1->getAlignment()); 11714 } 11715 if (InputsAreReverseConsecutive) { 11716 assert(LDL && "Input needs to be a LoadSDNode."); 11717 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 11718 LDL->getBasePtr(), LDL->getPointerInfo(), 11719 LDL->getAlignment()); 11720 SmallVector<int, 16> Ops; 11721 for (int i = N->getNumOperands() - 1; i >= 0; i--) 11722 Ops.push_back(i); 11723 11724 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 11725 DAG.getUNDEF(N->getValueType(0)), Ops); 11726 } 11727 return SDValue(); 11728 } 11729 11730 // This function adds the required vector_shuffle needed to get 11731 // the elements of the vector extract in the correct position 11732 // as specified by the CorrectElems encoding. 11733 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 11734 SDValue Input, uint64_t Elems, 11735 uint64_t CorrectElems) { 11736 SDLoc dl(N); 11737 11738 unsigned NumElems = Input.getValueType().getVectorNumElements(); 11739 SmallVector<int, 16> ShuffleMask(NumElems, -1); 11740 11741 // Knowing the element indices being extracted from the original 11742 // vector and the order in which they're being inserted, just put 11743 // them at element indices required for the instruction. 11744 for (unsigned i = 0; i < N->getNumOperands(); i++) { 11745 if (DAG.getDataLayout().isLittleEndian()) 11746 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 11747 else 11748 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 11749 CorrectElems = CorrectElems >> 8; 11750 Elems = Elems >> 8; 11751 } 11752 11753 SDValue Shuffle = 11754 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 11755 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 11756 11757 EVT Ty = N->getValueType(0); 11758 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 11759 return BV; 11760 } 11761 11762 // Look for build vector patterns where input operands come from sign 11763 // extended vector_extract elements of specific indices. If the correct indices 11764 // aren't used, add a vector shuffle to fix up the indices and create a new 11765 // PPCISD:SExtVElems node which selects the vector sign extend instructions 11766 // during instruction selection. 11767 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 11768 // This array encodes the indices that the vector sign extend instructions 11769 // extract from when extending from one type to another for both BE and LE. 11770 // The right nibble of each byte corresponds to the LE incides. 11771 // and the left nibble of each byte corresponds to the BE incides. 11772 // For example: 0x3074B8FC byte->word 11773 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 11774 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 11775 // For example: 0x000070F8 byte->double word 11776 // For LE: the allowed indices are: 0x0,0x8 11777 // For BE: the allowed indices are: 0x7,0xF 11778 uint64_t TargetElems[] = { 11779 0x3074B8FC, // b->w 11780 0x000070F8, // b->d 11781 0x10325476, // h->w 11782 0x00003074, // h->d 11783 0x00001032, // w->d 11784 }; 11785 11786 uint64_t Elems = 0; 11787 int Index; 11788 SDValue Input; 11789 11790 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 11791 if (!Op) 11792 return false; 11793 if (Op.getOpcode() != ISD::SIGN_EXTEND) 11794 return false; 11795 11796 SDValue Extract = Op.getOperand(0); 11797 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11798 return false; 11799 11800 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 11801 if (!ExtOp) 11802 return false; 11803 11804 Index = ExtOp->getZExtValue(); 11805 if (Input && Input != Extract.getOperand(0)) 11806 return false; 11807 11808 if (!Input) 11809 Input = Extract.getOperand(0); 11810 11811 Elems = Elems << 8; 11812 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 11813 Elems |= Index; 11814 11815 return true; 11816 }; 11817 11818 // If the build vector operands aren't sign extended vector extracts, 11819 // of the same input vector, then return. 11820 for (unsigned i = 0; i < N->getNumOperands(); i++) { 11821 if (!isSExtOfVecExtract(N->getOperand(i))) { 11822 return SDValue(); 11823 } 11824 } 11825 11826 // If the vector extract indicies are not correct, add the appropriate 11827 // vector_shuffle. 11828 int TgtElemArrayIdx; 11829 int InputSize = Input.getValueType().getScalarSizeInBits(); 11830 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 11831 if (InputSize + OutputSize == 40) 11832 TgtElemArrayIdx = 0; 11833 else if (InputSize + OutputSize == 72) 11834 TgtElemArrayIdx = 1; 11835 else if (InputSize + OutputSize == 48) 11836 TgtElemArrayIdx = 2; 11837 else if (InputSize + OutputSize == 80) 11838 TgtElemArrayIdx = 3; 11839 else if (InputSize + OutputSize == 96) 11840 TgtElemArrayIdx = 4; 11841 else 11842 return SDValue(); 11843 11844 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 11845 CorrectElems = DAG.getDataLayout().isLittleEndian() 11846 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 11847 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 11848 if (Elems != CorrectElems) { 11849 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 11850 } 11851 11852 // Regular lowering will catch cases where a shuffle is not needed. 11853 return SDValue(); 11854 } 11855 11856 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 11857 DAGCombinerInfo &DCI) const { 11858 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11859 "Should be called with a BUILD_VECTOR node"); 11860 11861 SelectionDAG &DAG = DCI.DAG; 11862 SDLoc dl(N); 11863 11864 if (!Subtarget.hasVSX()) 11865 return SDValue(); 11866 11867 // The target independent DAG combiner will leave a build_vector of 11868 // float-to-int conversions intact. We can generate MUCH better code for 11869 // a float-to-int conversion of a vector of floats. 11870 SDValue FirstInput = N->getOperand(0); 11871 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 11872 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 11873 if (Reduced) 11874 return Reduced; 11875 } 11876 11877 // If we're building a vector out of consecutive loads, just load that 11878 // vector type. 11879 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 11880 if (Reduced) 11881 return Reduced; 11882 11883 // If we're building a vector out of extended elements from another vector 11884 // we have P9 vector integer extend instructions. 11885 if (Subtarget.hasP9Altivec()) { 11886 Reduced = combineBVOfVecSExt(N, DAG); 11887 if (Reduced) 11888 return Reduced; 11889 } 11890 11891 11892 if (N->getValueType(0) != MVT::v2f64) 11893 return SDValue(); 11894 11895 // Looking for: 11896 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 11897 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 11898 FirstInput.getOpcode() != ISD::UINT_TO_FP) 11899 return SDValue(); 11900 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 11901 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 11902 return SDValue(); 11903 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 11904 return SDValue(); 11905 11906 SDValue Ext1 = FirstInput.getOperand(0); 11907 SDValue Ext2 = N->getOperand(1).getOperand(0); 11908 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11909 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11910 return SDValue(); 11911 11912 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 11913 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 11914 if (!Ext1Op || !Ext2Op) 11915 return SDValue(); 11916 if (Ext1.getValueType() != MVT::i32 || 11917 Ext2.getValueType() != MVT::i32) 11918 if (Ext1.getOperand(0) != Ext2.getOperand(0)) 11919 return SDValue(); 11920 11921 int FirstElem = Ext1Op->getZExtValue(); 11922 int SecondElem = Ext2Op->getZExtValue(); 11923 int SubvecIdx; 11924 if (FirstElem == 0 && SecondElem == 1) 11925 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 11926 else if (FirstElem == 2 && SecondElem == 3) 11927 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 11928 else 11929 return SDValue(); 11930 11931 SDValue SrcVec = Ext1.getOperand(0); 11932 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 11933 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 11934 return DAG.getNode(NodeType, dl, MVT::v2f64, 11935 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 11936 } 11937 11938 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 11939 DAGCombinerInfo &DCI) const { 11940 assert((N->getOpcode() == ISD::SINT_TO_FP || 11941 N->getOpcode() == ISD::UINT_TO_FP) && 11942 "Need an int -> FP conversion node here"); 11943 11944 if (useSoftFloat() || !Subtarget.has64BitSupport()) 11945 return SDValue(); 11946 11947 SelectionDAG &DAG = DCI.DAG; 11948 SDLoc dl(N); 11949 SDValue Op(N, 0); 11950 11951 // Don't handle ppc_fp128 here or i1 conversions. 11952 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 11953 return SDValue(); 11954 if (Op.getOperand(0).getValueType() == MVT::i1) 11955 return SDValue(); 11956 11957 SDValue FirstOperand(Op.getOperand(0)); 11958 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 11959 (FirstOperand.getValueType() == MVT::i8 || 11960 FirstOperand.getValueType() == MVT::i16); 11961 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 11962 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 11963 bool DstDouble = Op.getValueType() == MVT::f64; 11964 unsigned ConvOp = Signed ? 11965 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 11966 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 11967 SDValue WidthConst = 11968 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 11969 dl, false); 11970 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 11971 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 11972 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 11973 DAG.getVTList(MVT::f64, MVT::Other), 11974 Ops, MVT::i8, LDN->getMemOperand()); 11975 11976 // For signed conversion, we need to sign-extend the value in the VSR 11977 if (Signed) { 11978 SDValue ExtOps[] = { Ld, WidthConst }; 11979 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 11980 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 11981 } else 11982 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 11983 } 11984 11985 11986 // For i32 intermediate values, unfortunately, the conversion functions 11987 // leave the upper 32 bits of the value are undefined. Within the set of 11988 // scalar instructions, we have no method for zero- or sign-extending the 11989 // value. Thus, we cannot handle i32 intermediate values here. 11990 if (Op.getOperand(0).getValueType() == MVT::i32) 11991 return SDValue(); 11992 11993 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 11994 "UINT_TO_FP is supported only with FPCVT"); 11995 11996 // If we have FCFIDS, then use it when converting to single-precision. 11997 // Otherwise, convert to double-precision and then round. 11998 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 11999 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12000 : PPCISD::FCFIDS) 12001 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12002 : PPCISD::FCFID); 12003 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12004 ? MVT::f32 12005 : MVT::f64; 12006 12007 // If we're converting from a float, to an int, and back to a float again, 12008 // then we don't need the store/load pair at all. 12009 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12010 Subtarget.hasFPCVT()) || 12011 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12012 SDValue Src = Op.getOperand(0).getOperand(0); 12013 if (Src.getValueType() == MVT::f32) { 12014 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12015 DCI.AddToWorklist(Src.getNode()); 12016 } else if (Src.getValueType() != MVT::f64) { 12017 // Make sure that we don't pick up a ppc_fp128 source value. 12018 return SDValue(); 12019 } 12020 12021 unsigned FCTOp = 12022 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12023 PPCISD::FCTIDUZ; 12024 12025 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12026 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12027 12028 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12029 FP = DAG.getNode(ISD::FP_ROUND, dl, 12030 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12031 DCI.AddToWorklist(FP.getNode()); 12032 } 12033 12034 return FP; 12035 } 12036 12037 return SDValue(); 12038 } 12039 12040 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12041 // builtins) into loads with swaps. 12042 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12043 DAGCombinerInfo &DCI) const { 12044 SelectionDAG &DAG = DCI.DAG; 12045 SDLoc dl(N); 12046 SDValue Chain; 12047 SDValue Base; 12048 MachineMemOperand *MMO; 12049 12050 switch (N->getOpcode()) { 12051 default: 12052 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12053 case ISD::LOAD: { 12054 LoadSDNode *LD = cast<LoadSDNode>(N); 12055 Chain = LD->getChain(); 12056 Base = LD->getBasePtr(); 12057 MMO = LD->getMemOperand(); 12058 // If the MMO suggests this isn't a load of a full vector, leave 12059 // things alone. For a built-in, we have to make the change for 12060 // correctness, so if there is a size problem that will be a bug. 12061 if (MMO->getSize() < 16) 12062 return SDValue(); 12063 break; 12064 } 12065 case ISD::INTRINSIC_W_CHAIN: { 12066 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12067 Chain = Intrin->getChain(); 12068 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12069 // us what we want. Get operand 2 instead. 12070 Base = Intrin->getOperand(2); 12071 MMO = Intrin->getMemOperand(); 12072 break; 12073 } 12074 } 12075 12076 MVT VecTy = N->getValueType(0).getSimpleVT(); 12077 12078 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12079 // aligned and the type is a vector with elements up to 4 bytes 12080 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12081 && VecTy.getScalarSizeInBits() <= 32 ) { 12082 return SDValue(); 12083 } 12084 12085 SDValue LoadOps[] = { Chain, Base }; 12086 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12087 DAG.getVTList(MVT::v2f64, MVT::Other), 12088 LoadOps, MVT::v2f64, MMO); 12089 12090 DCI.AddToWorklist(Load.getNode()); 12091 Chain = Load.getValue(1); 12092 SDValue Swap = DAG.getNode( 12093 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12094 DCI.AddToWorklist(Swap.getNode()); 12095 12096 // Add a bitcast if the resulting load type doesn't match v2f64. 12097 if (VecTy != MVT::v2f64) { 12098 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12099 DCI.AddToWorklist(N.getNode()); 12100 // Package {bitcast value, swap's chain} to match Load's shape. 12101 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12102 N, Swap.getValue(1)); 12103 } 12104 12105 return Swap; 12106 } 12107 12108 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12109 // builtins) into stores with swaps. 12110 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12111 DAGCombinerInfo &DCI) const { 12112 SelectionDAG &DAG = DCI.DAG; 12113 SDLoc dl(N); 12114 SDValue Chain; 12115 SDValue Base; 12116 unsigned SrcOpnd; 12117 MachineMemOperand *MMO; 12118 12119 switch (N->getOpcode()) { 12120 default: 12121 llvm_unreachable("Unexpected opcode for little endian VSX store"); 12122 case ISD::STORE: { 12123 StoreSDNode *ST = cast<StoreSDNode>(N); 12124 Chain = ST->getChain(); 12125 Base = ST->getBasePtr(); 12126 MMO = ST->getMemOperand(); 12127 SrcOpnd = 1; 12128 // If the MMO suggests this isn't a store of a full vector, leave 12129 // things alone. For a built-in, we have to make the change for 12130 // correctness, so if there is a size problem that will be a bug. 12131 if (MMO->getSize() < 16) 12132 return SDValue(); 12133 break; 12134 } 12135 case ISD::INTRINSIC_VOID: { 12136 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12137 Chain = Intrin->getChain(); 12138 // Intrin->getBasePtr() oddly does not get what we want. 12139 Base = Intrin->getOperand(3); 12140 MMO = Intrin->getMemOperand(); 12141 SrcOpnd = 2; 12142 break; 12143 } 12144 } 12145 12146 SDValue Src = N->getOperand(SrcOpnd); 12147 MVT VecTy = Src.getValueType().getSimpleVT(); 12148 12149 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 12150 // aligned and the type is a vector with elements up to 4 bytes 12151 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12152 && VecTy.getScalarSizeInBits() <= 32 ) { 12153 return SDValue(); 12154 } 12155 12156 // All stores are done as v2f64 and possible bit cast. 12157 if (VecTy != MVT::v2f64) { 12158 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 12159 DCI.AddToWorklist(Src.getNode()); 12160 } 12161 12162 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 12163 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 12164 DCI.AddToWorklist(Swap.getNode()); 12165 Chain = Swap.getValue(1); 12166 SDValue StoreOps[] = { Chain, Swap, Base }; 12167 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 12168 DAG.getVTList(MVT::Other), 12169 StoreOps, VecTy, MMO); 12170 DCI.AddToWorklist(Store.getNode()); 12171 return Store; 12172 } 12173 12174 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 12175 DAGCombinerInfo &DCI) const { 12176 SelectionDAG &DAG = DCI.DAG; 12177 SDLoc dl(N); 12178 switch (N->getOpcode()) { 12179 default: break; 12180 case ISD::SHL: 12181 return combineSHL(N, DCI); 12182 case ISD::SRA: 12183 return combineSRA(N, DCI); 12184 case ISD::SRL: 12185 return combineSRL(N, DCI); 12186 case PPCISD::SHL: 12187 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 12188 return N->getOperand(0); 12189 break; 12190 case PPCISD::SRL: 12191 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 12192 return N->getOperand(0); 12193 break; 12194 case PPCISD::SRA: 12195 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 12196 if (C->isNullValue() || // 0 >>s V -> 0. 12197 C->isAllOnesValue()) // -1 >>s V -> -1. 12198 return N->getOperand(0); 12199 } 12200 break; 12201 case ISD::SIGN_EXTEND: 12202 case ISD::ZERO_EXTEND: 12203 case ISD::ANY_EXTEND: 12204 return DAGCombineExtBoolTrunc(N, DCI); 12205 case ISD::TRUNCATE: 12206 case ISD::SETCC: 12207 case ISD::SELECT_CC: 12208 return DAGCombineTruncBoolExt(N, DCI); 12209 case ISD::SINT_TO_FP: 12210 case ISD::UINT_TO_FP: 12211 return combineFPToIntToFP(N, DCI); 12212 case ISD::STORE: { 12213 EVT Op1VT = N->getOperand(1).getValueType(); 12214 bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) || 12215 (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16)); 12216 12217 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)). 12218 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() && 12219 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT && 12220 ValidTypeForStoreFltAsInt && 12221 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) { 12222 SDValue Val = N->getOperand(1).getOperand(0); 12223 if (Val.getValueType() == MVT::f32) { 12224 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 12225 DCI.AddToWorklist(Val.getNode()); 12226 } 12227 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val); 12228 DCI.AddToWorklist(Val.getNode()); 12229 12230 if (Op1VT == MVT::i32) { 12231 SDValue Ops[] = { 12232 N->getOperand(0), Val, N->getOperand(2), 12233 DAG.getValueType(N->getOperand(1).getValueType()) 12234 }; 12235 12236 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 12237 DAG.getVTList(MVT::Other), Ops, 12238 cast<StoreSDNode>(N)->getMemoryVT(), 12239 cast<StoreSDNode>(N)->getMemOperand()); 12240 } else { 12241 unsigned WidthInBytes = 12242 N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2; 12243 SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false); 12244 12245 SDValue Ops[] = { 12246 N->getOperand(0), Val, N->getOperand(2), WidthConst, 12247 DAG.getValueType(N->getOperand(1).getValueType()) 12248 }; 12249 Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl, 12250 DAG.getVTList(MVT::Other), Ops, 12251 cast<StoreSDNode>(N)->getMemoryVT(), 12252 cast<StoreSDNode>(N)->getMemOperand()); 12253 } 12254 12255 DCI.AddToWorklist(Val.getNode()); 12256 return Val; 12257 } 12258 12259 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 12260 if (cast<StoreSDNode>(N)->isUnindexed() && 12261 N->getOperand(1).getOpcode() == ISD::BSWAP && 12262 N->getOperand(1).getNode()->hasOneUse() && 12263 (N->getOperand(1).getValueType() == MVT::i32 || 12264 N->getOperand(1).getValueType() == MVT::i16 || 12265 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 12266 N->getOperand(1).getValueType() == MVT::i64))) { 12267 SDValue BSwapOp = N->getOperand(1).getOperand(0); 12268 // Do an any-extend to 32-bits if this is a half-word input. 12269 if (BSwapOp.getValueType() == MVT::i16) 12270 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 12271 12272 // If the type of BSWAP operand is wider than stored memory width 12273 // it need to be shifted to the right side before STBRX. 12274 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 12275 if (Op1VT.bitsGT(mVT)) { 12276 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 12277 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 12278 DAG.getConstant(Shift, dl, MVT::i32)); 12279 // Need to truncate if this is a bswap of i64 stored as i32/i16. 12280 if (Op1VT == MVT::i64) 12281 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 12282 } 12283 12284 SDValue Ops[] = { 12285 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 12286 }; 12287 return 12288 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 12289 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 12290 cast<StoreSDNode>(N)->getMemOperand()); 12291 } 12292 12293 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 12294 // So it can increase the chance of CSE constant construction. 12295 EVT VT = N->getOperand(1).getValueType(); 12296 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 12297 isa<ConstantSDNode>(N->getOperand(1)) && VT == MVT::i32) { 12298 // Need to sign-extended to 64-bits to handle negative values. 12299 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 12300 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 12301 MemVT.getSizeInBits()); 12302 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 12303 12304 // DAG.getTruncStore() can't be used here because it doesn't accept 12305 // the general (base + offset) addressing mode. 12306 // So we use UpdateNodeOperands and setTruncatingStore instead. 12307 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 12308 N->getOperand(3)); 12309 cast<StoreSDNode>(N)->setTruncatingStore(true); 12310 return SDValue(N, 0); 12311 } 12312 12313 // For little endian, VSX stores require generating xxswapd/lxvd2x. 12314 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12315 if (VT.isSimple()) { 12316 MVT StoreVT = VT.getSimpleVT(); 12317 if (Subtarget.needsSwapsForVSXMemOps() && 12318 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 12319 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 12320 return expandVSXStoreForLE(N, DCI); 12321 } 12322 break; 12323 } 12324 case ISD::LOAD: { 12325 LoadSDNode *LD = cast<LoadSDNode>(N); 12326 EVT VT = LD->getValueType(0); 12327 12328 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12329 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12330 if (VT.isSimple()) { 12331 MVT LoadVT = VT.getSimpleVT(); 12332 if (Subtarget.needsSwapsForVSXMemOps() && 12333 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 12334 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 12335 return expandVSXLoadForLE(N, DCI); 12336 } 12337 12338 // We sometimes end up with a 64-bit integer load, from which we extract 12339 // two single-precision floating-point numbers. This happens with 12340 // std::complex<float>, and other similar structures, because of the way we 12341 // canonicalize structure copies. However, if we lack direct moves, 12342 // then the final bitcasts from the extracted integer values to the 12343 // floating-point numbers turn into store/load pairs. Even with direct moves, 12344 // just loading the two floating-point numbers is likely better. 12345 auto ReplaceTwoFloatLoad = [&]() { 12346 if (VT != MVT::i64) 12347 return false; 12348 12349 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 12350 LD->isVolatile()) 12351 return false; 12352 12353 // We're looking for a sequence like this: 12354 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 12355 // t16: i64 = srl t13, Constant:i32<32> 12356 // t17: i32 = truncate t16 12357 // t18: f32 = bitcast t17 12358 // t19: i32 = truncate t13 12359 // t20: f32 = bitcast t19 12360 12361 if (!LD->hasNUsesOfValue(2, 0)) 12362 return false; 12363 12364 auto UI = LD->use_begin(); 12365 while (UI.getUse().getResNo() != 0) ++UI; 12366 SDNode *Trunc = *UI++; 12367 while (UI.getUse().getResNo() != 0) ++UI; 12368 SDNode *RightShift = *UI; 12369 if (Trunc->getOpcode() != ISD::TRUNCATE) 12370 std::swap(Trunc, RightShift); 12371 12372 if (Trunc->getOpcode() != ISD::TRUNCATE || 12373 Trunc->getValueType(0) != MVT::i32 || 12374 !Trunc->hasOneUse()) 12375 return false; 12376 if (RightShift->getOpcode() != ISD::SRL || 12377 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 12378 RightShift->getConstantOperandVal(1) != 32 || 12379 !RightShift->hasOneUse()) 12380 return false; 12381 12382 SDNode *Trunc2 = *RightShift->use_begin(); 12383 if (Trunc2->getOpcode() != ISD::TRUNCATE || 12384 Trunc2->getValueType(0) != MVT::i32 || 12385 !Trunc2->hasOneUse()) 12386 return false; 12387 12388 SDNode *Bitcast = *Trunc->use_begin(); 12389 SDNode *Bitcast2 = *Trunc2->use_begin(); 12390 12391 if (Bitcast->getOpcode() != ISD::BITCAST || 12392 Bitcast->getValueType(0) != MVT::f32) 12393 return false; 12394 if (Bitcast2->getOpcode() != ISD::BITCAST || 12395 Bitcast2->getValueType(0) != MVT::f32) 12396 return false; 12397 12398 if (Subtarget.isLittleEndian()) 12399 std::swap(Bitcast, Bitcast2); 12400 12401 // Bitcast has the second float (in memory-layout order) and Bitcast2 12402 // has the first one. 12403 12404 SDValue BasePtr = LD->getBasePtr(); 12405 if (LD->isIndexed()) { 12406 assert(LD->getAddressingMode() == ISD::PRE_INC && 12407 "Non-pre-inc AM on PPC?"); 12408 BasePtr = 12409 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 12410 LD->getOffset()); 12411 } 12412 12413 auto MMOFlags = 12414 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 12415 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 12416 LD->getPointerInfo(), LD->getAlignment(), 12417 MMOFlags, LD->getAAInfo()); 12418 SDValue AddPtr = 12419 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 12420 BasePtr, DAG.getIntPtrConstant(4, dl)); 12421 SDValue FloatLoad2 = DAG.getLoad( 12422 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 12423 LD->getPointerInfo().getWithOffset(4), 12424 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 12425 12426 if (LD->isIndexed()) { 12427 // Note that DAGCombine should re-form any pre-increment load(s) from 12428 // what is produced here if that makes sense. 12429 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 12430 } 12431 12432 DCI.CombineTo(Bitcast2, FloatLoad); 12433 DCI.CombineTo(Bitcast, FloatLoad2); 12434 12435 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 12436 SDValue(FloatLoad2.getNode(), 1)); 12437 return true; 12438 }; 12439 12440 if (ReplaceTwoFloatLoad()) 12441 return SDValue(N, 0); 12442 12443 EVT MemVT = LD->getMemoryVT(); 12444 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 12445 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 12446 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 12447 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 12448 if (LD->isUnindexed() && VT.isVector() && 12449 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 12450 // P8 and later hardware should just use LOAD. 12451 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 12452 VT == MVT::v4i32 || VT == MVT::v4f32)) || 12453 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 12454 LD->getAlignment() >= ScalarABIAlignment)) && 12455 LD->getAlignment() < ABIAlignment) { 12456 // This is a type-legal unaligned Altivec or QPX load. 12457 SDValue Chain = LD->getChain(); 12458 SDValue Ptr = LD->getBasePtr(); 12459 bool isLittleEndian = Subtarget.isLittleEndian(); 12460 12461 // This implements the loading of unaligned vectors as described in 12462 // the venerable Apple Velocity Engine overview. Specifically: 12463 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 12464 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 12465 // 12466 // The general idea is to expand a sequence of one or more unaligned 12467 // loads into an alignment-based permutation-control instruction (lvsl 12468 // or lvsr), a series of regular vector loads (which always truncate 12469 // their input address to an aligned address), and a series of 12470 // permutations. The results of these permutations are the requested 12471 // loaded values. The trick is that the last "extra" load is not taken 12472 // from the address you might suspect (sizeof(vector) bytes after the 12473 // last requested load), but rather sizeof(vector) - 1 bytes after the 12474 // last requested vector. The point of this is to avoid a page fault if 12475 // the base address happened to be aligned. This works because if the 12476 // base address is aligned, then adding less than a full vector length 12477 // will cause the last vector in the sequence to be (re)loaded. 12478 // Otherwise, the next vector will be fetched as you might suspect was 12479 // necessary. 12480 12481 // We might be able to reuse the permutation generation from 12482 // a different base address offset from this one by an aligned amount. 12483 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 12484 // optimization later. 12485 Intrinsic::ID Intr, IntrLD, IntrPerm; 12486 MVT PermCntlTy, PermTy, LDTy; 12487 if (Subtarget.hasAltivec()) { 12488 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 12489 Intrinsic::ppc_altivec_lvsl; 12490 IntrLD = Intrinsic::ppc_altivec_lvx; 12491 IntrPerm = Intrinsic::ppc_altivec_vperm; 12492 PermCntlTy = MVT::v16i8; 12493 PermTy = MVT::v4i32; 12494 LDTy = MVT::v4i32; 12495 } else { 12496 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 12497 Intrinsic::ppc_qpx_qvlpcls; 12498 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 12499 Intrinsic::ppc_qpx_qvlfs; 12500 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 12501 PermCntlTy = MVT::v4f64; 12502 PermTy = MVT::v4f64; 12503 LDTy = MemVT.getSimpleVT(); 12504 } 12505 12506 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 12507 12508 // Create the new MMO for the new base load. It is like the original MMO, 12509 // but represents an area in memory almost twice the vector size centered 12510 // on the original address. If the address is unaligned, we might start 12511 // reading up to (sizeof(vector)-1) bytes below the address of the 12512 // original unaligned load. 12513 MachineFunction &MF = DAG.getMachineFunction(); 12514 MachineMemOperand *BaseMMO = 12515 MF.getMachineMemOperand(LD->getMemOperand(), 12516 -(long)MemVT.getStoreSize()+1, 12517 2*MemVT.getStoreSize()-1); 12518 12519 // Create the new base load. 12520 SDValue LDXIntID = 12521 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 12522 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 12523 SDValue BaseLoad = 12524 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12525 DAG.getVTList(PermTy, MVT::Other), 12526 BaseLoadOps, LDTy, BaseMMO); 12527 12528 // Note that the value of IncOffset (which is provided to the next 12529 // load's pointer info offset value, and thus used to calculate the 12530 // alignment), and the value of IncValue (which is actually used to 12531 // increment the pointer value) are different! This is because we 12532 // require the next load to appear to be aligned, even though it 12533 // is actually offset from the base pointer by a lesser amount. 12534 int IncOffset = VT.getSizeInBits() / 8; 12535 int IncValue = IncOffset; 12536 12537 // Walk (both up and down) the chain looking for another load at the real 12538 // (aligned) offset (the alignment of the other load does not matter in 12539 // this case). If found, then do not use the offset reduction trick, as 12540 // that will prevent the loads from being later combined (as they would 12541 // otherwise be duplicates). 12542 if (!findConsecutiveLoad(LD, DAG)) 12543 --IncValue; 12544 12545 SDValue Increment = 12546 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 12547 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 12548 12549 MachineMemOperand *ExtraMMO = 12550 MF.getMachineMemOperand(LD->getMemOperand(), 12551 1, 2*MemVT.getStoreSize()-1); 12552 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 12553 SDValue ExtraLoad = 12554 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12555 DAG.getVTList(PermTy, MVT::Other), 12556 ExtraLoadOps, LDTy, ExtraMMO); 12557 12558 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 12559 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 12560 12561 // Because vperm has a big-endian bias, we must reverse the order 12562 // of the input vectors and complement the permute control vector 12563 // when generating little endian code. We have already handled the 12564 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 12565 // and ExtraLoad here. 12566 SDValue Perm; 12567 if (isLittleEndian) 12568 Perm = BuildIntrinsicOp(IntrPerm, 12569 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 12570 else 12571 Perm = BuildIntrinsicOp(IntrPerm, 12572 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 12573 12574 if (VT != PermTy) 12575 Perm = Subtarget.hasAltivec() ? 12576 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 12577 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 12578 DAG.getTargetConstant(1, dl, MVT::i64)); 12579 // second argument is 1 because this rounding 12580 // is always exact. 12581 12582 // The output of the permutation is our loaded result, the TokenFactor is 12583 // our new chain. 12584 DCI.CombineTo(N, Perm, TF); 12585 return SDValue(N, 0); 12586 } 12587 } 12588 break; 12589 case ISD::INTRINSIC_WO_CHAIN: { 12590 bool isLittleEndian = Subtarget.isLittleEndian(); 12591 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12592 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 12593 : Intrinsic::ppc_altivec_lvsl); 12594 if ((IID == Intr || 12595 IID == Intrinsic::ppc_qpx_qvlpcld || 12596 IID == Intrinsic::ppc_qpx_qvlpcls) && 12597 N->getOperand(1)->getOpcode() == ISD::ADD) { 12598 SDValue Add = N->getOperand(1); 12599 12600 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 12601 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 12602 12603 if (DAG.MaskedValueIsZero(Add->getOperand(1), 12604 APInt::getAllOnesValue(Bits /* alignment */) 12605 .zext(Add.getScalarValueSizeInBits()))) { 12606 SDNode *BasePtr = Add->getOperand(0).getNode(); 12607 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12608 UE = BasePtr->use_end(); 12609 UI != UE; ++UI) { 12610 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12611 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 12612 // We've found another LVSL/LVSR, and this address is an aligned 12613 // multiple of that one. The results will be the same, so use the 12614 // one we've just found instead. 12615 12616 return SDValue(*UI, 0); 12617 } 12618 } 12619 } 12620 12621 if (isa<ConstantSDNode>(Add->getOperand(1))) { 12622 SDNode *BasePtr = Add->getOperand(0).getNode(); 12623 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12624 UE = BasePtr->use_end(); UI != UE; ++UI) { 12625 if (UI->getOpcode() == ISD::ADD && 12626 isa<ConstantSDNode>(UI->getOperand(1)) && 12627 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 12628 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 12629 (1ULL << Bits) == 0) { 12630 SDNode *OtherAdd = *UI; 12631 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 12632 VE = OtherAdd->use_end(); VI != VE; ++VI) { 12633 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12634 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 12635 return SDValue(*VI, 0); 12636 } 12637 } 12638 } 12639 } 12640 } 12641 } 12642 } 12643 12644 break; 12645 case ISD::INTRINSIC_W_CHAIN: 12646 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12647 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12648 if (Subtarget.needsSwapsForVSXMemOps()) { 12649 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12650 default: 12651 break; 12652 case Intrinsic::ppc_vsx_lxvw4x: 12653 case Intrinsic::ppc_vsx_lxvd2x: 12654 return expandVSXLoadForLE(N, DCI); 12655 } 12656 } 12657 break; 12658 case ISD::INTRINSIC_VOID: 12659 // For little endian, VSX stores require generating xxswapd/stxvd2x. 12660 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12661 if (Subtarget.needsSwapsForVSXMemOps()) { 12662 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12663 default: 12664 break; 12665 case Intrinsic::ppc_vsx_stxvw4x: 12666 case Intrinsic::ppc_vsx_stxvd2x: 12667 return expandVSXStoreForLE(N, DCI); 12668 } 12669 } 12670 break; 12671 case ISD::BSWAP: 12672 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 12673 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 12674 N->getOperand(0).hasOneUse() && 12675 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 12676 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 12677 N->getValueType(0) == MVT::i64))) { 12678 SDValue Load = N->getOperand(0); 12679 LoadSDNode *LD = cast<LoadSDNode>(Load); 12680 // Create the byte-swapping load. 12681 SDValue Ops[] = { 12682 LD->getChain(), // Chain 12683 LD->getBasePtr(), // Ptr 12684 DAG.getValueType(N->getValueType(0)) // VT 12685 }; 12686 SDValue BSLoad = 12687 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 12688 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 12689 MVT::i64 : MVT::i32, MVT::Other), 12690 Ops, LD->getMemoryVT(), LD->getMemOperand()); 12691 12692 // If this is an i16 load, insert the truncate. 12693 SDValue ResVal = BSLoad; 12694 if (N->getValueType(0) == MVT::i16) 12695 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 12696 12697 // First, combine the bswap away. This makes the value produced by the 12698 // load dead. 12699 DCI.CombineTo(N, ResVal); 12700 12701 // Next, combine the load away, we give it a bogus result value but a real 12702 // chain result. The result value is dead because the bswap is dead. 12703 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 12704 12705 // Return N so it doesn't get rechecked! 12706 return SDValue(N, 0); 12707 } 12708 break; 12709 case PPCISD::VCMP: 12710 // If a VCMPo node already exists with exactly the same operands as this 12711 // node, use its result instead of this node (VCMPo computes both a CR6 and 12712 // a normal output). 12713 // 12714 if (!N->getOperand(0).hasOneUse() && 12715 !N->getOperand(1).hasOneUse() && 12716 !N->getOperand(2).hasOneUse()) { 12717 12718 // Scan all of the users of the LHS, looking for VCMPo's that match. 12719 SDNode *VCMPoNode = nullptr; 12720 12721 SDNode *LHSN = N->getOperand(0).getNode(); 12722 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 12723 UI != E; ++UI) 12724 if (UI->getOpcode() == PPCISD::VCMPo && 12725 UI->getOperand(1) == N->getOperand(1) && 12726 UI->getOperand(2) == N->getOperand(2) && 12727 UI->getOperand(0) == N->getOperand(0)) { 12728 VCMPoNode = *UI; 12729 break; 12730 } 12731 12732 // If there is no VCMPo node, or if the flag value has a single use, don't 12733 // transform this. 12734 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 12735 break; 12736 12737 // Look at the (necessarily single) use of the flag value. If it has a 12738 // chain, this transformation is more complex. Note that multiple things 12739 // could use the value result, which we should ignore. 12740 SDNode *FlagUser = nullptr; 12741 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 12742 FlagUser == nullptr; ++UI) { 12743 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 12744 SDNode *User = *UI; 12745 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 12746 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 12747 FlagUser = User; 12748 break; 12749 } 12750 } 12751 } 12752 12753 // If the user is a MFOCRF instruction, we know this is safe. 12754 // Otherwise we give up for right now. 12755 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 12756 return SDValue(VCMPoNode, 0); 12757 } 12758 break; 12759 case ISD::BRCOND: { 12760 SDValue Cond = N->getOperand(1); 12761 SDValue Target = N->getOperand(2); 12762 12763 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 12764 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 12765 Intrinsic::ppc_is_decremented_ctr_nonzero) { 12766 12767 // We now need to make the intrinsic dead (it cannot be instruction 12768 // selected). 12769 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 12770 assert(Cond.getNode()->hasOneUse() && 12771 "Counter decrement has more than one use"); 12772 12773 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 12774 N->getOperand(0), Target); 12775 } 12776 } 12777 break; 12778 case ISD::BR_CC: { 12779 // If this is a branch on an altivec predicate comparison, lower this so 12780 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 12781 // lowering is done pre-legalize, because the legalizer lowers the predicate 12782 // compare down to code that is difficult to reassemble. 12783 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 12784 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 12785 12786 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 12787 // value. If so, pass-through the AND to get to the intrinsic. 12788 if (LHS.getOpcode() == ISD::AND && 12789 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 12790 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 12791 Intrinsic::ppc_is_decremented_ctr_nonzero && 12792 isa<ConstantSDNode>(LHS.getOperand(1)) && 12793 !isNullConstant(LHS.getOperand(1))) 12794 LHS = LHS.getOperand(0); 12795 12796 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 12797 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 12798 Intrinsic::ppc_is_decremented_ctr_nonzero && 12799 isa<ConstantSDNode>(RHS)) { 12800 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 12801 "Counter decrement comparison is not EQ or NE"); 12802 12803 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 12804 bool isBDNZ = (CC == ISD::SETEQ && Val) || 12805 (CC == ISD::SETNE && !Val); 12806 12807 // We now need to make the intrinsic dead (it cannot be instruction 12808 // selected). 12809 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 12810 assert(LHS.getNode()->hasOneUse() && 12811 "Counter decrement has more than one use"); 12812 12813 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 12814 N->getOperand(0), N->getOperand(4)); 12815 } 12816 12817 int CompareOpc; 12818 bool isDot; 12819 12820 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12821 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 12822 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 12823 assert(isDot && "Can't compare against a vector result!"); 12824 12825 // If this is a comparison against something other than 0/1, then we know 12826 // that the condition is never/always true. 12827 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 12828 if (Val != 0 && Val != 1) { 12829 if (CC == ISD::SETEQ) // Cond never true, remove branch. 12830 return N->getOperand(0); 12831 // Always !=, turn it into an unconditional branch. 12832 return DAG.getNode(ISD::BR, dl, MVT::Other, 12833 N->getOperand(0), N->getOperand(4)); 12834 } 12835 12836 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 12837 12838 // Create the PPCISD altivec 'dot' comparison node. 12839 SDValue Ops[] = { 12840 LHS.getOperand(2), // LHS of compare 12841 LHS.getOperand(3), // RHS of compare 12842 DAG.getConstant(CompareOpc, dl, MVT::i32) 12843 }; 12844 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 12845 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 12846 12847 // Unpack the result based on how the target uses it. 12848 PPC::Predicate CompOpc; 12849 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 12850 default: // Can't happen, don't crash on invalid number though. 12851 case 0: // Branch on the value of the EQ bit of CR6. 12852 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 12853 break; 12854 case 1: // Branch on the inverted value of the EQ bit of CR6. 12855 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 12856 break; 12857 case 2: // Branch on the value of the LT bit of CR6. 12858 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 12859 break; 12860 case 3: // Branch on the inverted value of the LT bit of CR6. 12861 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 12862 break; 12863 } 12864 12865 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 12866 DAG.getConstant(CompOpc, dl, MVT::i32), 12867 DAG.getRegister(PPC::CR6, MVT::i32), 12868 N->getOperand(4), CompNode.getValue(1)); 12869 } 12870 break; 12871 } 12872 case ISD::BUILD_VECTOR: 12873 return DAGCombineBuildVector(N, DCI); 12874 } 12875 12876 return SDValue(); 12877 } 12878 12879 SDValue 12880 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12881 SelectionDAG &DAG, 12882 std::vector<SDNode *> *Created) const { 12883 // fold (sdiv X, pow2) 12884 EVT VT = N->getValueType(0); 12885 if (VT == MVT::i64 && !Subtarget.isPPC64()) 12886 return SDValue(); 12887 if ((VT != MVT::i32 && VT != MVT::i64) || 12888 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 12889 return SDValue(); 12890 12891 SDLoc DL(N); 12892 SDValue N0 = N->getOperand(0); 12893 12894 bool IsNegPow2 = (-Divisor).isPowerOf2(); 12895 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 12896 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 12897 12898 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 12899 if (Created) 12900 Created->push_back(Op.getNode()); 12901 12902 if (IsNegPow2) { 12903 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 12904 if (Created) 12905 Created->push_back(Op.getNode()); 12906 } 12907 12908 return Op; 12909 } 12910 12911 //===----------------------------------------------------------------------===// 12912 // Inline Assembly Support 12913 //===----------------------------------------------------------------------===// 12914 12915 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12916 KnownBits &Known, 12917 const APInt &DemandedElts, 12918 const SelectionDAG &DAG, 12919 unsigned Depth) const { 12920 Known.resetAll(); 12921 switch (Op.getOpcode()) { 12922 default: break; 12923 case PPCISD::LBRX: { 12924 // lhbrx is known to have the top bits cleared out. 12925 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 12926 Known.Zero = 0xFFFF0000; 12927 break; 12928 } 12929 case ISD::INTRINSIC_WO_CHAIN: { 12930 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 12931 default: break; 12932 case Intrinsic::ppc_altivec_vcmpbfp_p: 12933 case Intrinsic::ppc_altivec_vcmpeqfp_p: 12934 case Intrinsic::ppc_altivec_vcmpequb_p: 12935 case Intrinsic::ppc_altivec_vcmpequh_p: 12936 case Intrinsic::ppc_altivec_vcmpequw_p: 12937 case Intrinsic::ppc_altivec_vcmpequd_p: 12938 case Intrinsic::ppc_altivec_vcmpgefp_p: 12939 case Intrinsic::ppc_altivec_vcmpgtfp_p: 12940 case Intrinsic::ppc_altivec_vcmpgtsb_p: 12941 case Intrinsic::ppc_altivec_vcmpgtsh_p: 12942 case Intrinsic::ppc_altivec_vcmpgtsw_p: 12943 case Intrinsic::ppc_altivec_vcmpgtsd_p: 12944 case Intrinsic::ppc_altivec_vcmpgtub_p: 12945 case Intrinsic::ppc_altivec_vcmpgtuh_p: 12946 case Intrinsic::ppc_altivec_vcmpgtuw_p: 12947 case Intrinsic::ppc_altivec_vcmpgtud_p: 12948 Known.Zero = ~1U; // All bits but the low one are known to be zero. 12949 break; 12950 } 12951 } 12952 } 12953 } 12954 12955 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12956 switch (Subtarget.getDarwinDirective()) { 12957 default: break; 12958 case PPC::DIR_970: 12959 case PPC::DIR_PWR4: 12960 case PPC::DIR_PWR5: 12961 case PPC::DIR_PWR5X: 12962 case PPC::DIR_PWR6: 12963 case PPC::DIR_PWR6X: 12964 case PPC::DIR_PWR7: 12965 case PPC::DIR_PWR8: 12966 case PPC::DIR_PWR9: { 12967 if (!ML) 12968 break; 12969 12970 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 12971 12972 // For small loops (between 5 and 8 instructions), align to a 32-byte 12973 // boundary so that the entire loop fits in one instruction-cache line. 12974 uint64_t LoopSize = 0; 12975 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 12976 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 12977 LoopSize += TII->getInstSizeInBytes(*J); 12978 if (LoopSize > 32) 12979 break; 12980 } 12981 12982 if (LoopSize > 16 && LoopSize <= 32) 12983 return 5; 12984 12985 break; 12986 } 12987 } 12988 12989 return TargetLowering::getPrefLoopAlignment(ML); 12990 } 12991 12992 /// getConstraintType - Given a constraint, return the type of 12993 /// constraint it is for this target. 12994 PPCTargetLowering::ConstraintType 12995 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 12996 if (Constraint.size() == 1) { 12997 switch (Constraint[0]) { 12998 default: break; 12999 case 'b': 13000 case 'r': 13001 case 'f': 13002 case 'd': 13003 case 'v': 13004 case 'y': 13005 return C_RegisterClass; 13006 case 'Z': 13007 // FIXME: While Z does indicate a memory constraint, it specifically 13008 // indicates an r+r address (used in conjunction with the 'y' modifier 13009 // in the replacement string). Currently, we're forcing the base 13010 // register to be r0 in the asm printer (which is interpreted as zero) 13011 // and forming the complete address in the second register. This is 13012 // suboptimal. 13013 return C_Memory; 13014 } 13015 } else if (Constraint == "wc") { // individual CR bits. 13016 return C_RegisterClass; 13017 } else if (Constraint == "wa" || Constraint == "wd" || 13018 Constraint == "wf" || Constraint == "ws") { 13019 return C_RegisterClass; // VSX registers. 13020 } 13021 return TargetLowering::getConstraintType(Constraint); 13022 } 13023 13024 /// Examine constraint type and operand type and determine a weight value. 13025 /// This object must already have been set up with the operand type 13026 /// and the current alternative constraint selected. 13027 TargetLowering::ConstraintWeight 13028 PPCTargetLowering::getSingleConstraintMatchWeight( 13029 AsmOperandInfo &info, const char *constraint) const { 13030 ConstraintWeight weight = CW_Invalid; 13031 Value *CallOperandVal = info.CallOperandVal; 13032 // If we don't have a value, we can't do a match, 13033 // but allow it at the lowest weight. 13034 if (!CallOperandVal) 13035 return CW_Default; 13036 Type *type = CallOperandVal->getType(); 13037 13038 // Look at the constraint type. 13039 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 13040 return CW_Register; // an individual CR bit. 13041 else if ((StringRef(constraint) == "wa" || 13042 StringRef(constraint) == "wd" || 13043 StringRef(constraint) == "wf") && 13044 type->isVectorTy()) 13045 return CW_Register; 13046 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 13047 return CW_Register; 13048 13049 switch (*constraint) { 13050 default: 13051 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13052 break; 13053 case 'b': 13054 if (type->isIntegerTy()) 13055 weight = CW_Register; 13056 break; 13057 case 'f': 13058 if (type->isFloatTy()) 13059 weight = CW_Register; 13060 break; 13061 case 'd': 13062 if (type->isDoubleTy()) 13063 weight = CW_Register; 13064 break; 13065 case 'v': 13066 if (type->isVectorTy()) 13067 weight = CW_Register; 13068 break; 13069 case 'y': 13070 weight = CW_Register; 13071 break; 13072 case 'Z': 13073 weight = CW_Memory; 13074 break; 13075 } 13076 return weight; 13077 } 13078 13079 std::pair<unsigned, const TargetRegisterClass *> 13080 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 13081 StringRef Constraint, 13082 MVT VT) const { 13083 if (Constraint.size() == 1) { 13084 // GCC RS6000 Constraint Letters 13085 switch (Constraint[0]) { 13086 case 'b': // R1-R31 13087 if (VT == MVT::i64 && Subtarget.isPPC64()) 13088 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 13089 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 13090 case 'r': // R0-R31 13091 if (VT == MVT::i64 && Subtarget.isPPC64()) 13092 return std::make_pair(0U, &PPC::G8RCRegClass); 13093 return std::make_pair(0U, &PPC::GPRCRegClass); 13094 // 'd' and 'f' constraints are both defined to be "the floating point 13095 // registers", where one is for 32-bit and the other for 64-bit. We don't 13096 // really care overly much here so just give them all the same reg classes. 13097 case 'd': 13098 case 'f': 13099 if (VT == MVT::f32 || VT == MVT::i32) 13100 return std::make_pair(0U, &PPC::F4RCRegClass); 13101 if (VT == MVT::f64 || VT == MVT::i64) 13102 return std::make_pair(0U, &PPC::F8RCRegClass); 13103 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13104 return std::make_pair(0U, &PPC::QFRCRegClass); 13105 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13106 return std::make_pair(0U, &PPC::QSRCRegClass); 13107 break; 13108 case 'v': 13109 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13110 return std::make_pair(0U, &PPC::QFRCRegClass); 13111 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13112 return std::make_pair(0U, &PPC::QSRCRegClass); 13113 if (Subtarget.hasAltivec()) 13114 return std::make_pair(0U, &PPC::VRRCRegClass); 13115 break; 13116 case 'y': // crrc 13117 return std::make_pair(0U, &PPC::CRRCRegClass); 13118 } 13119 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 13120 // An individual CR bit. 13121 return std::make_pair(0U, &PPC::CRBITRCRegClass); 13122 } else if ((Constraint == "wa" || Constraint == "wd" || 13123 Constraint == "wf") && Subtarget.hasVSX()) { 13124 return std::make_pair(0U, &PPC::VSRCRegClass); 13125 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 13126 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 13127 return std::make_pair(0U, &PPC::VSSRCRegClass); 13128 else 13129 return std::make_pair(0U, &PPC::VSFRCRegClass); 13130 } 13131 13132 std::pair<unsigned, const TargetRegisterClass *> R = 13133 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13134 13135 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 13136 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 13137 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 13138 // register. 13139 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 13140 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 13141 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 13142 PPC::GPRCRegClass.contains(R.first)) 13143 return std::make_pair(TRI->getMatchingSuperReg(R.first, 13144 PPC::sub_32, &PPC::G8RCRegClass), 13145 &PPC::G8RCRegClass); 13146 13147 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 13148 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 13149 R.first = PPC::CR0; 13150 R.second = &PPC::CRRCRegClass; 13151 } 13152 13153 return R; 13154 } 13155 13156 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13157 /// vector. If it is invalid, don't add anything to Ops. 13158 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13159 std::string &Constraint, 13160 std::vector<SDValue>&Ops, 13161 SelectionDAG &DAG) const { 13162 SDValue Result; 13163 13164 // Only support length 1 constraints. 13165 if (Constraint.length() > 1) return; 13166 13167 char Letter = Constraint[0]; 13168 switch (Letter) { 13169 default: break; 13170 case 'I': 13171 case 'J': 13172 case 'K': 13173 case 'L': 13174 case 'M': 13175 case 'N': 13176 case 'O': 13177 case 'P': { 13178 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 13179 if (!CST) return; // Must be an immediate to match. 13180 SDLoc dl(Op); 13181 int64_t Value = CST->getSExtValue(); 13182 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 13183 // numbers are printed as such. 13184 switch (Letter) { 13185 default: llvm_unreachable("Unknown constraint letter!"); 13186 case 'I': // "I" is a signed 16-bit constant. 13187 if (isInt<16>(Value)) 13188 Result = DAG.getTargetConstant(Value, dl, TCVT); 13189 break; 13190 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 13191 if (isShiftedUInt<16, 16>(Value)) 13192 Result = DAG.getTargetConstant(Value, dl, TCVT); 13193 break; 13194 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 13195 if (isShiftedInt<16, 16>(Value)) 13196 Result = DAG.getTargetConstant(Value, dl, TCVT); 13197 break; 13198 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 13199 if (isUInt<16>(Value)) 13200 Result = DAG.getTargetConstant(Value, dl, TCVT); 13201 break; 13202 case 'M': // "M" is a constant that is greater than 31. 13203 if (Value > 31) 13204 Result = DAG.getTargetConstant(Value, dl, TCVT); 13205 break; 13206 case 'N': // "N" is a positive constant that is an exact power of two. 13207 if (Value > 0 && isPowerOf2_64(Value)) 13208 Result = DAG.getTargetConstant(Value, dl, TCVT); 13209 break; 13210 case 'O': // "O" is the constant zero. 13211 if (Value == 0) 13212 Result = DAG.getTargetConstant(Value, dl, TCVT); 13213 break; 13214 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 13215 if (isInt<16>(-Value)) 13216 Result = DAG.getTargetConstant(Value, dl, TCVT); 13217 break; 13218 } 13219 break; 13220 } 13221 } 13222 13223 if (Result.getNode()) { 13224 Ops.push_back(Result); 13225 return; 13226 } 13227 13228 // Handle standard constraint letters. 13229 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13230 } 13231 13232 // isLegalAddressingMode - Return true if the addressing mode represented 13233 // by AM is legal for this target, for a load/store of the specified type. 13234 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13235 const AddrMode &AM, Type *Ty, 13236 unsigned AS, Instruction *I) const { 13237 // PPC does not allow r+i addressing modes for vectors! 13238 if (Ty->isVectorTy() && AM.BaseOffs != 0) 13239 return false; 13240 13241 // PPC allows a sign-extended 16-bit immediate field. 13242 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 13243 return false; 13244 13245 // No global is ever allowed as a base. 13246 if (AM.BaseGV) 13247 return false; 13248 13249 // PPC only support r+r, 13250 switch (AM.Scale) { 13251 case 0: // "r+i" or just "i", depending on HasBaseReg. 13252 break; 13253 case 1: 13254 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 13255 return false; 13256 // Otherwise we have r+r or r+i. 13257 break; 13258 case 2: 13259 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 13260 return false; 13261 // Allow 2*r as r+r. 13262 break; 13263 default: 13264 // No other scales are supported. 13265 return false; 13266 } 13267 13268 return true; 13269 } 13270 13271 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 13272 SelectionDAG &DAG) const { 13273 MachineFunction &MF = DAG.getMachineFunction(); 13274 MachineFrameInfo &MFI = MF.getFrameInfo(); 13275 MFI.setReturnAddressIsTaken(true); 13276 13277 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 13278 return SDValue(); 13279 13280 SDLoc dl(Op); 13281 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13282 13283 // Make sure the function does not optimize away the store of the RA to 13284 // the stack. 13285 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 13286 FuncInfo->setLRStoreRequired(); 13287 bool isPPC64 = Subtarget.isPPC64(); 13288 auto PtrVT = getPointerTy(MF.getDataLayout()); 13289 13290 if (Depth > 0) { 13291 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 13292 SDValue Offset = 13293 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 13294 isPPC64 ? MVT::i64 : MVT::i32); 13295 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 13296 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 13297 MachinePointerInfo()); 13298 } 13299 13300 // Just load the return address off the stack. 13301 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 13302 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 13303 MachinePointerInfo()); 13304 } 13305 13306 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 13307 SelectionDAG &DAG) const { 13308 SDLoc dl(Op); 13309 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13310 13311 MachineFunction &MF = DAG.getMachineFunction(); 13312 MachineFrameInfo &MFI = MF.getFrameInfo(); 13313 MFI.setFrameAddressIsTaken(true); 13314 13315 EVT PtrVT = getPointerTy(MF.getDataLayout()); 13316 bool isPPC64 = PtrVT == MVT::i64; 13317 13318 // Naked functions never have a frame pointer, and so we use r1. For all 13319 // other functions, this decision must be delayed until during PEI. 13320 unsigned FrameReg; 13321 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 13322 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 13323 else 13324 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 13325 13326 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 13327 PtrVT); 13328 while (Depth--) 13329 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 13330 FrameAddr, MachinePointerInfo()); 13331 return FrameAddr; 13332 } 13333 13334 // FIXME? Maybe this could be a TableGen attribute on some registers and 13335 // this table could be generated automatically from RegInfo. 13336 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 13337 SelectionDAG &DAG) const { 13338 bool isPPC64 = Subtarget.isPPC64(); 13339 bool isDarwinABI = Subtarget.isDarwinABI(); 13340 13341 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 13342 (!isPPC64 && VT != MVT::i32)) 13343 report_fatal_error("Invalid register global variable type"); 13344 13345 bool is64Bit = isPPC64 && VT == MVT::i64; 13346 unsigned Reg = StringSwitch<unsigned>(RegName) 13347 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 13348 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 13349 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 13350 (is64Bit ? PPC::X13 : PPC::R13)) 13351 .Default(0); 13352 13353 if (Reg) 13354 return Reg; 13355 report_fatal_error("Invalid register name global variable"); 13356 } 13357 13358 bool 13359 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13360 // The PowerPC target isn't yet aware of offsets. 13361 return false; 13362 } 13363 13364 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13365 const CallInst &I, 13366 MachineFunction &MF, 13367 unsigned Intrinsic) const { 13368 switch (Intrinsic) { 13369 case Intrinsic::ppc_qpx_qvlfd: 13370 case Intrinsic::ppc_qpx_qvlfs: 13371 case Intrinsic::ppc_qpx_qvlfcd: 13372 case Intrinsic::ppc_qpx_qvlfcs: 13373 case Intrinsic::ppc_qpx_qvlfiwa: 13374 case Intrinsic::ppc_qpx_qvlfiwz: 13375 case Intrinsic::ppc_altivec_lvx: 13376 case Intrinsic::ppc_altivec_lvxl: 13377 case Intrinsic::ppc_altivec_lvebx: 13378 case Intrinsic::ppc_altivec_lvehx: 13379 case Intrinsic::ppc_altivec_lvewx: 13380 case Intrinsic::ppc_vsx_lxvd2x: 13381 case Intrinsic::ppc_vsx_lxvw4x: { 13382 EVT VT; 13383 switch (Intrinsic) { 13384 case Intrinsic::ppc_altivec_lvebx: 13385 VT = MVT::i8; 13386 break; 13387 case Intrinsic::ppc_altivec_lvehx: 13388 VT = MVT::i16; 13389 break; 13390 case Intrinsic::ppc_altivec_lvewx: 13391 VT = MVT::i32; 13392 break; 13393 case Intrinsic::ppc_vsx_lxvd2x: 13394 VT = MVT::v2f64; 13395 break; 13396 case Intrinsic::ppc_qpx_qvlfd: 13397 VT = MVT::v4f64; 13398 break; 13399 case Intrinsic::ppc_qpx_qvlfs: 13400 VT = MVT::v4f32; 13401 break; 13402 case Intrinsic::ppc_qpx_qvlfcd: 13403 VT = MVT::v2f64; 13404 break; 13405 case Intrinsic::ppc_qpx_qvlfcs: 13406 VT = MVT::v2f32; 13407 break; 13408 default: 13409 VT = MVT::v4i32; 13410 break; 13411 } 13412 13413 Info.opc = ISD::INTRINSIC_W_CHAIN; 13414 Info.memVT = VT; 13415 Info.ptrVal = I.getArgOperand(0); 13416 Info.offset = -VT.getStoreSize()+1; 13417 Info.size = 2*VT.getStoreSize()-1; 13418 Info.align = 1; 13419 Info.flags = MachineMemOperand::MOLoad; 13420 return true; 13421 } 13422 case Intrinsic::ppc_qpx_qvlfda: 13423 case Intrinsic::ppc_qpx_qvlfsa: 13424 case Intrinsic::ppc_qpx_qvlfcda: 13425 case Intrinsic::ppc_qpx_qvlfcsa: 13426 case Intrinsic::ppc_qpx_qvlfiwaa: 13427 case Intrinsic::ppc_qpx_qvlfiwza: { 13428 EVT VT; 13429 switch (Intrinsic) { 13430 case Intrinsic::ppc_qpx_qvlfda: 13431 VT = MVT::v4f64; 13432 break; 13433 case Intrinsic::ppc_qpx_qvlfsa: 13434 VT = MVT::v4f32; 13435 break; 13436 case Intrinsic::ppc_qpx_qvlfcda: 13437 VT = MVT::v2f64; 13438 break; 13439 case Intrinsic::ppc_qpx_qvlfcsa: 13440 VT = MVT::v2f32; 13441 break; 13442 default: 13443 VT = MVT::v4i32; 13444 break; 13445 } 13446 13447 Info.opc = ISD::INTRINSIC_W_CHAIN; 13448 Info.memVT = VT; 13449 Info.ptrVal = I.getArgOperand(0); 13450 Info.offset = 0; 13451 Info.size = VT.getStoreSize(); 13452 Info.align = 1; 13453 Info.flags = MachineMemOperand::MOLoad; 13454 return true; 13455 } 13456 case Intrinsic::ppc_qpx_qvstfd: 13457 case Intrinsic::ppc_qpx_qvstfs: 13458 case Intrinsic::ppc_qpx_qvstfcd: 13459 case Intrinsic::ppc_qpx_qvstfcs: 13460 case Intrinsic::ppc_qpx_qvstfiw: 13461 case Intrinsic::ppc_altivec_stvx: 13462 case Intrinsic::ppc_altivec_stvxl: 13463 case Intrinsic::ppc_altivec_stvebx: 13464 case Intrinsic::ppc_altivec_stvehx: 13465 case Intrinsic::ppc_altivec_stvewx: 13466 case Intrinsic::ppc_vsx_stxvd2x: 13467 case Intrinsic::ppc_vsx_stxvw4x: { 13468 EVT VT; 13469 switch (Intrinsic) { 13470 case Intrinsic::ppc_altivec_stvebx: 13471 VT = MVT::i8; 13472 break; 13473 case Intrinsic::ppc_altivec_stvehx: 13474 VT = MVT::i16; 13475 break; 13476 case Intrinsic::ppc_altivec_stvewx: 13477 VT = MVT::i32; 13478 break; 13479 case Intrinsic::ppc_vsx_stxvd2x: 13480 VT = MVT::v2f64; 13481 break; 13482 case Intrinsic::ppc_qpx_qvstfd: 13483 VT = MVT::v4f64; 13484 break; 13485 case Intrinsic::ppc_qpx_qvstfs: 13486 VT = MVT::v4f32; 13487 break; 13488 case Intrinsic::ppc_qpx_qvstfcd: 13489 VT = MVT::v2f64; 13490 break; 13491 case Intrinsic::ppc_qpx_qvstfcs: 13492 VT = MVT::v2f32; 13493 break; 13494 default: 13495 VT = MVT::v4i32; 13496 break; 13497 } 13498 13499 Info.opc = ISD::INTRINSIC_VOID; 13500 Info.memVT = VT; 13501 Info.ptrVal = I.getArgOperand(1); 13502 Info.offset = -VT.getStoreSize()+1; 13503 Info.size = 2*VT.getStoreSize()-1; 13504 Info.align = 1; 13505 Info.flags = MachineMemOperand::MOStore; 13506 return true; 13507 } 13508 case Intrinsic::ppc_qpx_qvstfda: 13509 case Intrinsic::ppc_qpx_qvstfsa: 13510 case Intrinsic::ppc_qpx_qvstfcda: 13511 case Intrinsic::ppc_qpx_qvstfcsa: 13512 case Intrinsic::ppc_qpx_qvstfiwa: { 13513 EVT VT; 13514 switch (Intrinsic) { 13515 case Intrinsic::ppc_qpx_qvstfda: 13516 VT = MVT::v4f64; 13517 break; 13518 case Intrinsic::ppc_qpx_qvstfsa: 13519 VT = MVT::v4f32; 13520 break; 13521 case Intrinsic::ppc_qpx_qvstfcda: 13522 VT = MVT::v2f64; 13523 break; 13524 case Intrinsic::ppc_qpx_qvstfcsa: 13525 VT = MVT::v2f32; 13526 break; 13527 default: 13528 VT = MVT::v4i32; 13529 break; 13530 } 13531 13532 Info.opc = ISD::INTRINSIC_VOID; 13533 Info.memVT = VT; 13534 Info.ptrVal = I.getArgOperand(1); 13535 Info.offset = 0; 13536 Info.size = VT.getStoreSize(); 13537 Info.align = 1; 13538 Info.flags = MachineMemOperand::MOStore; 13539 return true; 13540 } 13541 default: 13542 break; 13543 } 13544 13545 return false; 13546 } 13547 13548 /// getOptimalMemOpType - Returns the target specific optimal type for load 13549 /// and store operations as a result of memset, memcpy, and memmove 13550 /// lowering. If DstAlign is zero that means it's safe to destination 13551 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 13552 /// means there isn't a need to check it against alignment requirement, 13553 /// probably because the source does not need to be loaded. If 'IsMemset' is 13554 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 13555 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 13556 /// source is constant so it does not need to be loaded. 13557 /// It returns EVT::Other if the type should be determined using generic 13558 /// target-independent logic. 13559 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 13560 unsigned DstAlign, unsigned SrcAlign, 13561 bool IsMemset, bool ZeroMemset, 13562 bool MemcpyStrSrc, 13563 MachineFunction &MF) const { 13564 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 13565 const Function &F = MF.getFunction(); 13566 // When expanding a memset, require at least two QPX instructions to cover 13567 // the cost of loading the value to be stored from the constant pool. 13568 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 13569 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 13570 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 13571 return MVT::v4f64; 13572 } 13573 13574 // We should use Altivec/VSX loads and stores when available. For unaligned 13575 // addresses, unaligned VSX loads are only fast starting with the P8. 13576 if (Subtarget.hasAltivec() && Size >= 16 && 13577 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 13578 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 13579 return MVT::v4i32; 13580 } 13581 13582 if (Subtarget.isPPC64()) { 13583 return MVT::i64; 13584 } 13585 13586 return MVT::i32; 13587 } 13588 13589 /// \brief Returns true if it is beneficial to convert a load of a constant 13590 /// to just the constant itself. 13591 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13592 Type *Ty) const { 13593 assert(Ty->isIntegerTy()); 13594 13595 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 13596 return !(BitSize == 0 || BitSize > 64); 13597 } 13598 13599 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 13600 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13601 return false; 13602 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 13603 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 13604 return NumBits1 == 64 && NumBits2 == 32; 13605 } 13606 13607 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 13608 if (!VT1.isInteger() || !VT2.isInteger()) 13609 return false; 13610 unsigned NumBits1 = VT1.getSizeInBits(); 13611 unsigned NumBits2 = VT2.getSizeInBits(); 13612 return NumBits1 == 64 && NumBits2 == 32; 13613 } 13614 13615 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13616 // Generally speaking, zexts are not free, but they are free when they can be 13617 // folded with other operations. 13618 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 13619 EVT MemVT = LD->getMemoryVT(); 13620 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 13621 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 13622 (LD->getExtensionType() == ISD::NON_EXTLOAD || 13623 LD->getExtensionType() == ISD::ZEXTLOAD)) 13624 return true; 13625 } 13626 13627 // FIXME: Add other cases... 13628 // - 32-bit shifts with a zext to i64 13629 // - zext after ctlz, bswap, etc. 13630 // - zext after and by a constant mask 13631 13632 return TargetLowering::isZExtFree(Val, VT2); 13633 } 13634 13635 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 13636 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 13637 "invalid fpext types"); 13638 return true; 13639 } 13640 13641 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13642 return isInt<16>(Imm) || isUInt<16>(Imm); 13643 } 13644 13645 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13646 return isInt<16>(Imm) || isUInt<16>(Imm); 13647 } 13648 13649 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 13650 unsigned, 13651 unsigned, 13652 bool *Fast) const { 13653 if (DisablePPCUnaligned) 13654 return false; 13655 13656 // PowerPC supports unaligned memory access for simple non-vector types. 13657 // Although accessing unaligned addresses is not as efficient as accessing 13658 // aligned addresses, it is generally more efficient than manual expansion, 13659 // and generally only traps for software emulation when crossing page 13660 // boundaries. 13661 13662 if (!VT.isSimple()) 13663 return false; 13664 13665 if (VT.getSimpleVT().isVector()) { 13666 if (Subtarget.hasVSX()) { 13667 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 13668 VT != MVT::v4f32 && VT != MVT::v4i32) 13669 return false; 13670 } else { 13671 return false; 13672 } 13673 } 13674 13675 if (VT == MVT::ppcf128) 13676 return false; 13677 13678 if (Fast) 13679 *Fast = true; 13680 13681 return true; 13682 } 13683 13684 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 13685 VT = VT.getScalarType(); 13686 13687 if (!VT.isSimple()) 13688 return false; 13689 13690 switch (VT.getSimpleVT().SimpleTy) { 13691 case MVT::f32: 13692 case MVT::f64: 13693 return true; 13694 default: 13695 break; 13696 } 13697 13698 return false; 13699 } 13700 13701 const MCPhysReg * 13702 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 13703 // LR is a callee-save register, but we must treat it as clobbered by any call 13704 // site. Hence we include LR in the scratch registers, which are in turn added 13705 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 13706 // to CTR, which is used by any indirect call. 13707 static const MCPhysReg ScratchRegs[] = { 13708 PPC::X12, PPC::LR8, PPC::CTR8, 0 13709 }; 13710 13711 return ScratchRegs; 13712 } 13713 13714 unsigned PPCTargetLowering::getExceptionPointerRegister( 13715 const Constant *PersonalityFn) const { 13716 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 13717 } 13718 13719 unsigned PPCTargetLowering::getExceptionSelectorRegister( 13720 const Constant *PersonalityFn) const { 13721 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 13722 } 13723 13724 bool 13725 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 13726 EVT VT , unsigned DefinedValues) const { 13727 if (VT == MVT::v2i64) 13728 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 13729 13730 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 13731 return true; 13732 13733 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 13734 } 13735 13736 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 13737 if (DisableILPPref || Subtarget.enableMachineScheduler()) 13738 return TargetLowering::getSchedulingPreference(N); 13739 13740 return Sched::ILP; 13741 } 13742 13743 // Create a fast isel object. 13744 FastISel * 13745 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 13746 const TargetLibraryInfo *LibInfo) const { 13747 return PPC::createFastISel(FuncInfo, LibInfo); 13748 } 13749 13750 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13751 if (Subtarget.isDarwinABI()) return; 13752 if (!Subtarget.isPPC64()) return; 13753 13754 // Update IsSplitCSR in PPCFunctionInfo 13755 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 13756 PFI->setIsSplitCSR(true); 13757 } 13758 13759 void PPCTargetLowering::insertCopiesSplitCSR( 13760 MachineBasicBlock *Entry, 13761 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13762 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 13763 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13764 if (!IStart) 13765 return; 13766 13767 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 13768 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13769 MachineBasicBlock::iterator MBBI = Entry->begin(); 13770 for (const MCPhysReg *I = IStart; *I; ++I) { 13771 const TargetRegisterClass *RC = nullptr; 13772 if (PPC::G8RCRegClass.contains(*I)) 13773 RC = &PPC::G8RCRegClass; 13774 else if (PPC::F8RCRegClass.contains(*I)) 13775 RC = &PPC::F8RCRegClass; 13776 else if (PPC::CRRCRegClass.contains(*I)) 13777 RC = &PPC::CRRCRegClass; 13778 else if (PPC::VRRCRegClass.contains(*I)) 13779 RC = &PPC::VRRCRegClass; 13780 else 13781 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13782 13783 unsigned NewVR = MRI->createVirtualRegister(RC); 13784 // Create copy from CSR to a virtual register. 13785 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13786 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13787 // nounwind. If we want to generalize this later, we may need to emit 13788 // CFI pseudo-instructions. 13789 assert(Entry->getParent()->getFunction().hasFnAttribute( 13790 Attribute::NoUnwind) && 13791 "Function should be nounwind in insertCopiesSplitCSR!"); 13792 Entry->addLiveIn(*I); 13793 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 13794 .addReg(*I); 13795 13796 // Insert the copy-back instructions right before the terminator 13797 for (auto *Exit : Exits) 13798 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 13799 TII->get(TargetOpcode::COPY), *I) 13800 .addReg(NewVR); 13801 } 13802 } 13803 13804 // Override to enable LOAD_STACK_GUARD lowering on Linux. 13805 bool PPCTargetLowering::useLoadStackGuardNode() const { 13806 if (!Subtarget.isTargetLinux()) 13807 return TargetLowering::useLoadStackGuardNode(); 13808 return true; 13809 } 13810 13811 // Override to disable global variable loading on Linux. 13812 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 13813 if (!Subtarget.isTargetLinux()) 13814 return TargetLowering::insertSSPDeclarations(M); 13815 } 13816 13817 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 13818 if (!VT.isSimple() || !Subtarget.hasVSX()) 13819 return false; 13820 13821 switch(VT.getSimpleVT().SimpleTy) { 13822 default: 13823 // For FP types that are currently not supported by PPC backend, return 13824 // false. Examples: f16, f80. 13825 return false; 13826 case MVT::f32: 13827 case MVT::f64: 13828 case MVT::ppcf128: 13829 return Imm.isPosZero(); 13830 } 13831 } 13832 13833 // For vector shift operation op, fold 13834 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 13835 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 13836 SelectionDAG &DAG) { 13837 SDValue N0 = N->getOperand(0); 13838 SDValue N1 = N->getOperand(1); 13839 EVT VT = N0.getValueType(); 13840 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 13841 unsigned Opcode = N->getOpcode(); 13842 unsigned TargetOpcode; 13843 13844 switch (Opcode) { 13845 default: 13846 llvm_unreachable("Unexpected shift operation"); 13847 case ISD::SHL: 13848 TargetOpcode = PPCISD::SHL; 13849 break; 13850 case ISD::SRL: 13851 TargetOpcode = PPCISD::SRL; 13852 break; 13853 case ISD::SRA: 13854 TargetOpcode = PPCISD::SRA; 13855 break; 13856 } 13857 13858 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 13859 N1->getOpcode() == ISD::AND) 13860 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 13861 if (Mask->getZExtValue() == OpSizeInBits - 1) 13862 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 13863 13864 return SDValue(); 13865 } 13866 13867 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 13868 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13869 return Value; 13870 13871 return SDValue(); 13872 } 13873 13874 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 13875 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13876 return Value; 13877 13878 return SDValue(); 13879 } 13880 13881 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 13882 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13883 return Value; 13884 13885 return SDValue(); 13886 } 13887 13888 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 13889 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 13890 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 13891 return false; 13892 13893 // If not a tail call then no need to proceed. 13894 if (!CI->isTailCall()) 13895 return false; 13896 13897 // If tail calls are disabled for the caller then we are done. 13898 const Function *Caller = CI->getParent()->getParent(); 13899 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 13900 if (Attr.getValueAsString() == "true") 13901 return false; 13902 13903 // If sibling calls have been disabled and tail-calls aren't guaranteed 13904 // there is no reason to duplicate. 13905 auto &TM = getTargetMachine(); 13906 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 13907 return false; 13908 13909 // Can't tail call a function called indirectly, or if it has variadic args. 13910 const Function *Callee = CI->getCalledFunction(); 13911 if (!Callee || Callee->isVarArg()) 13912 return false; 13913 13914 // Make sure the callee and caller calling conventions are eligible for tco. 13915 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 13916 CI->getCallingConv())) 13917 return false; 13918 13919 // If the function is local then we have a good chance at tail-calling it 13920 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 13921 } 13922