1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the PPCISelLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "PPCISelLowering.h" 15 #include "MCTargetDesc/PPCPredicates.h" 16 #include "PPC.h" 17 #include "PPCCCState.h" 18 #include "PPCCallingConv.h" 19 #include "PPCFrameLowering.h" 20 #include "PPCInstrInfo.h" 21 #include "PPCMachineFunctionInfo.h" 22 #include "PPCPerfectShuffle.h" 23 #include "PPCRegisterInfo.h" 24 #include "PPCSubtarget.h" 25 #include "PPCTargetMachine.h" 26 #include "llvm/ADT/APFloat.h" 27 #include "llvm/ADT/APInt.h" 28 #include "llvm/ADT/ArrayRef.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/None.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallSet.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/CodeGen/CallingConvLower.h" 39 #include "llvm/CodeGen/ISDOpcodes.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineLoopInfo.h" 47 #include "llvm/CodeGen/MachineMemOperand.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/ValueTypes.h" 57 #include "llvm/IR/CallSite.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/Module.h" 70 #include "llvm/IR/Type.h" 71 #include "llvm/IR/Use.h" 72 #include "llvm/IR/Value.h" 73 #include "llvm/MC/MCExpr.h" 74 #include "llvm/MC/MCRegisterInfo.h" 75 #include "llvm/Support/AtomicOrdering.h" 76 #include "llvm/Support/BranchProbability.h" 77 #include "llvm/Support/Casting.h" 78 #include "llvm/Support/CodeGen.h" 79 #include "llvm/Support/CommandLine.h" 80 #include "llvm/Support/Compiler.h" 81 #include "llvm/Support/Debug.h" 82 #include "llvm/Support/ErrorHandling.h" 83 #include "llvm/Support/Format.h" 84 #include "llvm/Support/KnownBits.h" 85 #include "llvm/Support/MachineValueType.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include "llvm/Target/TargetMachine.h" 89 #include "llvm/Target/TargetOptions.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstdint> 93 #include <iterator> 94 #include <list> 95 #include <utility> 96 #include <vector> 97 98 using namespace llvm; 99 100 #define DEBUG_TYPE "ppc-lowering" 101 102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 104 105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 107 108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 110 111 static cl::opt<bool> DisableSCO("disable-ppc-sco", 112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 113 114 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 115 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 116 117 STATISTIC(NumTailCalls, "Number of tail calls"); 118 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 119 120 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 121 122 // FIXME: Remove this once the bug has been fixed! 123 extern cl::opt<bool> ANDIGlueBug; 124 125 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 126 const PPCSubtarget &STI) 127 : TargetLowering(TM), Subtarget(STI) { 128 // Use _setjmp/_longjmp instead of setjmp/longjmp. 129 setUseUnderscoreSetJmp(true); 130 setUseUnderscoreLongJmp(true); 131 132 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 133 // arguments are at least 4/8 bytes aligned. 134 bool isPPC64 = Subtarget.isPPC64(); 135 setMinStackArgumentAlignment(isPPC64 ? 8:4); 136 137 // Set up the register classes. 138 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 139 if (!useSoftFloat()) { 140 if (hasSPE()) { 141 addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass); 142 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 143 } else { 144 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 145 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 146 } 147 } 148 149 // Match BITREVERSE to customized fast code sequence in the td file. 150 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 151 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 152 153 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 154 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 155 156 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 157 for (MVT VT : MVT::integer_valuetypes()) { 158 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 159 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 160 } 161 162 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 163 164 // PowerPC has pre-inc load and store's. 165 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 166 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 167 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 168 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 169 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 170 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 171 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 172 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 173 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 174 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 175 if (!Subtarget.hasSPE()) { 176 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 177 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 178 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 179 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 180 } 181 182 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 183 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 184 for (MVT VT : ScalarIntVTs) { 185 setOperationAction(ISD::ADDC, VT, Legal); 186 setOperationAction(ISD::ADDE, VT, Legal); 187 setOperationAction(ISD::SUBC, VT, Legal); 188 setOperationAction(ISD::SUBE, VT, Legal); 189 } 190 191 if (Subtarget.useCRBits()) { 192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 193 194 if (isPPC64 || Subtarget.hasFPCVT()) { 195 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 196 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 197 isPPC64 ? MVT::i64 : MVT::i32); 198 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 199 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 200 isPPC64 ? MVT::i64 : MVT::i32); 201 } else { 202 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 203 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 204 } 205 206 // PowerPC does not support direct load/store of condition registers. 207 setOperationAction(ISD::LOAD, MVT::i1, Custom); 208 setOperationAction(ISD::STORE, MVT::i1, Custom); 209 210 // FIXME: Remove this once the ANDI glue bug is fixed: 211 if (ANDIGlueBug) 212 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 213 214 for (MVT VT : MVT::integer_valuetypes()) { 215 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 216 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 217 setTruncStoreAction(VT, MVT::i1, Expand); 218 } 219 220 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 221 } 222 223 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 224 // PPC (the libcall is not available). 225 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 226 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 227 228 // We do not currently implement these libm ops for PowerPC. 229 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 230 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 231 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 232 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 233 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 234 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 235 236 // PowerPC has no SREM/UREM instructions unless we are on P9 237 // On P9 we may use a hardware instruction to compute the remainder. 238 // The instructions are not legalized directly because in the cases where the 239 // result of both the remainder and the division is required it is more 240 // efficient to compute the remainder from the result of the division rather 241 // than use the remainder instruction. 242 if (Subtarget.isISA3_0()) { 243 setOperationAction(ISD::SREM, MVT::i32, Custom); 244 setOperationAction(ISD::UREM, MVT::i32, Custom); 245 setOperationAction(ISD::SREM, MVT::i64, Custom); 246 setOperationAction(ISD::UREM, MVT::i64, Custom); 247 } else { 248 setOperationAction(ISD::SREM, MVT::i32, Expand); 249 setOperationAction(ISD::UREM, MVT::i32, Expand); 250 setOperationAction(ISD::SREM, MVT::i64, Expand); 251 setOperationAction(ISD::UREM, MVT::i64, Expand); 252 } 253 254 if (Subtarget.hasP9Vector()) { 255 setOperationAction(ISD::ABS, MVT::v4i32, Legal); 256 setOperationAction(ISD::ABS, MVT::v8i16, Legal); 257 setOperationAction(ISD::ABS, MVT::v16i8, Legal); 258 } 259 260 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 261 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 262 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 263 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 264 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 265 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 266 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 267 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 268 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 269 270 // We don't support sin/cos/sqrt/fmod/pow 271 setOperationAction(ISD::FSIN , MVT::f64, Expand); 272 setOperationAction(ISD::FCOS , MVT::f64, Expand); 273 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 274 setOperationAction(ISD::FREM , MVT::f64, Expand); 275 setOperationAction(ISD::FPOW , MVT::f64, Expand); 276 setOperationAction(ISD::FSIN , MVT::f32, Expand); 277 setOperationAction(ISD::FCOS , MVT::f32, Expand); 278 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 279 setOperationAction(ISD::FREM , MVT::f32, Expand); 280 setOperationAction(ISD::FPOW , MVT::f32, Expand); 281 if (Subtarget.hasSPE()) { 282 setOperationAction(ISD::FMA , MVT::f64, Expand); 283 setOperationAction(ISD::FMA , MVT::f32, Expand); 284 } else { 285 setOperationAction(ISD::FMA , MVT::f64, Legal); 286 setOperationAction(ISD::FMA , MVT::f32, Legal); 287 } 288 289 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 290 291 // If we're enabling GP optimizations, use hardware square root 292 if (!Subtarget.hasFSQRT() && 293 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 294 Subtarget.hasFRE())) 295 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 296 297 if (!Subtarget.hasFSQRT() && 298 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 299 Subtarget.hasFRES())) 300 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 301 302 if (Subtarget.hasFCPSGN()) { 303 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 304 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 305 } else { 306 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 307 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 308 } 309 310 if (Subtarget.hasFPRND()) { 311 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 312 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 313 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 314 setOperationAction(ISD::FROUND, MVT::f64, Legal); 315 316 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 317 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 318 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 319 setOperationAction(ISD::FROUND, MVT::f32, Legal); 320 } 321 322 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 323 // to speed up scalar BSWAP64. 324 // CTPOP or CTTZ were introduced in P8/P9 respectively 325 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 326 if (Subtarget.isISA3_0()) { 327 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 328 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 329 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 330 } else { 331 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 332 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 333 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 334 } 335 336 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 337 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 338 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 339 } else { 340 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 341 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 342 } 343 344 // PowerPC does not have ROTR 345 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 346 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 347 348 if (!Subtarget.useCRBits()) { 349 // PowerPC does not have Select 350 setOperationAction(ISD::SELECT, MVT::i32, Expand); 351 setOperationAction(ISD::SELECT, MVT::i64, Expand); 352 setOperationAction(ISD::SELECT, MVT::f32, Expand); 353 setOperationAction(ISD::SELECT, MVT::f64, Expand); 354 } 355 356 // PowerPC wants to turn select_cc of FP into fsel when possible. 357 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 358 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 359 360 // PowerPC wants to optimize integer setcc a bit 361 if (!Subtarget.useCRBits()) 362 setOperationAction(ISD::SETCC, MVT::i32, Custom); 363 364 // PowerPC does not have BRCOND which requires SetCC 365 if (!Subtarget.useCRBits()) 366 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 367 368 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 369 370 if (Subtarget.hasSPE()) { 371 // SPE has built-in conversions 372 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 373 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 374 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 375 } else { 376 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 377 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 378 379 // PowerPC does not have [U|S]INT_TO_FP 380 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 381 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 382 } 383 384 if (Subtarget.hasDirectMove() && isPPC64) { 385 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 386 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 387 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 388 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 389 } else { 390 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 391 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 392 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 393 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 394 } 395 396 // We cannot sextinreg(i1). Expand to shifts. 397 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 398 399 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 400 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 401 // support continuation, user-level threading, and etc.. As a result, no 402 // other SjLj exception interfaces are implemented and please don't build 403 // your own exception handling based on them. 404 // LLVM/Clang supports zero-cost DWARF exception handling. 405 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 406 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 407 408 // We want to legalize GlobalAddress and ConstantPool nodes into the 409 // appropriate instructions to materialize the address. 410 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 411 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 412 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 413 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 414 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 415 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 416 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 417 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 418 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 419 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 420 421 // TRAP is legal. 422 setOperationAction(ISD::TRAP, MVT::Other, Legal); 423 424 // TRAMPOLINE is custom lowered. 425 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 426 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 427 428 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 429 setOperationAction(ISD::VASTART , MVT::Other, Custom); 430 431 if (Subtarget.isSVR4ABI()) { 432 if (isPPC64) { 433 // VAARG always uses double-word chunks, so promote anything smaller. 434 setOperationAction(ISD::VAARG, MVT::i1, Promote); 435 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 436 setOperationAction(ISD::VAARG, MVT::i8, Promote); 437 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 438 setOperationAction(ISD::VAARG, MVT::i16, Promote); 439 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 440 setOperationAction(ISD::VAARG, MVT::i32, Promote); 441 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 442 setOperationAction(ISD::VAARG, MVT::Other, Expand); 443 } else { 444 // VAARG is custom lowered with the 32-bit SVR4 ABI. 445 setOperationAction(ISD::VAARG, MVT::Other, Custom); 446 setOperationAction(ISD::VAARG, MVT::i64, Custom); 447 } 448 } else 449 setOperationAction(ISD::VAARG, MVT::Other, Expand); 450 451 if (Subtarget.isSVR4ABI() && !isPPC64) 452 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 453 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 454 else 455 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 456 457 // Use the default implementation. 458 setOperationAction(ISD::VAEND , MVT::Other, Expand); 459 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 460 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 461 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 462 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 463 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 464 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 465 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 466 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 467 468 // We want to custom lower some of our intrinsics. 469 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 470 471 // To handle counter-based loop conditions. 472 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 473 474 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 475 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 476 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 477 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 478 479 // Comparisons that require checking two conditions. 480 if (Subtarget.hasSPE()) { 481 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 482 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 483 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 484 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 485 } 486 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 487 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 488 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 489 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 490 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 491 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 492 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 493 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 494 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 495 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 496 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 497 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 498 499 if (Subtarget.has64BitSupport()) { 500 // They also have instructions for converting between i64 and fp. 501 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 502 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 503 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 504 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 505 // This is just the low 32 bits of a (signed) fp->i64 conversion. 506 // We cannot do this with Promote because i64 is not a legal type. 507 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 508 509 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 510 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 511 } else { 512 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 513 if (Subtarget.hasSPE()) 514 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 515 else 516 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 517 } 518 519 // With the instructions enabled under FPCVT, we can do everything. 520 if (Subtarget.hasFPCVT()) { 521 if (Subtarget.has64BitSupport()) { 522 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 523 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 524 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 525 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 526 } 527 528 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 529 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 530 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 531 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 532 } 533 534 if (Subtarget.use64BitRegs()) { 535 // 64-bit PowerPC implementations can support i64 types directly 536 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 537 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 538 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 539 // 64-bit PowerPC wants to expand i128 shifts itself. 540 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 541 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 542 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 543 } else { 544 // 32-bit PowerPC wants to expand i64 shifts itself. 545 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 546 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 547 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 548 } 549 550 if (Subtarget.hasAltivec()) { 551 // First set operation action for all vector types to expand. Then we 552 // will selectively turn on ones that can be effectively codegen'd. 553 for (MVT VT : MVT::vector_valuetypes()) { 554 // add/sub are legal for all supported vector VT's. 555 setOperationAction(ISD::ADD, VT, Legal); 556 setOperationAction(ISD::SUB, VT, Legal); 557 558 // Vector instructions introduced in P8 559 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 560 setOperationAction(ISD::CTPOP, VT, Legal); 561 setOperationAction(ISD::CTLZ, VT, Legal); 562 } 563 else { 564 setOperationAction(ISD::CTPOP, VT, Expand); 565 setOperationAction(ISD::CTLZ, VT, Expand); 566 } 567 568 // Vector instructions introduced in P9 569 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 570 setOperationAction(ISD::CTTZ, VT, Legal); 571 else 572 setOperationAction(ISD::CTTZ, VT, Expand); 573 574 // We promote all shuffles to v16i8. 575 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 576 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 577 578 // We promote all non-typed operations to v4i32. 579 setOperationAction(ISD::AND , VT, Promote); 580 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 581 setOperationAction(ISD::OR , VT, Promote); 582 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 583 setOperationAction(ISD::XOR , VT, Promote); 584 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 585 setOperationAction(ISD::LOAD , VT, Promote); 586 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 587 setOperationAction(ISD::SELECT, VT, Promote); 588 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 589 setOperationAction(ISD::SELECT_CC, VT, Promote); 590 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 591 setOperationAction(ISD::STORE, VT, Promote); 592 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 593 594 // No other operations are legal. 595 setOperationAction(ISD::MUL , VT, Expand); 596 setOperationAction(ISD::SDIV, VT, Expand); 597 setOperationAction(ISD::SREM, VT, Expand); 598 setOperationAction(ISD::UDIV, VT, Expand); 599 setOperationAction(ISD::UREM, VT, Expand); 600 setOperationAction(ISD::FDIV, VT, Expand); 601 setOperationAction(ISD::FREM, VT, Expand); 602 setOperationAction(ISD::FNEG, VT, Expand); 603 setOperationAction(ISD::FSQRT, VT, Expand); 604 setOperationAction(ISD::FLOG, VT, Expand); 605 setOperationAction(ISD::FLOG10, VT, Expand); 606 setOperationAction(ISD::FLOG2, VT, Expand); 607 setOperationAction(ISD::FEXP, VT, Expand); 608 setOperationAction(ISD::FEXP2, VT, Expand); 609 setOperationAction(ISD::FSIN, VT, Expand); 610 setOperationAction(ISD::FCOS, VT, Expand); 611 setOperationAction(ISD::FABS, VT, Expand); 612 setOperationAction(ISD::FFLOOR, VT, Expand); 613 setOperationAction(ISD::FCEIL, VT, Expand); 614 setOperationAction(ISD::FTRUNC, VT, Expand); 615 setOperationAction(ISD::FRINT, VT, Expand); 616 setOperationAction(ISD::FNEARBYINT, VT, Expand); 617 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 618 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 619 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 620 setOperationAction(ISD::MULHU, VT, Expand); 621 setOperationAction(ISD::MULHS, VT, Expand); 622 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 623 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 624 setOperationAction(ISD::UDIVREM, VT, Expand); 625 setOperationAction(ISD::SDIVREM, VT, Expand); 626 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 627 setOperationAction(ISD::FPOW, VT, Expand); 628 setOperationAction(ISD::BSWAP, VT, Expand); 629 setOperationAction(ISD::VSELECT, VT, Expand); 630 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 631 setOperationAction(ISD::ROTL, VT, Expand); 632 setOperationAction(ISD::ROTR, VT, Expand); 633 634 for (MVT InnerVT : MVT::vector_valuetypes()) { 635 setTruncStoreAction(VT, InnerVT, Expand); 636 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 637 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 638 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 639 } 640 } 641 642 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 643 // with merges, splats, etc. 644 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 645 646 setOperationAction(ISD::AND , MVT::v4i32, Legal); 647 setOperationAction(ISD::OR , MVT::v4i32, Legal); 648 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 649 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 650 setOperationAction(ISD::SELECT, MVT::v4i32, 651 Subtarget.useCRBits() ? Legal : Expand); 652 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 653 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 654 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 655 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 656 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 657 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 658 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 659 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 660 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 661 662 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 663 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 664 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 665 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 666 667 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 668 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 669 670 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 671 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 672 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 673 } 674 675 if (Subtarget.hasP8Altivec()) 676 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 677 else 678 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 679 680 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 681 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 682 683 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 684 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 685 686 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 687 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 688 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 689 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 690 691 // Altivec does not contain unordered floating-point compare instructions 692 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 693 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 694 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 695 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 696 697 if (Subtarget.hasVSX()) { 698 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 699 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 700 if (Subtarget.hasP8Vector()) { 701 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 702 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 703 } 704 if (Subtarget.hasDirectMove() && isPPC64) { 705 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 706 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 707 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 708 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 709 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 710 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 711 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 713 } 714 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 715 716 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 717 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 718 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 719 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 720 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 721 722 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 723 724 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 725 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 726 727 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 728 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 729 730 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 731 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal); 732 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 733 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 734 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 735 736 // Share the Altivec comparison restrictions. 737 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 738 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 739 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 740 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 741 742 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 743 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 744 745 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 746 747 if (Subtarget.hasP8Vector()) 748 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 749 750 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 751 752 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 753 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 754 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 755 756 if (Subtarget.hasP8Altivec()) { 757 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 758 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 759 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 760 761 // 128 bit shifts can be accomplished via 3 instructions for SHL and 762 // SRL, but not for SRA because of the instructions available: 763 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 764 // doing 765 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 766 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 767 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 768 769 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 770 } 771 else { 772 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 773 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 774 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 775 776 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 777 778 // VSX v2i64 only supports non-arithmetic operations. 779 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 780 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 781 } 782 783 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 784 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 785 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 786 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 787 788 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 789 790 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 791 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 792 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 793 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 794 795 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 796 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 797 798 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 799 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 800 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 801 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 802 803 if (Subtarget.hasDirectMove()) 804 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 805 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 806 807 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 808 } 809 810 if (Subtarget.hasP8Altivec()) { 811 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 812 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 813 } 814 815 if (Subtarget.hasP9Vector()) { 816 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 817 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 818 819 // 128 bit shifts can be accomplished via 3 instructions for SHL and 820 // SRL, but not for SRA because of the instructions available: 821 // VS{RL} and VS{RL}O. 822 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 823 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 824 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 825 826 if (EnableQuadPrecision) { 827 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 828 setOperationAction(ISD::FADD, MVT::f128, Legal); 829 setOperationAction(ISD::FSUB, MVT::f128, Legal); 830 setOperationAction(ISD::FDIV, MVT::f128, Legal); 831 setOperationAction(ISD::FMUL, MVT::f128, Legal); 832 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 833 // No extending loads to f128 on PPC. 834 for (MVT FPT : MVT::fp_valuetypes()) 835 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 836 setOperationAction(ISD::FMA, MVT::f128, Legal); 837 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 838 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 839 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 840 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 841 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 842 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 843 844 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 845 setOperationAction(ISD::FRINT, MVT::f128, Legal); 846 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 847 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 848 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 849 setOperationAction(ISD::FROUND, MVT::f128, Legal); 850 851 setOperationAction(ISD::SELECT, MVT::f128, Expand); 852 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 853 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 854 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 855 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 856 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 857 // No implementation for these ops for PowerPC. 858 setOperationAction(ISD::FSIN , MVT::f128, Expand); 859 setOperationAction(ISD::FCOS , MVT::f128, Expand); 860 setOperationAction(ISD::FPOW, MVT::f128, Expand); 861 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 862 setOperationAction(ISD::FREM, MVT::f128, Expand); 863 } 864 865 } 866 867 if (Subtarget.hasP9Altivec()) { 868 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 869 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 870 } 871 } 872 873 if (Subtarget.hasQPX()) { 874 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 875 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 876 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 877 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 878 879 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 880 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 881 882 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 883 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 884 885 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 886 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 887 888 if (!Subtarget.useCRBits()) 889 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 890 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 891 892 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 893 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 894 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 895 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 896 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 898 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 899 900 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 901 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 902 903 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 904 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 905 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 906 907 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 908 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 909 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 910 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 911 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 912 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 913 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 914 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 915 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 916 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 917 918 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 919 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 920 921 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 922 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 923 924 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 925 926 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 927 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 928 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 929 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 930 931 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 932 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 933 934 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 935 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 936 937 if (!Subtarget.useCRBits()) 938 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 939 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 940 941 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 942 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 943 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 944 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 945 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 946 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 947 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 948 949 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 950 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 951 952 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 953 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 954 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 955 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 956 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 957 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 958 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 959 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 960 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 961 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 962 963 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 964 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 965 966 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 967 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 968 969 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 970 971 setOperationAction(ISD::AND , MVT::v4i1, Legal); 972 setOperationAction(ISD::OR , MVT::v4i1, Legal); 973 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 974 975 if (!Subtarget.useCRBits()) 976 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 977 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 978 979 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 980 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 981 982 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 983 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 984 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 985 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 986 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 987 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 988 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 989 990 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 991 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 992 993 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 994 995 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 996 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 997 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 998 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 999 1000 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1001 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1002 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1003 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1004 1005 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1006 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1007 1008 // These need to set FE_INEXACT, and so cannot be vectorized here. 1009 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1010 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1011 1012 if (TM.Options.UnsafeFPMath) { 1013 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1014 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1015 1016 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1017 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1018 } else { 1019 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1020 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1021 1022 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1023 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1024 } 1025 } 1026 1027 if (Subtarget.has64BitSupport()) 1028 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1029 1030 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1031 1032 if (!isPPC64) { 1033 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1034 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1035 } 1036 1037 setBooleanContents(ZeroOrOneBooleanContent); 1038 1039 if (Subtarget.hasAltivec()) { 1040 // Altivec instructions set fields to all zeros or all ones. 1041 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1042 } 1043 1044 if (!isPPC64) { 1045 // These libcalls are not available in 32-bit. 1046 setLibcallName(RTLIB::SHL_I128, nullptr); 1047 setLibcallName(RTLIB::SRL_I128, nullptr); 1048 setLibcallName(RTLIB::SRA_I128, nullptr); 1049 } 1050 1051 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1052 1053 // We have target-specific dag combine patterns for the following nodes: 1054 setTargetDAGCombine(ISD::ADD); 1055 setTargetDAGCombine(ISD::SHL); 1056 setTargetDAGCombine(ISD::SRA); 1057 setTargetDAGCombine(ISD::SRL); 1058 setTargetDAGCombine(ISD::SINT_TO_FP); 1059 setTargetDAGCombine(ISD::BUILD_VECTOR); 1060 if (Subtarget.hasFPCVT()) 1061 setTargetDAGCombine(ISD::UINT_TO_FP); 1062 setTargetDAGCombine(ISD::LOAD); 1063 setTargetDAGCombine(ISD::STORE); 1064 setTargetDAGCombine(ISD::BR_CC); 1065 if (Subtarget.useCRBits()) 1066 setTargetDAGCombine(ISD::BRCOND); 1067 setTargetDAGCombine(ISD::BSWAP); 1068 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1069 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1070 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1071 1072 setTargetDAGCombine(ISD::SIGN_EXTEND); 1073 setTargetDAGCombine(ISD::ZERO_EXTEND); 1074 setTargetDAGCombine(ISD::ANY_EXTEND); 1075 1076 setTargetDAGCombine(ISD::TRUNCATE); 1077 1078 if (Subtarget.useCRBits()) { 1079 setTargetDAGCombine(ISD::TRUNCATE); 1080 setTargetDAGCombine(ISD::SETCC); 1081 setTargetDAGCombine(ISD::SELECT_CC); 1082 } 1083 1084 // Use reciprocal estimates. 1085 if (TM.Options.UnsafeFPMath) { 1086 setTargetDAGCombine(ISD::FDIV); 1087 setTargetDAGCombine(ISD::FSQRT); 1088 } 1089 1090 // Darwin long double math library functions have $LDBL128 appended. 1091 if (Subtarget.isDarwin()) { 1092 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1093 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1094 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1095 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1096 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1097 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1098 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1099 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1100 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1101 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1102 } 1103 1104 if (EnableQuadPrecision) { 1105 setLibcallName(RTLIB::LOG_F128, "logf128"); 1106 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1107 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1108 setLibcallName(RTLIB::EXP_F128, "expf128"); 1109 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1110 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1111 setLibcallName(RTLIB::COS_F128, "cosf128"); 1112 setLibcallName(RTLIB::POW_F128, "powf128"); 1113 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1114 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1115 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1116 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1117 } 1118 1119 // With 32 condition bits, we don't need to sink (and duplicate) compares 1120 // aggressively in CodeGenPrep. 1121 if (Subtarget.useCRBits()) { 1122 setHasMultipleConditionRegisters(); 1123 setJumpIsExpensive(); 1124 } 1125 1126 setMinFunctionAlignment(2); 1127 if (Subtarget.isDarwin()) 1128 setPrefFunctionAlignment(4); 1129 1130 switch (Subtarget.getDarwinDirective()) { 1131 default: break; 1132 case PPC::DIR_970: 1133 case PPC::DIR_A2: 1134 case PPC::DIR_E500: 1135 case PPC::DIR_E500mc: 1136 case PPC::DIR_E5500: 1137 case PPC::DIR_PWR4: 1138 case PPC::DIR_PWR5: 1139 case PPC::DIR_PWR5X: 1140 case PPC::DIR_PWR6: 1141 case PPC::DIR_PWR6X: 1142 case PPC::DIR_PWR7: 1143 case PPC::DIR_PWR8: 1144 case PPC::DIR_PWR9: 1145 setPrefFunctionAlignment(4); 1146 setPrefLoopAlignment(4); 1147 break; 1148 } 1149 1150 if (Subtarget.enableMachineScheduler()) 1151 setSchedulingPreference(Sched::Source); 1152 else 1153 setSchedulingPreference(Sched::Hybrid); 1154 1155 computeRegisterProperties(STI.getRegisterInfo()); 1156 1157 // The Freescale cores do better with aggressive inlining of memcpy and 1158 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1159 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1160 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1161 MaxStoresPerMemset = 32; 1162 MaxStoresPerMemsetOptSize = 16; 1163 MaxStoresPerMemcpy = 32; 1164 MaxStoresPerMemcpyOptSize = 8; 1165 MaxStoresPerMemmove = 32; 1166 MaxStoresPerMemmoveOptSize = 8; 1167 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1168 // The A2 also benefits from (very) aggressive inlining of memcpy and 1169 // friends. The overhead of a the function call, even when warm, can be 1170 // over one hundred cycles. 1171 MaxStoresPerMemset = 128; 1172 MaxStoresPerMemcpy = 128; 1173 MaxStoresPerMemmove = 128; 1174 MaxLoadsPerMemcmp = 128; 1175 } else { 1176 MaxLoadsPerMemcmp = 8; 1177 MaxLoadsPerMemcmpOptSize = 4; 1178 } 1179 } 1180 1181 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1182 /// the desired ByVal argument alignment. 1183 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1184 unsigned MaxMaxAlign) { 1185 if (MaxAlign == MaxMaxAlign) 1186 return; 1187 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1188 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1189 MaxAlign = 32; 1190 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1191 MaxAlign = 16; 1192 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1193 unsigned EltAlign = 0; 1194 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1195 if (EltAlign > MaxAlign) 1196 MaxAlign = EltAlign; 1197 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1198 for (auto *EltTy : STy->elements()) { 1199 unsigned EltAlign = 0; 1200 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1201 if (EltAlign > MaxAlign) 1202 MaxAlign = EltAlign; 1203 if (MaxAlign == MaxMaxAlign) 1204 break; 1205 } 1206 } 1207 } 1208 1209 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1210 /// function arguments in the caller parameter area. 1211 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1212 const DataLayout &DL) const { 1213 // Darwin passes everything on 4 byte boundary. 1214 if (Subtarget.isDarwin()) 1215 return 4; 1216 1217 // 16byte and wider vectors are passed on 16byte boundary. 1218 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1219 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1220 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1221 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1222 return Align; 1223 } 1224 1225 unsigned PPCTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1226 CallingConv:: ID CC, 1227 EVT VT) const { 1228 if (Subtarget.hasSPE() && VT == MVT::f64) 1229 return 2; 1230 return PPCTargetLowering::getNumRegisters(Context, VT); 1231 } 1232 1233 MVT PPCTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1234 CallingConv:: ID CC, 1235 EVT VT) const { 1236 if (Subtarget.hasSPE() && VT == MVT::f64) 1237 return MVT::i32; 1238 return PPCTargetLowering::getRegisterType(Context, VT); 1239 } 1240 1241 bool PPCTargetLowering::useSoftFloat() const { 1242 return Subtarget.useSoftFloat(); 1243 } 1244 1245 bool PPCTargetLowering::hasSPE() const { 1246 return Subtarget.hasSPE(); 1247 } 1248 1249 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1250 switch ((PPCISD::NodeType)Opcode) { 1251 case PPCISD::FIRST_NUMBER: break; 1252 case PPCISD::FSEL: return "PPCISD::FSEL"; 1253 case PPCISD::FCFID: return "PPCISD::FCFID"; 1254 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1255 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1256 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1257 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1258 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1259 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1260 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1261 case PPCISD::FP_TO_UINT_IN_VSR: 1262 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1263 case PPCISD::FP_TO_SINT_IN_VSR: 1264 return "PPCISD::FP_TO_SINT_IN_VSR"; 1265 case PPCISD::FRE: return "PPCISD::FRE"; 1266 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1267 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1268 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1269 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1270 case PPCISD::VPERM: return "PPCISD::VPERM"; 1271 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1272 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1273 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1274 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1275 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1276 case PPCISD::CMPB: return "PPCISD::CMPB"; 1277 case PPCISD::Hi: return "PPCISD::Hi"; 1278 case PPCISD::Lo: return "PPCISD::Lo"; 1279 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1280 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1281 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1282 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1283 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1284 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1285 case PPCISD::SRL: return "PPCISD::SRL"; 1286 case PPCISD::SRA: return "PPCISD::SRA"; 1287 case PPCISD::SHL: return "PPCISD::SHL"; 1288 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1289 case PPCISD::CALL: return "PPCISD::CALL"; 1290 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1291 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1292 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1293 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1294 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1295 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1296 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1297 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1298 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1299 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1300 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1301 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1302 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1303 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1304 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1305 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1306 case PPCISD::VCMP: return "PPCISD::VCMP"; 1307 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1308 case PPCISD::LBRX: return "PPCISD::LBRX"; 1309 case PPCISD::STBRX: return "PPCISD::STBRX"; 1310 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1311 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1312 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1313 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1314 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1315 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1316 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1317 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1318 case PPCISD::ST_VSR_SCAL_INT: 1319 return "PPCISD::ST_VSR_SCAL_INT"; 1320 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1321 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1322 case PPCISD::BDZ: return "PPCISD::BDZ"; 1323 case PPCISD::MFFS: return "PPCISD::MFFS"; 1324 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1325 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1326 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1327 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1328 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1329 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1330 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1331 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1332 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1333 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1334 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1335 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1336 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1337 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1338 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1339 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1340 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1341 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1342 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1343 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1344 case PPCISD::SC: return "PPCISD::SC"; 1345 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1346 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1347 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1348 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1349 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1350 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1351 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1352 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1353 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1354 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1355 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1356 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1357 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1358 } 1359 return nullptr; 1360 } 1361 1362 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1363 EVT VT) const { 1364 if (!VT.isVector()) 1365 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1366 1367 if (Subtarget.hasQPX()) 1368 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1369 1370 return VT.changeVectorElementTypeToInteger(); 1371 } 1372 1373 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1374 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1375 return true; 1376 } 1377 1378 //===----------------------------------------------------------------------===// 1379 // Node matching predicates, for use by the tblgen matching code. 1380 //===----------------------------------------------------------------------===// 1381 1382 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1383 static bool isFloatingPointZero(SDValue Op) { 1384 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1385 return CFP->getValueAPF().isZero(); 1386 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1387 // Maybe this has already been legalized into the constant pool? 1388 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1389 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1390 return CFP->getValueAPF().isZero(); 1391 } 1392 return false; 1393 } 1394 1395 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1396 /// true if Op is undef or if it matches the specified value. 1397 static bool isConstantOrUndef(int Op, int Val) { 1398 return Op < 0 || Op == Val; 1399 } 1400 1401 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1402 /// VPKUHUM instruction. 1403 /// The ShuffleKind distinguishes between big-endian operations with 1404 /// two different inputs (0), either-endian operations with two identical 1405 /// inputs (1), and little-endian operations with two different inputs (2). 1406 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1407 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1408 SelectionDAG &DAG) { 1409 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1410 if (ShuffleKind == 0) { 1411 if (IsLE) 1412 return false; 1413 for (unsigned i = 0; i != 16; ++i) 1414 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1415 return false; 1416 } else if (ShuffleKind == 2) { 1417 if (!IsLE) 1418 return false; 1419 for (unsigned i = 0; i != 16; ++i) 1420 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1421 return false; 1422 } else if (ShuffleKind == 1) { 1423 unsigned j = IsLE ? 0 : 1; 1424 for (unsigned i = 0; i != 8; ++i) 1425 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1426 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1427 return false; 1428 } 1429 return true; 1430 } 1431 1432 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1433 /// VPKUWUM instruction. 1434 /// The ShuffleKind distinguishes between big-endian operations with 1435 /// two different inputs (0), either-endian operations with two identical 1436 /// inputs (1), and little-endian operations with two different inputs (2). 1437 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1438 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1439 SelectionDAG &DAG) { 1440 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1441 if (ShuffleKind == 0) { 1442 if (IsLE) 1443 return false; 1444 for (unsigned i = 0; i != 16; i += 2) 1445 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1446 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1447 return false; 1448 } else if (ShuffleKind == 2) { 1449 if (!IsLE) 1450 return false; 1451 for (unsigned i = 0; i != 16; i += 2) 1452 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1453 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1454 return false; 1455 } else if (ShuffleKind == 1) { 1456 unsigned j = IsLE ? 0 : 2; 1457 for (unsigned i = 0; i != 8; i += 2) 1458 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1459 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1460 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1461 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1462 return false; 1463 } 1464 return true; 1465 } 1466 1467 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1468 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1469 /// current subtarget. 1470 /// 1471 /// The ShuffleKind distinguishes between big-endian operations with 1472 /// two different inputs (0), either-endian operations with two identical 1473 /// inputs (1), and little-endian operations with two different inputs (2). 1474 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1475 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1476 SelectionDAG &DAG) { 1477 const PPCSubtarget& Subtarget = 1478 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1479 if (!Subtarget.hasP8Vector()) 1480 return false; 1481 1482 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1483 if (ShuffleKind == 0) { 1484 if (IsLE) 1485 return false; 1486 for (unsigned i = 0; i != 16; i += 4) 1487 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1488 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1489 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1490 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1491 return false; 1492 } else if (ShuffleKind == 2) { 1493 if (!IsLE) 1494 return false; 1495 for (unsigned i = 0; i != 16; i += 4) 1496 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1497 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1498 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1499 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1500 return false; 1501 } else if (ShuffleKind == 1) { 1502 unsigned j = IsLE ? 0 : 4; 1503 for (unsigned i = 0; i != 8; i += 4) 1504 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1505 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1506 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1507 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1508 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1509 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1510 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1511 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1512 return false; 1513 } 1514 return true; 1515 } 1516 1517 /// isVMerge - Common function, used to match vmrg* shuffles. 1518 /// 1519 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1520 unsigned LHSStart, unsigned RHSStart) { 1521 if (N->getValueType(0) != MVT::v16i8) 1522 return false; 1523 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1524 "Unsupported merge size!"); 1525 1526 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1527 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1528 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1529 LHSStart+j+i*UnitSize) || 1530 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1531 RHSStart+j+i*UnitSize)) 1532 return false; 1533 } 1534 return true; 1535 } 1536 1537 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1538 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1539 /// The ShuffleKind distinguishes between big-endian merges with two 1540 /// different inputs (0), either-endian merges with two identical inputs (1), 1541 /// and little-endian merges with two different inputs (2). For the latter, 1542 /// the input operands are swapped (see PPCInstrAltivec.td). 1543 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1544 unsigned ShuffleKind, SelectionDAG &DAG) { 1545 if (DAG.getDataLayout().isLittleEndian()) { 1546 if (ShuffleKind == 1) // unary 1547 return isVMerge(N, UnitSize, 0, 0); 1548 else if (ShuffleKind == 2) // swapped 1549 return isVMerge(N, UnitSize, 0, 16); 1550 else 1551 return false; 1552 } else { 1553 if (ShuffleKind == 1) // unary 1554 return isVMerge(N, UnitSize, 8, 8); 1555 else if (ShuffleKind == 0) // normal 1556 return isVMerge(N, UnitSize, 8, 24); 1557 else 1558 return false; 1559 } 1560 } 1561 1562 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1563 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1564 /// The ShuffleKind distinguishes between big-endian merges with two 1565 /// different inputs (0), either-endian merges with two identical inputs (1), 1566 /// and little-endian merges with two different inputs (2). For the latter, 1567 /// the input operands are swapped (see PPCInstrAltivec.td). 1568 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1569 unsigned ShuffleKind, SelectionDAG &DAG) { 1570 if (DAG.getDataLayout().isLittleEndian()) { 1571 if (ShuffleKind == 1) // unary 1572 return isVMerge(N, UnitSize, 8, 8); 1573 else if (ShuffleKind == 2) // swapped 1574 return isVMerge(N, UnitSize, 8, 24); 1575 else 1576 return false; 1577 } else { 1578 if (ShuffleKind == 1) // unary 1579 return isVMerge(N, UnitSize, 0, 0); 1580 else if (ShuffleKind == 0) // normal 1581 return isVMerge(N, UnitSize, 0, 16); 1582 else 1583 return false; 1584 } 1585 } 1586 1587 /** 1588 * Common function used to match vmrgew and vmrgow shuffles 1589 * 1590 * The indexOffset determines whether to look for even or odd words in 1591 * the shuffle mask. This is based on the of the endianness of the target 1592 * machine. 1593 * - Little Endian: 1594 * - Use offset of 0 to check for odd elements 1595 * - Use offset of 4 to check for even elements 1596 * - Big Endian: 1597 * - Use offset of 0 to check for even elements 1598 * - Use offset of 4 to check for odd elements 1599 * A detailed description of the vector element ordering for little endian and 1600 * big endian can be found at 1601 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1602 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1603 * compiler differences mean to you 1604 * 1605 * The mask to the shuffle vector instruction specifies the indices of the 1606 * elements from the two input vectors to place in the result. The elements are 1607 * numbered in array-access order, starting with the first vector. These vectors 1608 * are always of type v16i8, thus each vector will contain 16 elements of size 1609 * 8. More info on the shuffle vector can be found in the 1610 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1611 * Language Reference. 1612 * 1613 * The RHSStartValue indicates whether the same input vectors are used (unary) 1614 * or two different input vectors are used, based on the following: 1615 * - If the instruction uses the same vector for both inputs, the range of the 1616 * indices will be 0 to 15. In this case, the RHSStart value passed should 1617 * be 0. 1618 * - If the instruction has two different vectors then the range of the 1619 * indices will be 0 to 31. In this case, the RHSStart value passed should 1620 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1621 * to 31 specify elements in the second vector). 1622 * 1623 * \param[in] N The shuffle vector SD Node to analyze 1624 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1625 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1626 * vector to the shuffle_vector instruction 1627 * \return true iff this shuffle vector represents an even or odd word merge 1628 */ 1629 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1630 unsigned RHSStartValue) { 1631 if (N->getValueType(0) != MVT::v16i8) 1632 return false; 1633 1634 for (unsigned i = 0; i < 2; ++i) 1635 for (unsigned j = 0; j < 4; ++j) 1636 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1637 i*RHSStartValue+j+IndexOffset) || 1638 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1639 i*RHSStartValue+j+IndexOffset+8)) 1640 return false; 1641 return true; 1642 } 1643 1644 /** 1645 * Determine if the specified shuffle mask is suitable for the vmrgew or 1646 * vmrgow instructions. 1647 * 1648 * \param[in] N The shuffle vector SD Node to analyze 1649 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1650 * \param[in] ShuffleKind Identify the type of merge: 1651 * - 0 = big-endian merge with two different inputs; 1652 * - 1 = either-endian merge with two identical inputs; 1653 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1654 * little-endian merges). 1655 * \param[in] DAG The current SelectionDAG 1656 * \return true iff this shuffle mask 1657 */ 1658 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1659 unsigned ShuffleKind, SelectionDAG &DAG) { 1660 if (DAG.getDataLayout().isLittleEndian()) { 1661 unsigned indexOffset = CheckEven ? 4 : 0; 1662 if (ShuffleKind == 1) // Unary 1663 return isVMerge(N, indexOffset, 0); 1664 else if (ShuffleKind == 2) // swapped 1665 return isVMerge(N, indexOffset, 16); 1666 else 1667 return false; 1668 } 1669 else { 1670 unsigned indexOffset = CheckEven ? 0 : 4; 1671 if (ShuffleKind == 1) // Unary 1672 return isVMerge(N, indexOffset, 0); 1673 else if (ShuffleKind == 0) // Normal 1674 return isVMerge(N, indexOffset, 16); 1675 else 1676 return false; 1677 } 1678 return false; 1679 } 1680 1681 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1682 /// amount, otherwise return -1. 1683 /// The ShuffleKind distinguishes between big-endian operations with two 1684 /// different inputs (0), either-endian operations with two identical inputs 1685 /// (1), and little-endian operations with two different inputs (2). For the 1686 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1687 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1688 SelectionDAG &DAG) { 1689 if (N->getValueType(0) != MVT::v16i8) 1690 return -1; 1691 1692 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1693 1694 // Find the first non-undef value in the shuffle mask. 1695 unsigned i; 1696 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1697 /*search*/; 1698 1699 if (i == 16) return -1; // all undef. 1700 1701 // Otherwise, check to see if the rest of the elements are consecutively 1702 // numbered from this value. 1703 unsigned ShiftAmt = SVOp->getMaskElt(i); 1704 if (ShiftAmt < i) return -1; 1705 1706 ShiftAmt -= i; 1707 bool isLE = DAG.getDataLayout().isLittleEndian(); 1708 1709 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1710 // Check the rest of the elements to see if they are consecutive. 1711 for (++i; i != 16; ++i) 1712 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1713 return -1; 1714 } else if (ShuffleKind == 1) { 1715 // Check the rest of the elements to see if they are consecutive. 1716 for (++i; i != 16; ++i) 1717 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1718 return -1; 1719 } else 1720 return -1; 1721 1722 if (isLE) 1723 ShiftAmt = 16 - ShiftAmt; 1724 1725 return ShiftAmt; 1726 } 1727 1728 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1729 /// specifies a splat of a single element that is suitable for input to 1730 /// VSPLTB/VSPLTH/VSPLTW. 1731 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1732 assert(N->getValueType(0) == MVT::v16i8 && 1733 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1734 1735 // The consecutive indices need to specify an element, not part of two 1736 // different elements. So abandon ship early if this isn't the case. 1737 if (N->getMaskElt(0) % EltSize != 0) 1738 return false; 1739 1740 // This is a splat operation if each element of the permute is the same, and 1741 // if the value doesn't reference the second vector. 1742 unsigned ElementBase = N->getMaskElt(0); 1743 1744 // FIXME: Handle UNDEF elements too! 1745 if (ElementBase >= 16) 1746 return false; 1747 1748 // Check that the indices are consecutive, in the case of a multi-byte element 1749 // splatted with a v16i8 mask. 1750 for (unsigned i = 1; i != EltSize; ++i) 1751 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1752 return false; 1753 1754 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1755 if (N->getMaskElt(i) < 0) continue; 1756 for (unsigned j = 0; j != EltSize; ++j) 1757 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1758 return false; 1759 } 1760 return true; 1761 } 1762 1763 /// Check that the mask is shuffling N byte elements. Within each N byte 1764 /// element of the mask, the indices could be either in increasing or 1765 /// decreasing order as long as they are consecutive. 1766 /// \param[in] N the shuffle vector SD Node to analyze 1767 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1768 /// Word/DoubleWord/QuadWord). 1769 /// \param[in] StepLen the delta indices number among the N byte element, if 1770 /// the mask is in increasing/decreasing order then it is 1/-1. 1771 /// \return true iff the mask is shuffling N byte elements. 1772 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1773 int StepLen) { 1774 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1775 "Unexpected element width."); 1776 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1777 1778 unsigned NumOfElem = 16 / Width; 1779 unsigned MaskVal[16]; // Width is never greater than 16 1780 for (unsigned i = 0; i < NumOfElem; ++i) { 1781 MaskVal[0] = N->getMaskElt(i * Width); 1782 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1783 return false; 1784 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1785 return false; 1786 } 1787 1788 for (unsigned int j = 1; j < Width; ++j) { 1789 MaskVal[j] = N->getMaskElt(i * Width + j); 1790 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1791 return false; 1792 } 1793 } 1794 } 1795 1796 return true; 1797 } 1798 1799 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1800 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1801 if (!isNByteElemShuffleMask(N, 4, 1)) 1802 return false; 1803 1804 // Now we look at mask elements 0,4,8,12 1805 unsigned M0 = N->getMaskElt(0) / 4; 1806 unsigned M1 = N->getMaskElt(4) / 4; 1807 unsigned M2 = N->getMaskElt(8) / 4; 1808 unsigned M3 = N->getMaskElt(12) / 4; 1809 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1810 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1811 1812 // Below, let H and L be arbitrary elements of the shuffle mask 1813 // where H is in the range [4,7] and L is in the range [0,3]. 1814 // H, 1, 2, 3 or L, 5, 6, 7 1815 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1816 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1817 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1818 InsertAtByte = IsLE ? 12 : 0; 1819 Swap = M0 < 4; 1820 return true; 1821 } 1822 // 0, H, 2, 3 or 4, L, 6, 7 1823 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1824 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1825 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1826 InsertAtByte = IsLE ? 8 : 4; 1827 Swap = M1 < 4; 1828 return true; 1829 } 1830 // 0, 1, H, 3 or 4, 5, L, 7 1831 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1832 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1833 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1834 InsertAtByte = IsLE ? 4 : 8; 1835 Swap = M2 < 4; 1836 return true; 1837 } 1838 // 0, 1, 2, H or 4, 5, 6, L 1839 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1840 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1841 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1842 InsertAtByte = IsLE ? 0 : 12; 1843 Swap = M3 < 4; 1844 return true; 1845 } 1846 1847 // If both vector operands for the shuffle are the same vector, the mask will 1848 // contain only elements from the first one and the second one will be undef. 1849 if (N->getOperand(1).isUndef()) { 1850 ShiftElts = 0; 1851 Swap = true; 1852 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1853 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1854 InsertAtByte = IsLE ? 12 : 0; 1855 return true; 1856 } 1857 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1858 InsertAtByte = IsLE ? 8 : 4; 1859 return true; 1860 } 1861 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1862 InsertAtByte = IsLE ? 4 : 8; 1863 return true; 1864 } 1865 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1866 InsertAtByte = IsLE ? 0 : 12; 1867 return true; 1868 } 1869 } 1870 1871 return false; 1872 } 1873 1874 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1875 bool &Swap, bool IsLE) { 1876 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1877 // Ensure each byte index of the word is consecutive. 1878 if (!isNByteElemShuffleMask(N, 4, 1)) 1879 return false; 1880 1881 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1882 unsigned M0 = N->getMaskElt(0) / 4; 1883 unsigned M1 = N->getMaskElt(4) / 4; 1884 unsigned M2 = N->getMaskElt(8) / 4; 1885 unsigned M3 = N->getMaskElt(12) / 4; 1886 1887 // If both vector operands for the shuffle are the same vector, the mask will 1888 // contain only elements from the first one and the second one will be undef. 1889 if (N->getOperand(1).isUndef()) { 1890 assert(M0 < 4 && "Indexing into an undef vector?"); 1891 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1892 return false; 1893 1894 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1895 Swap = false; 1896 return true; 1897 } 1898 1899 // Ensure each word index of the ShuffleVector Mask is consecutive. 1900 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1901 return false; 1902 1903 if (IsLE) { 1904 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1905 // Input vectors don't need to be swapped if the leading element 1906 // of the result is one of the 3 left elements of the second vector 1907 // (or if there is no shift to be done at all). 1908 Swap = false; 1909 ShiftElts = (8 - M0) % 8; 1910 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1911 // Input vectors need to be swapped if the leading element 1912 // of the result is one of the 3 left elements of the first vector 1913 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1914 Swap = true; 1915 ShiftElts = (4 - M0) % 4; 1916 } 1917 1918 return true; 1919 } else { // BE 1920 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1921 // Input vectors don't need to be swapped if the leading element 1922 // of the result is one of the 4 elements of the first vector. 1923 Swap = false; 1924 ShiftElts = M0; 1925 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1926 // Input vectors need to be swapped if the leading element 1927 // of the result is one of the 4 elements of the right vector. 1928 Swap = true; 1929 ShiftElts = M0 - 4; 1930 } 1931 1932 return true; 1933 } 1934 } 1935 1936 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1937 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1938 1939 if (!isNByteElemShuffleMask(N, Width, -1)) 1940 return false; 1941 1942 for (int i = 0; i < 16; i += Width) 1943 if (N->getMaskElt(i) != i + Width - 1) 1944 return false; 1945 1946 return true; 1947 } 1948 1949 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1950 return isXXBRShuffleMaskHelper(N, 2); 1951 } 1952 1953 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1954 return isXXBRShuffleMaskHelper(N, 4); 1955 } 1956 1957 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 1958 return isXXBRShuffleMaskHelper(N, 8); 1959 } 1960 1961 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 1962 return isXXBRShuffleMaskHelper(N, 16); 1963 } 1964 1965 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 1966 /// if the inputs to the instruction should be swapped and set \p DM to the 1967 /// value for the immediate. 1968 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 1969 /// AND element 0 of the result comes from the first input (LE) or second input 1970 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 1971 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 1972 /// mask. 1973 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 1974 bool &Swap, bool IsLE) { 1975 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1976 1977 // Ensure each byte index of the double word is consecutive. 1978 if (!isNByteElemShuffleMask(N, 8, 1)) 1979 return false; 1980 1981 unsigned M0 = N->getMaskElt(0) / 8; 1982 unsigned M1 = N->getMaskElt(8) / 8; 1983 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 1984 1985 // If both vector operands for the shuffle are the same vector, the mask will 1986 // contain only elements from the first one and the second one will be undef. 1987 if (N->getOperand(1).isUndef()) { 1988 if ((M0 | M1) < 2) { 1989 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 1990 Swap = false; 1991 return true; 1992 } else 1993 return false; 1994 } 1995 1996 if (IsLE) { 1997 if (M0 > 1 && M1 < 2) { 1998 Swap = false; 1999 } else if (M0 < 2 && M1 > 1) { 2000 M0 = (M0 + 2) % 4; 2001 M1 = (M1 + 2) % 4; 2002 Swap = true; 2003 } else 2004 return false; 2005 2006 // Note: if control flow comes here that means Swap is already set above 2007 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2008 return true; 2009 } else { // BE 2010 if (M0 < 2 && M1 > 1) { 2011 Swap = false; 2012 } else if (M0 > 1 && M1 < 2) { 2013 M0 = (M0 + 2) % 4; 2014 M1 = (M1 + 2) % 4; 2015 Swap = true; 2016 } else 2017 return false; 2018 2019 // Note: if control flow comes here that means Swap is already set above 2020 DM = (M0 << 1) + (M1 & 1); 2021 return true; 2022 } 2023 } 2024 2025 2026 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 2027 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 2028 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 2029 SelectionDAG &DAG) { 2030 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2031 assert(isSplatShuffleMask(SVOp, EltSize)); 2032 if (DAG.getDataLayout().isLittleEndian()) 2033 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2034 else 2035 return SVOp->getMaskElt(0) / EltSize; 2036 } 2037 2038 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2039 /// by using a vspltis[bhw] instruction of the specified element size, return 2040 /// the constant being splatted. The ByteSize field indicates the number of 2041 /// bytes of each element [124] -> [bhw]. 2042 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2043 SDValue OpVal(nullptr, 0); 2044 2045 // If ByteSize of the splat is bigger than the element size of the 2046 // build_vector, then we have a case where we are checking for a splat where 2047 // multiple elements of the buildvector are folded together into a single 2048 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2049 unsigned EltSize = 16/N->getNumOperands(); 2050 if (EltSize < ByteSize) { 2051 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2052 SDValue UniquedVals[4]; 2053 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2054 2055 // See if all of the elements in the buildvector agree across. 2056 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2057 if (N->getOperand(i).isUndef()) continue; 2058 // If the element isn't a constant, bail fully out. 2059 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2060 2061 if (!UniquedVals[i&(Multiple-1)].getNode()) 2062 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2063 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2064 return SDValue(); // no match. 2065 } 2066 2067 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2068 // either constant or undef values that are identical for each chunk. See 2069 // if these chunks can form into a larger vspltis*. 2070 2071 // Check to see if all of the leading entries are either 0 or -1. If 2072 // neither, then this won't fit into the immediate field. 2073 bool LeadingZero = true; 2074 bool LeadingOnes = true; 2075 for (unsigned i = 0; i != Multiple-1; ++i) { 2076 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2077 2078 LeadingZero &= isNullConstant(UniquedVals[i]); 2079 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2080 } 2081 // Finally, check the least significant entry. 2082 if (LeadingZero) { 2083 if (!UniquedVals[Multiple-1].getNode()) 2084 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2085 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2086 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2087 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2088 } 2089 if (LeadingOnes) { 2090 if (!UniquedVals[Multiple-1].getNode()) 2091 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2092 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2093 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2094 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2095 } 2096 2097 return SDValue(); 2098 } 2099 2100 // Check to see if this buildvec has a single non-undef value in its elements. 2101 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2102 if (N->getOperand(i).isUndef()) continue; 2103 if (!OpVal.getNode()) 2104 OpVal = N->getOperand(i); 2105 else if (OpVal != N->getOperand(i)) 2106 return SDValue(); 2107 } 2108 2109 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2110 2111 unsigned ValSizeInBytes = EltSize; 2112 uint64_t Value = 0; 2113 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2114 Value = CN->getZExtValue(); 2115 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2116 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2117 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2118 } 2119 2120 // If the splat value is larger than the element value, then we can never do 2121 // this splat. The only case that we could fit the replicated bits into our 2122 // immediate field for would be zero, and we prefer to use vxor for it. 2123 if (ValSizeInBytes < ByteSize) return SDValue(); 2124 2125 // If the element value is larger than the splat value, check if it consists 2126 // of a repeated bit pattern of size ByteSize. 2127 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2128 return SDValue(); 2129 2130 // Properly sign extend the value. 2131 int MaskVal = SignExtend32(Value, ByteSize * 8); 2132 2133 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2134 if (MaskVal == 0) return SDValue(); 2135 2136 // Finally, if this value fits in a 5 bit sext field, return it 2137 if (SignExtend32<5>(MaskVal) == MaskVal) 2138 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2139 return SDValue(); 2140 } 2141 2142 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2143 /// amount, otherwise return -1. 2144 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2145 EVT VT = N->getValueType(0); 2146 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2147 return -1; 2148 2149 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2150 2151 // Find the first non-undef value in the shuffle mask. 2152 unsigned i; 2153 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2154 /*search*/; 2155 2156 if (i == 4) return -1; // all undef. 2157 2158 // Otherwise, check to see if the rest of the elements are consecutively 2159 // numbered from this value. 2160 unsigned ShiftAmt = SVOp->getMaskElt(i); 2161 if (ShiftAmt < i) return -1; 2162 ShiftAmt -= i; 2163 2164 // Check the rest of the elements to see if they are consecutive. 2165 for (++i; i != 4; ++i) 2166 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2167 return -1; 2168 2169 return ShiftAmt; 2170 } 2171 2172 //===----------------------------------------------------------------------===// 2173 // Addressing Mode Selection 2174 //===----------------------------------------------------------------------===// 2175 2176 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2177 /// or 64-bit immediate, and if the value can be accurately represented as a 2178 /// sign extension from a 16-bit value. If so, this returns true and the 2179 /// immediate. 2180 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2181 if (!isa<ConstantSDNode>(N)) 2182 return false; 2183 2184 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2185 if (N->getValueType(0) == MVT::i32) 2186 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2187 else 2188 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2189 } 2190 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2191 return isIntS16Immediate(Op.getNode(), Imm); 2192 } 2193 2194 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2195 /// can be represented as an indexed [r+r] operation. Returns false if it 2196 /// can be more efficiently represented with [r+imm]. 2197 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2198 SDValue &Index, 2199 SelectionDAG &DAG) const { 2200 int16_t imm = 0; 2201 if (N.getOpcode() == ISD::ADD) { 2202 if (isIntS16Immediate(N.getOperand(1), imm)) 2203 return false; // r+i 2204 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2205 return false; // r+i 2206 2207 Base = N.getOperand(0); 2208 Index = N.getOperand(1); 2209 return true; 2210 } else if (N.getOpcode() == ISD::OR) { 2211 if (isIntS16Immediate(N.getOperand(1), imm)) 2212 return false; // r+i can fold it if we can. 2213 2214 // If this is an or of disjoint bitfields, we can codegen this as an add 2215 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2216 // disjoint. 2217 KnownBits LHSKnown, RHSKnown; 2218 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2219 2220 if (LHSKnown.Zero.getBoolValue()) { 2221 DAG.computeKnownBits(N.getOperand(1), RHSKnown); 2222 // If all of the bits are known zero on the LHS or RHS, the add won't 2223 // carry. 2224 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2225 Base = N.getOperand(0); 2226 Index = N.getOperand(1); 2227 return true; 2228 } 2229 } 2230 } 2231 2232 return false; 2233 } 2234 2235 // If we happen to be doing an i64 load or store into a stack slot that has 2236 // less than a 4-byte alignment, then the frame-index elimination may need to 2237 // use an indexed load or store instruction (because the offset may not be a 2238 // multiple of 4). The extra register needed to hold the offset comes from the 2239 // register scavenger, and it is possible that the scavenger will need to use 2240 // an emergency spill slot. As a result, we need to make sure that a spill slot 2241 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2242 // stack slot. 2243 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2244 // FIXME: This does not handle the LWA case. 2245 if (VT != MVT::i64) 2246 return; 2247 2248 // NOTE: We'll exclude negative FIs here, which come from argument 2249 // lowering, because there are no known test cases triggering this problem 2250 // using packed structures (or similar). We can remove this exclusion if 2251 // we find such a test case. The reason why this is so test-case driven is 2252 // because this entire 'fixup' is only to prevent crashes (from the 2253 // register scavenger) on not-really-valid inputs. For example, if we have: 2254 // %a = alloca i1 2255 // %b = bitcast i1* %a to i64* 2256 // store i64* a, i64 b 2257 // then the store should really be marked as 'align 1', but is not. If it 2258 // were marked as 'align 1' then the indexed form would have been 2259 // instruction-selected initially, and the problem this 'fixup' is preventing 2260 // won't happen regardless. 2261 if (FrameIdx < 0) 2262 return; 2263 2264 MachineFunction &MF = DAG.getMachineFunction(); 2265 MachineFrameInfo &MFI = MF.getFrameInfo(); 2266 2267 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2268 if (Align >= 4) 2269 return; 2270 2271 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2272 FuncInfo->setHasNonRISpills(); 2273 } 2274 2275 /// Returns true if the address N can be represented by a base register plus 2276 /// a signed 16-bit displacement [r+imm], and if it is not better 2277 /// represented as reg+reg. If \p Alignment is non-zero, only accept 2278 /// displacements that are multiples of that value. 2279 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2280 SDValue &Base, 2281 SelectionDAG &DAG, 2282 unsigned Alignment) const { 2283 // FIXME dl should come from parent load or store, not from address 2284 SDLoc dl(N); 2285 // If this can be more profitably realized as r+r, fail. 2286 if (SelectAddressRegReg(N, Disp, Base, DAG)) 2287 return false; 2288 2289 if (N.getOpcode() == ISD::ADD) { 2290 int16_t imm = 0; 2291 if (isIntS16Immediate(N.getOperand(1), imm) && 2292 (!Alignment || (imm % Alignment) == 0)) { 2293 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2294 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2295 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2296 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2297 } else { 2298 Base = N.getOperand(0); 2299 } 2300 return true; // [r+i] 2301 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2302 // Match LOAD (ADD (X, Lo(G))). 2303 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2304 && "Cannot handle constant offsets yet!"); 2305 Disp = N.getOperand(1).getOperand(0); // The global address. 2306 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2307 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2308 Disp.getOpcode() == ISD::TargetConstantPool || 2309 Disp.getOpcode() == ISD::TargetJumpTable); 2310 Base = N.getOperand(0); 2311 return true; // [&g+r] 2312 } 2313 } else if (N.getOpcode() == ISD::OR) { 2314 int16_t imm = 0; 2315 if (isIntS16Immediate(N.getOperand(1), imm) && 2316 (!Alignment || (imm % Alignment) == 0)) { 2317 // If this is an or of disjoint bitfields, we can codegen this as an add 2318 // (for better address arithmetic) if the LHS and RHS of the OR are 2319 // provably disjoint. 2320 KnownBits LHSKnown; 2321 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2322 2323 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2324 // If all of the bits are known zero on the LHS or RHS, the add won't 2325 // carry. 2326 if (FrameIndexSDNode *FI = 2327 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2328 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2329 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2330 } else { 2331 Base = N.getOperand(0); 2332 } 2333 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2334 return true; 2335 } 2336 } 2337 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2338 // Loading from a constant address. 2339 2340 // If this address fits entirely in a 16-bit sext immediate field, codegen 2341 // this as "d, 0" 2342 int16_t Imm; 2343 if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) { 2344 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2345 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2346 CN->getValueType(0)); 2347 return true; 2348 } 2349 2350 // Handle 32-bit sext immediates with LIS + addr mode. 2351 if ((CN->getValueType(0) == MVT::i32 || 2352 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2353 (!Alignment || (CN->getZExtValue() % Alignment) == 0)) { 2354 int Addr = (int)CN->getZExtValue(); 2355 2356 // Otherwise, break this down into an LIS + disp. 2357 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2358 2359 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2360 MVT::i32); 2361 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2362 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2363 return true; 2364 } 2365 } 2366 2367 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2368 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2369 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2370 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2371 } else 2372 Base = N; 2373 return true; // [r+0] 2374 } 2375 2376 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2377 /// represented as an indexed [r+r] operation. 2378 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2379 SDValue &Index, 2380 SelectionDAG &DAG) const { 2381 // Check to see if we can easily represent this as an [r+r] address. This 2382 // will fail if it thinks that the address is more profitably represented as 2383 // reg+imm, e.g. where imm = 0. 2384 if (SelectAddressRegReg(N, Base, Index, DAG)) 2385 return true; 2386 2387 // If the address is the result of an add, we will utilize the fact that the 2388 // address calculation includes an implicit add. However, we can reduce 2389 // register pressure if we do not materialize a constant just for use as the 2390 // index register. We only get rid of the add if it is not an add of a 2391 // value and a 16-bit signed constant and both have a single use. 2392 int16_t imm = 0; 2393 if (N.getOpcode() == ISD::ADD && 2394 (!isIntS16Immediate(N.getOperand(1), imm) || 2395 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2396 Base = N.getOperand(0); 2397 Index = N.getOperand(1); 2398 return true; 2399 } 2400 2401 // Otherwise, do it the hard way, using R0 as the base register. 2402 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2403 N.getValueType()); 2404 Index = N; 2405 return true; 2406 } 2407 2408 /// Returns true if we should use a direct load into vector instruction 2409 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2410 static bool usePartialVectorLoads(SDNode *N) { 2411 if (!N->hasOneUse()) 2412 return false; 2413 2414 // If there are any other uses other than scalar to vector, then we should 2415 // keep it as a scalar load -> direct move pattern to prevent multiple 2416 // loads. Currently, only check for i64 since we have lxsd/lfd to do this 2417 // efficiently, but no update equivalent. 2418 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2419 EVT MemVT = LD->getMemoryVT(); 2420 if (MemVT.isSimple() && MemVT.getSimpleVT().SimpleTy == MVT::i64) { 2421 SDNode *User = *(LD->use_begin()); 2422 if (User->getOpcode() == ISD::SCALAR_TO_VECTOR) 2423 return true; 2424 } 2425 } 2426 2427 return false; 2428 } 2429 2430 /// getPreIndexedAddressParts - returns true by value, base pointer and 2431 /// offset pointer and addressing mode by reference if the node's address 2432 /// can be legally represented as pre-indexed load / store address. 2433 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2434 SDValue &Offset, 2435 ISD::MemIndexedMode &AM, 2436 SelectionDAG &DAG) const { 2437 if (DisablePPCPreinc) return false; 2438 2439 bool isLoad = true; 2440 SDValue Ptr; 2441 EVT VT; 2442 unsigned Alignment; 2443 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2444 Ptr = LD->getBasePtr(); 2445 VT = LD->getMemoryVT(); 2446 Alignment = LD->getAlignment(); 2447 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2448 Ptr = ST->getBasePtr(); 2449 VT = ST->getMemoryVT(); 2450 Alignment = ST->getAlignment(); 2451 isLoad = false; 2452 } else 2453 return false; 2454 2455 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2456 // instructions because we can fold these into a more efficient instruction 2457 // instead, (such as LXSD). 2458 if (isLoad && usePartialVectorLoads(N)) { 2459 return false; 2460 } 2461 2462 // PowerPC doesn't have preinc load/store instructions for vectors (except 2463 // for QPX, which does have preinc r+r forms). 2464 if (VT.isVector()) { 2465 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2466 return false; 2467 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2468 AM = ISD::PRE_INC; 2469 return true; 2470 } 2471 } 2472 2473 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2474 // Common code will reject creating a pre-inc form if the base pointer 2475 // is a frame index, or if N is a store and the base pointer is either 2476 // the same as or a predecessor of the value being stored. Check for 2477 // those situations here, and try with swapped Base/Offset instead. 2478 bool Swap = false; 2479 2480 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2481 Swap = true; 2482 else if (!isLoad) { 2483 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2484 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2485 Swap = true; 2486 } 2487 2488 if (Swap) 2489 std::swap(Base, Offset); 2490 2491 AM = ISD::PRE_INC; 2492 return true; 2493 } 2494 2495 // LDU/STU can only handle immediates that are a multiple of 4. 2496 if (VT != MVT::i64) { 2497 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2498 return false; 2499 } else { 2500 // LDU/STU need an address with at least 4-byte alignment. 2501 if (Alignment < 4) 2502 return false; 2503 2504 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2505 return false; 2506 } 2507 2508 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2509 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2510 // sext i32 to i64 when addr mode is r+i. 2511 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2512 LD->getExtensionType() == ISD::SEXTLOAD && 2513 isa<ConstantSDNode>(Offset)) 2514 return false; 2515 } 2516 2517 AM = ISD::PRE_INC; 2518 return true; 2519 } 2520 2521 //===----------------------------------------------------------------------===// 2522 // LowerOperation implementation 2523 //===----------------------------------------------------------------------===// 2524 2525 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2526 /// and LoOpFlags to the target MO flags. 2527 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2528 unsigned &HiOpFlags, unsigned &LoOpFlags, 2529 const GlobalValue *GV = nullptr) { 2530 HiOpFlags = PPCII::MO_HA; 2531 LoOpFlags = PPCII::MO_LO; 2532 2533 // Don't use the pic base if not in PIC relocation model. 2534 if (IsPIC) { 2535 HiOpFlags |= PPCII::MO_PIC_FLAG; 2536 LoOpFlags |= PPCII::MO_PIC_FLAG; 2537 } 2538 2539 // If this is a reference to a global value that requires a non-lazy-ptr, make 2540 // sure that instruction lowering adds it. 2541 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2542 HiOpFlags |= PPCII::MO_NLP_FLAG; 2543 LoOpFlags |= PPCII::MO_NLP_FLAG; 2544 2545 if (GV->hasHiddenVisibility()) { 2546 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2547 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2548 } 2549 } 2550 } 2551 2552 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2553 SelectionDAG &DAG) { 2554 SDLoc DL(HiPart); 2555 EVT PtrVT = HiPart.getValueType(); 2556 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2557 2558 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2559 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2560 2561 // With PIC, the first instruction is actually "GR+hi(&G)". 2562 if (isPIC) 2563 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2564 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2565 2566 // Generate non-pic code that has direct accesses to the constant pool. 2567 // The address of the global is just (hi(&g)+lo(&g)). 2568 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2569 } 2570 2571 static void setUsesTOCBasePtr(MachineFunction &MF) { 2572 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2573 FuncInfo->setUsesTOCBasePtr(); 2574 } 2575 2576 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2577 setUsesTOCBasePtr(DAG.getMachineFunction()); 2578 } 2579 2580 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2581 SDValue GA) { 2582 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2583 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2584 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2585 2586 SDValue Ops[] = { GA, Reg }; 2587 return DAG.getMemIntrinsicNode( 2588 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2589 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2590 MachineMemOperand::MOLoad); 2591 } 2592 2593 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2594 SelectionDAG &DAG) const { 2595 EVT PtrVT = Op.getValueType(); 2596 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2597 const Constant *C = CP->getConstVal(); 2598 2599 // 64-bit SVR4 ABI code is always position-independent. 2600 // The actual address of the GlobalValue is stored in the TOC. 2601 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2602 setUsesTOCBasePtr(DAG); 2603 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2604 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2605 } 2606 2607 unsigned MOHiFlag, MOLoFlag; 2608 bool IsPIC = isPositionIndependent(); 2609 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2610 2611 if (IsPIC && Subtarget.isSVR4ABI()) { 2612 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2613 PPCII::MO_PIC_FLAG); 2614 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2615 } 2616 2617 SDValue CPIHi = 2618 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2619 SDValue CPILo = 2620 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2621 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2622 } 2623 2624 // For 64-bit PowerPC, prefer the more compact relative encodings. 2625 // This trades 32 bits per jump table entry for one or two instructions 2626 // on the jump site. 2627 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2628 if (isJumpTableRelative()) 2629 return MachineJumpTableInfo::EK_LabelDifference32; 2630 2631 return TargetLowering::getJumpTableEncoding(); 2632 } 2633 2634 bool PPCTargetLowering::isJumpTableRelative() const { 2635 if (Subtarget.isPPC64()) 2636 return true; 2637 return TargetLowering::isJumpTableRelative(); 2638 } 2639 2640 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2641 SelectionDAG &DAG) const { 2642 if (!Subtarget.isPPC64()) 2643 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2644 2645 switch (getTargetMachine().getCodeModel()) { 2646 case CodeModel::Small: 2647 case CodeModel::Medium: 2648 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2649 default: 2650 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2651 getPointerTy(DAG.getDataLayout())); 2652 } 2653 } 2654 2655 const MCExpr * 2656 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2657 unsigned JTI, 2658 MCContext &Ctx) const { 2659 if (!Subtarget.isPPC64()) 2660 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2661 2662 switch (getTargetMachine().getCodeModel()) { 2663 case CodeModel::Small: 2664 case CodeModel::Medium: 2665 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2666 default: 2667 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2668 } 2669 } 2670 2671 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2672 EVT PtrVT = Op.getValueType(); 2673 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2674 2675 // 64-bit SVR4 ABI code is always position-independent. 2676 // The actual address of the GlobalValue is stored in the TOC. 2677 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2678 setUsesTOCBasePtr(DAG); 2679 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2680 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2681 } 2682 2683 unsigned MOHiFlag, MOLoFlag; 2684 bool IsPIC = isPositionIndependent(); 2685 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2686 2687 if (IsPIC && Subtarget.isSVR4ABI()) { 2688 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2689 PPCII::MO_PIC_FLAG); 2690 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2691 } 2692 2693 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2694 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2695 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2696 } 2697 2698 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2699 SelectionDAG &DAG) const { 2700 EVT PtrVT = Op.getValueType(); 2701 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2702 const BlockAddress *BA = BASDN->getBlockAddress(); 2703 2704 // 64-bit SVR4 ABI code is always position-independent. 2705 // The actual BlockAddress is stored in the TOC. 2706 if (Subtarget.isSVR4ABI() && 2707 (Subtarget.isPPC64() || isPositionIndependent())) { 2708 if (Subtarget.isPPC64()) 2709 setUsesTOCBasePtr(DAG); 2710 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2711 return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA); 2712 } 2713 2714 unsigned MOHiFlag, MOLoFlag; 2715 bool IsPIC = isPositionIndependent(); 2716 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2717 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2718 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2719 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2720 } 2721 2722 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2723 SelectionDAG &DAG) const { 2724 // FIXME: TLS addresses currently use medium model code sequences, 2725 // which is the most useful form. Eventually support for small and 2726 // large models could be added if users need it, at the cost of 2727 // additional complexity. 2728 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2729 if (DAG.getTarget().useEmulatedTLS()) 2730 return LowerToTLSEmulatedModel(GA, DAG); 2731 2732 SDLoc dl(GA); 2733 const GlobalValue *GV = GA->getGlobal(); 2734 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2735 bool is64bit = Subtarget.isPPC64(); 2736 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2737 PICLevel::Level picLevel = M->getPICLevel(); 2738 2739 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 2740 2741 if (Model == TLSModel::LocalExec) { 2742 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2743 PPCII::MO_TPREL_HA); 2744 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2745 PPCII::MO_TPREL_LO); 2746 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2747 : DAG.getRegister(PPC::R2, MVT::i32); 2748 2749 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2750 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2751 } 2752 2753 if (Model == TLSModel::InitialExec) { 2754 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2755 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2756 PPCII::MO_TLS); 2757 SDValue GOTPtr; 2758 if (is64bit) { 2759 setUsesTOCBasePtr(DAG); 2760 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2761 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2762 PtrVT, GOTReg, TGA); 2763 } else 2764 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2765 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2766 PtrVT, TGA, GOTPtr); 2767 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2768 } 2769 2770 if (Model == TLSModel::GeneralDynamic) { 2771 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2772 SDValue GOTPtr; 2773 if (is64bit) { 2774 setUsesTOCBasePtr(DAG); 2775 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2776 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2777 GOTReg, TGA); 2778 } else { 2779 if (picLevel == PICLevel::SmallPIC) 2780 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2781 else 2782 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2783 } 2784 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2785 GOTPtr, TGA, TGA); 2786 } 2787 2788 if (Model == TLSModel::LocalDynamic) { 2789 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2790 SDValue GOTPtr; 2791 if (is64bit) { 2792 setUsesTOCBasePtr(DAG); 2793 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2794 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2795 GOTReg, TGA); 2796 } else { 2797 if (picLevel == PICLevel::SmallPIC) 2798 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2799 else 2800 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2801 } 2802 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2803 PtrVT, GOTPtr, TGA, TGA); 2804 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2805 PtrVT, TLSAddr, TGA); 2806 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2807 } 2808 2809 llvm_unreachable("Unknown TLS model!"); 2810 } 2811 2812 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2813 SelectionDAG &DAG) const { 2814 EVT PtrVT = Op.getValueType(); 2815 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2816 SDLoc DL(GSDN); 2817 const GlobalValue *GV = GSDN->getGlobal(); 2818 2819 // 64-bit SVR4 ABI code is always position-independent. 2820 // The actual address of the GlobalValue is stored in the TOC. 2821 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2822 setUsesTOCBasePtr(DAG); 2823 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2824 return getTOCEntry(DAG, DL, true, GA); 2825 } 2826 2827 unsigned MOHiFlag, MOLoFlag; 2828 bool IsPIC = isPositionIndependent(); 2829 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2830 2831 if (IsPIC && Subtarget.isSVR4ABI()) { 2832 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2833 GSDN->getOffset(), 2834 PPCII::MO_PIC_FLAG); 2835 return getTOCEntry(DAG, DL, false, GA); 2836 } 2837 2838 SDValue GAHi = 2839 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2840 SDValue GALo = 2841 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2842 2843 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2844 2845 // If the global reference is actually to a non-lazy-pointer, we have to do an 2846 // extra load to get the address of the global. 2847 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2848 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2849 return Ptr; 2850 } 2851 2852 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2853 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2854 SDLoc dl(Op); 2855 2856 if (Op.getValueType() == MVT::v2i64) { 2857 // When the operands themselves are v2i64 values, we need to do something 2858 // special because VSX has no underlying comparison operations for these. 2859 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2860 // Equality can be handled by casting to the legal type for Altivec 2861 // comparisons, everything else needs to be expanded. 2862 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2863 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2864 DAG.getSetCC(dl, MVT::v4i32, 2865 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2866 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2867 CC)); 2868 } 2869 2870 return SDValue(); 2871 } 2872 2873 // We handle most of these in the usual way. 2874 return Op; 2875 } 2876 2877 // If we're comparing for equality to zero, expose the fact that this is 2878 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2879 // fold the new nodes. 2880 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2881 return V; 2882 2883 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2884 // Leave comparisons against 0 and -1 alone for now, since they're usually 2885 // optimized. FIXME: revisit this when we can custom lower all setcc 2886 // optimizations. 2887 if (C->isAllOnesValue() || C->isNullValue()) 2888 return SDValue(); 2889 } 2890 2891 // If we have an integer seteq/setne, turn it into a compare against zero 2892 // by xor'ing the rhs with the lhs, which is faster than setting a 2893 // condition register, reading it back out, and masking the correct bit. The 2894 // normal approach here uses sub to do this instead of xor. Using xor exposes 2895 // the result to other bit-twiddling opportunities. 2896 EVT LHSVT = Op.getOperand(0).getValueType(); 2897 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2898 EVT VT = Op.getValueType(); 2899 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2900 Op.getOperand(1)); 2901 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2902 } 2903 return SDValue(); 2904 } 2905 2906 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2907 SDNode *Node = Op.getNode(); 2908 EVT VT = Node->getValueType(0); 2909 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2910 SDValue InChain = Node->getOperand(0); 2911 SDValue VAListPtr = Node->getOperand(1); 2912 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2913 SDLoc dl(Node); 2914 2915 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2916 2917 // gpr_index 2918 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2919 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2920 InChain = GprIndex.getValue(1); 2921 2922 if (VT == MVT::i64) { 2923 // Check if GprIndex is even 2924 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2925 DAG.getConstant(1, dl, MVT::i32)); 2926 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2927 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2928 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2929 DAG.getConstant(1, dl, MVT::i32)); 2930 // Align GprIndex to be even if it isn't 2931 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2932 GprIndex); 2933 } 2934 2935 // fpr index is 1 byte after gpr 2936 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2937 DAG.getConstant(1, dl, MVT::i32)); 2938 2939 // fpr 2940 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2941 FprPtr, MachinePointerInfo(SV), MVT::i8); 2942 InChain = FprIndex.getValue(1); 2943 2944 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2945 DAG.getConstant(8, dl, MVT::i32)); 2946 2947 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2948 DAG.getConstant(4, dl, MVT::i32)); 2949 2950 // areas 2951 SDValue OverflowArea = 2952 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 2953 InChain = OverflowArea.getValue(1); 2954 2955 SDValue RegSaveArea = 2956 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 2957 InChain = RegSaveArea.getValue(1); 2958 2959 // select overflow_area if index > 8 2960 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2961 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 2962 2963 // adjustment constant gpr_index * 4/8 2964 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2965 VT.isInteger() ? GprIndex : FprIndex, 2966 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 2967 MVT::i32)); 2968 2969 // OurReg = RegSaveArea + RegConstant 2970 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2971 RegConstant); 2972 2973 // Floating types are 32 bytes into RegSaveArea 2974 if (VT.isFloatingPoint()) 2975 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 2976 DAG.getConstant(32, dl, MVT::i32)); 2977 2978 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 2979 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 2980 VT.isInteger() ? GprIndex : FprIndex, 2981 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 2982 MVT::i32)); 2983 2984 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 2985 VT.isInteger() ? VAListPtr : FprPtr, 2986 MachinePointerInfo(SV), MVT::i8); 2987 2988 // determine if we should load from reg_save_area or overflow_area 2989 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 2990 2991 // increase overflow_area by 4/8 if gpr/fpr > 8 2992 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 2993 DAG.getConstant(VT.isInteger() ? 4 : 8, 2994 dl, MVT::i32)); 2995 2996 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 2997 OverflowAreaPlusN); 2998 2999 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3000 MachinePointerInfo(), MVT::i32); 3001 3002 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3003 } 3004 3005 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3006 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3007 3008 // We have to copy the entire va_list struct: 3009 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3010 return DAG.getMemcpy(Op.getOperand(0), Op, 3011 Op.getOperand(1), Op.getOperand(2), 3012 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3013 false, MachinePointerInfo(), MachinePointerInfo()); 3014 } 3015 3016 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3017 SelectionDAG &DAG) const { 3018 return Op.getOperand(0); 3019 } 3020 3021 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3022 SelectionDAG &DAG) const { 3023 SDValue Chain = Op.getOperand(0); 3024 SDValue Trmp = Op.getOperand(1); // trampoline 3025 SDValue FPtr = Op.getOperand(2); // nested function 3026 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3027 SDLoc dl(Op); 3028 3029 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3030 bool isPPC64 = (PtrVT == MVT::i64); 3031 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3032 3033 TargetLowering::ArgListTy Args; 3034 TargetLowering::ArgListEntry Entry; 3035 3036 Entry.Ty = IntPtrTy; 3037 Entry.Node = Trmp; Args.push_back(Entry); 3038 3039 // TrampSize == (isPPC64 ? 48 : 40); 3040 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3041 isPPC64 ? MVT::i64 : MVT::i32); 3042 Args.push_back(Entry); 3043 3044 Entry.Node = FPtr; Args.push_back(Entry); 3045 Entry.Node = Nest; Args.push_back(Entry); 3046 3047 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3048 TargetLowering::CallLoweringInfo CLI(DAG); 3049 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3050 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3051 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3052 3053 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3054 return CallResult.second; 3055 } 3056 3057 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3058 MachineFunction &MF = DAG.getMachineFunction(); 3059 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3060 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3061 3062 SDLoc dl(Op); 3063 3064 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3065 // vastart just stores the address of the VarArgsFrameIndex slot into the 3066 // memory location argument. 3067 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3068 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3069 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3070 MachinePointerInfo(SV)); 3071 } 3072 3073 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3074 // We suppose the given va_list is already allocated. 3075 // 3076 // typedef struct { 3077 // char gpr; /* index into the array of 8 GPRs 3078 // * stored in the register save area 3079 // * gpr=0 corresponds to r3, 3080 // * gpr=1 to r4, etc. 3081 // */ 3082 // char fpr; /* index into the array of 8 FPRs 3083 // * stored in the register save area 3084 // * fpr=0 corresponds to f1, 3085 // * fpr=1 to f2, etc. 3086 // */ 3087 // char *overflow_arg_area; 3088 // /* location on stack that holds 3089 // * the next overflow argument 3090 // */ 3091 // char *reg_save_area; 3092 // /* where r3:r10 and f1:f8 (if saved) 3093 // * are stored 3094 // */ 3095 // } va_list[1]; 3096 3097 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3098 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3099 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3100 PtrVT); 3101 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3102 PtrVT); 3103 3104 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3105 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3106 3107 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3108 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3109 3110 uint64_t FPROffset = 1; 3111 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3112 3113 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3114 3115 // Store first byte : number of int regs 3116 SDValue firstStore = 3117 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3118 MachinePointerInfo(SV), MVT::i8); 3119 uint64_t nextOffset = FPROffset; 3120 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3121 ConstFPROffset); 3122 3123 // Store second byte : number of float regs 3124 SDValue secondStore = 3125 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3126 MachinePointerInfo(SV, nextOffset), MVT::i8); 3127 nextOffset += StackOffset; 3128 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3129 3130 // Store second word : arguments given on stack 3131 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3132 MachinePointerInfo(SV, nextOffset)); 3133 nextOffset += FrameOffset; 3134 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3135 3136 // Store third word : arguments given in registers 3137 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3138 MachinePointerInfo(SV, nextOffset)); 3139 } 3140 3141 #include "PPCGenCallingConv.inc" 3142 3143 // Function whose sole purpose is to kill compiler warnings 3144 // stemming from unused functions included from PPCGenCallingConv.inc. 3145 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { 3146 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; 3147 } 3148 3149 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 3150 CCValAssign::LocInfo &LocInfo, 3151 ISD::ArgFlagsTy &ArgFlags, 3152 CCState &State) { 3153 return true; 3154 } 3155 3156 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 3157 MVT &LocVT, 3158 CCValAssign::LocInfo &LocInfo, 3159 ISD::ArgFlagsTy &ArgFlags, 3160 CCState &State) { 3161 static const MCPhysReg ArgRegs[] = { 3162 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3163 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3164 }; 3165 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3166 3167 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3168 3169 // Skip one register if the first unallocated register has an even register 3170 // number and there are still argument registers available which have not been 3171 // allocated yet. RegNum is actually an index into ArgRegs, which means we 3172 // need to skip a register if RegNum is odd. 3173 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 3174 State.AllocateReg(ArgRegs[RegNum]); 3175 } 3176 3177 // Always return false here, as this function only makes sure that the first 3178 // unallocated register has an odd register number and does not actually 3179 // allocate a register for the current argument. 3180 return false; 3181 } 3182 3183 bool 3184 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT, 3185 MVT &LocVT, 3186 CCValAssign::LocInfo &LocInfo, 3187 ISD::ArgFlagsTy &ArgFlags, 3188 CCState &State) { 3189 static const MCPhysReg ArgRegs[] = { 3190 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3191 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3192 }; 3193 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3194 3195 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3196 int RegsLeft = NumArgRegs - RegNum; 3197 3198 // Skip if there is not enough registers left for long double type (4 gpr regs 3199 // in soft float mode) and put long double argument on the stack. 3200 if (RegNum != NumArgRegs && RegsLeft < 4) { 3201 for (int i = 0; i < RegsLeft; i++) { 3202 State.AllocateReg(ArgRegs[RegNum + i]); 3203 } 3204 } 3205 3206 return false; 3207 } 3208 3209 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 3210 MVT &LocVT, 3211 CCValAssign::LocInfo &LocInfo, 3212 ISD::ArgFlagsTy &ArgFlags, 3213 CCState &State) { 3214 static const MCPhysReg ArgRegs[] = { 3215 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3216 PPC::F8 3217 }; 3218 3219 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3220 3221 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3222 3223 // If there is only one Floating-point register left we need to put both f64 3224 // values of a split ppc_fp128 value on the stack. 3225 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 3226 State.AllocateReg(ArgRegs[RegNum]); 3227 } 3228 3229 // Always return false here, as this function only makes sure that the two f64 3230 // values a ppc_fp128 value is split into are both passed in registers or both 3231 // passed on the stack and does not actually allocate a register for the 3232 // current argument. 3233 return false; 3234 } 3235 3236 /// FPR - The set of FP registers that should be allocated for arguments, 3237 /// on Darwin. 3238 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3239 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3240 PPC::F11, PPC::F12, PPC::F13}; 3241 3242 /// QFPR - The set of QPX registers that should be allocated for arguments. 3243 static const MCPhysReg QFPR[] = { 3244 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3245 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3246 3247 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3248 /// the stack. 3249 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3250 unsigned PtrByteSize) { 3251 unsigned ArgSize = ArgVT.getStoreSize(); 3252 if (Flags.isByVal()) 3253 ArgSize = Flags.getByValSize(); 3254 3255 // Round up to multiples of the pointer size, except for array members, 3256 // which are always packed. 3257 if (!Flags.isInConsecutiveRegs()) 3258 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3259 3260 return ArgSize; 3261 } 3262 3263 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3264 /// on the stack. 3265 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3266 ISD::ArgFlagsTy Flags, 3267 unsigned PtrByteSize) { 3268 unsigned Align = PtrByteSize; 3269 3270 // Altivec parameters are padded to a 16 byte boundary. 3271 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3272 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3273 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3274 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3275 Align = 16; 3276 // QPX vector types stored in double-precision are padded to a 32 byte 3277 // boundary. 3278 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3279 Align = 32; 3280 3281 // ByVal parameters are aligned as requested. 3282 if (Flags.isByVal()) { 3283 unsigned BVAlign = Flags.getByValAlign(); 3284 if (BVAlign > PtrByteSize) { 3285 if (BVAlign % PtrByteSize != 0) 3286 llvm_unreachable( 3287 "ByVal alignment is not a multiple of the pointer size"); 3288 3289 Align = BVAlign; 3290 } 3291 } 3292 3293 // Array members are always packed to their original alignment. 3294 if (Flags.isInConsecutiveRegs()) { 3295 // If the array member was split into multiple registers, the first 3296 // needs to be aligned to the size of the full type. (Except for 3297 // ppcf128, which is only aligned as its f64 components.) 3298 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3299 Align = OrigVT.getStoreSize(); 3300 else 3301 Align = ArgVT.getStoreSize(); 3302 } 3303 3304 return Align; 3305 } 3306 3307 /// CalculateStackSlotUsed - Return whether this argument will use its 3308 /// stack slot (instead of being passed in registers). ArgOffset, 3309 /// AvailableFPRs, and AvailableVRs must hold the current argument 3310 /// position, and will be updated to account for this argument. 3311 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3312 ISD::ArgFlagsTy Flags, 3313 unsigned PtrByteSize, 3314 unsigned LinkageSize, 3315 unsigned ParamAreaSize, 3316 unsigned &ArgOffset, 3317 unsigned &AvailableFPRs, 3318 unsigned &AvailableVRs, bool HasQPX) { 3319 bool UseMemory = false; 3320 3321 // Respect alignment of argument on the stack. 3322 unsigned Align = 3323 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3324 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3325 // If there's no space left in the argument save area, we must 3326 // use memory (this check also catches zero-sized arguments). 3327 if (ArgOffset >= LinkageSize + ParamAreaSize) 3328 UseMemory = true; 3329 3330 // Allocate argument on the stack. 3331 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3332 if (Flags.isInConsecutiveRegsLast()) 3333 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3334 // If we overran the argument save area, we must use memory 3335 // (this check catches arguments passed partially in memory) 3336 if (ArgOffset > LinkageSize + ParamAreaSize) 3337 UseMemory = true; 3338 3339 // However, if the argument is actually passed in an FPR or a VR, 3340 // we don't use memory after all. 3341 if (!Flags.isByVal()) { 3342 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3343 // QPX registers overlap with the scalar FP registers. 3344 (HasQPX && (ArgVT == MVT::v4f32 || 3345 ArgVT == MVT::v4f64 || 3346 ArgVT == MVT::v4i1))) 3347 if (AvailableFPRs > 0) { 3348 --AvailableFPRs; 3349 return false; 3350 } 3351 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3352 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3353 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3354 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3355 if (AvailableVRs > 0) { 3356 --AvailableVRs; 3357 return false; 3358 } 3359 } 3360 3361 return UseMemory; 3362 } 3363 3364 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3365 /// ensure minimum alignment required for target. 3366 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3367 unsigned NumBytes) { 3368 unsigned TargetAlign = Lowering->getStackAlignment(); 3369 unsigned AlignMask = TargetAlign - 1; 3370 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3371 return NumBytes; 3372 } 3373 3374 SDValue PPCTargetLowering::LowerFormalArguments( 3375 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3376 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3377 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3378 if (Subtarget.isSVR4ABI()) { 3379 if (Subtarget.isPPC64()) 3380 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3381 dl, DAG, InVals); 3382 else 3383 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3384 dl, DAG, InVals); 3385 } else { 3386 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3387 dl, DAG, InVals); 3388 } 3389 } 3390 3391 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3392 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3393 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3394 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3395 3396 // 32-bit SVR4 ABI Stack Frame Layout: 3397 // +-----------------------------------+ 3398 // +--> | Back chain | 3399 // | +-----------------------------------+ 3400 // | | Floating-point register save area | 3401 // | +-----------------------------------+ 3402 // | | General register save area | 3403 // | +-----------------------------------+ 3404 // | | CR save word | 3405 // | +-----------------------------------+ 3406 // | | VRSAVE save word | 3407 // | +-----------------------------------+ 3408 // | | Alignment padding | 3409 // | +-----------------------------------+ 3410 // | | Vector register save area | 3411 // | +-----------------------------------+ 3412 // | | Local variable space | 3413 // | +-----------------------------------+ 3414 // | | Parameter list area | 3415 // | +-----------------------------------+ 3416 // | | LR save word | 3417 // | +-----------------------------------+ 3418 // SP--> +--- | Back chain | 3419 // +-----------------------------------+ 3420 // 3421 // Specifications: 3422 // System V Application Binary Interface PowerPC Processor Supplement 3423 // AltiVec Technology Programming Interface Manual 3424 3425 MachineFunction &MF = DAG.getMachineFunction(); 3426 MachineFrameInfo &MFI = MF.getFrameInfo(); 3427 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3428 3429 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3430 // Potential tail calls could cause overwriting of argument stack slots. 3431 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3432 (CallConv == CallingConv::Fast)); 3433 unsigned PtrByteSize = 4; 3434 3435 // Assign locations to all of the incoming arguments. 3436 SmallVector<CCValAssign, 16> ArgLocs; 3437 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3438 *DAG.getContext()); 3439 3440 // Reserve space for the linkage area on the stack. 3441 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3442 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3443 if (useSoftFloat() || hasSPE()) 3444 CCInfo.PreAnalyzeFormalArguments(Ins); 3445 3446 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3447 CCInfo.clearWasPPCF128(); 3448 3449 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3450 CCValAssign &VA = ArgLocs[i]; 3451 3452 // Arguments stored in registers. 3453 if (VA.isRegLoc()) { 3454 const TargetRegisterClass *RC; 3455 EVT ValVT = VA.getValVT(); 3456 3457 switch (ValVT.getSimpleVT().SimpleTy) { 3458 default: 3459 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3460 case MVT::i1: 3461 case MVT::i32: 3462 RC = &PPC::GPRCRegClass; 3463 break; 3464 case MVT::f32: 3465 if (Subtarget.hasP8Vector()) 3466 RC = &PPC::VSSRCRegClass; 3467 else if (Subtarget.hasSPE()) 3468 RC = &PPC::SPE4RCRegClass; 3469 else 3470 RC = &PPC::F4RCRegClass; 3471 break; 3472 case MVT::f64: 3473 if (Subtarget.hasVSX()) 3474 RC = &PPC::VSFRCRegClass; 3475 else if (Subtarget.hasSPE()) 3476 RC = &PPC::SPERCRegClass; 3477 else 3478 RC = &PPC::F8RCRegClass; 3479 break; 3480 case MVT::v16i8: 3481 case MVT::v8i16: 3482 case MVT::v4i32: 3483 RC = &PPC::VRRCRegClass; 3484 break; 3485 case MVT::v4f32: 3486 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3487 break; 3488 case MVT::v2f64: 3489 case MVT::v2i64: 3490 RC = &PPC::VRRCRegClass; 3491 break; 3492 case MVT::v4f64: 3493 RC = &PPC::QFRCRegClass; 3494 break; 3495 case MVT::v4i1: 3496 RC = &PPC::QBRCRegClass; 3497 break; 3498 } 3499 3500 // Transform the arguments stored in physical registers into virtual ones. 3501 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3502 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3503 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3504 3505 if (ValVT == MVT::i1) 3506 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3507 3508 InVals.push_back(ArgValue); 3509 } else { 3510 // Argument stored in memory. 3511 assert(VA.isMemLoc()); 3512 3513 // Get the extended size of the argument type in stack 3514 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3515 // Get the actual size of the argument type 3516 unsigned ObjSize = VA.getValVT().getStoreSize(); 3517 unsigned ArgOffset = VA.getLocMemOffset(); 3518 // Stack objects in PPC32 are right justified. 3519 ArgOffset += ArgSize - ObjSize; 3520 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3521 3522 // Create load nodes to retrieve arguments from the stack. 3523 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3524 InVals.push_back( 3525 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3526 } 3527 } 3528 3529 // Assign locations to all of the incoming aggregate by value arguments. 3530 // Aggregates passed by value are stored in the local variable space of the 3531 // caller's stack frame, right above the parameter list area. 3532 SmallVector<CCValAssign, 16> ByValArgLocs; 3533 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3534 ByValArgLocs, *DAG.getContext()); 3535 3536 // Reserve stack space for the allocations in CCInfo. 3537 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3538 3539 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3540 3541 // Area that is at least reserved in the caller of this function. 3542 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3543 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3544 3545 // Set the size that is at least reserved in caller of this function. Tail 3546 // call optimized function's reserved stack space needs to be aligned so that 3547 // taking the difference between two stack areas will result in an aligned 3548 // stack. 3549 MinReservedArea = 3550 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3551 FuncInfo->setMinReservedArea(MinReservedArea); 3552 3553 SmallVector<SDValue, 8> MemOps; 3554 3555 // If the function takes variable number of arguments, make a frame index for 3556 // the start of the first vararg value... for expansion of llvm.va_start. 3557 if (isVarArg) { 3558 static const MCPhysReg GPArgRegs[] = { 3559 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3560 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3561 }; 3562 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3563 3564 static const MCPhysReg FPArgRegs[] = { 3565 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3566 PPC::F8 3567 }; 3568 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3569 3570 if (useSoftFloat() || hasSPE()) 3571 NumFPArgRegs = 0; 3572 3573 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3574 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3575 3576 // Make room for NumGPArgRegs and NumFPArgRegs. 3577 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3578 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3579 3580 FuncInfo->setVarArgsStackOffset( 3581 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3582 CCInfo.getNextStackOffset(), true)); 3583 3584 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3585 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3586 3587 // The fixed integer arguments of a variadic function are stored to the 3588 // VarArgsFrameIndex on the stack so that they may be loaded by 3589 // dereferencing the result of va_next. 3590 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3591 // Get an existing live-in vreg, or add a new one. 3592 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3593 if (!VReg) 3594 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3595 3596 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3597 SDValue Store = 3598 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3599 MemOps.push_back(Store); 3600 // Increment the address by four for the next argument to store 3601 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3602 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3603 } 3604 3605 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3606 // is set. 3607 // The double arguments are stored to the VarArgsFrameIndex 3608 // on the stack. 3609 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3610 // Get an existing live-in vreg, or add a new one. 3611 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3612 if (!VReg) 3613 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3614 3615 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3616 SDValue Store = 3617 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3618 MemOps.push_back(Store); 3619 // Increment the address by eight for the next argument to store 3620 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3621 PtrVT); 3622 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3623 } 3624 } 3625 3626 if (!MemOps.empty()) 3627 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3628 3629 return Chain; 3630 } 3631 3632 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3633 // value to MVT::i64 and then truncate to the correct register size. 3634 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3635 EVT ObjectVT, SelectionDAG &DAG, 3636 SDValue ArgVal, 3637 const SDLoc &dl) const { 3638 if (Flags.isSExt()) 3639 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3640 DAG.getValueType(ObjectVT)); 3641 else if (Flags.isZExt()) 3642 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3643 DAG.getValueType(ObjectVT)); 3644 3645 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3646 } 3647 3648 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3649 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3650 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3651 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3652 // TODO: add description of PPC stack frame format, or at least some docs. 3653 // 3654 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3655 bool isLittleEndian = Subtarget.isLittleEndian(); 3656 MachineFunction &MF = DAG.getMachineFunction(); 3657 MachineFrameInfo &MFI = MF.getFrameInfo(); 3658 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3659 3660 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3661 "fastcc not supported on varargs functions"); 3662 3663 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3664 // Potential tail calls could cause overwriting of argument stack slots. 3665 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3666 (CallConv == CallingConv::Fast)); 3667 unsigned PtrByteSize = 8; 3668 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3669 3670 static const MCPhysReg GPR[] = { 3671 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3672 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3673 }; 3674 static const MCPhysReg VR[] = { 3675 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3676 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3677 }; 3678 3679 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3680 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3681 const unsigned Num_VR_Regs = array_lengthof(VR); 3682 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3683 3684 // Do a first pass over the arguments to determine whether the ABI 3685 // guarantees that our caller has allocated the parameter save area 3686 // on its stack frame. In the ELFv1 ABI, this is always the case; 3687 // in the ELFv2 ABI, it is true if this is a vararg function or if 3688 // any parameter is located in a stack slot. 3689 3690 bool HasParameterArea = !isELFv2ABI || isVarArg; 3691 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3692 unsigned NumBytes = LinkageSize; 3693 unsigned AvailableFPRs = Num_FPR_Regs; 3694 unsigned AvailableVRs = Num_VR_Regs; 3695 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3696 if (Ins[i].Flags.isNest()) 3697 continue; 3698 3699 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3700 PtrByteSize, LinkageSize, ParamAreaSize, 3701 NumBytes, AvailableFPRs, AvailableVRs, 3702 Subtarget.hasQPX())) 3703 HasParameterArea = true; 3704 } 3705 3706 // Add DAG nodes to load the arguments or copy them out of registers. On 3707 // entry to a function on PPC, the arguments start after the linkage area, 3708 // although the first ones are often in registers. 3709 3710 unsigned ArgOffset = LinkageSize; 3711 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3712 unsigned &QFPR_idx = FPR_idx; 3713 SmallVector<SDValue, 8> MemOps; 3714 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3715 unsigned CurArgIdx = 0; 3716 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3717 SDValue ArgVal; 3718 bool needsLoad = false; 3719 EVT ObjectVT = Ins[ArgNo].VT; 3720 EVT OrigVT = Ins[ArgNo].ArgVT; 3721 unsigned ObjSize = ObjectVT.getStoreSize(); 3722 unsigned ArgSize = ObjSize; 3723 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3724 if (Ins[ArgNo].isOrigArg()) { 3725 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3726 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3727 } 3728 // We re-align the argument offset for each argument, except when using the 3729 // fast calling convention, when we need to make sure we do that only when 3730 // we'll actually use a stack slot. 3731 unsigned CurArgOffset, Align; 3732 auto ComputeArgOffset = [&]() { 3733 /* Respect alignment of argument on the stack. */ 3734 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3735 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3736 CurArgOffset = ArgOffset; 3737 }; 3738 3739 if (CallConv != CallingConv::Fast) { 3740 ComputeArgOffset(); 3741 3742 /* Compute GPR index associated with argument offset. */ 3743 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3744 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3745 } 3746 3747 // FIXME the codegen can be much improved in some cases. 3748 // We do not have to keep everything in memory. 3749 if (Flags.isByVal()) { 3750 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3751 3752 if (CallConv == CallingConv::Fast) 3753 ComputeArgOffset(); 3754 3755 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3756 ObjSize = Flags.getByValSize(); 3757 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3758 // Empty aggregate parameters do not take up registers. Examples: 3759 // struct { } a; 3760 // union { } b; 3761 // int c[0]; 3762 // etc. However, we have to provide a place-holder in InVals, so 3763 // pretend we have an 8-byte item at the current address for that 3764 // purpose. 3765 if (!ObjSize) { 3766 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3767 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3768 InVals.push_back(FIN); 3769 continue; 3770 } 3771 3772 // Create a stack object covering all stack doublewords occupied 3773 // by the argument. If the argument is (fully or partially) on 3774 // the stack, or if the argument is fully in registers but the 3775 // caller has allocated the parameter save anyway, we can refer 3776 // directly to the caller's stack frame. Otherwise, create a 3777 // local copy in our own frame. 3778 int FI; 3779 if (HasParameterArea || 3780 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3781 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3782 else 3783 FI = MFI.CreateStackObject(ArgSize, Align, false); 3784 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3785 3786 // Handle aggregates smaller than 8 bytes. 3787 if (ObjSize < PtrByteSize) { 3788 // The value of the object is its address, which differs from the 3789 // address of the enclosing doubleword on big-endian systems. 3790 SDValue Arg = FIN; 3791 if (!isLittleEndian) { 3792 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3793 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3794 } 3795 InVals.push_back(Arg); 3796 3797 if (GPR_idx != Num_GPR_Regs) { 3798 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3799 FuncInfo->addLiveInAttr(VReg, Flags); 3800 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3801 SDValue Store; 3802 3803 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3804 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3805 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3806 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3807 MachinePointerInfo(&*FuncArg), ObjType); 3808 } else { 3809 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3810 // store the whole register as-is to the parameter save area 3811 // slot. 3812 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3813 MachinePointerInfo(&*FuncArg)); 3814 } 3815 3816 MemOps.push_back(Store); 3817 } 3818 // Whether we copied from a register or not, advance the offset 3819 // into the parameter save area by a full doubleword. 3820 ArgOffset += PtrByteSize; 3821 continue; 3822 } 3823 3824 // The value of the object is its address, which is the address of 3825 // its first stack doubleword. 3826 InVals.push_back(FIN); 3827 3828 // Store whatever pieces of the object are in registers to memory. 3829 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3830 if (GPR_idx == Num_GPR_Regs) 3831 break; 3832 3833 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3834 FuncInfo->addLiveInAttr(VReg, Flags); 3835 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3836 SDValue Addr = FIN; 3837 if (j) { 3838 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3839 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3840 } 3841 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3842 MachinePointerInfo(&*FuncArg, j)); 3843 MemOps.push_back(Store); 3844 ++GPR_idx; 3845 } 3846 ArgOffset += ArgSize; 3847 continue; 3848 } 3849 3850 switch (ObjectVT.getSimpleVT().SimpleTy) { 3851 default: llvm_unreachable("Unhandled argument type!"); 3852 case MVT::i1: 3853 case MVT::i32: 3854 case MVT::i64: 3855 if (Flags.isNest()) { 3856 // The 'nest' parameter, if any, is passed in R11. 3857 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3858 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3859 3860 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3861 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3862 3863 break; 3864 } 3865 3866 // These can be scalar arguments or elements of an integer array type 3867 // passed directly. Clang may use those instead of "byval" aggregate 3868 // types to avoid forcing arguments to memory unnecessarily. 3869 if (GPR_idx != Num_GPR_Regs) { 3870 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3871 FuncInfo->addLiveInAttr(VReg, Flags); 3872 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3873 3874 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3875 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3876 // value to MVT::i64 and then truncate to the correct register size. 3877 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3878 } else { 3879 if (CallConv == CallingConv::Fast) 3880 ComputeArgOffset(); 3881 3882 needsLoad = true; 3883 ArgSize = PtrByteSize; 3884 } 3885 if (CallConv != CallingConv::Fast || needsLoad) 3886 ArgOffset += 8; 3887 break; 3888 3889 case MVT::f32: 3890 case MVT::f64: 3891 // These can be scalar arguments or elements of a float array type 3892 // passed directly. The latter are used to implement ELFv2 homogenous 3893 // float aggregates. 3894 if (FPR_idx != Num_FPR_Regs) { 3895 unsigned VReg; 3896 3897 if (ObjectVT == MVT::f32) 3898 VReg = MF.addLiveIn(FPR[FPR_idx], 3899 Subtarget.hasP8Vector() 3900 ? &PPC::VSSRCRegClass 3901 : &PPC::F4RCRegClass); 3902 else 3903 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3904 ? &PPC::VSFRCRegClass 3905 : &PPC::F8RCRegClass); 3906 3907 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3908 ++FPR_idx; 3909 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3910 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3911 // once we support fp <-> gpr moves. 3912 3913 // This can only ever happen in the presence of f32 array types, 3914 // since otherwise we never run out of FPRs before running out 3915 // of GPRs. 3916 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3917 FuncInfo->addLiveInAttr(VReg, Flags); 3918 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3919 3920 if (ObjectVT == MVT::f32) { 3921 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3922 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3923 DAG.getConstant(32, dl, MVT::i32)); 3924 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3925 } 3926 3927 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3928 } else { 3929 if (CallConv == CallingConv::Fast) 3930 ComputeArgOffset(); 3931 3932 needsLoad = true; 3933 } 3934 3935 // When passing an array of floats, the array occupies consecutive 3936 // space in the argument area; only round up to the next doubleword 3937 // at the end of the array. Otherwise, each float takes 8 bytes. 3938 if (CallConv != CallingConv::Fast || needsLoad) { 3939 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3940 ArgOffset += ArgSize; 3941 if (Flags.isInConsecutiveRegsLast()) 3942 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3943 } 3944 break; 3945 case MVT::v4f32: 3946 case MVT::v4i32: 3947 case MVT::v8i16: 3948 case MVT::v16i8: 3949 case MVT::v2f64: 3950 case MVT::v2i64: 3951 case MVT::v1i128: 3952 case MVT::f128: 3953 if (!Subtarget.hasQPX()) { 3954 // These can be scalar arguments or elements of a vector array type 3955 // passed directly. The latter are used to implement ELFv2 homogenous 3956 // vector aggregates. 3957 if (VR_idx != Num_VR_Regs) { 3958 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3959 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3960 ++VR_idx; 3961 } else { 3962 if (CallConv == CallingConv::Fast) 3963 ComputeArgOffset(); 3964 needsLoad = true; 3965 } 3966 if (CallConv != CallingConv::Fast || needsLoad) 3967 ArgOffset += 16; 3968 break; 3969 } // not QPX 3970 3971 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3972 "Invalid QPX parameter type"); 3973 LLVM_FALLTHROUGH; 3974 3975 case MVT::v4f64: 3976 case MVT::v4i1: 3977 // QPX vectors are treated like their scalar floating-point subregisters 3978 // (except that they're larger). 3979 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3980 if (QFPR_idx != Num_QFPR_Regs) { 3981 const TargetRegisterClass *RC; 3982 switch (ObjectVT.getSimpleVT().SimpleTy) { 3983 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3984 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3985 default: RC = &PPC::QBRCRegClass; break; 3986 } 3987 3988 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3989 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3990 ++QFPR_idx; 3991 } else { 3992 if (CallConv == CallingConv::Fast) 3993 ComputeArgOffset(); 3994 needsLoad = true; 3995 } 3996 if (CallConv != CallingConv::Fast || needsLoad) 3997 ArgOffset += Sz; 3998 break; 3999 } 4000 4001 // We need to load the argument to a virtual register if we determined 4002 // above that we ran out of physical registers of the appropriate type. 4003 if (needsLoad) { 4004 if (ObjSize < ArgSize && !isLittleEndian) 4005 CurArgOffset += ArgSize - ObjSize; 4006 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4007 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4008 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4009 } 4010 4011 InVals.push_back(ArgVal); 4012 } 4013 4014 // Area that is at least reserved in the caller of this function. 4015 unsigned MinReservedArea; 4016 if (HasParameterArea) 4017 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4018 else 4019 MinReservedArea = LinkageSize; 4020 4021 // Set the size that is at least reserved in caller of this function. Tail 4022 // call optimized functions' reserved stack space needs to be aligned so that 4023 // taking the difference between two stack areas will result in an aligned 4024 // stack. 4025 MinReservedArea = 4026 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4027 FuncInfo->setMinReservedArea(MinReservedArea); 4028 4029 // If the function takes variable number of arguments, make a frame index for 4030 // the start of the first vararg value... for expansion of llvm.va_start. 4031 if (isVarArg) { 4032 int Depth = ArgOffset; 4033 4034 FuncInfo->setVarArgsFrameIndex( 4035 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4036 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4037 4038 // If this function is vararg, store any remaining integer argument regs 4039 // to their spots on the stack so that they may be loaded by dereferencing 4040 // the result of va_next. 4041 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4042 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4043 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4044 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4045 SDValue Store = 4046 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4047 MemOps.push_back(Store); 4048 // Increment the address by four for the next argument to store 4049 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4050 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4051 } 4052 } 4053 4054 if (!MemOps.empty()) 4055 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4056 4057 return Chain; 4058 } 4059 4060 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4061 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4062 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4063 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4064 // TODO: add description of PPC stack frame format, or at least some docs. 4065 // 4066 MachineFunction &MF = DAG.getMachineFunction(); 4067 MachineFrameInfo &MFI = MF.getFrameInfo(); 4068 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4069 4070 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4071 bool isPPC64 = PtrVT == MVT::i64; 4072 // Potential tail calls could cause overwriting of argument stack slots. 4073 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4074 (CallConv == CallingConv::Fast)); 4075 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4076 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4077 unsigned ArgOffset = LinkageSize; 4078 // Area that is at least reserved in caller of this function. 4079 unsigned MinReservedArea = ArgOffset; 4080 4081 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4082 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4083 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4084 }; 4085 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4086 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4087 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4088 }; 4089 static const MCPhysReg VR[] = { 4090 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4091 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4092 }; 4093 4094 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4095 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4096 const unsigned Num_VR_Regs = array_lengthof( VR); 4097 4098 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4099 4100 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4101 4102 // In 32-bit non-varargs functions, the stack space for vectors is after the 4103 // stack space for non-vectors. We do not use this space unless we have 4104 // too many vectors to fit in registers, something that only occurs in 4105 // constructed examples:), but we have to walk the arglist to figure 4106 // that out...for the pathological case, compute VecArgOffset as the 4107 // start of the vector parameter area. Computing VecArgOffset is the 4108 // entire point of the following loop. 4109 unsigned VecArgOffset = ArgOffset; 4110 if (!isVarArg && !isPPC64) { 4111 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4112 ++ArgNo) { 4113 EVT ObjectVT = Ins[ArgNo].VT; 4114 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4115 4116 if (Flags.isByVal()) { 4117 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4118 unsigned ObjSize = Flags.getByValSize(); 4119 unsigned ArgSize = 4120 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4121 VecArgOffset += ArgSize; 4122 continue; 4123 } 4124 4125 switch(ObjectVT.getSimpleVT().SimpleTy) { 4126 default: llvm_unreachable("Unhandled argument type!"); 4127 case MVT::i1: 4128 case MVT::i32: 4129 case MVT::f32: 4130 VecArgOffset += 4; 4131 break; 4132 case MVT::i64: // PPC64 4133 case MVT::f64: 4134 // FIXME: We are guaranteed to be !isPPC64 at this point. 4135 // Does MVT::i64 apply? 4136 VecArgOffset += 8; 4137 break; 4138 case MVT::v4f32: 4139 case MVT::v4i32: 4140 case MVT::v8i16: 4141 case MVT::v16i8: 4142 // Nothing to do, we're only looking at Nonvector args here. 4143 break; 4144 } 4145 } 4146 } 4147 // We've found where the vector parameter area in memory is. Skip the 4148 // first 12 parameters; these don't use that memory. 4149 VecArgOffset = ((VecArgOffset+15)/16)*16; 4150 VecArgOffset += 12*16; 4151 4152 // Add DAG nodes to load the arguments or copy them out of registers. On 4153 // entry to a function on PPC, the arguments start after the linkage area, 4154 // although the first ones are often in registers. 4155 4156 SmallVector<SDValue, 8> MemOps; 4157 unsigned nAltivecParamsAtEnd = 0; 4158 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4159 unsigned CurArgIdx = 0; 4160 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4161 SDValue ArgVal; 4162 bool needsLoad = false; 4163 EVT ObjectVT = Ins[ArgNo].VT; 4164 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4165 unsigned ArgSize = ObjSize; 4166 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4167 if (Ins[ArgNo].isOrigArg()) { 4168 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4169 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4170 } 4171 unsigned CurArgOffset = ArgOffset; 4172 4173 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4174 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4175 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4176 if (isVarArg || isPPC64) { 4177 MinReservedArea = ((MinReservedArea+15)/16)*16; 4178 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4179 Flags, 4180 PtrByteSize); 4181 } else nAltivecParamsAtEnd++; 4182 } else 4183 // Calculate min reserved area. 4184 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4185 Flags, 4186 PtrByteSize); 4187 4188 // FIXME the codegen can be much improved in some cases. 4189 // We do not have to keep everything in memory. 4190 if (Flags.isByVal()) { 4191 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4192 4193 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4194 ObjSize = Flags.getByValSize(); 4195 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4196 // Objects of size 1 and 2 are right justified, everything else is 4197 // left justified. This means the memory address is adjusted forwards. 4198 if (ObjSize==1 || ObjSize==2) { 4199 CurArgOffset = CurArgOffset + (4 - ObjSize); 4200 } 4201 // The value of the object is its address. 4202 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4203 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4204 InVals.push_back(FIN); 4205 if (ObjSize==1 || ObjSize==2) { 4206 if (GPR_idx != Num_GPR_Regs) { 4207 unsigned VReg; 4208 if (isPPC64) 4209 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4210 else 4211 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4212 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4213 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4214 SDValue Store = 4215 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4216 MachinePointerInfo(&*FuncArg), ObjType); 4217 MemOps.push_back(Store); 4218 ++GPR_idx; 4219 } 4220 4221 ArgOffset += PtrByteSize; 4222 4223 continue; 4224 } 4225 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4226 // Store whatever pieces of the object are in registers 4227 // to memory. ArgOffset will be the address of the beginning 4228 // of the object. 4229 if (GPR_idx != Num_GPR_Regs) { 4230 unsigned VReg; 4231 if (isPPC64) 4232 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4233 else 4234 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4235 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4236 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4237 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4238 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4239 MachinePointerInfo(&*FuncArg, j)); 4240 MemOps.push_back(Store); 4241 ++GPR_idx; 4242 ArgOffset += PtrByteSize; 4243 } else { 4244 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4245 break; 4246 } 4247 } 4248 continue; 4249 } 4250 4251 switch (ObjectVT.getSimpleVT().SimpleTy) { 4252 default: llvm_unreachable("Unhandled argument type!"); 4253 case MVT::i1: 4254 case MVT::i32: 4255 if (!isPPC64) { 4256 if (GPR_idx != Num_GPR_Regs) { 4257 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4258 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4259 4260 if (ObjectVT == MVT::i1) 4261 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4262 4263 ++GPR_idx; 4264 } else { 4265 needsLoad = true; 4266 ArgSize = PtrByteSize; 4267 } 4268 // All int arguments reserve stack space in the Darwin ABI. 4269 ArgOffset += PtrByteSize; 4270 break; 4271 } 4272 LLVM_FALLTHROUGH; 4273 case MVT::i64: // PPC64 4274 if (GPR_idx != Num_GPR_Regs) { 4275 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4276 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4277 4278 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4279 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4280 // value to MVT::i64 and then truncate to the correct register size. 4281 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4282 4283 ++GPR_idx; 4284 } else { 4285 needsLoad = true; 4286 ArgSize = PtrByteSize; 4287 } 4288 // All int arguments reserve stack space in the Darwin ABI. 4289 ArgOffset += 8; 4290 break; 4291 4292 case MVT::f32: 4293 case MVT::f64: 4294 // Every 4 bytes of argument space consumes one of the GPRs available for 4295 // argument passing. 4296 if (GPR_idx != Num_GPR_Regs) { 4297 ++GPR_idx; 4298 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4299 ++GPR_idx; 4300 } 4301 if (FPR_idx != Num_FPR_Regs) { 4302 unsigned VReg; 4303 4304 if (ObjectVT == MVT::f32) 4305 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4306 else 4307 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4308 4309 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4310 ++FPR_idx; 4311 } else { 4312 needsLoad = true; 4313 } 4314 4315 // All FP arguments reserve stack space in the Darwin ABI. 4316 ArgOffset += isPPC64 ? 8 : ObjSize; 4317 break; 4318 case MVT::v4f32: 4319 case MVT::v4i32: 4320 case MVT::v8i16: 4321 case MVT::v16i8: 4322 // Note that vector arguments in registers don't reserve stack space, 4323 // except in varargs functions. 4324 if (VR_idx != Num_VR_Regs) { 4325 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4326 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4327 if (isVarArg) { 4328 while ((ArgOffset % 16) != 0) { 4329 ArgOffset += PtrByteSize; 4330 if (GPR_idx != Num_GPR_Regs) 4331 GPR_idx++; 4332 } 4333 ArgOffset += 16; 4334 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4335 } 4336 ++VR_idx; 4337 } else { 4338 if (!isVarArg && !isPPC64) { 4339 // Vectors go after all the nonvectors. 4340 CurArgOffset = VecArgOffset; 4341 VecArgOffset += 16; 4342 } else { 4343 // Vectors are aligned. 4344 ArgOffset = ((ArgOffset+15)/16)*16; 4345 CurArgOffset = ArgOffset; 4346 ArgOffset += 16; 4347 } 4348 needsLoad = true; 4349 } 4350 break; 4351 } 4352 4353 // We need to load the argument to a virtual register if we determined above 4354 // that we ran out of physical registers of the appropriate type. 4355 if (needsLoad) { 4356 int FI = MFI.CreateFixedObject(ObjSize, 4357 CurArgOffset + (ArgSize - ObjSize), 4358 isImmutable); 4359 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4360 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4361 } 4362 4363 InVals.push_back(ArgVal); 4364 } 4365 4366 // Allow for Altivec parameters at the end, if needed. 4367 if (nAltivecParamsAtEnd) { 4368 MinReservedArea = ((MinReservedArea+15)/16)*16; 4369 MinReservedArea += 16*nAltivecParamsAtEnd; 4370 } 4371 4372 // Area that is at least reserved in the caller of this function. 4373 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4374 4375 // Set the size that is at least reserved in caller of this function. Tail 4376 // call optimized functions' reserved stack space needs to be aligned so that 4377 // taking the difference between two stack areas will result in an aligned 4378 // stack. 4379 MinReservedArea = 4380 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4381 FuncInfo->setMinReservedArea(MinReservedArea); 4382 4383 // If the function takes variable number of arguments, make a frame index for 4384 // the start of the first vararg value... for expansion of llvm.va_start. 4385 if (isVarArg) { 4386 int Depth = ArgOffset; 4387 4388 FuncInfo->setVarArgsFrameIndex( 4389 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4390 Depth, true)); 4391 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4392 4393 // If this function is vararg, store any remaining integer argument regs 4394 // to their spots on the stack so that they may be loaded by dereferencing 4395 // the result of va_next. 4396 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4397 unsigned VReg; 4398 4399 if (isPPC64) 4400 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4401 else 4402 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4403 4404 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4405 SDValue Store = 4406 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4407 MemOps.push_back(Store); 4408 // Increment the address by four for the next argument to store 4409 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4410 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4411 } 4412 } 4413 4414 if (!MemOps.empty()) 4415 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4416 4417 return Chain; 4418 } 4419 4420 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4421 /// adjusted to accommodate the arguments for the tailcall. 4422 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4423 unsigned ParamSize) { 4424 4425 if (!isTailCall) return 0; 4426 4427 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4428 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4429 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4430 // Remember only if the new adjustment is bigger. 4431 if (SPDiff < FI->getTailCallSPDelta()) 4432 FI->setTailCallSPDelta(SPDiff); 4433 4434 return SPDiff; 4435 } 4436 4437 static bool isFunctionGlobalAddress(SDValue Callee); 4438 4439 static bool 4440 callsShareTOCBase(const Function *Caller, SDValue Callee, 4441 const TargetMachine &TM) { 4442 // If !G, Callee can be an external symbol. 4443 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4444 if (!G) 4445 return false; 4446 4447 // The medium and large code models are expected to provide a sufficiently 4448 // large TOC to provide all data addressing needs of a module with a 4449 // single TOC. Since each module will be addressed with a single TOC then we 4450 // only need to check that caller and callee don't cross dso boundaries. 4451 if (CodeModel::Medium == TM.getCodeModel() || 4452 CodeModel::Large == TM.getCodeModel()) 4453 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal()); 4454 4455 // Otherwise we need to ensure callee and caller are in the same section, 4456 // since the linker may allocate multiple TOCs, and we don't know which 4457 // sections will belong to the same TOC base. 4458 4459 const GlobalValue *GV = G->getGlobal(); 4460 if (!GV->isStrongDefinitionForLinker()) 4461 return false; 4462 4463 // Any explicitly-specified sections and section prefixes must also match. 4464 // Also, if we're using -ffunction-sections, then each function is always in 4465 // a different section (the same is true for COMDAT functions). 4466 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4467 GV->getSection() != Caller->getSection()) 4468 return false; 4469 if (const auto *F = dyn_cast<Function>(GV)) { 4470 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4471 return false; 4472 } 4473 4474 // If the callee might be interposed, then we can't assume the ultimate call 4475 // target will be in the same section. Even in cases where we can assume that 4476 // interposition won't happen, in any case where the linker might insert a 4477 // stub to allow for interposition, we must generate code as though 4478 // interposition might occur. To understand why this matters, consider a 4479 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4480 // in the same section, but a is in a different module (i.e. has a different 4481 // TOC base pointer). If the linker allows for interposition between b and c, 4482 // then it will generate a stub for the call edge between b and c which will 4483 // save the TOC pointer into the designated stack slot allocated by b. If we 4484 // return true here, and therefore allow a tail call between b and c, that 4485 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4486 // pointer into the stack slot allocated by a (where the a -> b stub saved 4487 // a's TOC base pointer). If we're not considering a tail call, but rather, 4488 // whether a nop is needed after the call instruction in b, because the linker 4489 // will insert a stub, it might complain about a missing nop if we omit it 4490 // (although many don't complain in this case). 4491 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4492 return false; 4493 4494 return true; 4495 } 4496 4497 static bool 4498 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4499 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4500 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4501 4502 const unsigned PtrByteSize = 8; 4503 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4504 4505 static const MCPhysReg GPR[] = { 4506 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4507 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4508 }; 4509 static const MCPhysReg VR[] = { 4510 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4511 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4512 }; 4513 4514 const unsigned NumGPRs = array_lengthof(GPR); 4515 const unsigned NumFPRs = 13; 4516 const unsigned NumVRs = array_lengthof(VR); 4517 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4518 4519 unsigned NumBytes = LinkageSize; 4520 unsigned AvailableFPRs = NumFPRs; 4521 unsigned AvailableVRs = NumVRs; 4522 4523 for (const ISD::OutputArg& Param : Outs) { 4524 if (Param.Flags.isNest()) continue; 4525 4526 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4527 PtrByteSize, LinkageSize, ParamAreaSize, 4528 NumBytes, AvailableFPRs, AvailableVRs, 4529 Subtarget.hasQPX())) 4530 return true; 4531 } 4532 return false; 4533 } 4534 4535 static bool 4536 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4537 if (CS.arg_size() != CallerFn->arg_size()) 4538 return false; 4539 4540 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4541 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4542 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4543 4544 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4545 const Value* CalleeArg = *CalleeArgIter; 4546 const Value* CallerArg = &(*CallerArgIter); 4547 if (CalleeArg == CallerArg) 4548 continue; 4549 4550 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4551 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4552 // } 4553 // 1st argument of callee is undef and has the same type as caller. 4554 if (CalleeArg->getType() == CallerArg->getType() && 4555 isa<UndefValue>(CalleeArg)) 4556 continue; 4557 4558 return false; 4559 } 4560 4561 return true; 4562 } 4563 4564 // Returns true if TCO is possible between the callers and callees 4565 // calling conventions. 4566 static bool 4567 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4568 CallingConv::ID CalleeCC) { 4569 // Tail calls are possible with fastcc and ccc. 4570 auto isTailCallableCC = [] (CallingConv::ID CC){ 4571 return CC == CallingConv::C || CC == CallingConv::Fast; 4572 }; 4573 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4574 return false; 4575 4576 // We can safely tail call both fastcc and ccc callees from a c calling 4577 // convention caller. If the caller is fastcc, we may have less stack space 4578 // than a non-fastcc caller with the same signature so disable tail-calls in 4579 // that case. 4580 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4581 } 4582 4583 bool 4584 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4585 SDValue Callee, 4586 CallingConv::ID CalleeCC, 4587 ImmutableCallSite CS, 4588 bool isVarArg, 4589 const SmallVectorImpl<ISD::OutputArg> &Outs, 4590 const SmallVectorImpl<ISD::InputArg> &Ins, 4591 SelectionDAG& DAG) const { 4592 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4593 4594 if (DisableSCO && !TailCallOpt) return false; 4595 4596 // Variadic argument functions are not supported. 4597 if (isVarArg) return false; 4598 4599 auto &Caller = DAG.getMachineFunction().getFunction(); 4600 // Check that the calling conventions are compatible for tco. 4601 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4602 return false; 4603 4604 // Caller contains any byval parameter is not supported. 4605 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4606 return false; 4607 4608 // Callee contains any byval parameter is not supported, too. 4609 // Note: This is a quick work around, because in some cases, e.g. 4610 // caller's stack size > callee's stack size, we are still able to apply 4611 // sibling call optimization. For example, gcc is able to do SCO for caller1 4612 // in the following example, but not for caller2. 4613 // struct test { 4614 // long int a; 4615 // char ary[56]; 4616 // } gTest; 4617 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4618 // b->a = v.a; 4619 // return 0; 4620 // } 4621 // void caller1(struct test a, struct test c, struct test *b) { 4622 // callee(gTest, b); } 4623 // void caller2(struct test *b) { callee(gTest, b); } 4624 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4625 return false; 4626 4627 // If callee and caller use different calling conventions, we cannot pass 4628 // parameters on stack since offsets for the parameter area may be different. 4629 if (Caller.getCallingConv() != CalleeCC && 4630 needStackSlotPassParameters(Subtarget, Outs)) 4631 return false; 4632 4633 // No TCO/SCO on indirect call because Caller have to restore its TOC 4634 if (!isFunctionGlobalAddress(Callee) && 4635 !isa<ExternalSymbolSDNode>(Callee)) 4636 return false; 4637 4638 // If the caller and callee potentially have different TOC bases then we 4639 // cannot tail call since we need to restore the TOC pointer after the call. 4640 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4641 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4642 return false; 4643 4644 // TCO allows altering callee ABI, so we don't have to check further. 4645 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4646 return true; 4647 4648 if (DisableSCO) return false; 4649 4650 // If callee use the same argument list that caller is using, then we can 4651 // apply SCO on this case. If it is not, then we need to check if callee needs 4652 // stack for passing arguments. 4653 if (!hasSameArgumentList(&Caller, CS) && 4654 needStackSlotPassParameters(Subtarget, Outs)) { 4655 return false; 4656 } 4657 4658 return true; 4659 } 4660 4661 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4662 /// for tail call optimization. Targets which want to do tail call 4663 /// optimization should implement this function. 4664 bool 4665 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4666 CallingConv::ID CalleeCC, 4667 bool isVarArg, 4668 const SmallVectorImpl<ISD::InputArg> &Ins, 4669 SelectionDAG& DAG) const { 4670 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4671 return false; 4672 4673 // Variable argument functions are not supported. 4674 if (isVarArg) 4675 return false; 4676 4677 MachineFunction &MF = DAG.getMachineFunction(); 4678 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4679 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4680 // Functions containing by val parameters are not supported. 4681 for (unsigned i = 0; i != Ins.size(); i++) { 4682 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4683 if (Flags.isByVal()) return false; 4684 } 4685 4686 // Non-PIC/GOT tail calls are supported. 4687 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4688 return true; 4689 4690 // At the moment we can only do local tail calls (in same module, hidden 4691 // or protected) if we are generating PIC. 4692 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4693 return G->getGlobal()->hasHiddenVisibility() 4694 || G->getGlobal()->hasProtectedVisibility(); 4695 } 4696 4697 return false; 4698 } 4699 4700 /// isCallCompatibleAddress - Return the immediate to use if the specified 4701 /// 32-bit value is representable in the immediate field of a BxA instruction. 4702 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4703 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4704 if (!C) return nullptr; 4705 4706 int Addr = C->getZExtValue(); 4707 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4708 SignExtend32<26>(Addr) != Addr) 4709 return nullptr; // Top 6 bits have to be sext of immediate. 4710 4711 return DAG 4712 .getConstant( 4713 (int)C->getZExtValue() >> 2, SDLoc(Op), 4714 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4715 .getNode(); 4716 } 4717 4718 namespace { 4719 4720 struct TailCallArgumentInfo { 4721 SDValue Arg; 4722 SDValue FrameIdxOp; 4723 int FrameIdx = 0; 4724 4725 TailCallArgumentInfo() = default; 4726 }; 4727 4728 } // end anonymous namespace 4729 4730 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4731 static void StoreTailCallArgumentsToStackSlot( 4732 SelectionDAG &DAG, SDValue Chain, 4733 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4734 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4735 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4736 SDValue Arg = TailCallArgs[i].Arg; 4737 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4738 int FI = TailCallArgs[i].FrameIdx; 4739 // Store relative to framepointer. 4740 MemOpChains.push_back(DAG.getStore( 4741 Chain, dl, Arg, FIN, 4742 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4743 } 4744 } 4745 4746 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4747 /// the appropriate stack slot for the tail call optimized function call. 4748 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4749 SDValue OldRetAddr, SDValue OldFP, 4750 int SPDiff, const SDLoc &dl) { 4751 if (SPDiff) { 4752 // Calculate the new stack slot for the return address. 4753 MachineFunction &MF = DAG.getMachineFunction(); 4754 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4755 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4756 bool isPPC64 = Subtarget.isPPC64(); 4757 int SlotSize = isPPC64 ? 8 : 4; 4758 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4759 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4760 NewRetAddrLoc, true); 4761 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4762 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4763 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4764 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4765 4766 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4767 // slot as the FP is never overwritten. 4768 if (Subtarget.isDarwinABI()) { 4769 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4770 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4771 true); 4772 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4773 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4774 MachinePointerInfo::getFixedStack( 4775 DAG.getMachineFunction(), NewFPIdx)); 4776 } 4777 } 4778 return Chain; 4779 } 4780 4781 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4782 /// the position of the argument. 4783 static void 4784 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4785 SDValue Arg, int SPDiff, unsigned ArgOffset, 4786 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4787 int Offset = ArgOffset + SPDiff; 4788 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4789 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4790 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4791 SDValue FIN = DAG.getFrameIndex(FI, VT); 4792 TailCallArgumentInfo Info; 4793 Info.Arg = Arg; 4794 Info.FrameIdxOp = FIN; 4795 Info.FrameIdx = FI; 4796 TailCallArguments.push_back(Info); 4797 } 4798 4799 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4800 /// stack slot. Returns the chain as result and the loaded frame pointers in 4801 /// LROpOut/FPOpout. Used when tail calling. 4802 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4803 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4804 SDValue &FPOpOut, const SDLoc &dl) const { 4805 if (SPDiff) { 4806 // Load the LR and FP stack slot for later adjusting. 4807 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4808 LROpOut = getReturnAddrFrameIndex(DAG); 4809 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4810 Chain = SDValue(LROpOut.getNode(), 1); 4811 4812 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4813 // slot as the FP is never overwritten. 4814 if (Subtarget.isDarwinABI()) { 4815 FPOpOut = getFramePointerFrameIndex(DAG); 4816 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4817 Chain = SDValue(FPOpOut.getNode(), 1); 4818 } 4819 } 4820 return Chain; 4821 } 4822 4823 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4824 /// by "Src" to address "Dst" of size "Size". Alignment information is 4825 /// specified by the specific parameter attribute. The copy will be passed as 4826 /// a byval function parameter. 4827 /// Sometimes what we are copying is the end of a larger object, the part that 4828 /// does not fit in registers. 4829 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4830 SDValue Chain, ISD::ArgFlagsTy Flags, 4831 SelectionDAG &DAG, const SDLoc &dl) { 4832 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4833 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4834 false, false, false, MachinePointerInfo(), 4835 MachinePointerInfo()); 4836 } 4837 4838 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4839 /// tail calls. 4840 static void LowerMemOpCallTo( 4841 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4842 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4843 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4844 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4845 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4846 if (!isTailCall) { 4847 if (isVector) { 4848 SDValue StackPtr; 4849 if (isPPC64) 4850 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4851 else 4852 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4853 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4854 DAG.getConstant(ArgOffset, dl, PtrVT)); 4855 } 4856 MemOpChains.push_back( 4857 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4858 // Calculate and remember argument location. 4859 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4860 TailCallArguments); 4861 } 4862 4863 static void 4864 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4865 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4866 SDValue FPOp, 4867 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4868 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4869 // might overwrite each other in case of tail call optimization. 4870 SmallVector<SDValue, 8> MemOpChains2; 4871 // Do not flag preceding copytoreg stuff together with the following stuff. 4872 InFlag = SDValue(); 4873 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4874 MemOpChains2, dl); 4875 if (!MemOpChains2.empty()) 4876 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4877 4878 // Store the return address to the appropriate stack slot. 4879 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4880 4881 // Emit callseq_end just before tailcall node. 4882 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4883 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4884 InFlag = Chain.getValue(1); 4885 } 4886 4887 // Is this global address that of a function that can be called by name? (as 4888 // opposed to something that must hold a descriptor for an indirect call). 4889 static bool isFunctionGlobalAddress(SDValue Callee) { 4890 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4891 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4892 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4893 return false; 4894 4895 return G->getGlobal()->getValueType()->isFunctionTy(); 4896 } 4897 4898 return false; 4899 } 4900 4901 static unsigned 4902 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4903 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4904 bool isPatchPoint, bool hasNest, 4905 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4906 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4907 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4908 bool isPPC64 = Subtarget.isPPC64(); 4909 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4910 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4911 4912 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4913 NodeTys.push_back(MVT::Other); // Returns a chain 4914 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4915 4916 unsigned CallOpc = PPCISD::CALL; 4917 4918 bool needIndirectCall = true; 4919 if (!isSVR4ABI || !isPPC64) 4920 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4921 // If this is an absolute destination address, use the munged value. 4922 Callee = SDValue(Dest, 0); 4923 needIndirectCall = false; 4924 } 4925 4926 // PC-relative references to external symbols should go through $stub, unless 4927 // we're building with the leopard linker or later, which automatically 4928 // synthesizes these stubs. 4929 const TargetMachine &TM = DAG.getTarget(); 4930 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4931 const GlobalValue *GV = nullptr; 4932 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4933 GV = G->getGlobal(); 4934 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4935 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4936 4937 if (isFunctionGlobalAddress(Callee)) { 4938 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4939 // A call to a TLS address is actually an indirect call to a 4940 // thread-specific pointer. 4941 unsigned OpFlags = 0; 4942 if (UsePlt) 4943 OpFlags = PPCII::MO_PLT; 4944 4945 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4946 // every direct call is) turn it into a TargetGlobalAddress / 4947 // TargetExternalSymbol node so that legalize doesn't hack it. 4948 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4949 Callee.getValueType(), 0, OpFlags); 4950 needIndirectCall = false; 4951 } 4952 4953 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4954 unsigned char OpFlags = 0; 4955 4956 if (UsePlt) 4957 OpFlags = PPCII::MO_PLT; 4958 4959 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4960 OpFlags); 4961 needIndirectCall = false; 4962 } 4963 4964 if (isPatchPoint) { 4965 // We'll form an invalid direct call when lowering a patchpoint; the full 4966 // sequence for an indirect call is complicated, and many of the 4967 // instructions introduced might have side effects (and, thus, can't be 4968 // removed later). The call itself will be removed as soon as the 4969 // argument/return lowering is complete, so the fact that it has the wrong 4970 // kind of operands should not really matter. 4971 needIndirectCall = false; 4972 } 4973 4974 if (needIndirectCall) { 4975 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4976 // to do the call, we can't use PPCISD::CALL. 4977 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4978 4979 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4980 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4981 // entry point, but to the function descriptor (the function entry point 4982 // address is part of the function descriptor though). 4983 // The function descriptor is a three doubleword structure with the 4984 // following fields: function entry point, TOC base address and 4985 // environment pointer. 4986 // Thus for a call through a function pointer, the following actions need 4987 // to be performed: 4988 // 1. Save the TOC of the caller in the TOC save area of its stack 4989 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4990 // 2. Load the address of the function entry point from the function 4991 // descriptor. 4992 // 3. Load the TOC of the callee from the function descriptor into r2. 4993 // 4. Load the environment pointer from the function descriptor into 4994 // r11. 4995 // 5. Branch to the function entry point address. 4996 // 6. On return of the callee, the TOC of the caller needs to be 4997 // restored (this is done in FinishCall()). 4998 // 4999 // The loads are scheduled at the beginning of the call sequence, and the 5000 // register copies are flagged together to ensure that no other 5001 // operations can be scheduled in between. E.g. without flagging the 5002 // copies together, a TOC access in the caller could be scheduled between 5003 // the assignment of the callee TOC and the branch to the callee, which 5004 // results in the TOC access going through the TOC of the callee instead 5005 // of going through the TOC of the caller, which leads to incorrect code. 5006 5007 // Load the address of the function entry point from the function 5008 // descriptor. 5009 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 5010 if (LDChain.getValueType() == MVT::Glue) 5011 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 5012 5013 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5014 ? (MachineMemOperand::MODereferenceable | 5015 MachineMemOperand::MOInvariant) 5016 : MachineMemOperand::MONone; 5017 5018 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5019 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 5020 /* Alignment = */ 8, MMOFlags); 5021 5022 // Load environment pointer into r11. 5023 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 5024 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 5025 SDValue LoadEnvPtr = 5026 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 5027 /* Alignment = */ 8, MMOFlags); 5028 5029 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 5030 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 5031 SDValue TOCPtr = 5032 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 5033 /* Alignment = */ 8, MMOFlags); 5034 5035 setUsesTOCBasePtr(DAG); 5036 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 5037 InFlag); 5038 Chain = TOCVal.getValue(0); 5039 InFlag = TOCVal.getValue(1); 5040 5041 // If the function call has an explicit 'nest' parameter, it takes the 5042 // place of the environment pointer. 5043 if (!hasNest) { 5044 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 5045 InFlag); 5046 5047 Chain = EnvVal.getValue(0); 5048 InFlag = EnvVal.getValue(1); 5049 } 5050 5051 MTCTROps[0] = Chain; 5052 MTCTROps[1] = LoadFuncPtr; 5053 MTCTROps[2] = InFlag; 5054 } 5055 5056 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 5057 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 5058 InFlag = Chain.getValue(1); 5059 5060 NodeTys.clear(); 5061 NodeTys.push_back(MVT::Other); 5062 NodeTys.push_back(MVT::Glue); 5063 Ops.push_back(Chain); 5064 CallOpc = PPCISD::BCTRL; 5065 Callee.setNode(nullptr); 5066 // Add use of X11 (holding environment pointer) 5067 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 5068 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 5069 // Add CTR register as callee so a bctr can be emitted later. 5070 if (isTailCall) 5071 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 5072 } 5073 5074 // If this is a direct call, pass the chain and the callee. 5075 if (Callee.getNode()) { 5076 Ops.push_back(Chain); 5077 Ops.push_back(Callee); 5078 } 5079 // If this is a tail call add stack pointer delta. 5080 if (isTailCall) 5081 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5082 5083 // Add argument registers to the end of the list so that they are known live 5084 // into the call. 5085 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5086 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5087 RegsToPass[i].second.getValueType())); 5088 5089 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 5090 // into the call. 5091 if (isSVR4ABI && isPPC64 && !isPatchPoint) { 5092 setUsesTOCBasePtr(DAG); 5093 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 5094 } 5095 5096 return CallOpc; 5097 } 5098 5099 SDValue PPCTargetLowering::LowerCallResult( 5100 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5101 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5102 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5103 SmallVector<CCValAssign, 16> RVLocs; 5104 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5105 *DAG.getContext()); 5106 5107 CCRetInfo.AnalyzeCallResult( 5108 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5109 ? RetCC_PPC_Cold 5110 : RetCC_PPC); 5111 5112 // Copy all of the result registers out of their specified physreg. 5113 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5114 CCValAssign &VA = RVLocs[i]; 5115 assert(VA.isRegLoc() && "Can only return in registers!"); 5116 5117 SDValue Val = DAG.getCopyFromReg(Chain, dl, 5118 VA.getLocReg(), VA.getLocVT(), InFlag); 5119 Chain = Val.getValue(1); 5120 InFlag = Val.getValue(2); 5121 5122 switch (VA.getLocInfo()) { 5123 default: llvm_unreachable("Unknown loc info!"); 5124 case CCValAssign::Full: break; 5125 case CCValAssign::AExt: 5126 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5127 break; 5128 case CCValAssign::ZExt: 5129 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5130 DAG.getValueType(VA.getValVT())); 5131 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5132 break; 5133 case CCValAssign::SExt: 5134 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5135 DAG.getValueType(VA.getValVT())); 5136 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5137 break; 5138 } 5139 5140 InVals.push_back(Val); 5141 } 5142 5143 return Chain; 5144 } 5145 5146 SDValue PPCTargetLowering::FinishCall( 5147 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5148 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5149 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 5150 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5151 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5152 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5153 std::vector<EVT> NodeTys; 5154 SmallVector<SDValue, 8> Ops; 5155 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 5156 SPDiff, isTailCall, isPatchPoint, hasNest, 5157 RegsToPass, Ops, NodeTys, CS, Subtarget); 5158 5159 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5160 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5161 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5162 5163 // When performing tail call optimization the callee pops its arguments off 5164 // the stack. Account for this here so these bytes can be pushed back on in 5165 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5166 int BytesCalleePops = 5167 (CallConv == CallingConv::Fast && 5168 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5169 5170 // Add a register mask operand representing the call-preserved registers. 5171 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5172 const uint32_t *Mask = 5173 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5174 assert(Mask && "Missing call preserved mask for calling convention"); 5175 Ops.push_back(DAG.getRegisterMask(Mask)); 5176 5177 if (InFlag.getNode()) 5178 Ops.push_back(InFlag); 5179 5180 // Emit tail call. 5181 if (isTailCall) { 5182 assert(((Callee.getOpcode() == ISD::Register && 5183 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5184 Callee.getOpcode() == ISD::TargetExternalSymbol || 5185 Callee.getOpcode() == ISD::TargetGlobalAddress || 5186 isa<ConstantSDNode>(Callee)) && 5187 "Expecting an global address, external symbol, absolute value or register"); 5188 5189 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5190 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5191 } 5192 5193 // Add a NOP immediately after the branch instruction when using the 64-bit 5194 // SVR4 ABI. At link time, if caller and callee are in a different module and 5195 // thus have a different TOC, the call will be replaced with a call to a stub 5196 // function which saves the current TOC, loads the TOC of the callee and 5197 // branches to the callee. The NOP will be replaced with a load instruction 5198 // which restores the TOC of the caller from the TOC save slot of the current 5199 // stack frame. If caller and callee belong to the same module (and have the 5200 // same TOC), the NOP will remain unchanged. 5201 5202 MachineFunction &MF = DAG.getMachineFunction(); 5203 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 5204 !isPatchPoint) { 5205 if (CallOpc == PPCISD::BCTRL) { 5206 // This is a call through a function pointer. 5207 // Restore the caller TOC from the save area into R2. 5208 // See PrepareCall() for more information about calls through function 5209 // pointers in the 64-bit SVR4 ABI. 5210 // We are using a target-specific load with r2 hard coded, because the 5211 // result of a target-independent load would never go directly into r2, 5212 // since r2 is a reserved register (which prevents the register allocator 5213 // from allocating it), resulting in an additional register being 5214 // allocated and an unnecessary move instruction being generated. 5215 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5216 5217 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5218 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5219 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5220 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5221 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5222 5223 // The address needs to go after the chain input but before the flag (or 5224 // any other variadic arguments). 5225 Ops.insert(std::next(Ops.begin()), AddTOC); 5226 } else if (CallOpc == PPCISD::CALL && 5227 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5228 // Otherwise insert NOP for non-local calls. 5229 CallOpc = PPCISD::CALL_NOP; 5230 } 5231 } 5232 5233 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5234 InFlag = Chain.getValue(1); 5235 5236 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5237 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5238 InFlag, dl); 5239 if (!Ins.empty()) 5240 InFlag = Chain.getValue(1); 5241 5242 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5243 Ins, dl, DAG, InVals); 5244 } 5245 5246 SDValue 5247 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5248 SmallVectorImpl<SDValue> &InVals) const { 5249 SelectionDAG &DAG = CLI.DAG; 5250 SDLoc &dl = CLI.DL; 5251 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5252 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5253 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5254 SDValue Chain = CLI.Chain; 5255 SDValue Callee = CLI.Callee; 5256 bool &isTailCall = CLI.IsTailCall; 5257 CallingConv::ID CallConv = CLI.CallConv; 5258 bool isVarArg = CLI.IsVarArg; 5259 bool isPatchPoint = CLI.IsPatchPoint; 5260 ImmutableCallSite CS = CLI.CS; 5261 5262 if (isTailCall) { 5263 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5264 isTailCall = false; 5265 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5266 isTailCall = 5267 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5268 isVarArg, Outs, Ins, DAG); 5269 else 5270 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5271 Ins, DAG); 5272 if (isTailCall) { 5273 ++NumTailCalls; 5274 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5275 ++NumSiblingCalls; 5276 5277 assert(isa<GlobalAddressSDNode>(Callee) && 5278 "Callee should be an llvm::Function object."); 5279 LLVM_DEBUG( 5280 const GlobalValue *GV = 5281 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5282 const unsigned Width = 5283 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5284 dbgs() << "TCO caller: " 5285 << left_justify(DAG.getMachineFunction().getName(), Width) 5286 << ", callee linkage: " << GV->getVisibility() << ", " 5287 << GV->getLinkage() << "\n"); 5288 } 5289 } 5290 5291 if (!isTailCall && CS && CS.isMustTailCall()) 5292 report_fatal_error("failed to perform tail call elimination on a call " 5293 "site marked musttail"); 5294 5295 // When long calls (i.e. indirect calls) are always used, calls are always 5296 // made via function pointer. If we have a function name, first translate it 5297 // into a pointer. 5298 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5299 !isTailCall) 5300 Callee = LowerGlobalAddress(Callee, DAG); 5301 5302 if (Subtarget.isSVR4ABI()) { 5303 if (Subtarget.isPPC64()) 5304 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5305 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5306 dl, DAG, InVals, CS); 5307 else 5308 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5309 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5310 dl, DAG, InVals, CS); 5311 } 5312 5313 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5314 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5315 dl, DAG, InVals, CS); 5316 } 5317 5318 SDValue PPCTargetLowering::LowerCall_32SVR4( 5319 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5320 bool isTailCall, bool isPatchPoint, 5321 const SmallVectorImpl<ISD::OutputArg> &Outs, 5322 const SmallVectorImpl<SDValue> &OutVals, 5323 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5324 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5325 ImmutableCallSite CS) const { 5326 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5327 // of the 32-bit SVR4 ABI stack frame layout. 5328 5329 assert((CallConv == CallingConv::C || 5330 CallConv == CallingConv::Cold || 5331 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5332 5333 unsigned PtrByteSize = 4; 5334 5335 MachineFunction &MF = DAG.getMachineFunction(); 5336 5337 // Mark this function as potentially containing a function that contains a 5338 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5339 // and restoring the callers stack pointer in this functions epilog. This is 5340 // done because by tail calling the called function might overwrite the value 5341 // in this function's (MF) stack pointer stack slot 0(SP). 5342 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5343 CallConv == CallingConv::Fast) 5344 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5345 5346 // Count how many bytes are to be pushed on the stack, including the linkage 5347 // area, parameter list area and the part of the local variable space which 5348 // contains copies of aggregates which are passed by value. 5349 5350 // Assign locations to all of the outgoing arguments. 5351 SmallVector<CCValAssign, 16> ArgLocs; 5352 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5353 5354 // Reserve space for the linkage area on the stack. 5355 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5356 PtrByteSize); 5357 if (useSoftFloat()) 5358 CCInfo.PreAnalyzeCallOperands(Outs); 5359 5360 if (isVarArg) { 5361 // Handle fixed and variable vector arguments differently. 5362 // Fixed vector arguments go into registers as long as registers are 5363 // available. Variable vector arguments always go into memory. 5364 unsigned NumArgs = Outs.size(); 5365 5366 for (unsigned i = 0; i != NumArgs; ++i) { 5367 MVT ArgVT = Outs[i].VT; 5368 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5369 bool Result; 5370 5371 if (Outs[i].IsFixed) { 5372 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5373 CCInfo); 5374 } else { 5375 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5376 ArgFlags, CCInfo); 5377 } 5378 5379 if (Result) { 5380 #ifndef NDEBUG 5381 errs() << "Call operand #" << i << " has unhandled type " 5382 << EVT(ArgVT).getEVTString() << "\n"; 5383 #endif 5384 llvm_unreachable(nullptr); 5385 } 5386 } 5387 } else { 5388 // All arguments are treated the same. 5389 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5390 } 5391 CCInfo.clearWasPPCF128(); 5392 5393 // Assign locations to all of the outgoing aggregate by value arguments. 5394 SmallVector<CCValAssign, 16> ByValArgLocs; 5395 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5396 5397 // Reserve stack space for the allocations in CCInfo. 5398 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5399 5400 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5401 5402 // Size of the linkage area, parameter list area and the part of the local 5403 // space variable where copies of aggregates which are passed by value are 5404 // stored. 5405 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5406 5407 // Calculate by how many bytes the stack has to be adjusted in case of tail 5408 // call optimization. 5409 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5410 5411 // Adjust the stack pointer for the new arguments... 5412 // These operations are automatically eliminated by the prolog/epilog pass 5413 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5414 SDValue CallSeqStart = Chain; 5415 5416 // Load the return address and frame pointer so it can be moved somewhere else 5417 // later. 5418 SDValue LROp, FPOp; 5419 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5420 5421 // Set up a copy of the stack pointer for use loading and storing any 5422 // arguments that may not fit in the registers available for argument 5423 // passing. 5424 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5425 5426 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5427 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5428 SmallVector<SDValue, 8> MemOpChains; 5429 5430 bool seenFloatArg = false; 5431 // Walk the register/memloc assignments, inserting copies/loads. 5432 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 5433 i != e; 5434 ++i) { 5435 CCValAssign &VA = ArgLocs[i]; 5436 SDValue Arg = OutVals[i]; 5437 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5438 5439 if (Flags.isByVal()) { 5440 // Argument is an aggregate which is passed by value, thus we need to 5441 // create a copy of it in the local variable space of the current stack 5442 // frame (which is the stack frame of the caller) and pass the address of 5443 // this copy to the callee. 5444 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5445 CCValAssign &ByValVA = ByValArgLocs[j++]; 5446 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5447 5448 // Memory reserved in the local variable space of the callers stack frame. 5449 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5450 5451 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5452 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5453 StackPtr, PtrOff); 5454 5455 // Create a copy of the argument in the local area of the current 5456 // stack frame. 5457 SDValue MemcpyCall = 5458 CreateCopyOfByValArgument(Arg, PtrOff, 5459 CallSeqStart.getNode()->getOperand(0), 5460 Flags, DAG, dl); 5461 5462 // This must go outside the CALLSEQ_START..END. 5463 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5464 SDLoc(MemcpyCall)); 5465 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5466 NewCallSeqStart.getNode()); 5467 Chain = CallSeqStart = NewCallSeqStart; 5468 5469 // Pass the address of the aggregate copy on the stack either in a 5470 // physical register or in the parameter list area of the current stack 5471 // frame to the callee. 5472 Arg = PtrOff; 5473 } 5474 5475 // When useCRBits() is true, there can be i1 arguments. 5476 // It is because getRegisterType(MVT::i1) => MVT::i1, 5477 // and for other integer types getRegisterType() => MVT::i32. 5478 // Extend i1 and ensure callee will get i32. 5479 if (Arg.getValueType() == MVT::i1) 5480 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5481 dl, MVT::i32, Arg); 5482 5483 if (VA.isRegLoc()) { 5484 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5485 // Put argument in a physical register. 5486 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5487 } else { 5488 // Put argument in the parameter list area of the current stack frame. 5489 assert(VA.isMemLoc()); 5490 unsigned LocMemOffset = VA.getLocMemOffset(); 5491 5492 if (!isTailCall) { 5493 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5494 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5495 StackPtr, PtrOff); 5496 5497 MemOpChains.push_back( 5498 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5499 } else { 5500 // Calculate and remember argument location. 5501 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5502 TailCallArguments); 5503 } 5504 } 5505 } 5506 5507 if (!MemOpChains.empty()) 5508 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5509 5510 // Build a sequence of copy-to-reg nodes chained together with token chain 5511 // and flag operands which copy the outgoing args into the appropriate regs. 5512 SDValue InFlag; 5513 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5514 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5515 RegsToPass[i].second, InFlag); 5516 InFlag = Chain.getValue(1); 5517 } 5518 5519 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5520 // registers. 5521 if (isVarArg) { 5522 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5523 SDValue Ops[] = { Chain, InFlag }; 5524 5525 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5526 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5527 5528 InFlag = Chain.getValue(1); 5529 } 5530 5531 if (isTailCall) 5532 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5533 TailCallArguments); 5534 5535 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5536 /* unused except on PPC64 ELFv1 */ false, DAG, 5537 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5538 NumBytes, Ins, InVals, CS); 5539 } 5540 5541 // Copy an argument into memory, being careful to do this outside the 5542 // call sequence for the call to which the argument belongs. 5543 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5544 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5545 SelectionDAG &DAG, const SDLoc &dl) const { 5546 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5547 CallSeqStart.getNode()->getOperand(0), 5548 Flags, DAG, dl); 5549 // The MEMCPY must go outside the CALLSEQ_START..END. 5550 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5551 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5552 SDLoc(MemcpyCall)); 5553 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5554 NewCallSeqStart.getNode()); 5555 return NewCallSeqStart; 5556 } 5557 5558 SDValue PPCTargetLowering::LowerCall_64SVR4( 5559 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5560 bool isTailCall, bool isPatchPoint, 5561 const SmallVectorImpl<ISD::OutputArg> &Outs, 5562 const SmallVectorImpl<SDValue> &OutVals, 5563 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5564 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5565 ImmutableCallSite CS) const { 5566 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5567 bool isLittleEndian = Subtarget.isLittleEndian(); 5568 unsigned NumOps = Outs.size(); 5569 bool hasNest = false; 5570 bool IsSibCall = false; 5571 5572 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5573 unsigned PtrByteSize = 8; 5574 5575 MachineFunction &MF = DAG.getMachineFunction(); 5576 5577 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5578 IsSibCall = true; 5579 5580 // Mark this function as potentially containing a function that contains a 5581 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5582 // and restoring the callers stack pointer in this functions epilog. This is 5583 // done because by tail calling the called function might overwrite the value 5584 // in this function's (MF) stack pointer stack slot 0(SP). 5585 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5586 CallConv == CallingConv::Fast) 5587 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5588 5589 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5590 "fastcc not supported on varargs functions"); 5591 5592 // Count how many bytes are to be pushed on the stack, including the linkage 5593 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5594 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5595 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5596 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5597 unsigned NumBytes = LinkageSize; 5598 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5599 unsigned &QFPR_idx = FPR_idx; 5600 5601 static const MCPhysReg GPR[] = { 5602 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5603 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5604 }; 5605 static const MCPhysReg VR[] = { 5606 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5607 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5608 }; 5609 5610 const unsigned NumGPRs = array_lengthof(GPR); 5611 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5612 const unsigned NumVRs = array_lengthof(VR); 5613 const unsigned NumQFPRs = NumFPRs; 5614 5615 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5616 // can be passed to the callee in registers. 5617 // For the fast calling convention, there is another check below. 5618 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5619 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5620 if (!HasParameterArea) { 5621 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5622 unsigned AvailableFPRs = NumFPRs; 5623 unsigned AvailableVRs = NumVRs; 5624 unsigned NumBytesTmp = NumBytes; 5625 for (unsigned i = 0; i != NumOps; ++i) { 5626 if (Outs[i].Flags.isNest()) continue; 5627 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5628 PtrByteSize, LinkageSize, ParamAreaSize, 5629 NumBytesTmp, AvailableFPRs, AvailableVRs, 5630 Subtarget.hasQPX())) 5631 HasParameterArea = true; 5632 } 5633 } 5634 5635 // When using the fast calling convention, we don't provide backing for 5636 // arguments that will be in registers. 5637 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5638 5639 // Avoid allocating parameter area for fastcc functions if all the arguments 5640 // can be passed in the registers. 5641 if (CallConv == CallingConv::Fast) 5642 HasParameterArea = false; 5643 5644 // Add up all the space actually used. 5645 for (unsigned i = 0; i != NumOps; ++i) { 5646 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5647 EVT ArgVT = Outs[i].VT; 5648 EVT OrigVT = Outs[i].ArgVT; 5649 5650 if (Flags.isNest()) 5651 continue; 5652 5653 if (CallConv == CallingConv::Fast) { 5654 if (Flags.isByVal()) { 5655 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5656 if (NumGPRsUsed > NumGPRs) 5657 HasParameterArea = true; 5658 } else { 5659 switch (ArgVT.getSimpleVT().SimpleTy) { 5660 default: llvm_unreachable("Unexpected ValueType for argument!"); 5661 case MVT::i1: 5662 case MVT::i32: 5663 case MVT::i64: 5664 if (++NumGPRsUsed <= NumGPRs) 5665 continue; 5666 break; 5667 case MVT::v4i32: 5668 case MVT::v8i16: 5669 case MVT::v16i8: 5670 case MVT::v2f64: 5671 case MVT::v2i64: 5672 case MVT::v1i128: 5673 case MVT::f128: 5674 if (++NumVRsUsed <= NumVRs) 5675 continue; 5676 break; 5677 case MVT::v4f32: 5678 // When using QPX, this is handled like a FP register, otherwise, it 5679 // is an Altivec register. 5680 if (Subtarget.hasQPX()) { 5681 if (++NumFPRsUsed <= NumFPRs) 5682 continue; 5683 } else { 5684 if (++NumVRsUsed <= NumVRs) 5685 continue; 5686 } 5687 break; 5688 case MVT::f32: 5689 case MVT::f64: 5690 case MVT::v4f64: // QPX 5691 case MVT::v4i1: // QPX 5692 if (++NumFPRsUsed <= NumFPRs) 5693 continue; 5694 break; 5695 } 5696 HasParameterArea = true; 5697 } 5698 } 5699 5700 /* Respect alignment of argument on the stack. */ 5701 unsigned Align = 5702 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5703 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5704 5705 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5706 if (Flags.isInConsecutiveRegsLast()) 5707 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5708 } 5709 5710 unsigned NumBytesActuallyUsed = NumBytes; 5711 5712 // In the old ELFv1 ABI, 5713 // the prolog code of the callee may store up to 8 GPR argument registers to 5714 // the stack, allowing va_start to index over them in memory if its varargs. 5715 // Because we cannot tell if this is needed on the caller side, we have to 5716 // conservatively assume that it is needed. As such, make sure we have at 5717 // least enough stack space for the caller to store the 8 GPRs. 5718 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5719 // really requires memory operands, e.g. a vararg function. 5720 if (HasParameterArea) 5721 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5722 else 5723 NumBytes = LinkageSize; 5724 5725 // Tail call needs the stack to be aligned. 5726 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5727 CallConv == CallingConv::Fast) 5728 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5729 5730 int SPDiff = 0; 5731 5732 // Calculate by how many bytes the stack has to be adjusted in case of tail 5733 // call optimization. 5734 if (!IsSibCall) 5735 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5736 5737 // To protect arguments on the stack from being clobbered in a tail call, 5738 // force all the loads to happen before doing any other lowering. 5739 if (isTailCall) 5740 Chain = DAG.getStackArgumentTokenFactor(Chain); 5741 5742 // Adjust the stack pointer for the new arguments... 5743 // These operations are automatically eliminated by the prolog/epilog pass 5744 if (!IsSibCall) 5745 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5746 SDValue CallSeqStart = Chain; 5747 5748 // Load the return address and frame pointer so it can be move somewhere else 5749 // later. 5750 SDValue LROp, FPOp; 5751 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5752 5753 // Set up a copy of the stack pointer for use loading and storing any 5754 // arguments that may not fit in the registers available for argument 5755 // passing. 5756 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5757 5758 // Figure out which arguments are going to go in registers, and which in 5759 // memory. Also, if this is a vararg function, floating point operations 5760 // must be stored to our stack, and loaded into integer regs as well, if 5761 // any integer regs are available for argument passing. 5762 unsigned ArgOffset = LinkageSize; 5763 5764 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5765 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5766 5767 SmallVector<SDValue, 8> MemOpChains; 5768 for (unsigned i = 0; i != NumOps; ++i) { 5769 SDValue Arg = OutVals[i]; 5770 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5771 EVT ArgVT = Outs[i].VT; 5772 EVT OrigVT = Outs[i].ArgVT; 5773 5774 // PtrOff will be used to store the current argument to the stack if a 5775 // register cannot be found for it. 5776 SDValue PtrOff; 5777 5778 // We re-align the argument offset for each argument, except when using the 5779 // fast calling convention, when we need to make sure we do that only when 5780 // we'll actually use a stack slot. 5781 auto ComputePtrOff = [&]() { 5782 /* Respect alignment of argument on the stack. */ 5783 unsigned Align = 5784 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5785 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5786 5787 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5788 5789 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5790 }; 5791 5792 if (CallConv != CallingConv::Fast) { 5793 ComputePtrOff(); 5794 5795 /* Compute GPR index associated with argument offset. */ 5796 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5797 GPR_idx = std::min(GPR_idx, NumGPRs); 5798 } 5799 5800 // Promote integers to 64-bit values. 5801 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5802 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5803 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5804 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5805 } 5806 5807 // FIXME memcpy is used way more than necessary. Correctness first. 5808 // Note: "by value" is code for passing a structure by value, not 5809 // basic types. 5810 if (Flags.isByVal()) { 5811 // Note: Size includes alignment padding, so 5812 // struct x { short a; char b; } 5813 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5814 // These are the proper values we need for right-justifying the 5815 // aggregate in a parameter register. 5816 unsigned Size = Flags.getByValSize(); 5817 5818 // An empty aggregate parameter takes up no storage and no 5819 // registers. 5820 if (Size == 0) 5821 continue; 5822 5823 if (CallConv == CallingConv::Fast) 5824 ComputePtrOff(); 5825 5826 // All aggregates smaller than 8 bytes must be passed right-justified. 5827 if (Size==1 || Size==2 || Size==4) { 5828 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5829 if (GPR_idx != NumGPRs) { 5830 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5831 MachinePointerInfo(), VT); 5832 MemOpChains.push_back(Load.getValue(1)); 5833 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5834 5835 ArgOffset += PtrByteSize; 5836 continue; 5837 } 5838 } 5839 5840 if (GPR_idx == NumGPRs && Size < 8) { 5841 SDValue AddPtr = PtrOff; 5842 if (!isLittleEndian) { 5843 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5844 PtrOff.getValueType()); 5845 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5846 } 5847 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5848 CallSeqStart, 5849 Flags, DAG, dl); 5850 ArgOffset += PtrByteSize; 5851 continue; 5852 } 5853 // Copy entire object into memory. There are cases where gcc-generated 5854 // code assumes it is there, even if it could be put entirely into 5855 // registers. (This is not what the doc says.) 5856 5857 // FIXME: The above statement is likely due to a misunderstanding of the 5858 // documents. All arguments must be copied into the parameter area BY 5859 // THE CALLEE in the event that the callee takes the address of any 5860 // formal argument. That has not yet been implemented. However, it is 5861 // reasonable to use the stack area as a staging area for the register 5862 // load. 5863 5864 // Skip this for small aggregates, as we will use the same slot for a 5865 // right-justified copy, below. 5866 if (Size >= 8) 5867 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5868 CallSeqStart, 5869 Flags, DAG, dl); 5870 5871 // When a register is available, pass a small aggregate right-justified. 5872 if (Size < 8 && GPR_idx != NumGPRs) { 5873 // The easiest way to get this right-justified in a register 5874 // is to copy the structure into the rightmost portion of a 5875 // local variable slot, then load the whole slot into the 5876 // register. 5877 // FIXME: The memcpy seems to produce pretty awful code for 5878 // small aggregates, particularly for packed ones. 5879 // FIXME: It would be preferable to use the slot in the 5880 // parameter save area instead of a new local variable. 5881 SDValue AddPtr = PtrOff; 5882 if (!isLittleEndian) { 5883 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5884 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5885 } 5886 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5887 CallSeqStart, 5888 Flags, DAG, dl); 5889 5890 // Load the slot into the register. 5891 SDValue Load = 5892 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5893 MemOpChains.push_back(Load.getValue(1)); 5894 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5895 5896 // Done with this argument. 5897 ArgOffset += PtrByteSize; 5898 continue; 5899 } 5900 5901 // For aggregates larger than PtrByteSize, copy the pieces of the 5902 // object that fit into registers from the parameter save area. 5903 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5904 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5905 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5906 if (GPR_idx != NumGPRs) { 5907 SDValue Load = 5908 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5909 MemOpChains.push_back(Load.getValue(1)); 5910 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5911 ArgOffset += PtrByteSize; 5912 } else { 5913 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5914 break; 5915 } 5916 } 5917 continue; 5918 } 5919 5920 switch (Arg.getSimpleValueType().SimpleTy) { 5921 default: llvm_unreachable("Unexpected ValueType for argument!"); 5922 case MVT::i1: 5923 case MVT::i32: 5924 case MVT::i64: 5925 if (Flags.isNest()) { 5926 // The 'nest' parameter, if any, is passed in R11. 5927 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5928 hasNest = true; 5929 break; 5930 } 5931 5932 // These can be scalar arguments or elements of an integer array type 5933 // passed directly. Clang may use those instead of "byval" aggregate 5934 // types to avoid forcing arguments to memory unnecessarily. 5935 if (GPR_idx != NumGPRs) { 5936 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5937 } else { 5938 if (CallConv == CallingConv::Fast) 5939 ComputePtrOff(); 5940 5941 assert(HasParameterArea && 5942 "Parameter area must exist to pass an argument in memory."); 5943 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5944 true, isTailCall, false, MemOpChains, 5945 TailCallArguments, dl); 5946 if (CallConv == CallingConv::Fast) 5947 ArgOffset += PtrByteSize; 5948 } 5949 if (CallConv != CallingConv::Fast) 5950 ArgOffset += PtrByteSize; 5951 break; 5952 case MVT::f32: 5953 case MVT::f64: { 5954 // These can be scalar arguments or elements of a float array type 5955 // passed directly. The latter are used to implement ELFv2 homogenous 5956 // float aggregates. 5957 5958 // Named arguments go into FPRs first, and once they overflow, the 5959 // remaining arguments go into GPRs and then the parameter save area. 5960 // Unnamed arguments for vararg functions always go to GPRs and 5961 // then the parameter save area. For now, put all arguments to vararg 5962 // routines always in both locations (FPR *and* GPR or stack slot). 5963 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5964 bool NeededLoad = false; 5965 5966 // First load the argument into the next available FPR. 5967 if (FPR_idx != NumFPRs) 5968 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5969 5970 // Next, load the argument into GPR or stack slot if needed. 5971 if (!NeedGPROrStack) 5972 ; 5973 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5974 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5975 // once we support fp <-> gpr moves. 5976 5977 // In the non-vararg case, this can only ever happen in the 5978 // presence of f32 array types, since otherwise we never run 5979 // out of FPRs before running out of GPRs. 5980 SDValue ArgVal; 5981 5982 // Double values are always passed in a single GPR. 5983 if (Arg.getValueType() != MVT::f32) { 5984 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5985 5986 // Non-array float values are extended and passed in a GPR. 5987 } else if (!Flags.isInConsecutiveRegs()) { 5988 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5989 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5990 5991 // If we have an array of floats, we collect every odd element 5992 // together with its predecessor into one GPR. 5993 } else if (ArgOffset % PtrByteSize != 0) { 5994 SDValue Lo, Hi; 5995 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5996 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5997 if (!isLittleEndian) 5998 std::swap(Lo, Hi); 5999 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6000 6001 // The final element, if even, goes into the first half of a GPR. 6002 } else if (Flags.isInConsecutiveRegsLast()) { 6003 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6004 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6005 if (!isLittleEndian) 6006 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6007 DAG.getConstant(32, dl, MVT::i32)); 6008 6009 // Non-final even elements are skipped; they will be handled 6010 // together the with subsequent argument on the next go-around. 6011 } else 6012 ArgVal = SDValue(); 6013 6014 if (ArgVal.getNode()) 6015 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6016 } else { 6017 if (CallConv == CallingConv::Fast) 6018 ComputePtrOff(); 6019 6020 // Single-precision floating-point values are mapped to the 6021 // second (rightmost) word of the stack doubleword. 6022 if (Arg.getValueType() == MVT::f32 && 6023 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6024 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6025 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6026 } 6027 6028 assert(HasParameterArea && 6029 "Parameter area must exist to pass an argument in memory."); 6030 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6031 true, isTailCall, false, MemOpChains, 6032 TailCallArguments, dl); 6033 6034 NeededLoad = true; 6035 } 6036 // When passing an array of floats, the array occupies consecutive 6037 // space in the argument area; only round up to the next doubleword 6038 // at the end of the array. Otherwise, each float takes 8 bytes. 6039 if (CallConv != CallingConv::Fast || NeededLoad) { 6040 ArgOffset += (Arg.getValueType() == MVT::f32 && 6041 Flags.isInConsecutiveRegs()) ? 4 : 8; 6042 if (Flags.isInConsecutiveRegsLast()) 6043 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6044 } 6045 break; 6046 } 6047 case MVT::v4f32: 6048 case MVT::v4i32: 6049 case MVT::v8i16: 6050 case MVT::v16i8: 6051 case MVT::v2f64: 6052 case MVT::v2i64: 6053 case MVT::v1i128: 6054 case MVT::f128: 6055 if (!Subtarget.hasQPX()) { 6056 // These can be scalar arguments or elements of a vector array type 6057 // passed directly. The latter are used to implement ELFv2 homogenous 6058 // vector aggregates. 6059 6060 // For a varargs call, named arguments go into VRs or on the stack as 6061 // usual; unnamed arguments always go to the stack or the corresponding 6062 // GPRs when within range. For now, we always put the value in both 6063 // locations (or even all three). 6064 if (isVarArg) { 6065 assert(HasParameterArea && 6066 "Parameter area must exist if we have a varargs call."); 6067 // We could elide this store in the case where the object fits 6068 // entirely in R registers. Maybe later. 6069 SDValue Store = 6070 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6071 MemOpChains.push_back(Store); 6072 if (VR_idx != NumVRs) { 6073 SDValue Load = 6074 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6075 MemOpChains.push_back(Load.getValue(1)); 6076 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6077 } 6078 ArgOffset += 16; 6079 for (unsigned i=0; i<16; i+=PtrByteSize) { 6080 if (GPR_idx == NumGPRs) 6081 break; 6082 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6083 DAG.getConstant(i, dl, PtrVT)); 6084 SDValue Load = 6085 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6086 MemOpChains.push_back(Load.getValue(1)); 6087 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6088 } 6089 break; 6090 } 6091 6092 // Non-varargs Altivec params go into VRs or on the stack. 6093 if (VR_idx != NumVRs) { 6094 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6095 } else { 6096 if (CallConv == CallingConv::Fast) 6097 ComputePtrOff(); 6098 6099 assert(HasParameterArea && 6100 "Parameter area must exist to pass an argument in memory."); 6101 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6102 true, isTailCall, true, MemOpChains, 6103 TailCallArguments, dl); 6104 if (CallConv == CallingConv::Fast) 6105 ArgOffset += 16; 6106 } 6107 6108 if (CallConv != CallingConv::Fast) 6109 ArgOffset += 16; 6110 break; 6111 } // not QPX 6112 6113 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6114 "Invalid QPX parameter type"); 6115 6116 LLVM_FALLTHROUGH; 6117 case MVT::v4f64: 6118 case MVT::v4i1: { 6119 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6120 if (isVarArg) { 6121 assert(HasParameterArea && 6122 "Parameter area must exist if we have a varargs call."); 6123 // We could elide this store in the case where the object fits 6124 // entirely in R registers. Maybe later. 6125 SDValue Store = 6126 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6127 MemOpChains.push_back(Store); 6128 if (QFPR_idx != NumQFPRs) { 6129 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6130 PtrOff, MachinePointerInfo()); 6131 MemOpChains.push_back(Load.getValue(1)); 6132 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6133 } 6134 ArgOffset += (IsF32 ? 16 : 32); 6135 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6136 if (GPR_idx == NumGPRs) 6137 break; 6138 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6139 DAG.getConstant(i, dl, PtrVT)); 6140 SDValue Load = 6141 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6142 MemOpChains.push_back(Load.getValue(1)); 6143 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6144 } 6145 break; 6146 } 6147 6148 // Non-varargs QPX params go into registers or on the stack. 6149 if (QFPR_idx != NumQFPRs) { 6150 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6151 } else { 6152 if (CallConv == CallingConv::Fast) 6153 ComputePtrOff(); 6154 6155 assert(HasParameterArea && 6156 "Parameter area must exist to pass an argument in memory."); 6157 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6158 true, isTailCall, true, MemOpChains, 6159 TailCallArguments, dl); 6160 if (CallConv == CallingConv::Fast) 6161 ArgOffset += (IsF32 ? 16 : 32); 6162 } 6163 6164 if (CallConv != CallingConv::Fast) 6165 ArgOffset += (IsF32 ? 16 : 32); 6166 break; 6167 } 6168 } 6169 } 6170 6171 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6172 "mismatch in size of parameter area"); 6173 (void)NumBytesActuallyUsed; 6174 6175 if (!MemOpChains.empty()) 6176 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6177 6178 // Check if this is an indirect call (MTCTR/BCTRL). 6179 // See PrepareCall() for more information about calls through function 6180 // pointers in the 64-bit SVR4 ABI. 6181 if (!isTailCall && !isPatchPoint && 6182 !isFunctionGlobalAddress(Callee) && 6183 !isa<ExternalSymbolSDNode>(Callee)) { 6184 // Load r2 into a virtual register and store it to the TOC save area. 6185 setUsesTOCBasePtr(DAG); 6186 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6187 // TOC save area offset. 6188 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6189 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6190 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6191 Chain = DAG.getStore( 6192 Val.getValue(1), dl, Val, AddPtr, 6193 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6194 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6195 // This does not mean the MTCTR instruction must use R12; it's easier 6196 // to model this as an extra parameter, so do that. 6197 if (isELFv2ABI && !isPatchPoint) 6198 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6199 } 6200 6201 // Build a sequence of copy-to-reg nodes chained together with token chain 6202 // and flag operands which copy the outgoing args into the appropriate regs. 6203 SDValue InFlag; 6204 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6205 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6206 RegsToPass[i].second, InFlag); 6207 InFlag = Chain.getValue(1); 6208 } 6209 6210 if (isTailCall && !IsSibCall) 6211 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6212 TailCallArguments); 6213 6214 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6215 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6216 SPDiff, NumBytes, Ins, InVals, CS); 6217 } 6218 6219 SDValue PPCTargetLowering::LowerCall_Darwin( 6220 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6221 bool isTailCall, bool isPatchPoint, 6222 const SmallVectorImpl<ISD::OutputArg> &Outs, 6223 const SmallVectorImpl<SDValue> &OutVals, 6224 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6225 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6226 ImmutableCallSite CS) const { 6227 unsigned NumOps = Outs.size(); 6228 6229 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6230 bool isPPC64 = PtrVT == MVT::i64; 6231 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6232 6233 MachineFunction &MF = DAG.getMachineFunction(); 6234 6235 // Mark this function as potentially containing a function that contains a 6236 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6237 // and restoring the callers stack pointer in this functions epilog. This is 6238 // done because by tail calling the called function might overwrite the value 6239 // in this function's (MF) stack pointer stack slot 0(SP). 6240 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6241 CallConv == CallingConv::Fast) 6242 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6243 6244 // Count how many bytes are to be pushed on the stack, including the linkage 6245 // area, and parameter passing area. We start with 24/48 bytes, which is 6246 // prereserved space for [SP][CR][LR][3 x unused]. 6247 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6248 unsigned NumBytes = LinkageSize; 6249 6250 // Add up all the space actually used. 6251 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6252 // they all go in registers, but we must reserve stack space for them for 6253 // possible use by the caller. In varargs or 64-bit calls, parameters are 6254 // assigned stack space in order, with padding so Altivec parameters are 6255 // 16-byte aligned. 6256 unsigned nAltivecParamsAtEnd = 0; 6257 for (unsigned i = 0; i != NumOps; ++i) { 6258 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6259 EVT ArgVT = Outs[i].VT; 6260 // Varargs Altivec parameters are padded to a 16 byte boundary. 6261 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6262 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6263 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6264 if (!isVarArg && !isPPC64) { 6265 // Non-varargs Altivec parameters go after all the non-Altivec 6266 // parameters; handle those later so we know how much padding we need. 6267 nAltivecParamsAtEnd++; 6268 continue; 6269 } 6270 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6271 NumBytes = ((NumBytes+15)/16)*16; 6272 } 6273 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6274 } 6275 6276 // Allow for Altivec parameters at the end, if needed. 6277 if (nAltivecParamsAtEnd) { 6278 NumBytes = ((NumBytes+15)/16)*16; 6279 NumBytes += 16*nAltivecParamsAtEnd; 6280 } 6281 6282 // The prolog code of the callee may store up to 8 GPR argument registers to 6283 // the stack, allowing va_start to index over them in memory if its varargs. 6284 // Because we cannot tell if this is needed on the caller side, we have to 6285 // conservatively assume that it is needed. As such, make sure we have at 6286 // least enough stack space for the caller to store the 8 GPRs. 6287 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6288 6289 // Tail call needs the stack to be aligned. 6290 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6291 CallConv == CallingConv::Fast) 6292 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6293 6294 // Calculate by how many bytes the stack has to be adjusted in case of tail 6295 // call optimization. 6296 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6297 6298 // To protect arguments on the stack from being clobbered in a tail call, 6299 // force all the loads to happen before doing any other lowering. 6300 if (isTailCall) 6301 Chain = DAG.getStackArgumentTokenFactor(Chain); 6302 6303 // Adjust the stack pointer for the new arguments... 6304 // These operations are automatically eliminated by the prolog/epilog pass 6305 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6306 SDValue CallSeqStart = Chain; 6307 6308 // Load the return address and frame pointer so it can be move somewhere else 6309 // later. 6310 SDValue LROp, FPOp; 6311 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6312 6313 // Set up a copy of the stack pointer for use loading and storing any 6314 // arguments that may not fit in the registers available for argument 6315 // passing. 6316 SDValue StackPtr; 6317 if (isPPC64) 6318 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6319 else 6320 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6321 6322 // Figure out which arguments are going to go in registers, and which in 6323 // memory. Also, if this is a vararg function, floating point operations 6324 // must be stored to our stack, and loaded into integer regs as well, if 6325 // any integer regs are available for argument passing. 6326 unsigned ArgOffset = LinkageSize; 6327 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6328 6329 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6330 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6331 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6332 }; 6333 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6334 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6335 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6336 }; 6337 static const MCPhysReg VR[] = { 6338 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6339 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6340 }; 6341 const unsigned NumGPRs = array_lengthof(GPR_32); 6342 const unsigned NumFPRs = 13; 6343 const unsigned NumVRs = array_lengthof(VR); 6344 6345 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6346 6347 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6348 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6349 6350 SmallVector<SDValue, 8> MemOpChains; 6351 for (unsigned i = 0; i != NumOps; ++i) { 6352 SDValue Arg = OutVals[i]; 6353 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6354 6355 // PtrOff will be used to store the current argument to the stack if a 6356 // register cannot be found for it. 6357 SDValue PtrOff; 6358 6359 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6360 6361 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6362 6363 // On PPC64, promote integers to 64-bit values. 6364 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6365 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6366 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6367 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6368 } 6369 6370 // FIXME memcpy is used way more than necessary. Correctness first. 6371 // Note: "by value" is code for passing a structure by value, not 6372 // basic types. 6373 if (Flags.isByVal()) { 6374 unsigned Size = Flags.getByValSize(); 6375 // Very small objects are passed right-justified. Everything else is 6376 // passed left-justified. 6377 if (Size==1 || Size==2) { 6378 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6379 if (GPR_idx != NumGPRs) { 6380 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6381 MachinePointerInfo(), VT); 6382 MemOpChains.push_back(Load.getValue(1)); 6383 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6384 6385 ArgOffset += PtrByteSize; 6386 } else { 6387 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6388 PtrOff.getValueType()); 6389 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6390 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6391 CallSeqStart, 6392 Flags, DAG, dl); 6393 ArgOffset += PtrByteSize; 6394 } 6395 continue; 6396 } 6397 // Copy entire object into memory. There are cases where gcc-generated 6398 // code assumes it is there, even if it could be put entirely into 6399 // registers. (This is not what the doc says.) 6400 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6401 CallSeqStart, 6402 Flags, DAG, dl); 6403 6404 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6405 // copy the pieces of the object that fit into registers from the 6406 // parameter save area. 6407 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6408 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6409 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6410 if (GPR_idx != NumGPRs) { 6411 SDValue Load = 6412 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6413 MemOpChains.push_back(Load.getValue(1)); 6414 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6415 ArgOffset += PtrByteSize; 6416 } else { 6417 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6418 break; 6419 } 6420 } 6421 continue; 6422 } 6423 6424 switch (Arg.getSimpleValueType().SimpleTy) { 6425 default: llvm_unreachable("Unexpected ValueType for argument!"); 6426 case MVT::i1: 6427 case MVT::i32: 6428 case MVT::i64: 6429 if (GPR_idx != NumGPRs) { 6430 if (Arg.getValueType() == MVT::i1) 6431 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6432 6433 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6434 } else { 6435 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6436 isPPC64, isTailCall, false, MemOpChains, 6437 TailCallArguments, dl); 6438 } 6439 ArgOffset += PtrByteSize; 6440 break; 6441 case MVT::f32: 6442 case MVT::f64: 6443 if (FPR_idx != NumFPRs) { 6444 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6445 6446 if (isVarArg) { 6447 SDValue Store = 6448 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6449 MemOpChains.push_back(Store); 6450 6451 // Float varargs are always shadowed in available integer registers 6452 if (GPR_idx != NumGPRs) { 6453 SDValue Load = 6454 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6455 MemOpChains.push_back(Load.getValue(1)); 6456 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6457 } 6458 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6459 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6460 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6461 SDValue Load = 6462 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6463 MemOpChains.push_back(Load.getValue(1)); 6464 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6465 } 6466 } else { 6467 // If we have any FPRs remaining, we may also have GPRs remaining. 6468 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6469 // GPRs. 6470 if (GPR_idx != NumGPRs) 6471 ++GPR_idx; 6472 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6473 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6474 ++GPR_idx; 6475 } 6476 } else 6477 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6478 isPPC64, isTailCall, false, MemOpChains, 6479 TailCallArguments, dl); 6480 if (isPPC64) 6481 ArgOffset += 8; 6482 else 6483 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6484 break; 6485 case MVT::v4f32: 6486 case MVT::v4i32: 6487 case MVT::v8i16: 6488 case MVT::v16i8: 6489 if (isVarArg) { 6490 // These go aligned on the stack, or in the corresponding R registers 6491 // when within range. The Darwin PPC ABI doc claims they also go in 6492 // V registers; in fact gcc does this only for arguments that are 6493 // prototyped, not for those that match the ... We do it for all 6494 // arguments, seems to work. 6495 while (ArgOffset % 16 !=0) { 6496 ArgOffset += PtrByteSize; 6497 if (GPR_idx != NumGPRs) 6498 GPR_idx++; 6499 } 6500 // We could elide this store in the case where the object fits 6501 // entirely in R registers. Maybe later. 6502 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6503 DAG.getConstant(ArgOffset, dl, PtrVT)); 6504 SDValue Store = 6505 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6506 MemOpChains.push_back(Store); 6507 if (VR_idx != NumVRs) { 6508 SDValue Load = 6509 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6510 MemOpChains.push_back(Load.getValue(1)); 6511 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6512 } 6513 ArgOffset += 16; 6514 for (unsigned i=0; i<16; i+=PtrByteSize) { 6515 if (GPR_idx == NumGPRs) 6516 break; 6517 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6518 DAG.getConstant(i, dl, PtrVT)); 6519 SDValue Load = 6520 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6521 MemOpChains.push_back(Load.getValue(1)); 6522 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6523 } 6524 break; 6525 } 6526 6527 // Non-varargs Altivec params generally go in registers, but have 6528 // stack space allocated at the end. 6529 if (VR_idx != NumVRs) { 6530 // Doesn't have GPR space allocated. 6531 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6532 } else if (nAltivecParamsAtEnd==0) { 6533 // We are emitting Altivec params in order. 6534 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6535 isPPC64, isTailCall, true, MemOpChains, 6536 TailCallArguments, dl); 6537 ArgOffset += 16; 6538 } 6539 break; 6540 } 6541 } 6542 // If all Altivec parameters fit in registers, as they usually do, 6543 // they get stack space following the non-Altivec parameters. We 6544 // don't track this here because nobody below needs it. 6545 // If there are more Altivec parameters than fit in registers emit 6546 // the stores here. 6547 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6548 unsigned j = 0; 6549 // Offset is aligned; skip 1st 12 params which go in V registers. 6550 ArgOffset = ((ArgOffset+15)/16)*16; 6551 ArgOffset += 12*16; 6552 for (unsigned i = 0; i != NumOps; ++i) { 6553 SDValue Arg = OutVals[i]; 6554 EVT ArgType = Outs[i].VT; 6555 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6556 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6557 if (++j > NumVRs) { 6558 SDValue PtrOff; 6559 // We are emitting Altivec params in order. 6560 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6561 isPPC64, isTailCall, true, MemOpChains, 6562 TailCallArguments, dl); 6563 ArgOffset += 16; 6564 } 6565 } 6566 } 6567 } 6568 6569 if (!MemOpChains.empty()) 6570 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6571 6572 // On Darwin, R12 must contain the address of an indirect callee. This does 6573 // not mean the MTCTR instruction must use R12; it's easier to model this as 6574 // an extra parameter, so do that. 6575 if (!isTailCall && 6576 !isFunctionGlobalAddress(Callee) && 6577 !isa<ExternalSymbolSDNode>(Callee) && 6578 !isBLACompatibleAddress(Callee, DAG)) 6579 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6580 PPC::R12), Callee)); 6581 6582 // Build a sequence of copy-to-reg nodes chained together with token chain 6583 // and flag operands which copy the outgoing args into the appropriate regs. 6584 SDValue InFlag; 6585 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6586 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6587 RegsToPass[i].second, InFlag); 6588 InFlag = Chain.getValue(1); 6589 } 6590 6591 if (isTailCall) 6592 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6593 TailCallArguments); 6594 6595 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6596 /* unused except on PPC64 ELFv1 */ false, DAG, 6597 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6598 NumBytes, Ins, InVals, CS); 6599 } 6600 6601 bool 6602 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6603 MachineFunction &MF, bool isVarArg, 6604 const SmallVectorImpl<ISD::OutputArg> &Outs, 6605 LLVMContext &Context) const { 6606 SmallVector<CCValAssign, 16> RVLocs; 6607 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6608 return CCInfo.CheckReturn( 6609 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6610 ? RetCC_PPC_Cold 6611 : RetCC_PPC); 6612 } 6613 6614 SDValue 6615 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6616 bool isVarArg, 6617 const SmallVectorImpl<ISD::OutputArg> &Outs, 6618 const SmallVectorImpl<SDValue> &OutVals, 6619 const SDLoc &dl, SelectionDAG &DAG) const { 6620 SmallVector<CCValAssign, 16> RVLocs; 6621 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6622 *DAG.getContext()); 6623 CCInfo.AnalyzeReturn(Outs, 6624 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6625 ? RetCC_PPC_Cold 6626 : RetCC_PPC); 6627 6628 SDValue Flag; 6629 SmallVector<SDValue, 4> RetOps(1, Chain); 6630 6631 // Copy the result values into the output registers. 6632 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6633 CCValAssign &VA = RVLocs[i]; 6634 assert(VA.isRegLoc() && "Can only return in registers!"); 6635 6636 SDValue Arg = OutVals[i]; 6637 6638 switch (VA.getLocInfo()) { 6639 default: llvm_unreachable("Unknown loc info!"); 6640 case CCValAssign::Full: break; 6641 case CCValAssign::AExt: 6642 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6643 break; 6644 case CCValAssign::ZExt: 6645 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6646 break; 6647 case CCValAssign::SExt: 6648 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6649 break; 6650 } 6651 6652 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6653 Flag = Chain.getValue(1); 6654 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6655 } 6656 6657 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6658 const MCPhysReg *I = 6659 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6660 if (I) { 6661 for (; *I; ++I) { 6662 6663 if (PPC::G8RCRegClass.contains(*I)) 6664 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6665 else if (PPC::F8RCRegClass.contains(*I)) 6666 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6667 else if (PPC::CRRCRegClass.contains(*I)) 6668 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6669 else if (PPC::VRRCRegClass.contains(*I)) 6670 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6671 else 6672 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6673 } 6674 } 6675 6676 RetOps[0] = Chain; // Update chain. 6677 6678 // Add the flag if we have it. 6679 if (Flag.getNode()) 6680 RetOps.push_back(Flag); 6681 6682 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6683 } 6684 6685 SDValue 6686 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6687 SelectionDAG &DAG) const { 6688 SDLoc dl(Op); 6689 6690 // Get the correct type for integers. 6691 EVT IntVT = Op.getValueType(); 6692 6693 // Get the inputs. 6694 SDValue Chain = Op.getOperand(0); 6695 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6696 // Build a DYNAREAOFFSET node. 6697 SDValue Ops[2] = {Chain, FPSIdx}; 6698 SDVTList VTs = DAG.getVTList(IntVT); 6699 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6700 } 6701 6702 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6703 SelectionDAG &DAG) const { 6704 // When we pop the dynamic allocation we need to restore the SP link. 6705 SDLoc dl(Op); 6706 6707 // Get the correct type for pointers. 6708 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6709 6710 // Construct the stack pointer operand. 6711 bool isPPC64 = Subtarget.isPPC64(); 6712 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6713 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6714 6715 // Get the operands for the STACKRESTORE. 6716 SDValue Chain = Op.getOperand(0); 6717 SDValue SaveSP = Op.getOperand(1); 6718 6719 // Load the old link SP. 6720 SDValue LoadLinkSP = 6721 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6722 6723 // Restore the stack pointer. 6724 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6725 6726 // Store the old link SP. 6727 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6728 } 6729 6730 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6731 MachineFunction &MF = DAG.getMachineFunction(); 6732 bool isPPC64 = Subtarget.isPPC64(); 6733 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6734 6735 // Get current frame pointer save index. The users of this index will be 6736 // primarily DYNALLOC instructions. 6737 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6738 int RASI = FI->getReturnAddrSaveIndex(); 6739 6740 // If the frame pointer save index hasn't been defined yet. 6741 if (!RASI) { 6742 // Find out what the fix offset of the frame pointer save area. 6743 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6744 // Allocate the frame index for frame pointer save area. 6745 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6746 // Save the result. 6747 FI->setReturnAddrSaveIndex(RASI); 6748 } 6749 return DAG.getFrameIndex(RASI, PtrVT); 6750 } 6751 6752 SDValue 6753 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6754 MachineFunction &MF = DAG.getMachineFunction(); 6755 bool isPPC64 = Subtarget.isPPC64(); 6756 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6757 6758 // Get current frame pointer save index. The users of this index will be 6759 // primarily DYNALLOC instructions. 6760 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6761 int FPSI = FI->getFramePointerSaveIndex(); 6762 6763 // If the frame pointer save index hasn't been defined yet. 6764 if (!FPSI) { 6765 // Find out what the fix offset of the frame pointer save area. 6766 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6767 // Allocate the frame index for frame pointer save area. 6768 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6769 // Save the result. 6770 FI->setFramePointerSaveIndex(FPSI); 6771 } 6772 return DAG.getFrameIndex(FPSI, PtrVT); 6773 } 6774 6775 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6776 SelectionDAG &DAG) const { 6777 // Get the inputs. 6778 SDValue Chain = Op.getOperand(0); 6779 SDValue Size = Op.getOperand(1); 6780 SDLoc dl(Op); 6781 6782 // Get the correct type for pointers. 6783 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6784 // Negate the size. 6785 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6786 DAG.getConstant(0, dl, PtrVT), Size); 6787 // Construct a node for the frame pointer save index. 6788 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6789 // Build a DYNALLOC node. 6790 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6791 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6792 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6793 } 6794 6795 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6796 SelectionDAG &DAG) const { 6797 MachineFunction &MF = DAG.getMachineFunction(); 6798 6799 bool isPPC64 = Subtarget.isPPC64(); 6800 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6801 6802 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6803 return DAG.getFrameIndex(FI, PtrVT); 6804 } 6805 6806 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6807 SelectionDAG &DAG) const { 6808 SDLoc DL(Op); 6809 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6810 DAG.getVTList(MVT::i32, MVT::Other), 6811 Op.getOperand(0), Op.getOperand(1)); 6812 } 6813 6814 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6815 SelectionDAG &DAG) const { 6816 SDLoc DL(Op); 6817 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6818 Op.getOperand(0), Op.getOperand(1)); 6819 } 6820 6821 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6822 if (Op.getValueType().isVector()) 6823 return LowerVectorLoad(Op, DAG); 6824 6825 assert(Op.getValueType() == MVT::i1 && 6826 "Custom lowering only for i1 loads"); 6827 6828 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6829 6830 SDLoc dl(Op); 6831 LoadSDNode *LD = cast<LoadSDNode>(Op); 6832 6833 SDValue Chain = LD->getChain(); 6834 SDValue BasePtr = LD->getBasePtr(); 6835 MachineMemOperand *MMO = LD->getMemOperand(); 6836 6837 SDValue NewLD = 6838 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6839 BasePtr, MVT::i8, MMO); 6840 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6841 6842 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6843 return DAG.getMergeValues(Ops, dl); 6844 } 6845 6846 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6847 if (Op.getOperand(1).getValueType().isVector()) 6848 return LowerVectorStore(Op, DAG); 6849 6850 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6851 "Custom lowering only for i1 stores"); 6852 6853 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6854 6855 SDLoc dl(Op); 6856 StoreSDNode *ST = cast<StoreSDNode>(Op); 6857 6858 SDValue Chain = ST->getChain(); 6859 SDValue BasePtr = ST->getBasePtr(); 6860 SDValue Value = ST->getValue(); 6861 MachineMemOperand *MMO = ST->getMemOperand(); 6862 6863 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6864 Value); 6865 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6866 } 6867 6868 // FIXME: Remove this once the ANDI glue bug is fixed: 6869 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6870 assert(Op.getValueType() == MVT::i1 && 6871 "Custom lowering only for i1 results"); 6872 6873 SDLoc DL(Op); 6874 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6875 Op.getOperand(0)); 6876 } 6877 6878 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6879 /// possible. 6880 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6881 // Not FP? Not a fsel. 6882 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6883 !Op.getOperand(2).getValueType().isFloatingPoint()) 6884 return Op; 6885 6886 // We might be able to do better than this under some circumstances, but in 6887 // general, fsel-based lowering of select is a finite-math-only optimization. 6888 // For more information, see section F.3 of the 2.06 ISA specification. 6889 if (!DAG.getTarget().Options.NoInfsFPMath || 6890 !DAG.getTarget().Options.NoNaNsFPMath) 6891 return Op; 6892 // TODO: Propagate flags from the select rather than global settings. 6893 SDNodeFlags Flags; 6894 Flags.setNoInfs(true); 6895 Flags.setNoNaNs(true); 6896 6897 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6898 6899 EVT ResVT = Op.getValueType(); 6900 EVT CmpVT = Op.getOperand(0).getValueType(); 6901 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6902 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6903 SDLoc dl(Op); 6904 6905 // If the RHS of the comparison is a 0.0, we don't need to do the 6906 // subtraction at all. 6907 SDValue Sel1; 6908 if (isFloatingPointZero(RHS)) 6909 switch (CC) { 6910 default: break; // SETUO etc aren't handled by fsel. 6911 case ISD::SETNE: 6912 std::swap(TV, FV); 6913 LLVM_FALLTHROUGH; 6914 case ISD::SETEQ: 6915 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6916 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6917 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6918 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6919 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6920 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6921 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6922 case ISD::SETULT: 6923 case ISD::SETLT: 6924 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6925 LLVM_FALLTHROUGH; 6926 case ISD::SETOGE: 6927 case ISD::SETGE: 6928 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6929 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6930 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6931 case ISD::SETUGT: 6932 case ISD::SETGT: 6933 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6934 LLVM_FALLTHROUGH; 6935 case ISD::SETOLE: 6936 case ISD::SETLE: 6937 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6938 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6939 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6940 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6941 } 6942 6943 SDValue Cmp; 6944 switch (CC) { 6945 default: break; // SETUO etc aren't handled by fsel. 6946 case ISD::SETNE: 6947 std::swap(TV, FV); 6948 LLVM_FALLTHROUGH; 6949 case ISD::SETEQ: 6950 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6951 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6952 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6953 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6954 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6955 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6956 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6957 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6958 case ISD::SETULT: 6959 case ISD::SETLT: 6960 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6961 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6962 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6963 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6964 case ISD::SETOGE: 6965 case ISD::SETGE: 6966 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6967 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6968 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6969 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6970 case ISD::SETUGT: 6971 case ISD::SETGT: 6972 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6973 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6974 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6975 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6976 case ISD::SETOLE: 6977 case ISD::SETLE: 6978 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6979 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6980 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6981 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6982 } 6983 return Op; 6984 } 6985 6986 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 6987 SelectionDAG &DAG, 6988 const SDLoc &dl) const { 6989 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6990 SDValue Src = Op.getOperand(0); 6991 if (Src.getValueType() == MVT::f32) 6992 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6993 6994 SDValue Tmp; 6995 switch (Op.getSimpleValueType().SimpleTy) { 6996 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6997 case MVT::i32: 6998 Tmp = DAG.getNode( 6999 Op.getOpcode() == ISD::FP_TO_SINT 7000 ? PPCISD::FCTIWZ 7001 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7002 dl, MVT::f64, Src); 7003 break; 7004 case MVT::i64: 7005 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7006 "i64 FP_TO_UINT is supported only with FPCVT"); 7007 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7008 PPCISD::FCTIDUZ, 7009 dl, MVT::f64, Src); 7010 break; 7011 } 7012 7013 // Convert the FP value to an int value through memory. 7014 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7015 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7016 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7017 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7018 MachinePointerInfo MPI = 7019 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7020 7021 // Emit a store to the stack slot. 7022 SDValue Chain; 7023 if (i32Stack) { 7024 MachineFunction &MF = DAG.getMachineFunction(); 7025 MachineMemOperand *MMO = 7026 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7027 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7028 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7029 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7030 } else 7031 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7032 7033 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7034 // add in a bias on big endian. 7035 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7036 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7037 DAG.getConstant(4, dl, FIPtr.getValueType())); 7038 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7039 } 7040 7041 RLI.Chain = Chain; 7042 RLI.Ptr = FIPtr; 7043 RLI.MPI = MPI; 7044 } 7045 7046 /// Custom lowers floating point to integer conversions to use 7047 /// the direct move instructions available in ISA 2.07 to avoid the 7048 /// need for load/store combinations. 7049 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7050 SelectionDAG &DAG, 7051 const SDLoc &dl) const { 7052 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7053 SDValue Src = Op.getOperand(0); 7054 7055 if (Src.getValueType() == MVT::f32) 7056 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7057 7058 SDValue Tmp; 7059 switch (Op.getSimpleValueType().SimpleTy) { 7060 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7061 case MVT::i32: 7062 Tmp = DAG.getNode( 7063 Op.getOpcode() == ISD::FP_TO_SINT 7064 ? PPCISD::FCTIWZ 7065 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7066 dl, MVT::f64, Src); 7067 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7068 break; 7069 case MVT::i64: 7070 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7071 "i64 FP_TO_UINT is supported only with FPCVT"); 7072 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7073 PPCISD::FCTIDUZ, 7074 dl, MVT::f64, Src); 7075 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7076 break; 7077 } 7078 return Tmp; 7079 } 7080 7081 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7082 const SDLoc &dl) const { 7083 7084 // FP to INT conversions are legal for f128. 7085 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7086 return Op; 7087 7088 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7089 // PPC (the libcall is not available). 7090 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7091 if (Op.getValueType() == MVT::i32) { 7092 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7093 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7094 MVT::f64, Op.getOperand(0), 7095 DAG.getIntPtrConstant(0, dl)); 7096 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7097 MVT::f64, Op.getOperand(0), 7098 DAG.getIntPtrConstant(1, dl)); 7099 7100 // Add the two halves of the long double in round-to-zero mode. 7101 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7102 7103 // Now use a smaller FP_TO_SINT. 7104 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7105 } 7106 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7107 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7108 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7109 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7110 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7111 // FIXME: generated code sucks. 7112 // TODO: Are there fast-math-flags to propagate to this FSUB? 7113 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7114 Op.getOperand(0), Tmp); 7115 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7116 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7117 DAG.getConstant(0x80000000, dl, MVT::i32)); 7118 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7119 Op.getOperand(0)); 7120 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7121 ISD::SETGE); 7122 } 7123 } 7124 7125 return SDValue(); 7126 } 7127 7128 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7129 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7130 7131 ReuseLoadInfo RLI; 7132 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7133 7134 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7135 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7136 } 7137 7138 // We're trying to insert a regular store, S, and then a load, L. If the 7139 // incoming value, O, is a load, we might just be able to have our load use the 7140 // address used by O. However, we don't know if anything else will store to 7141 // that address before we can load from it. To prevent this situation, we need 7142 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7143 // the same chain operand as O, we create a token factor from the chain results 7144 // of O and L, and we replace all uses of O's chain result with that token 7145 // factor (see spliceIntoChain below for this last part). 7146 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7147 ReuseLoadInfo &RLI, 7148 SelectionDAG &DAG, 7149 ISD::LoadExtType ET) const { 7150 SDLoc dl(Op); 7151 if (ET == ISD::NON_EXTLOAD && 7152 (Op.getOpcode() == ISD::FP_TO_UINT || 7153 Op.getOpcode() == ISD::FP_TO_SINT) && 7154 isOperationLegalOrCustom(Op.getOpcode(), 7155 Op.getOperand(0).getValueType())) { 7156 7157 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7158 return true; 7159 } 7160 7161 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7162 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7163 LD->isNonTemporal()) 7164 return false; 7165 if (LD->getMemoryVT() != MemVT) 7166 return false; 7167 7168 RLI.Ptr = LD->getBasePtr(); 7169 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7170 assert(LD->getAddressingMode() == ISD::PRE_INC && 7171 "Non-pre-inc AM on PPC?"); 7172 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7173 LD->getOffset()); 7174 } 7175 7176 RLI.Chain = LD->getChain(); 7177 RLI.MPI = LD->getPointerInfo(); 7178 RLI.IsDereferenceable = LD->isDereferenceable(); 7179 RLI.IsInvariant = LD->isInvariant(); 7180 RLI.Alignment = LD->getAlignment(); 7181 RLI.AAInfo = LD->getAAInfo(); 7182 RLI.Ranges = LD->getRanges(); 7183 7184 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7185 return true; 7186 } 7187 7188 // Given the head of the old chain, ResChain, insert a token factor containing 7189 // it and NewResChain, and make users of ResChain now be users of that token 7190 // factor. 7191 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7192 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7193 SDValue NewResChain, 7194 SelectionDAG &DAG) const { 7195 if (!ResChain) 7196 return; 7197 7198 SDLoc dl(NewResChain); 7199 7200 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7201 NewResChain, DAG.getUNDEF(MVT::Other)); 7202 assert(TF.getNode() != NewResChain.getNode() && 7203 "A new TF really is required here"); 7204 7205 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7206 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7207 } 7208 7209 /// Analyze profitability of direct move 7210 /// prefer float load to int load plus direct move 7211 /// when there is no integer use of int load 7212 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7213 SDNode *Origin = Op.getOperand(0).getNode(); 7214 if (Origin->getOpcode() != ISD::LOAD) 7215 return true; 7216 7217 // If there is no LXSIBZX/LXSIHZX, like Power8, 7218 // prefer direct move if the memory size is 1 or 2 bytes. 7219 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7220 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7221 return true; 7222 7223 for (SDNode::use_iterator UI = Origin->use_begin(), 7224 UE = Origin->use_end(); 7225 UI != UE; ++UI) { 7226 7227 // Only look at the users of the loaded value. 7228 if (UI.getUse().get().getResNo() != 0) 7229 continue; 7230 7231 if (UI->getOpcode() != ISD::SINT_TO_FP && 7232 UI->getOpcode() != ISD::UINT_TO_FP) 7233 return true; 7234 } 7235 7236 return false; 7237 } 7238 7239 /// Custom lowers integer to floating point conversions to use 7240 /// the direct move instructions available in ISA 2.07 to avoid the 7241 /// need for load/store combinations. 7242 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7243 SelectionDAG &DAG, 7244 const SDLoc &dl) const { 7245 assert((Op.getValueType() == MVT::f32 || 7246 Op.getValueType() == MVT::f64) && 7247 "Invalid floating point type as target of conversion"); 7248 assert(Subtarget.hasFPCVT() && 7249 "Int to FP conversions with direct moves require FPCVT"); 7250 SDValue FP; 7251 SDValue Src = Op.getOperand(0); 7252 bool SinglePrec = Op.getValueType() == MVT::f32; 7253 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7254 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7255 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7256 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7257 7258 if (WordInt) { 7259 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7260 dl, MVT::f64, Src); 7261 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7262 } 7263 else { 7264 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7265 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7266 } 7267 7268 return FP; 7269 } 7270 7271 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7272 7273 EVT VecVT = Vec.getValueType(); 7274 assert(VecVT.isVector() && "Expected a vector type."); 7275 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7276 7277 EVT EltVT = VecVT.getVectorElementType(); 7278 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7279 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7280 7281 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7282 SmallVector<SDValue, 16> Ops(NumConcat); 7283 Ops[0] = Vec; 7284 SDValue UndefVec = DAG.getUNDEF(VecVT); 7285 for (unsigned i = 1; i < NumConcat; ++i) 7286 Ops[i] = UndefVec; 7287 7288 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7289 } 7290 7291 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, 7292 SelectionDAG &DAG, 7293 const SDLoc &dl) const { 7294 7295 unsigned Opc = Op.getOpcode(); 7296 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7297 "Unexpected conversion type"); 7298 assert(Op.getValueType() == MVT::v2f64 && "Supports v2f64 only."); 7299 7300 // CPU's prior to P9 don't have a way to sign-extend in vectors. 7301 bool SignedConv = Opc == ISD::SINT_TO_FP; 7302 if (SignedConv && !Subtarget.hasP9Altivec()) 7303 return SDValue(); 7304 7305 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7306 EVT WideVT = Wide.getValueType(); 7307 unsigned WideNumElts = WideVT.getVectorNumElements(); 7308 7309 SmallVector<int, 16> ShuffV; 7310 for (unsigned i = 0; i < WideNumElts; ++i) 7311 ShuffV.push_back(i + WideNumElts); 7312 7313 if (Subtarget.isLittleEndian()) { 7314 ShuffV[0] = 0; 7315 ShuffV[WideNumElts / 2] = 1; 7316 } 7317 else { 7318 ShuffV[WideNumElts / 2 - 1] = 0; 7319 ShuffV[WideNumElts - 1] = 1; 7320 } 7321 7322 SDValue ShuffleSrc2 = SignedConv ? DAG.getUNDEF(WideVT) : 7323 DAG.getConstant(0, dl, WideVT); 7324 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7325 unsigned ExtendOp = SignedConv ? (unsigned) PPCISD::SExtVElems : 7326 (unsigned) ISD::BITCAST; 7327 SDValue Extend = DAG.getNode(ExtendOp, dl, MVT::v2i64, Arrange); 7328 7329 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7330 } 7331 7332 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7333 SelectionDAG &DAG) const { 7334 SDLoc dl(Op); 7335 7336 if (Op.getValueType() == MVT::v2f64 && 7337 Op.getOperand(0).getValueType() == MVT::v2i16) 7338 return LowerINT_TO_FPVector(Op, DAG, dl); 7339 7340 // Conversions to f128 are legal. 7341 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7342 return Op; 7343 7344 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7345 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7346 return SDValue(); 7347 7348 SDValue Value = Op.getOperand(0); 7349 // The values are now known to be -1 (false) or 1 (true). To convert this 7350 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7351 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7352 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7353 7354 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7355 7356 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7357 7358 if (Op.getValueType() != MVT::v4f64) 7359 Value = DAG.getNode(ISD::FP_ROUND, dl, 7360 Op.getValueType(), Value, 7361 DAG.getIntPtrConstant(1, dl)); 7362 return Value; 7363 } 7364 7365 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7366 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7367 return SDValue(); 7368 7369 if (Op.getOperand(0).getValueType() == MVT::i1) 7370 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7371 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7372 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7373 7374 // If we have direct moves, we can do all the conversion, skip the store/load 7375 // however, without FPCVT we can't do most conversions. 7376 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7377 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7378 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7379 7380 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7381 "UINT_TO_FP is supported only with FPCVT"); 7382 7383 // If we have FCFIDS, then use it when converting to single-precision. 7384 // Otherwise, convert to double-precision and then round. 7385 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7386 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7387 : PPCISD::FCFIDS) 7388 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7389 : PPCISD::FCFID); 7390 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7391 ? MVT::f32 7392 : MVT::f64; 7393 7394 if (Op.getOperand(0).getValueType() == MVT::i64) { 7395 SDValue SINT = Op.getOperand(0); 7396 // When converting to single-precision, we actually need to convert 7397 // to double-precision first and then round to single-precision. 7398 // To avoid double-rounding effects during that operation, we have 7399 // to prepare the input operand. Bits that might be truncated when 7400 // converting to double-precision are replaced by a bit that won't 7401 // be lost at this stage, but is below the single-precision rounding 7402 // position. 7403 // 7404 // However, if -enable-unsafe-fp-math is in effect, accept double 7405 // rounding to avoid the extra overhead. 7406 if (Op.getValueType() == MVT::f32 && 7407 !Subtarget.hasFPCVT() && 7408 !DAG.getTarget().Options.UnsafeFPMath) { 7409 7410 // Twiddle input to make sure the low 11 bits are zero. (If this 7411 // is the case, we are guaranteed the value will fit into the 53 bit 7412 // mantissa of an IEEE double-precision value without rounding.) 7413 // If any of those low 11 bits were not zero originally, make sure 7414 // bit 12 (value 2048) is set instead, so that the final rounding 7415 // to single-precision gets the correct result. 7416 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7417 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7418 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7419 Round, DAG.getConstant(2047, dl, MVT::i64)); 7420 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7421 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7422 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7423 7424 // However, we cannot use that value unconditionally: if the magnitude 7425 // of the input value is small, the bit-twiddling we did above might 7426 // end up visibly changing the output. Fortunately, in that case, we 7427 // don't need to twiddle bits since the original input will convert 7428 // exactly to double-precision floating-point already. Therefore, 7429 // construct a conditional to use the original value if the top 11 7430 // bits are all sign-bit copies, and use the rounded value computed 7431 // above otherwise. 7432 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7433 SINT, DAG.getConstant(53, dl, MVT::i32)); 7434 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7435 Cond, DAG.getConstant(1, dl, MVT::i64)); 7436 Cond = DAG.getSetCC(dl, MVT::i32, 7437 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7438 7439 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7440 } 7441 7442 ReuseLoadInfo RLI; 7443 SDValue Bits; 7444 7445 MachineFunction &MF = DAG.getMachineFunction(); 7446 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7447 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7448 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7449 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7450 } else if (Subtarget.hasLFIWAX() && 7451 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7452 MachineMemOperand *MMO = 7453 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7454 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7455 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7456 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7457 DAG.getVTList(MVT::f64, MVT::Other), 7458 Ops, MVT::i32, MMO); 7459 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7460 } else if (Subtarget.hasFPCVT() && 7461 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7462 MachineMemOperand *MMO = 7463 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7464 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7465 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7466 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7467 DAG.getVTList(MVT::f64, MVT::Other), 7468 Ops, MVT::i32, MMO); 7469 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7470 } else if (((Subtarget.hasLFIWAX() && 7471 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7472 (Subtarget.hasFPCVT() && 7473 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7474 SINT.getOperand(0).getValueType() == MVT::i32) { 7475 MachineFrameInfo &MFI = MF.getFrameInfo(); 7476 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7477 7478 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7479 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7480 7481 SDValue Store = 7482 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7483 MachinePointerInfo::getFixedStack( 7484 DAG.getMachineFunction(), FrameIdx)); 7485 7486 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7487 "Expected an i32 store"); 7488 7489 RLI.Ptr = FIdx; 7490 RLI.Chain = Store; 7491 RLI.MPI = 7492 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7493 RLI.Alignment = 4; 7494 7495 MachineMemOperand *MMO = 7496 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7497 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7498 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7499 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7500 PPCISD::LFIWZX : PPCISD::LFIWAX, 7501 dl, DAG.getVTList(MVT::f64, MVT::Other), 7502 Ops, MVT::i32, MMO); 7503 } else 7504 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7505 7506 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7507 7508 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7509 FP = DAG.getNode(ISD::FP_ROUND, dl, 7510 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7511 return FP; 7512 } 7513 7514 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7515 "Unhandled INT_TO_FP type in custom expander!"); 7516 // Since we only generate this in 64-bit mode, we can take advantage of 7517 // 64-bit registers. In particular, sign extend the input value into the 7518 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7519 // then lfd it and fcfid it. 7520 MachineFunction &MF = DAG.getMachineFunction(); 7521 MachineFrameInfo &MFI = MF.getFrameInfo(); 7522 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7523 7524 SDValue Ld; 7525 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7526 ReuseLoadInfo RLI; 7527 bool ReusingLoad; 7528 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7529 DAG))) { 7530 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7531 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7532 7533 SDValue Store = 7534 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7535 MachinePointerInfo::getFixedStack( 7536 DAG.getMachineFunction(), FrameIdx)); 7537 7538 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7539 "Expected an i32 store"); 7540 7541 RLI.Ptr = FIdx; 7542 RLI.Chain = Store; 7543 RLI.MPI = 7544 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7545 RLI.Alignment = 4; 7546 } 7547 7548 MachineMemOperand *MMO = 7549 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7550 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7551 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7552 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7553 PPCISD::LFIWZX : PPCISD::LFIWAX, 7554 dl, DAG.getVTList(MVT::f64, MVT::Other), 7555 Ops, MVT::i32, MMO); 7556 if (ReusingLoad) 7557 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7558 } else { 7559 assert(Subtarget.isPPC64() && 7560 "i32->FP without LFIWAX supported only on PPC64"); 7561 7562 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7563 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7564 7565 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7566 Op.getOperand(0)); 7567 7568 // STD the extended value into the stack slot. 7569 SDValue Store = DAG.getStore( 7570 DAG.getEntryNode(), dl, Ext64, FIdx, 7571 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7572 7573 // Load the value as a double. 7574 Ld = DAG.getLoad( 7575 MVT::f64, dl, Store, FIdx, 7576 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7577 } 7578 7579 // FCFID it and return it. 7580 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7581 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7582 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7583 DAG.getIntPtrConstant(0, dl)); 7584 return FP; 7585 } 7586 7587 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7588 SelectionDAG &DAG) const { 7589 SDLoc dl(Op); 7590 /* 7591 The rounding mode is in bits 30:31 of FPSR, and has the following 7592 settings: 7593 00 Round to nearest 7594 01 Round to 0 7595 10 Round to +inf 7596 11 Round to -inf 7597 7598 FLT_ROUNDS, on the other hand, expects the following: 7599 -1 Undefined 7600 0 Round to 0 7601 1 Round to nearest 7602 2 Round to +inf 7603 3 Round to -inf 7604 7605 To perform the conversion, we do: 7606 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7607 */ 7608 7609 MachineFunction &MF = DAG.getMachineFunction(); 7610 EVT VT = Op.getValueType(); 7611 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7612 7613 // Save FP Control Word to register 7614 EVT NodeTys[] = { 7615 MVT::f64, // return register 7616 MVT::Glue // unused in this context 7617 }; 7618 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7619 7620 // Save FP register to stack slot 7621 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7622 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7623 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7624 MachinePointerInfo()); 7625 7626 // Load FP Control Word from low 32 bits of stack slot. 7627 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7628 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7629 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7630 7631 // Transform as necessary 7632 SDValue CWD1 = 7633 DAG.getNode(ISD::AND, dl, MVT::i32, 7634 CWD, DAG.getConstant(3, dl, MVT::i32)); 7635 SDValue CWD2 = 7636 DAG.getNode(ISD::SRL, dl, MVT::i32, 7637 DAG.getNode(ISD::AND, dl, MVT::i32, 7638 DAG.getNode(ISD::XOR, dl, MVT::i32, 7639 CWD, DAG.getConstant(3, dl, MVT::i32)), 7640 DAG.getConstant(3, dl, MVT::i32)), 7641 DAG.getConstant(1, dl, MVT::i32)); 7642 7643 SDValue RetVal = 7644 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7645 7646 return DAG.getNode((VT.getSizeInBits() < 16 ? 7647 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7648 } 7649 7650 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7651 EVT VT = Op.getValueType(); 7652 unsigned BitWidth = VT.getSizeInBits(); 7653 SDLoc dl(Op); 7654 assert(Op.getNumOperands() == 3 && 7655 VT == Op.getOperand(1).getValueType() && 7656 "Unexpected SHL!"); 7657 7658 // Expand into a bunch of logical ops. Note that these ops 7659 // depend on the PPC behavior for oversized shift amounts. 7660 SDValue Lo = Op.getOperand(0); 7661 SDValue Hi = Op.getOperand(1); 7662 SDValue Amt = Op.getOperand(2); 7663 EVT AmtVT = Amt.getValueType(); 7664 7665 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7666 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7667 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7668 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7669 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7670 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7671 DAG.getConstant(-BitWidth, dl, AmtVT)); 7672 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7673 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7674 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7675 SDValue OutOps[] = { OutLo, OutHi }; 7676 return DAG.getMergeValues(OutOps, dl); 7677 } 7678 7679 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7680 EVT VT = Op.getValueType(); 7681 SDLoc dl(Op); 7682 unsigned BitWidth = VT.getSizeInBits(); 7683 assert(Op.getNumOperands() == 3 && 7684 VT == Op.getOperand(1).getValueType() && 7685 "Unexpected SRL!"); 7686 7687 // Expand into a bunch of logical ops. Note that these ops 7688 // depend on the PPC behavior for oversized shift amounts. 7689 SDValue Lo = Op.getOperand(0); 7690 SDValue Hi = Op.getOperand(1); 7691 SDValue Amt = Op.getOperand(2); 7692 EVT AmtVT = Amt.getValueType(); 7693 7694 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7695 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7696 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7697 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7698 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7699 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7700 DAG.getConstant(-BitWidth, dl, AmtVT)); 7701 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7702 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7703 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7704 SDValue OutOps[] = { OutLo, OutHi }; 7705 return DAG.getMergeValues(OutOps, dl); 7706 } 7707 7708 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7709 SDLoc dl(Op); 7710 EVT VT = Op.getValueType(); 7711 unsigned BitWidth = VT.getSizeInBits(); 7712 assert(Op.getNumOperands() == 3 && 7713 VT == Op.getOperand(1).getValueType() && 7714 "Unexpected SRA!"); 7715 7716 // Expand into a bunch of logical ops, followed by a select_cc. 7717 SDValue Lo = Op.getOperand(0); 7718 SDValue Hi = Op.getOperand(1); 7719 SDValue Amt = Op.getOperand(2); 7720 EVT AmtVT = Amt.getValueType(); 7721 7722 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7723 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7724 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7725 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7726 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7727 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7728 DAG.getConstant(-BitWidth, dl, AmtVT)); 7729 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7730 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7731 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7732 Tmp4, Tmp6, ISD::SETLE); 7733 SDValue OutOps[] = { OutLo, OutHi }; 7734 return DAG.getMergeValues(OutOps, dl); 7735 } 7736 7737 //===----------------------------------------------------------------------===// 7738 // Vector related lowering. 7739 // 7740 7741 /// BuildSplatI - Build a canonical splati of Val with an element size of 7742 /// SplatSize. Cast the result to VT. 7743 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7744 SelectionDAG &DAG, const SDLoc &dl) { 7745 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7746 7747 static const MVT VTys[] = { // canonical VT to use for each size. 7748 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7749 }; 7750 7751 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7752 7753 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7754 if (Val == -1) 7755 SplatSize = 1; 7756 7757 EVT CanonicalVT = VTys[SplatSize-1]; 7758 7759 // Build a canonical splat for this value. 7760 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7761 } 7762 7763 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7764 /// specified intrinsic ID. 7765 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7766 const SDLoc &dl, EVT DestVT = MVT::Other) { 7767 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7768 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7769 DAG.getConstant(IID, dl, MVT::i32), Op); 7770 } 7771 7772 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7773 /// specified intrinsic ID. 7774 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7775 SelectionDAG &DAG, const SDLoc &dl, 7776 EVT DestVT = MVT::Other) { 7777 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7778 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7779 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7780 } 7781 7782 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7783 /// specified intrinsic ID. 7784 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7785 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7786 EVT DestVT = MVT::Other) { 7787 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7788 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7789 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7790 } 7791 7792 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7793 /// amount. The result has the specified value type. 7794 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7795 SelectionDAG &DAG, const SDLoc &dl) { 7796 // Force LHS/RHS to be the right type. 7797 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7798 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7799 7800 int Ops[16]; 7801 for (unsigned i = 0; i != 16; ++i) 7802 Ops[i] = i + Amt; 7803 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7804 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7805 } 7806 7807 /// Do we have an efficient pattern in a .td file for this node? 7808 /// 7809 /// \param V - pointer to the BuildVectorSDNode being matched 7810 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7811 /// 7812 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7813 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7814 /// the opposite is true (expansion is beneficial) are: 7815 /// - The node builds a vector out of integers that are not 32 or 64-bits 7816 /// - The node builds a vector out of constants 7817 /// - The node is a "load-and-splat" 7818 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7819 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7820 bool HasDirectMove, 7821 bool HasP8Vector) { 7822 EVT VecVT = V->getValueType(0); 7823 bool RightType = VecVT == MVT::v2f64 || 7824 (HasP8Vector && VecVT == MVT::v4f32) || 7825 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7826 if (!RightType) 7827 return false; 7828 7829 bool IsSplat = true; 7830 bool IsLoad = false; 7831 SDValue Op0 = V->getOperand(0); 7832 7833 // This function is called in a block that confirms the node is not a constant 7834 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7835 // different constants. 7836 if (V->isConstant()) 7837 return false; 7838 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7839 if (V->getOperand(i).isUndef()) 7840 return false; 7841 // We want to expand nodes that represent load-and-splat even if the 7842 // loaded value is a floating point truncation or conversion to int. 7843 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7844 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7845 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7846 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7847 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7848 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7849 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7850 IsLoad = true; 7851 // If the operands are different or the input is not a load and has more 7852 // uses than just this BV node, then it isn't a splat. 7853 if (V->getOperand(i) != Op0 || 7854 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7855 IsSplat = false; 7856 } 7857 return !(IsSplat && IsLoad); 7858 } 7859 7860 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 7861 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 7862 7863 SDLoc dl(Op); 7864 SDValue Op0 = Op->getOperand(0); 7865 7866 if (!EnableQuadPrecision || 7867 (Op.getValueType() != MVT::f128 ) || 7868 (Op0.getOpcode() != ISD::BUILD_PAIR) || 7869 (Op0.getOperand(0).getValueType() != MVT::i64) || 7870 (Op0.getOperand(1).getValueType() != MVT::i64)) 7871 return SDValue(); 7872 7873 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 7874 Op0.getOperand(1)); 7875 } 7876 7877 // If this is a case we can't handle, return null and let the default 7878 // expansion code take care of it. If we CAN select this case, and if it 7879 // selects to a single instruction, return Op. Otherwise, if we can codegen 7880 // this case more efficiently than a constant pool load, lower it to the 7881 // sequence of ops that should be used. 7882 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7883 SelectionDAG &DAG) const { 7884 SDLoc dl(Op); 7885 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7886 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7887 7888 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7889 // We first build an i32 vector, load it into a QPX register, 7890 // then convert it to a floating-point vector and compare it 7891 // to a zero vector to get the boolean result. 7892 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7893 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7894 MachinePointerInfo PtrInfo = 7895 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7896 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7897 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7898 7899 assert(BVN->getNumOperands() == 4 && 7900 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7901 7902 bool IsConst = true; 7903 for (unsigned i = 0; i < 4; ++i) { 7904 if (BVN->getOperand(i).isUndef()) continue; 7905 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7906 IsConst = false; 7907 break; 7908 } 7909 } 7910 7911 if (IsConst) { 7912 Constant *One = 7913 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7914 Constant *NegOne = 7915 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7916 7917 Constant *CV[4]; 7918 for (unsigned i = 0; i < 4; ++i) { 7919 if (BVN->getOperand(i).isUndef()) 7920 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7921 else if (isNullConstant(BVN->getOperand(i))) 7922 CV[i] = NegOne; 7923 else 7924 CV[i] = One; 7925 } 7926 7927 Constant *CP = ConstantVector::get(CV); 7928 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7929 16 /* alignment */); 7930 7931 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7932 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7933 return DAG.getMemIntrinsicNode( 7934 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7935 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7936 } 7937 7938 SmallVector<SDValue, 4> Stores; 7939 for (unsigned i = 0; i < 4; ++i) { 7940 if (BVN->getOperand(i).isUndef()) continue; 7941 7942 unsigned Offset = 4*i; 7943 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7944 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7945 7946 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7947 if (StoreSize > 4) { 7948 Stores.push_back( 7949 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7950 PtrInfo.getWithOffset(Offset), MVT::i32)); 7951 } else { 7952 SDValue StoreValue = BVN->getOperand(i); 7953 if (StoreSize < 4) 7954 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7955 7956 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7957 PtrInfo.getWithOffset(Offset))); 7958 } 7959 } 7960 7961 SDValue StoreChain; 7962 if (!Stores.empty()) 7963 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7964 else 7965 StoreChain = DAG.getEntryNode(); 7966 7967 // Now load from v4i32 into the QPX register; this will extend it to 7968 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7969 // is typed as v4f64 because the QPX register integer states are not 7970 // explicitly represented. 7971 7972 SDValue Ops[] = {StoreChain, 7973 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7974 FIdx}; 7975 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7976 7977 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 7978 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7979 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7980 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 7981 LoadedVect); 7982 7983 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 7984 7985 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 7986 } 7987 7988 // All other QPX vectors are handled by generic code. 7989 if (Subtarget.hasQPX()) 7990 return SDValue(); 7991 7992 // Check if this is a splat of a constant value. 7993 APInt APSplatBits, APSplatUndef; 7994 unsigned SplatBitSize; 7995 bool HasAnyUndefs; 7996 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 7997 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 7998 SplatBitSize > 32) { 7999 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8000 // lowered to VSX instructions under certain conditions. 8001 // Without VSX, there is no pattern more efficient than expanding the node. 8002 if (Subtarget.hasVSX() && 8003 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8004 Subtarget.hasP8Vector())) 8005 return Op; 8006 return SDValue(); 8007 } 8008 8009 unsigned SplatBits = APSplatBits.getZExtValue(); 8010 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8011 unsigned SplatSize = SplatBitSize / 8; 8012 8013 // First, handle single instruction cases. 8014 8015 // All zeros? 8016 if (SplatBits == 0) { 8017 // Canonicalize all zero vectors to be v4i32. 8018 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8019 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8020 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8021 } 8022 return Op; 8023 } 8024 8025 // We have XXSPLTIB for constant splats one byte wide 8026 if (Subtarget.hasP9Vector() && SplatSize == 1) { 8027 // This is a splat of 1-byte elements with some elements potentially undef. 8028 // Rather than trying to match undef in the SDAG patterns, ensure that all 8029 // elements are the same constant. 8030 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 8031 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 8032 dl, MVT::i32)); 8033 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 8034 if (Op.getValueType() != MVT::v16i8) 8035 return DAG.getBitcast(Op.getValueType(), NewBV); 8036 return NewBV; 8037 } 8038 8039 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 8040 // detect that constant splats like v8i16: 0xABAB are really just splats 8041 // of a 1-byte constant. In this case, we need to convert the node to a 8042 // splat of v16i8 and a bitcast. 8043 if (Op.getValueType() != MVT::v16i8) 8044 return DAG.getBitcast(Op.getValueType(), 8045 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 8046 8047 return Op; 8048 } 8049 8050 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8051 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8052 (32-SplatBitSize)); 8053 if (SextVal >= -16 && SextVal <= 15) 8054 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8055 8056 // Two instruction sequences. 8057 8058 // If this value is in the range [-32,30] and is even, use: 8059 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8060 // If this value is in the range [17,31] and is odd, use: 8061 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8062 // If this value is in the range [-31,-17] and is odd, use: 8063 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8064 // Note the last two are three-instruction sequences. 8065 if (SextVal >= -32 && SextVal <= 31) { 8066 // To avoid having these optimizations undone by constant folding, 8067 // we convert to a pseudo that will be expanded later into one of 8068 // the above forms. 8069 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8070 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8071 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8072 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8073 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8074 if (VT == Op.getValueType()) 8075 return RetVal; 8076 else 8077 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8078 } 8079 8080 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8081 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8082 // for fneg/fabs. 8083 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8084 // Make -1 and vspltisw -1: 8085 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8086 8087 // Make the VSLW intrinsic, computing 0x8000_0000. 8088 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8089 OnesV, DAG, dl); 8090 8091 // xor by OnesV to invert it. 8092 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8093 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8094 } 8095 8096 // Check to see if this is a wide variety of vsplti*, binop self cases. 8097 static const signed char SplatCsts[] = { 8098 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8099 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8100 }; 8101 8102 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8103 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8104 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8105 int i = SplatCsts[idx]; 8106 8107 // Figure out what shift amount will be used by altivec if shifted by i in 8108 // this splat size. 8109 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8110 8111 // vsplti + shl self. 8112 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8113 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8114 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8115 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8116 Intrinsic::ppc_altivec_vslw 8117 }; 8118 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8119 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8120 } 8121 8122 // vsplti + srl self. 8123 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8124 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8125 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8126 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8127 Intrinsic::ppc_altivec_vsrw 8128 }; 8129 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8130 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8131 } 8132 8133 // vsplti + sra self. 8134 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8135 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8136 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8137 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8138 Intrinsic::ppc_altivec_vsraw 8139 }; 8140 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8141 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8142 } 8143 8144 // vsplti + rol self. 8145 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8146 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8147 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8148 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8149 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8150 Intrinsic::ppc_altivec_vrlw 8151 }; 8152 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8153 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8154 } 8155 8156 // t = vsplti c, result = vsldoi t, t, 1 8157 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8158 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8159 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8160 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8161 } 8162 // t = vsplti c, result = vsldoi t, t, 2 8163 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8164 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8165 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8166 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8167 } 8168 // t = vsplti c, result = vsldoi t, t, 3 8169 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8170 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8171 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8172 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8173 } 8174 } 8175 8176 return SDValue(); 8177 } 8178 8179 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8180 /// the specified operations to build the shuffle. 8181 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8182 SDValue RHS, SelectionDAG &DAG, 8183 const SDLoc &dl) { 8184 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8185 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8186 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8187 8188 enum { 8189 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8190 OP_VMRGHW, 8191 OP_VMRGLW, 8192 OP_VSPLTISW0, 8193 OP_VSPLTISW1, 8194 OP_VSPLTISW2, 8195 OP_VSPLTISW3, 8196 OP_VSLDOI4, 8197 OP_VSLDOI8, 8198 OP_VSLDOI12 8199 }; 8200 8201 if (OpNum == OP_COPY) { 8202 if (LHSID == (1*9+2)*9+3) return LHS; 8203 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8204 return RHS; 8205 } 8206 8207 SDValue OpLHS, OpRHS; 8208 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8209 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8210 8211 int ShufIdxs[16]; 8212 switch (OpNum) { 8213 default: llvm_unreachable("Unknown i32 permute!"); 8214 case OP_VMRGHW: 8215 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8216 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8217 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8218 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8219 break; 8220 case OP_VMRGLW: 8221 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8222 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8223 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8224 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8225 break; 8226 case OP_VSPLTISW0: 8227 for (unsigned i = 0; i != 16; ++i) 8228 ShufIdxs[i] = (i&3)+0; 8229 break; 8230 case OP_VSPLTISW1: 8231 for (unsigned i = 0; i != 16; ++i) 8232 ShufIdxs[i] = (i&3)+4; 8233 break; 8234 case OP_VSPLTISW2: 8235 for (unsigned i = 0; i != 16; ++i) 8236 ShufIdxs[i] = (i&3)+8; 8237 break; 8238 case OP_VSPLTISW3: 8239 for (unsigned i = 0; i != 16; ++i) 8240 ShufIdxs[i] = (i&3)+12; 8241 break; 8242 case OP_VSLDOI4: 8243 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8244 case OP_VSLDOI8: 8245 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8246 case OP_VSLDOI12: 8247 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8248 } 8249 EVT VT = OpLHS.getValueType(); 8250 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8251 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8252 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8253 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8254 } 8255 8256 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8257 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8258 /// SDValue. 8259 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8260 SelectionDAG &DAG) const { 8261 const unsigned BytesInVector = 16; 8262 bool IsLE = Subtarget.isLittleEndian(); 8263 SDLoc dl(N); 8264 SDValue V1 = N->getOperand(0); 8265 SDValue V2 = N->getOperand(1); 8266 unsigned ShiftElts = 0, InsertAtByte = 0; 8267 bool Swap = false; 8268 8269 // Shifts required to get the byte we want at element 7. 8270 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8271 0, 15, 14, 13, 12, 11, 10, 9}; 8272 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8273 1, 2, 3, 4, 5, 6, 7, 8}; 8274 8275 ArrayRef<int> Mask = N->getMask(); 8276 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8277 8278 // For each mask element, find out if we're just inserting something 8279 // from V2 into V1 or vice versa. 8280 // Possible permutations inserting an element from V2 into V1: 8281 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8282 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8283 // ... 8284 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8285 // Inserting from V1 into V2 will be similar, except mask range will be 8286 // [16,31]. 8287 8288 bool FoundCandidate = false; 8289 // If both vector operands for the shuffle are the same vector, the mask 8290 // will contain only elements from the first one and the second one will be 8291 // undef. 8292 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8293 // Go through the mask of half-words to find an element that's being moved 8294 // from one vector to the other. 8295 for (unsigned i = 0; i < BytesInVector; ++i) { 8296 unsigned CurrentElement = Mask[i]; 8297 // If 2nd operand is undefined, we should only look for element 7 in the 8298 // Mask. 8299 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8300 continue; 8301 8302 bool OtherElementsInOrder = true; 8303 // Examine the other elements in the Mask to see if they're in original 8304 // order. 8305 for (unsigned j = 0; j < BytesInVector; ++j) { 8306 if (j == i) 8307 continue; 8308 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8309 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8310 // in which we always assume we're always picking from the 1st operand. 8311 int MaskOffset = 8312 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8313 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8314 OtherElementsInOrder = false; 8315 break; 8316 } 8317 } 8318 // If other elements are in original order, we record the number of shifts 8319 // we need to get the element we want into element 7. Also record which byte 8320 // in the vector we should insert into. 8321 if (OtherElementsInOrder) { 8322 // If 2nd operand is undefined, we assume no shifts and no swapping. 8323 if (V2.isUndef()) { 8324 ShiftElts = 0; 8325 Swap = false; 8326 } else { 8327 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8328 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8329 : BigEndianShifts[CurrentElement & 0xF]; 8330 Swap = CurrentElement < BytesInVector; 8331 } 8332 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8333 FoundCandidate = true; 8334 break; 8335 } 8336 } 8337 8338 if (!FoundCandidate) 8339 return SDValue(); 8340 8341 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8342 // optionally with VECSHL if shift is required. 8343 if (Swap) 8344 std::swap(V1, V2); 8345 if (V2.isUndef()) 8346 V2 = V1; 8347 if (ShiftElts) { 8348 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8349 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8350 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8351 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8352 } 8353 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8354 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8355 } 8356 8357 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8358 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8359 /// SDValue. 8360 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8361 SelectionDAG &DAG) const { 8362 const unsigned NumHalfWords = 8; 8363 const unsigned BytesInVector = NumHalfWords * 2; 8364 // Check that the shuffle is on half-words. 8365 if (!isNByteElemShuffleMask(N, 2, 1)) 8366 return SDValue(); 8367 8368 bool IsLE = Subtarget.isLittleEndian(); 8369 SDLoc dl(N); 8370 SDValue V1 = N->getOperand(0); 8371 SDValue V2 = N->getOperand(1); 8372 unsigned ShiftElts = 0, InsertAtByte = 0; 8373 bool Swap = false; 8374 8375 // Shifts required to get the half-word we want at element 3. 8376 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8377 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8378 8379 uint32_t Mask = 0; 8380 uint32_t OriginalOrderLow = 0x1234567; 8381 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8382 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8383 // 32-bit space, only need 4-bit nibbles per element. 8384 for (unsigned i = 0; i < NumHalfWords; ++i) { 8385 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8386 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8387 } 8388 8389 // For each mask element, find out if we're just inserting something 8390 // from V2 into V1 or vice versa. Possible permutations inserting an element 8391 // from V2 into V1: 8392 // X, 1, 2, 3, 4, 5, 6, 7 8393 // 0, X, 2, 3, 4, 5, 6, 7 8394 // 0, 1, X, 3, 4, 5, 6, 7 8395 // 0, 1, 2, X, 4, 5, 6, 7 8396 // 0, 1, 2, 3, X, 5, 6, 7 8397 // 0, 1, 2, 3, 4, X, 6, 7 8398 // 0, 1, 2, 3, 4, 5, X, 7 8399 // 0, 1, 2, 3, 4, 5, 6, X 8400 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8401 8402 bool FoundCandidate = false; 8403 // Go through the mask of half-words to find an element that's being moved 8404 // from one vector to the other. 8405 for (unsigned i = 0; i < NumHalfWords; ++i) { 8406 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8407 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8408 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8409 uint32_t TargetOrder = 0x0; 8410 8411 // If both vector operands for the shuffle are the same vector, the mask 8412 // will contain only elements from the first one and the second one will be 8413 // undef. 8414 if (V2.isUndef()) { 8415 ShiftElts = 0; 8416 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8417 TargetOrder = OriginalOrderLow; 8418 Swap = false; 8419 // Skip if not the correct element or mask of other elements don't equal 8420 // to our expected order. 8421 if (MaskOneElt == VINSERTHSrcElem && 8422 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8423 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8424 FoundCandidate = true; 8425 break; 8426 } 8427 } else { // If both operands are defined. 8428 // Target order is [8,15] if the current mask is between [0,7]. 8429 TargetOrder = 8430 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8431 // Skip if mask of other elements don't equal our expected order. 8432 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8433 // We only need the last 3 bits for the number of shifts. 8434 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8435 : BigEndianShifts[MaskOneElt & 0x7]; 8436 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8437 Swap = MaskOneElt < NumHalfWords; 8438 FoundCandidate = true; 8439 break; 8440 } 8441 } 8442 } 8443 8444 if (!FoundCandidate) 8445 return SDValue(); 8446 8447 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8448 // optionally with VECSHL if shift is required. 8449 if (Swap) 8450 std::swap(V1, V2); 8451 if (V2.isUndef()) 8452 V2 = V1; 8453 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8454 if (ShiftElts) { 8455 // Double ShiftElts because we're left shifting on v16i8 type. 8456 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8457 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8458 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8459 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8460 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8461 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8462 } 8463 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8464 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8465 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8466 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8467 } 8468 8469 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8470 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8471 /// return the code it can be lowered into. Worst case, it can always be 8472 /// lowered into a vperm. 8473 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8474 SelectionDAG &DAG) const { 8475 SDLoc dl(Op); 8476 SDValue V1 = Op.getOperand(0); 8477 SDValue V2 = Op.getOperand(1); 8478 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8479 EVT VT = Op.getValueType(); 8480 bool isLittleEndian = Subtarget.isLittleEndian(); 8481 8482 unsigned ShiftElts, InsertAtByte; 8483 bool Swap = false; 8484 if (Subtarget.hasP9Vector() && 8485 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8486 isLittleEndian)) { 8487 if (Swap) 8488 std::swap(V1, V2); 8489 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8490 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8491 if (ShiftElts) { 8492 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8493 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8494 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8495 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8496 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8497 } 8498 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8499 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8500 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8501 } 8502 8503 if (Subtarget.hasP9Altivec()) { 8504 SDValue NewISDNode; 8505 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8506 return NewISDNode; 8507 8508 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8509 return NewISDNode; 8510 } 8511 8512 if (Subtarget.hasVSX() && 8513 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8514 if (Swap) 8515 std::swap(V1, V2); 8516 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8517 SDValue Conv2 = 8518 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8519 8520 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8521 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8522 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8523 } 8524 8525 if (Subtarget.hasVSX() && 8526 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8527 if (Swap) 8528 std::swap(V1, V2); 8529 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8530 SDValue Conv2 = 8531 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8532 8533 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8534 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8535 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8536 } 8537 8538 if (Subtarget.hasP9Vector()) { 8539 if (PPC::isXXBRHShuffleMask(SVOp)) { 8540 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8541 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8542 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8543 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8544 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8545 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8546 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8547 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8548 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8549 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8550 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8551 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8552 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8553 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8554 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8555 } 8556 } 8557 8558 if (Subtarget.hasVSX()) { 8559 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8560 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8561 8562 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8563 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8564 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8565 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8566 } 8567 8568 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8569 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8570 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8571 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8572 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8573 } 8574 } 8575 8576 if (Subtarget.hasQPX()) { 8577 if (VT.getVectorNumElements() != 4) 8578 return SDValue(); 8579 8580 if (V2.isUndef()) V2 = V1; 8581 8582 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8583 if (AlignIdx != -1) { 8584 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8585 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8586 } else if (SVOp->isSplat()) { 8587 int SplatIdx = SVOp->getSplatIndex(); 8588 if (SplatIdx >= 4) { 8589 std::swap(V1, V2); 8590 SplatIdx -= 4; 8591 } 8592 8593 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8594 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8595 } 8596 8597 // Lower this into a qvgpci/qvfperm pair. 8598 8599 // Compute the qvgpci literal 8600 unsigned idx = 0; 8601 for (unsigned i = 0; i < 4; ++i) { 8602 int m = SVOp->getMaskElt(i); 8603 unsigned mm = m >= 0 ? (unsigned) m : i; 8604 idx |= mm << (3-i)*3; 8605 } 8606 8607 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8608 DAG.getConstant(idx, dl, MVT::i32)); 8609 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8610 } 8611 8612 // Cases that are handled by instructions that take permute immediates 8613 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8614 // selected by the instruction selector. 8615 if (V2.isUndef()) { 8616 if (PPC::isSplatShuffleMask(SVOp, 1) || 8617 PPC::isSplatShuffleMask(SVOp, 2) || 8618 PPC::isSplatShuffleMask(SVOp, 4) || 8619 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8620 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8621 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8622 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8623 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8624 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8625 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8626 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8627 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8628 (Subtarget.hasP8Altivec() && ( 8629 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8630 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8631 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8632 return Op; 8633 } 8634 } 8635 8636 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8637 // and produce a fixed permutation. If any of these match, do not lower to 8638 // VPERM. 8639 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8640 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8641 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8642 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8643 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8644 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8645 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8646 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8647 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8648 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8649 (Subtarget.hasP8Altivec() && ( 8650 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8651 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8652 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8653 return Op; 8654 8655 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8656 // perfect shuffle table to emit an optimal matching sequence. 8657 ArrayRef<int> PermMask = SVOp->getMask(); 8658 8659 unsigned PFIndexes[4]; 8660 bool isFourElementShuffle = true; 8661 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8662 unsigned EltNo = 8; // Start out undef. 8663 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8664 if (PermMask[i*4+j] < 0) 8665 continue; // Undef, ignore it. 8666 8667 unsigned ByteSource = PermMask[i*4+j]; 8668 if ((ByteSource & 3) != j) { 8669 isFourElementShuffle = false; 8670 break; 8671 } 8672 8673 if (EltNo == 8) { 8674 EltNo = ByteSource/4; 8675 } else if (EltNo != ByteSource/4) { 8676 isFourElementShuffle = false; 8677 break; 8678 } 8679 } 8680 PFIndexes[i] = EltNo; 8681 } 8682 8683 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8684 // perfect shuffle vector to determine if it is cost effective to do this as 8685 // discrete instructions, or whether we should use a vperm. 8686 // For now, we skip this for little endian until such time as we have a 8687 // little-endian perfect shuffle table. 8688 if (isFourElementShuffle && !isLittleEndian) { 8689 // Compute the index in the perfect shuffle table. 8690 unsigned PFTableIndex = 8691 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8692 8693 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8694 unsigned Cost = (PFEntry >> 30); 8695 8696 // Determining when to avoid vperm is tricky. Many things affect the cost 8697 // of vperm, particularly how many times the perm mask needs to be computed. 8698 // For example, if the perm mask can be hoisted out of a loop or is already 8699 // used (perhaps because there are multiple permutes with the same shuffle 8700 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8701 // the loop requires an extra register. 8702 // 8703 // As a compromise, we only emit discrete instructions if the shuffle can be 8704 // generated in 3 or fewer operations. When we have loop information 8705 // available, if this block is within a loop, we should avoid using vperm 8706 // for 3-operation perms and use a constant pool load instead. 8707 if (Cost < 3) 8708 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8709 } 8710 8711 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8712 // vector that will get spilled to the constant pool. 8713 if (V2.isUndef()) V2 = V1; 8714 8715 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8716 // that it is in input element units, not in bytes. Convert now. 8717 8718 // For little endian, the order of the input vectors is reversed, and 8719 // the permutation mask is complemented with respect to 31. This is 8720 // necessary to produce proper semantics with the big-endian-biased vperm 8721 // instruction. 8722 EVT EltVT = V1.getValueType().getVectorElementType(); 8723 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8724 8725 SmallVector<SDValue, 16> ResultMask; 8726 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8727 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8728 8729 for (unsigned j = 0; j != BytesPerElement; ++j) 8730 if (isLittleEndian) 8731 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8732 dl, MVT::i32)); 8733 else 8734 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8735 MVT::i32)); 8736 } 8737 8738 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8739 if (isLittleEndian) 8740 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8741 V2, V1, VPermMask); 8742 else 8743 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8744 V1, V2, VPermMask); 8745 } 8746 8747 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 8748 /// vector comparison. If it is, return true and fill in Opc/isDot with 8749 /// information about the intrinsic. 8750 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 8751 bool &isDot, const PPCSubtarget &Subtarget) { 8752 unsigned IntrinsicID = 8753 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 8754 CompareOpc = -1; 8755 isDot = false; 8756 switch (IntrinsicID) { 8757 default: 8758 return false; 8759 // Comparison predicates. 8760 case Intrinsic::ppc_altivec_vcmpbfp_p: 8761 CompareOpc = 966; 8762 isDot = true; 8763 break; 8764 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8765 CompareOpc = 198; 8766 isDot = true; 8767 break; 8768 case Intrinsic::ppc_altivec_vcmpequb_p: 8769 CompareOpc = 6; 8770 isDot = true; 8771 break; 8772 case Intrinsic::ppc_altivec_vcmpequh_p: 8773 CompareOpc = 70; 8774 isDot = true; 8775 break; 8776 case Intrinsic::ppc_altivec_vcmpequw_p: 8777 CompareOpc = 134; 8778 isDot = true; 8779 break; 8780 case Intrinsic::ppc_altivec_vcmpequd_p: 8781 if (Subtarget.hasP8Altivec()) { 8782 CompareOpc = 199; 8783 isDot = true; 8784 } else 8785 return false; 8786 break; 8787 case Intrinsic::ppc_altivec_vcmpneb_p: 8788 case Intrinsic::ppc_altivec_vcmpneh_p: 8789 case Intrinsic::ppc_altivec_vcmpnew_p: 8790 case Intrinsic::ppc_altivec_vcmpnezb_p: 8791 case Intrinsic::ppc_altivec_vcmpnezh_p: 8792 case Intrinsic::ppc_altivec_vcmpnezw_p: 8793 if (Subtarget.hasP9Altivec()) { 8794 switch (IntrinsicID) { 8795 default: 8796 llvm_unreachable("Unknown comparison intrinsic."); 8797 case Intrinsic::ppc_altivec_vcmpneb_p: 8798 CompareOpc = 7; 8799 break; 8800 case Intrinsic::ppc_altivec_vcmpneh_p: 8801 CompareOpc = 71; 8802 break; 8803 case Intrinsic::ppc_altivec_vcmpnew_p: 8804 CompareOpc = 135; 8805 break; 8806 case Intrinsic::ppc_altivec_vcmpnezb_p: 8807 CompareOpc = 263; 8808 break; 8809 case Intrinsic::ppc_altivec_vcmpnezh_p: 8810 CompareOpc = 327; 8811 break; 8812 case Intrinsic::ppc_altivec_vcmpnezw_p: 8813 CompareOpc = 391; 8814 break; 8815 } 8816 isDot = true; 8817 } else 8818 return false; 8819 break; 8820 case Intrinsic::ppc_altivec_vcmpgefp_p: 8821 CompareOpc = 454; 8822 isDot = true; 8823 break; 8824 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8825 CompareOpc = 710; 8826 isDot = true; 8827 break; 8828 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8829 CompareOpc = 774; 8830 isDot = true; 8831 break; 8832 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8833 CompareOpc = 838; 8834 isDot = true; 8835 break; 8836 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8837 CompareOpc = 902; 8838 isDot = true; 8839 break; 8840 case Intrinsic::ppc_altivec_vcmpgtsd_p: 8841 if (Subtarget.hasP8Altivec()) { 8842 CompareOpc = 967; 8843 isDot = true; 8844 } else 8845 return false; 8846 break; 8847 case Intrinsic::ppc_altivec_vcmpgtub_p: 8848 CompareOpc = 518; 8849 isDot = true; 8850 break; 8851 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8852 CompareOpc = 582; 8853 isDot = true; 8854 break; 8855 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8856 CompareOpc = 646; 8857 isDot = true; 8858 break; 8859 case Intrinsic::ppc_altivec_vcmpgtud_p: 8860 if (Subtarget.hasP8Altivec()) { 8861 CompareOpc = 711; 8862 isDot = true; 8863 } else 8864 return false; 8865 break; 8866 8867 // VSX predicate comparisons use the same infrastructure 8868 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8869 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8870 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8871 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8872 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8873 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8874 if (Subtarget.hasVSX()) { 8875 switch (IntrinsicID) { 8876 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8877 CompareOpc = 99; 8878 break; 8879 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8880 CompareOpc = 115; 8881 break; 8882 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8883 CompareOpc = 107; 8884 break; 8885 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8886 CompareOpc = 67; 8887 break; 8888 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8889 CompareOpc = 83; 8890 break; 8891 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8892 CompareOpc = 75; 8893 break; 8894 } 8895 isDot = true; 8896 } else 8897 return false; 8898 break; 8899 8900 // Normal Comparisons. 8901 case Intrinsic::ppc_altivec_vcmpbfp: 8902 CompareOpc = 966; 8903 break; 8904 case Intrinsic::ppc_altivec_vcmpeqfp: 8905 CompareOpc = 198; 8906 break; 8907 case Intrinsic::ppc_altivec_vcmpequb: 8908 CompareOpc = 6; 8909 break; 8910 case Intrinsic::ppc_altivec_vcmpequh: 8911 CompareOpc = 70; 8912 break; 8913 case Intrinsic::ppc_altivec_vcmpequw: 8914 CompareOpc = 134; 8915 break; 8916 case Intrinsic::ppc_altivec_vcmpequd: 8917 if (Subtarget.hasP8Altivec()) 8918 CompareOpc = 199; 8919 else 8920 return false; 8921 break; 8922 case Intrinsic::ppc_altivec_vcmpneb: 8923 case Intrinsic::ppc_altivec_vcmpneh: 8924 case Intrinsic::ppc_altivec_vcmpnew: 8925 case Intrinsic::ppc_altivec_vcmpnezb: 8926 case Intrinsic::ppc_altivec_vcmpnezh: 8927 case Intrinsic::ppc_altivec_vcmpnezw: 8928 if (Subtarget.hasP9Altivec()) 8929 switch (IntrinsicID) { 8930 default: 8931 llvm_unreachable("Unknown comparison intrinsic."); 8932 case Intrinsic::ppc_altivec_vcmpneb: 8933 CompareOpc = 7; 8934 break; 8935 case Intrinsic::ppc_altivec_vcmpneh: 8936 CompareOpc = 71; 8937 break; 8938 case Intrinsic::ppc_altivec_vcmpnew: 8939 CompareOpc = 135; 8940 break; 8941 case Intrinsic::ppc_altivec_vcmpnezb: 8942 CompareOpc = 263; 8943 break; 8944 case Intrinsic::ppc_altivec_vcmpnezh: 8945 CompareOpc = 327; 8946 break; 8947 case Intrinsic::ppc_altivec_vcmpnezw: 8948 CompareOpc = 391; 8949 break; 8950 } 8951 else 8952 return false; 8953 break; 8954 case Intrinsic::ppc_altivec_vcmpgefp: 8955 CompareOpc = 454; 8956 break; 8957 case Intrinsic::ppc_altivec_vcmpgtfp: 8958 CompareOpc = 710; 8959 break; 8960 case Intrinsic::ppc_altivec_vcmpgtsb: 8961 CompareOpc = 774; 8962 break; 8963 case Intrinsic::ppc_altivec_vcmpgtsh: 8964 CompareOpc = 838; 8965 break; 8966 case Intrinsic::ppc_altivec_vcmpgtsw: 8967 CompareOpc = 902; 8968 break; 8969 case Intrinsic::ppc_altivec_vcmpgtsd: 8970 if (Subtarget.hasP8Altivec()) 8971 CompareOpc = 967; 8972 else 8973 return false; 8974 break; 8975 case Intrinsic::ppc_altivec_vcmpgtub: 8976 CompareOpc = 518; 8977 break; 8978 case Intrinsic::ppc_altivec_vcmpgtuh: 8979 CompareOpc = 582; 8980 break; 8981 case Intrinsic::ppc_altivec_vcmpgtuw: 8982 CompareOpc = 646; 8983 break; 8984 case Intrinsic::ppc_altivec_vcmpgtud: 8985 if (Subtarget.hasP8Altivec()) 8986 CompareOpc = 711; 8987 else 8988 return false; 8989 break; 8990 } 8991 return true; 8992 } 8993 8994 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 8995 /// lower, do it, otherwise return null. 8996 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 8997 SelectionDAG &DAG) const { 8998 unsigned IntrinsicID = 8999 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9000 9001 SDLoc dl(Op); 9002 9003 if (IntrinsicID == Intrinsic::thread_pointer) { 9004 // Reads the thread pointer register, used for __builtin_thread_pointer. 9005 if (Subtarget.isPPC64()) 9006 return DAG.getRegister(PPC::X13, MVT::i64); 9007 return DAG.getRegister(PPC::R2, MVT::i32); 9008 } 9009 9010 // We are looking for absolute values here. 9011 // The idea is to try to fit one of two patterns: 9012 // max (a, (0-a)) OR max ((0-a), a) 9013 if (Subtarget.hasP9Vector() && 9014 (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw || 9015 IntrinsicID == Intrinsic::ppc_altivec_vmaxsh || 9016 IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) { 9017 SDValue V1 = Op.getOperand(1); 9018 SDValue V2 = Op.getOperand(2); 9019 if (V1.getSimpleValueType() == V2.getSimpleValueType() && 9020 (V1.getSimpleValueType() == MVT::v4i32 || 9021 V1.getSimpleValueType() == MVT::v8i16 || 9022 V1.getSimpleValueType() == MVT::v16i8)) { 9023 if ( V1.getOpcode() == ISD::SUB && 9024 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 9025 V1.getOperand(1) == V2 ) { 9026 // Generate the abs instruction with the operands 9027 return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2); 9028 } 9029 9030 if ( V2.getOpcode() == ISD::SUB && 9031 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 9032 V2.getOperand(1) == V1 ) { 9033 // Generate the abs instruction with the operands 9034 return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1); 9035 } 9036 } 9037 } 9038 9039 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9040 // opcode number of the comparison. 9041 int CompareOpc; 9042 bool isDot; 9043 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9044 return SDValue(); // Don't custom lower most intrinsics. 9045 9046 // If this is a non-dot comparison, make the VCMP node and we are done. 9047 if (!isDot) { 9048 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9049 Op.getOperand(1), Op.getOperand(2), 9050 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9051 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9052 } 9053 9054 // Create the PPCISD altivec 'dot' comparison node. 9055 SDValue Ops[] = { 9056 Op.getOperand(2), // LHS 9057 Op.getOperand(3), // RHS 9058 DAG.getConstant(CompareOpc, dl, MVT::i32) 9059 }; 9060 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9061 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9062 9063 // Now that we have the comparison, emit a copy from the CR to a GPR. 9064 // This is flagged to the above dot comparison. 9065 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9066 DAG.getRegister(PPC::CR6, MVT::i32), 9067 CompNode.getValue(1)); 9068 9069 // Unpack the result based on how the target uses it. 9070 unsigned BitNo; // Bit # of CR6. 9071 bool InvertBit; // Invert result? 9072 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9073 default: // Can't happen, don't crash on invalid number though. 9074 case 0: // Return the value of the EQ bit of CR6. 9075 BitNo = 0; InvertBit = false; 9076 break; 9077 case 1: // Return the inverted value of the EQ bit of CR6. 9078 BitNo = 0; InvertBit = true; 9079 break; 9080 case 2: // Return the value of the LT bit of CR6. 9081 BitNo = 2; InvertBit = false; 9082 break; 9083 case 3: // Return the inverted value of the LT bit of CR6. 9084 BitNo = 2; InvertBit = true; 9085 break; 9086 } 9087 9088 // Shift the bit into the low position. 9089 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9090 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9091 // Isolate the bit. 9092 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9093 DAG.getConstant(1, dl, MVT::i32)); 9094 9095 // If we are supposed to, toggle the bit. 9096 if (InvertBit) 9097 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9098 DAG.getConstant(1, dl, MVT::i32)); 9099 return Flags; 9100 } 9101 9102 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9103 SelectionDAG &DAG) const { 9104 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9105 // the beginning of the argument list. 9106 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9107 SDLoc DL(Op); 9108 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9109 case Intrinsic::ppc_cfence: { 9110 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9111 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9112 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9113 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9114 Op.getOperand(ArgStart + 1)), 9115 Op.getOperand(0)), 9116 0); 9117 } 9118 default: 9119 break; 9120 } 9121 return SDValue(); 9122 } 9123 9124 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9125 // Check for a DIV with the same operands as this REM. 9126 for (auto UI : Op.getOperand(1)->uses()) { 9127 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9128 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9129 if (UI->getOperand(0) == Op.getOperand(0) && 9130 UI->getOperand(1) == Op.getOperand(1)) 9131 return SDValue(); 9132 } 9133 return Op; 9134 } 9135 9136 // Lower scalar BSWAP64 to xxbrd. 9137 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9138 SDLoc dl(Op); 9139 // MTVSRDD 9140 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9141 Op.getOperand(0)); 9142 // XXBRD 9143 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9144 // MFVSRD 9145 int VectorIndex = 0; 9146 if (Subtarget.isLittleEndian()) 9147 VectorIndex = 1; 9148 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9149 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9150 return Op; 9151 } 9152 9153 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9154 // compared to a value that is atomically loaded (atomic loads zero-extend). 9155 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9156 SelectionDAG &DAG) const { 9157 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9158 "Expecting an atomic compare-and-swap here."); 9159 SDLoc dl(Op); 9160 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9161 EVT MemVT = AtomicNode->getMemoryVT(); 9162 if (MemVT.getSizeInBits() >= 32) 9163 return Op; 9164 9165 SDValue CmpOp = Op.getOperand(2); 9166 // If this is already correctly zero-extended, leave it alone. 9167 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9168 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9169 return Op; 9170 9171 // Clear the high bits of the compare operand. 9172 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9173 SDValue NewCmpOp = 9174 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9175 DAG.getConstant(MaskVal, dl, MVT::i32)); 9176 9177 // Replace the existing compare operand with the properly zero-extended one. 9178 SmallVector<SDValue, 4> Ops; 9179 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9180 Ops.push_back(AtomicNode->getOperand(i)); 9181 Ops[2] = NewCmpOp; 9182 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9183 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9184 auto NodeTy = 9185 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9186 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9187 } 9188 9189 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9190 SelectionDAG &DAG) const { 9191 SDLoc dl(Op); 9192 // Create a stack slot that is 16-byte aligned. 9193 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9194 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9195 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9196 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9197 9198 // Store the input value into Value#0 of the stack slot. 9199 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9200 MachinePointerInfo()); 9201 // Load it out. 9202 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9203 } 9204 9205 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9206 SelectionDAG &DAG) const { 9207 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9208 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9209 9210 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9211 // We have legal lowering for constant indices but not for variable ones. 9212 if (!C) 9213 return SDValue(); 9214 9215 EVT VT = Op.getValueType(); 9216 SDLoc dl(Op); 9217 SDValue V1 = Op.getOperand(0); 9218 SDValue V2 = Op.getOperand(1); 9219 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9220 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9221 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9222 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9223 unsigned InsertAtElement = C->getZExtValue(); 9224 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9225 if (Subtarget.isLittleEndian()) { 9226 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9227 } 9228 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9229 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9230 } 9231 return Op; 9232 } 9233 9234 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9235 SelectionDAG &DAG) const { 9236 SDLoc dl(Op); 9237 SDNode *N = Op.getNode(); 9238 9239 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9240 "Unknown extract_vector_elt type"); 9241 9242 SDValue Value = N->getOperand(0); 9243 9244 // The first part of this is like the store lowering except that we don't 9245 // need to track the chain. 9246 9247 // The values are now known to be -1 (false) or 1 (true). To convert this 9248 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9249 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9250 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9251 9252 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9253 // understand how to form the extending load. 9254 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9255 9256 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9257 9258 // Now convert to an integer and store. 9259 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9260 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9261 Value); 9262 9263 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9264 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9265 MachinePointerInfo PtrInfo = 9266 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9267 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9268 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9269 9270 SDValue StoreChain = DAG.getEntryNode(); 9271 SDValue Ops[] = {StoreChain, 9272 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9273 Value, FIdx}; 9274 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9275 9276 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9277 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9278 9279 // Extract the value requested. 9280 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9281 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9282 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9283 9284 SDValue IntVal = 9285 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9286 9287 if (!Subtarget.useCRBits()) 9288 return IntVal; 9289 9290 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9291 } 9292 9293 /// Lowering for QPX v4i1 loads 9294 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9295 SelectionDAG &DAG) const { 9296 SDLoc dl(Op); 9297 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9298 SDValue LoadChain = LN->getChain(); 9299 SDValue BasePtr = LN->getBasePtr(); 9300 9301 if (Op.getValueType() == MVT::v4f64 || 9302 Op.getValueType() == MVT::v4f32) { 9303 EVT MemVT = LN->getMemoryVT(); 9304 unsigned Alignment = LN->getAlignment(); 9305 9306 // If this load is properly aligned, then it is legal. 9307 if (Alignment >= MemVT.getStoreSize()) 9308 return Op; 9309 9310 EVT ScalarVT = Op.getValueType().getScalarType(), 9311 ScalarMemVT = MemVT.getScalarType(); 9312 unsigned Stride = ScalarMemVT.getStoreSize(); 9313 9314 SDValue Vals[4], LoadChains[4]; 9315 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9316 SDValue Load; 9317 if (ScalarVT != ScalarMemVT) 9318 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9319 BasePtr, 9320 LN->getPointerInfo().getWithOffset(Idx * Stride), 9321 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9322 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9323 else 9324 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9325 LN->getPointerInfo().getWithOffset(Idx * Stride), 9326 MinAlign(Alignment, Idx * Stride), 9327 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9328 9329 if (Idx == 0 && LN->isIndexed()) { 9330 assert(LN->getAddressingMode() == ISD::PRE_INC && 9331 "Unknown addressing mode on vector load"); 9332 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9333 LN->getAddressingMode()); 9334 } 9335 9336 Vals[Idx] = Load; 9337 LoadChains[Idx] = Load.getValue(1); 9338 9339 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9340 DAG.getConstant(Stride, dl, 9341 BasePtr.getValueType())); 9342 } 9343 9344 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9345 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9346 9347 if (LN->isIndexed()) { 9348 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9349 return DAG.getMergeValues(RetOps, dl); 9350 } 9351 9352 SDValue RetOps[] = { Value, TF }; 9353 return DAG.getMergeValues(RetOps, dl); 9354 } 9355 9356 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9357 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9358 9359 // To lower v4i1 from a byte array, we load the byte elements of the 9360 // vector and then reuse the BUILD_VECTOR logic. 9361 9362 SDValue VectElmts[4], VectElmtChains[4]; 9363 for (unsigned i = 0; i < 4; ++i) { 9364 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9365 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9366 9367 VectElmts[i] = DAG.getExtLoad( 9368 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9369 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9370 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9371 VectElmtChains[i] = VectElmts[i].getValue(1); 9372 } 9373 9374 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9375 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9376 9377 SDValue RVals[] = { Value, LoadChain }; 9378 return DAG.getMergeValues(RVals, dl); 9379 } 9380 9381 /// Lowering for QPX v4i1 stores 9382 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9383 SelectionDAG &DAG) const { 9384 SDLoc dl(Op); 9385 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9386 SDValue StoreChain = SN->getChain(); 9387 SDValue BasePtr = SN->getBasePtr(); 9388 SDValue Value = SN->getValue(); 9389 9390 if (Value.getValueType() == MVT::v4f64 || 9391 Value.getValueType() == MVT::v4f32) { 9392 EVT MemVT = SN->getMemoryVT(); 9393 unsigned Alignment = SN->getAlignment(); 9394 9395 // If this store is properly aligned, then it is legal. 9396 if (Alignment >= MemVT.getStoreSize()) 9397 return Op; 9398 9399 EVT ScalarVT = Value.getValueType().getScalarType(), 9400 ScalarMemVT = MemVT.getScalarType(); 9401 unsigned Stride = ScalarMemVT.getStoreSize(); 9402 9403 SDValue Stores[4]; 9404 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9405 SDValue Ex = DAG.getNode( 9406 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9407 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9408 SDValue Store; 9409 if (ScalarVT != ScalarMemVT) 9410 Store = 9411 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9412 SN->getPointerInfo().getWithOffset(Idx * Stride), 9413 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9414 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9415 else 9416 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9417 SN->getPointerInfo().getWithOffset(Idx * Stride), 9418 MinAlign(Alignment, Idx * Stride), 9419 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9420 9421 if (Idx == 0 && SN->isIndexed()) { 9422 assert(SN->getAddressingMode() == ISD::PRE_INC && 9423 "Unknown addressing mode on vector store"); 9424 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9425 SN->getAddressingMode()); 9426 } 9427 9428 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9429 DAG.getConstant(Stride, dl, 9430 BasePtr.getValueType())); 9431 Stores[Idx] = Store; 9432 } 9433 9434 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9435 9436 if (SN->isIndexed()) { 9437 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9438 return DAG.getMergeValues(RetOps, dl); 9439 } 9440 9441 return TF; 9442 } 9443 9444 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9445 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9446 9447 // The values are now known to be -1 (false) or 1 (true). To convert this 9448 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9449 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9450 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9451 9452 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9453 // understand how to form the extending load. 9454 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9455 9456 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9457 9458 // Now convert to an integer and store. 9459 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9460 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9461 Value); 9462 9463 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9464 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9465 MachinePointerInfo PtrInfo = 9466 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9467 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9468 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9469 9470 SDValue Ops[] = {StoreChain, 9471 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9472 Value, FIdx}; 9473 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9474 9475 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9476 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9477 9478 // Move data into the byte array. 9479 SDValue Loads[4], LoadChains[4]; 9480 for (unsigned i = 0; i < 4; ++i) { 9481 unsigned Offset = 4*i; 9482 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9483 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9484 9485 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9486 PtrInfo.getWithOffset(Offset)); 9487 LoadChains[i] = Loads[i].getValue(1); 9488 } 9489 9490 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9491 9492 SDValue Stores[4]; 9493 for (unsigned i = 0; i < 4; ++i) { 9494 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9495 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9496 9497 Stores[i] = DAG.getTruncStore( 9498 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9499 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9500 SN->getAAInfo()); 9501 } 9502 9503 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9504 9505 return StoreChain; 9506 } 9507 9508 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9509 SDLoc dl(Op); 9510 if (Op.getValueType() == MVT::v4i32) { 9511 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9512 9513 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9514 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9515 9516 SDValue RHSSwap = // = vrlw RHS, 16 9517 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9518 9519 // Shrinkify inputs to v8i16. 9520 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9521 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9522 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9523 9524 // Low parts multiplied together, generating 32-bit results (we ignore the 9525 // top parts). 9526 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9527 LHS, RHS, DAG, dl, MVT::v4i32); 9528 9529 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9530 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9531 // Shift the high parts up 16 bits. 9532 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9533 Neg16, DAG, dl); 9534 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9535 } else if (Op.getValueType() == MVT::v8i16) { 9536 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9537 9538 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9539 9540 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9541 LHS, RHS, Zero, DAG, dl); 9542 } else if (Op.getValueType() == MVT::v16i8) { 9543 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9544 bool isLittleEndian = Subtarget.isLittleEndian(); 9545 9546 // Multiply the even 8-bit parts, producing 16-bit sums. 9547 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9548 LHS, RHS, DAG, dl, MVT::v8i16); 9549 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9550 9551 // Multiply the odd 8-bit parts, producing 16-bit sums. 9552 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9553 LHS, RHS, DAG, dl, MVT::v8i16); 9554 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9555 9556 // Merge the results together. Because vmuleub and vmuloub are 9557 // instructions with a big-endian bias, we must reverse the 9558 // element numbering and reverse the meaning of "odd" and "even" 9559 // when generating little endian code. 9560 int Ops[16]; 9561 for (unsigned i = 0; i != 8; ++i) { 9562 if (isLittleEndian) { 9563 Ops[i*2 ] = 2*i; 9564 Ops[i*2+1] = 2*i+16; 9565 } else { 9566 Ops[i*2 ] = 2*i+1; 9567 Ops[i*2+1] = 2*i+1+16; 9568 } 9569 } 9570 if (isLittleEndian) 9571 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9572 else 9573 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9574 } else { 9575 llvm_unreachable("Unknown mul to lower!"); 9576 } 9577 } 9578 9579 /// LowerOperation - Provide custom lowering hooks for some operations. 9580 /// 9581 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9582 switch (Op.getOpcode()) { 9583 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9584 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9585 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9586 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9587 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9588 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9589 case ISD::SETCC: return LowerSETCC(Op, DAG); 9590 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9591 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9592 9593 // Variable argument lowering. 9594 case ISD::VASTART: return LowerVASTART(Op, DAG); 9595 case ISD::VAARG: return LowerVAARG(Op, DAG); 9596 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9597 9598 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 9599 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9600 case ISD::GET_DYNAMIC_AREA_OFFSET: 9601 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9602 9603 // Exception handling lowering. 9604 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 9605 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9606 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9607 9608 case ISD::LOAD: return LowerLOAD(Op, DAG); 9609 case ISD::STORE: return LowerSTORE(Op, DAG); 9610 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9611 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9612 case ISD::FP_TO_UINT: 9613 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 9614 case ISD::UINT_TO_FP: 9615 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9616 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9617 9618 // Lower 64-bit shifts. 9619 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9620 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9621 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9622 9623 // Vector-related lowering. 9624 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9625 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9626 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9627 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9628 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9629 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9630 case ISD::MUL: return LowerMUL(Op, DAG); 9631 9632 // For counter-based loop handling. 9633 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9634 9635 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 9636 9637 // Frame & Return address. 9638 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9639 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9640 9641 case ISD::INTRINSIC_VOID: 9642 return LowerINTRINSIC_VOID(Op, DAG); 9643 case ISD::SREM: 9644 case ISD::UREM: 9645 return LowerREM(Op, DAG); 9646 case ISD::BSWAP: 9647 return LowerBSWAP(Op, DAG); 9648 case ISD::ATOMIC_CMP_SWAP: 9649 return LowerATOMIC_CMP_SWAP(Op, DAG); 9650 } 9651 } 9652 9653 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9654 SmallVectorImpl<SDValue>&Results, 9655 SelectionDAG &DAG) const { 9656 SDLoc dl(N); 9657 switch (N->getOpcode()) { 9658 default: 9659 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9660 case ISD::READCYCLECOUNTER: { 9661 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9662 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9663 9664 Results.push_back(RTB); 9665 Results.push_back(RTB.getValue(1)); 9666 Results.push_back(RTB.getValue(2)); 9667 break; 9668 } 9669 case ISD::INTRINSIC_W_CHAIN: { 9670 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9671 Intrinsic::ppc_is_decremented_ctr_nonzero) 9672 break; 9673 9674 assert(N->getValueType(0) == MVT::i1 && 9675 "Unexpected result type for CTR decrement intrinsic"); 9676 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9677 N->getValueType(0)); 9678 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9679 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9680 N->getOperand(1)); 9681 9682 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 9683 Results.push_back(NewInt.getValue(1)); 9684 break; 9685 } 9686 case ISD::VAARG: { 9687 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 9688 return; 9689 9690 EVT VT = N->getValueType(0); 9691 9692 if (VT == MVT::i64) { 9693 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 9694 9695 Results.push_back(NewNode); 9696 Results.push_back(NewNode.getValue(1)); 9697 } 9698 return; 9699 } 9700 case ISD::FP_TO_SINT: 9701 case ISD::FP_TO_UINT: 9702 // LowerFP_TO_INT() can only handle f32 and f64. 9703 if (N->getOperand(0).getValueType() == MVT::ppcf128) 9704 return; 9705 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 9706 return; 9707 case ISD::BITCAST: 9708 // Don't handle bitcast here. 9709 return; 9710 } 9711 } 9712 9713 //===----------------------------------------------------------------------===// 9714 // Other Lowering Code 9715 //===----------------------------------------------------------------------===// 9716 9717 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 9718 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9719 Function *Func = Intrinsic::getDeclaration(M, Id); 9720 return Builder.CreateCall(Func, {}); 9721 } 9722 9723 // The mappings for emitLeading/TrailingFence is taken from 9724 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 9725 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 9726 Instruction *Inst, 9727 AtomicOrdering Ord) const { 9728 if (Ord == AtomicOrdering::SequentiallyConsistent) 9729 return callIntrinsic(Builder, Intrinsic::ppc_sync); 9730 if (isReleaseOrStronger(Ord)) 9731 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9732 return nullptr; 9733 } 9734 9735 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 9736 Instruction *Inst, 9737 AtomicOrdering Ord) const { 9738 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 9739 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 9740 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 9741 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 9742 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 9743 return Builder.CreateCall( 9744 Intrinsic::getDeclaration( 9745 Builder.GetInsertBlock()->getParent()->getParent(), 9746 Intrinsic::ppc_cfence, {Inst->getType()}), 9747 {Inst}); 9748 // FIXME: Can use isync for rmw operation. 9749 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9750 } 9751 return nullptr; 9752 } 9753 9754 MachineBasicBlock * 9755 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 9756 unsigned AtomicSize, 9757 unsigned BinOpcode, 9758 unsigned CmpOpcode, 9759 unsigned CmpPred) const { 9760 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9761 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9762 9763 auto LoadMnemonic = PPC::LDARX; 9764 auto StoreMnemonic = PPC::STDCX; 9765 switch (AtomicSize) { 9766 default: 9767 llvm_unreachable("Unexpected size of atomic entity"); 9768 case 1: 9769 LoadMnemonic = PPC::LBARX; 9770 StoreMnemonic = PPC::STBCX; 9771 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9772 break; 9773 case 2: 9774 LoadMnemonic = PPC::LHARX; 9775 StoreMnemonic = PPC::STHCX; 9776 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9777 break; 9778 case 4: 9779 LoadMnemonic = PPC::LWARX; 9780 StoreMnemonic = PPC::STWCX; 9781 break; 9782 case 8: 9783 LoadMnemonic = PPC::LDARX; 9784 StoreMnemonic = PPC::STDCX; 9785 break; 9786 } 9787 9788 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9789 MachineFunction *F = BB->getParent(); 9790 MachineFunction::iterator It = ++BB->getIterator(); 9791 9792 unsigned dest = MI.getOperand(0).getReg(); 9793 unsigned ptrA = MI.getOperand(1).getReg(); 9794 unsigned ptrB = MI.getOperand(2).getReg(); 9795 unsigned incr = MI.getOperand(3).getReg(); 9796 DebugLoc dl = MI.getDebugLoc(); 9797 9798 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9799 MachineBasicBlock *loop2MBB = 9800 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9801 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9802 F->insert(It, loopMBB); 9803 if (CmpOpcode) 9804 F->insert(It, loop2MBB); 9805 F->insert(It, exitMBB); 9806 exitMBB->splice(exitMBB->begin(), BB, 9807 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9808 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9809 9810 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9811 unsigned TmpReg = (!BinOpcode) ? incr : 9812 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 9813 : &PPC::GPRCRegClass); 9814 9815 // thisMBB: 9816 // ... 9817 // fallthrough --> loopMBB 9818 BB->addSuccessor(loopMBB); 9819 9820 // loopMBB: 9821 // l[wd]arx dest, ptr 9822 // add r0, dest, incr 9823 // st[wd]cx. r0, ptr 9824 // bne- loopMBB 9825 // fallthrough --> exitMBB 9826 9827 // For max/min... 9828 // loopMBB: 9829 // l[wd]arx dest, ptr 9830 // cmpl?[wd] incr, dest 9831 // bgt exitMBB 9832 // loop2MBB: 9833 // st[wd]cx. dest, ptr 9834 // bne- loopMBB 9835 // fallthrough --> exitMBB 9836 9837 BB = loopMBB; 9838 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9839 .addReg(ptrA).addReg(ptrB); 9840 if (BinOpcode) 9841 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 9842 if (CmpOpcode) { 9843 // Signed comparisons of byte or halfword values must be sign-extended. 9844 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 9845 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9846 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 9847 ExtReg).addReg(dest); 9848 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9849 .addReg(incr).addReg(ExtReg); 9850 } else 9851 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9852 .addReg(incr).addReg(dest); 9853 9854 BuildMI(BB, dl, TII->get(PPC::BCC)) 9855 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9856 BB->addSuccessor(loop2MBB); 9857 BB->addSuccessor(exitMBB); 9858 BB = loop2MBB; 9859 } 9860 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9861 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 9862 BuildMI(BB, dl, TII->get(PPC::BCC)) 9863 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9864 BB->addSuccessor(loopMBB); 9865 BB->addSuccessor(exitMBB); 9866 9867 // exitMBB: 9868 // ... 9869 BB = exitMBB; 9870 return BB; 9871 } 9872 9873 MachineBasicBlock * 9874 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI, 9875 MachineBasicBlock *BB, 9876 bool is8bit, // operation 9877 unsigned BinOpcode, 9878 unsigned CmpOpcode, 9879 unsigned CmpPred) const { 9880 // If we support part-word atomic mnemonics, just use them 9881 if (Subtarget.hasPartwordAtomics()) 9882 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, 9883 CmpOpcode, CmpPred); 9884 9885 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9886 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9887 // In 64 bit mode we have to use 64 bits for addresses, even though the 9888 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 9889 // registers without caring whether they're 32 or 64, but here we're 9890 // doing actual arithmetic on the addresses. 9891 bool is64bit = Subtarget.isPPC64(); 9892 bool isLittleEndian = Subtarget.isLittleEndian(); 9893 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9894 9895 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9896 MachineFunction *F = BB->getParent(); 9897 MachineFunction::iterator It = ++BB->getIterator(); 9898 9899 unsigned dest = MI.getOperand(0).getReg(); 9900 unsigned ptrA = MI.getOperand(1).getReg(); 9901 unsigned ptrB = MI.getOperand(2).getReg(); 9902 unsigned incr = MI.getOperand(3).getReg(); 9903 DebugLoc dl = MI.getDebugLoc(); 9904 9905 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9906 MachineBasicBlock *loop2MBB = 9907 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9908 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9909 F->insert(It, loopMBB); 9910 if (CmpOpcode) 9911 F->insert(It, loop2MBB); 9912 F->insert(It, exitMBB); 9913 exitMBB->splice(exitMBB->begin(), BB, 9914 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9915 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9916 9917 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9918 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 9919 : &PPC::GPRCRegClass; 9920 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9921 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 9922 unsigned ShiftReg = 9923 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 9924 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 9925 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 9926 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 9927 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 9928 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 9929 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 9930 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 9931 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 9932 unsigned Ptr1Reg; 9933 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 9934 9935 // thisMBB: 9936 // ... 9937 // fallthrough --> loopMBB 9938 BB->addSuccessor(loopMBB); 9939 9940 // The 4-byte load must be aligned, while a char or short may be 9941 // anywhere in the word. Hence all this nasty bookkeeping code. 9942 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9943 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9944 // xori shift, shift1, 24 [16] 9945 // rlwinm ptr, ptr1, 0, 0, 29 9946 // slw incr2, incr, shift 9947 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9948 // slw mask, mask2, shift 9949 // loopMBB: 9950 // lwarx tmpDest, ptr 9951 // add tmp, tmpDest, incr2 9952 // andc tmp2, tmpDest, mask 9953 // and tmp3, tmp, mask 9954 // or tmp4, tmp3, tmp2 9955 // stwcx. tmp4, ptr 9956 // bne- loopMBB 9957 // fallthrough --> exitMBB 9958 // srw dest, tmpDest, shift 9959 if (ptrA != ZeroReg) { 9960 Ptr1Reg = RegInfo.createVirtualRegister(RC); 9961 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 9962 .addReg(ptrA).addReg(ptrB); 9963 } else { 9964 Ptr1Reg = ptrB; 9965 } 9966 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 9967 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 9968 if (!isLittleEndian) 9969 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 9970 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 9971 if (is64bit) 9972 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 9973 .addReg(Ptr1Reg).addImm(0).addImm(61); 9974 else 9975 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 9976 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 9977 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 9978 .addReg(incr).addReg(ShiftReg); 9979 if (is8bit) 9980 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 9981 else { 9982 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 9983 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 9984 } 9985 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 9986 .addReg(Mask2Reg).addReg(ShiftReg); 9987 9988 BB = loopMBB; 9989 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 9990 .addReg(ZeroReg).addReg(PtrReg); 9991 if (BinOpcode) 9992 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 9993 .addReg(Incr2Reg).addReg(TmpDestReg); 9994 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 9995 .addReg(TmpDestReg).addReg(MaskReg); 9996 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 9997 .addReg(TmpReg).addReg(MaskReg); 9998 if (CmpOpcode) { 9999 // For unsigned comparisons, we can directly compare the shifted values. 10000 // For signed comparisons we shift and sign extend. 10001 unsigned SReg = RegInfo.createVirtualRegister(RC); 10002 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg) 10003 .addReg(TmpDestReg).addReg(MaskReg); 10004 unsigned ValueReg = SReg; 10005 unsigned CmpReg = Incr2Reg; 10006 if (CmpOpcode == PPC::CMPW) { 10007 ValueReg = RegInfo.createVirtualRegister(RC); 10008 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10009 .addReg(SReg).addReg(ShiftReg); 10010 unsigned ValueSReg = RegInfo.createVirtualRegister(RC); 10011 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10012 .addReg(ValueReg); 10013 ValueReg = ValueSReg; 10014 CmpReg = incr; 10015 } 10016 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10017 .addReg(CmpReg).addReg(ValueReg); 10018 BuildMI(BB, dl, TII->get(PPC::BCC)) 10019 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10020 BB->addSuccessor(loop2MBB); 10021 BB->addSuccessor(exitMBB); 10022 BB = loop2MBB; 10023 } 10024 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 10025 .addReg(Tmp3Reg).addReg(Tmp2Reg); 10026 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10027 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 10028 BuildMI(BB, dl, TII->get(PPC::BCC)) 10029 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10030 BB->addSuccessor(loopMBB); 10031 BB->addSuccessor(exitMBB); 10032 10033 // exitMBB: 10034 // ... 10035 BB = exitMBB; 10036 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 10037 .addReg(ShiftReg); 10038 return BB; 10039 } 10040 10041 llvm::MachineBasicBlock * 10042 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10043 MachineBasicBlock *MBB) const { 10044 DebugLoc DL = MI.getDebugLoc(); 10045 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10046 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10047 10048 MachineFunction *MF = MBB->getParent(); 10049 MachineRegisterInfo &MRI = MF->getRegInfo(); 10050 10051 const BasicBlock *BB = MBB->getBasicBlock(); 10052 MachineFunction::iterator I = ++MBB->getIterator(); 10053 10054 unsigned DstReg = MI.getOperand(0).getReg(); 10055 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10056 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10057 unsigned mainDstReg = MRI.createVirtualRegister(RC); 10058 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 10059 10060 MVT PVT = getPointerTy(MF->getDataLayout()); 10061 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10062 "Invalid Pointer Size!"); 10063 // For v = setjmp(buf), we generate 10064 // 10065 // thisMBB: 10066 // SjLjSetup mainMBB 10067 // bl mainMBB 10068 // v_restore = 1 10069 // b sinkMBB 10070 // 10071 // mainMBB: 10072 // buf[LabelOffset] = LR 10073 // v_main = 0 10074 // 10075 // sinkMBB: 10076 // v = phi(main, restore) 10077 // 10078 10079 MachineBasicBlock *thisMBB = MBB; 10080 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10081 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10082 MF->insert(I, mainMBB); 10083 MF->insert(I, sinkMBB); 10084 10085 MachineInstrBuilder MIB; 10086 10087 // Transfer the remainder of BB and its successor edges to sinkMBB. 10088 sinkMBB->splice(sinkMBB->begin(), MBB, 10089 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10090 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10091 10092 // Note that the structure of the jmp_buf used here is not compatible 10093 // with that used by libc, and is not designed to be. Specifically, it 10094 // stores only those 'reserved' registers that LLVM does not otherwise 10095 // understand how to spill. Also, by convention, by the time this 10096 // intrinsic is called, Clang has already stored the frame address in the 10097 // first slot of the buffer and stack address in the third. Following the 10098 // X86 target code, we'll store the jump address in the second slot. We also 10099 // need to save the TOC pointer (R2) to handle jumps between shared 10100 // libraries, and that will be stored in the fourth slot. The thread 10101 // identifier (R13) is not affected. 10102 10103 // thisMBB: 10104 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10105 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10106 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10107 10108 // Prepare IP either in reg. 10109 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10110 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 10111 unsigned BufReg = MI.getOperand(1).getReg(); 10112 10113 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 10114 setUsesTOCBasePtr(*MBB->getParent()); 10115 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10116 .addReg(PPC::X2) 10117 .addImm(TOCOffset) 10118 .addReg(BufReg) 10119 .cloneMemRefs(MI); 10120 } 10121 10122 // Naked functions never have a base pointer, and so we use r1. For all 10123 // other functions, this decision must be delayed until during PEI. 10124 unsigned BaseReg; 10125 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10126 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10127 else 10128 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10129 10130 MIB = BuildMI(*thisMBB, MI, DL, 10131 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10132 .addReg(BaseReg) 10133 .addImm(BPOffset) 10134 .addReg(BufReg) 10135 .cloneMemRefs(MI); 10136 10137 // Setup 10138 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10139 MIB.addRegMask(TRI->getNoPreservedMask()); 10140 10141 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10142 10143 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10144 .addMBB(mainMBB); 10145 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10146 10147 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10148 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10149 10150 // mainMBB: 10151 // mainDstReg = 0 10152 MIB = 10153 BuildMI(mainMBB, DL, 10154 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10155 10156 // Store IP 10157 if (Subtarget.isPPC64()) { 10158 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10159 .addReg(LabelReg) 10160 .addImm(LabelOffset) 10161 .addReg(BufReg); 10162 } else { 10163 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10164 .addReg(LabelReg) 10165 .addImm(LabelOffset) 10166 .addReg(BufReg); 10167 } 10168 MIB.cloneMemRefs(MI); 10169 10170 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10171 mainMBB->addSuccessor(sinkMBB); 10172 10173 // sinkMBB: 10174 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10175 TII->get(PPC::PHI), DstReg) 10176 .addReg(mainDstReg).addMBB(mainMBB) 10177 .addReg(restoreDstReg).addMBB(thisMBB); 10178 10179 MI.eraseFromParent(); 10180 return sinkMBB; 10181 } 10182 10183 MachineBasicBlock * 10184 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10185 MachineBasicBlock *MBB) const { 10186 DebugLoc DL = MI.getDebugLoc(); 10187 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10188 10189 MachineFunction *MF = MBB->getParent(); 10190 MachineRegisterInfo &MRI = MF->getRegInfo(); 10191 10192 MVT PVT = getPointerTy(MF->getDataLayout()); 10193 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10194 "Invalid Pointer Size!"); 10195 10196 const TargetRegisterClass *RC = 10197 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10198 unsigned Tmp = MRI.createVirtualRegister(RC); 10199 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10200 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10201 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10202 unsigned BP = 10203 (PVT == MVT::i64) 10204 ? PPC::X30 10205 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10206 : PPC::R30); 10207 10208 MachineInstrBuilder MIB; 10209 10210 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10211 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10212 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10213 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10214 10215 unsigned BufReg = MI.getOperand(0).getReg(); 10216 10217 // Reload FP (the jumped-to function may not have had a 10218 // frame pointer, and if so, then its r31 will be restored 10219 // as necessary). 10220 if (PVT == MVT::i64) { 10221 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10222 .addImm(0) 10223 .addReg(BufReg); 10224 } else { 10225 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10226 .addImm(0) 10227 .addReg(BufReg); 10228 } 10229 MIB.cloneMemRefs(MI); 10230 10231 // Reload IP 10232 if (PVT == MVT::i64) { 10233 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10234 .addImm(LabelOffset) 10235 .addReg(BufReg); 10236 } else { 10237 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10238 .addImm(LabelOffset) 10239 .addReg(BufReg); 10240 } 10241 MIB.cloneMemRefs(MI); 10242 10243 // Reload SP 10244 if (PVT == MVT::i64) { 10245 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10246 .addImm(SPOffset) 10247 .addReg(BufReg); 10248 } else { 10249 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10250 .addImm(SPOffset) 10251 .addReg(BufReg); 10252 } 10253 MIB.cloneMemRefs(MI); 10254 10255 // Reload BP 10256 if (PVT == MVT::i64) { 10257 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10258 .addImm(BPOffset) 10259 .addReg(BufReg); 10260 } else { 10261 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10262 .addImm(BPOffset) 10263 .addReg(BufReg); 10264 } 10265 MIB.cloneMemRefs(MI); 10266 10267 // Reload TOC 10268 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10269 setUsesTOCBasePtr(*MBB->getParent()); 10270 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10271 .addImm(TOCOffset) 10272 .addReg(BufReg) 10273 .cloneMemRefs(MI); 10274 } 10275 10276 // Jump 10277 BuildMI(*MBB, MI, DL, 10278 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10279 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10280 10281 MI.eraseFromParent(); 10282 return MBB; 10283 } 10284 10285 MachineBasicBlock * 10286 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10287 MachineBasicBlock *BB) const { 10288 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10289 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10290 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10291 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10292 // Call lowering should have added an r2 operand to indicate a dependence 10293 // on the TOC base pointer value. It can't however, because there is no 10294 // way to mark the dependence as implicit there, and so the stackmap code 10295 // will confuse it with a regular operand. Instead, add the dependence 10296 // here. 10297 setUsesTOCBasePtr(*BB->getParent()); 10298 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10299 } 10300 10301 return emitPatchPoint(MI, BB); 10302 } 10303 10304 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10305 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10306 return emitEHSjLjSetJmp(MI, BB); 10307 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10308 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10309 return emitEHSjLjLongJmp(MI, BB); 10310 } 10311 10312 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10313 10314 // To "insert" these instructions we actually have to insert their 10315 // control-flow patterns. 10316 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10317 MachineFunction::iterator It = ++BB->getIterator(); 10318 10319 MachineFunction *F = BB->getParent(); 10320 10321 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10322 MI.getOpcode() == PPC::SELECT_CC_I8 || 10323 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) { 10324 SmallVector<MachineOperand, 2> Cond; 10325 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10326 MI.getOpcode() == PPC::SELECT_CC_I8) 10327 Cond.push_back(MI.getOperand(4)); 10328 else 10329 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10330 Cond.push_back(MI.getOperand(1)); 10331 10332 DebugLoc dl = MI.getDebugLoc(); 10333 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10334 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10335 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10336 MI.getOpcode() == PPC::SELECT_CC_I8 || 10337 MI.getOpcode() == PPC::SELECT_CC_F4 || 10338 MI.getOpcode() == PPC::SELECT_CC_F8 || 10339 MI.getOpcode() == PPC::SELECT_CC_F16 || 10340 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10341 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10342 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10343 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10344 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10345 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10346 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10347 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 10348 MI.getOpcode() == PPC::SELECT_CC_SPE || 10349 MI.getOpcode() == PPC::SELECT_I4 || 10350 MI.getOpcode() == PPC::SELECT_I8 || 10351 MI.getOpcode() == PPC::SELECT_F4 || 10352 MI.getOpcode() == PPC::SELECT_F8 || 10353 MI.getOpcode() == PPC::SELECT_F16 || 10354 MI.getOpcode() == PPC::SELECT_QFRC || 10355 MI.getOpcode() == PPC::SELECT_QSRC || 10356 MI.getOpcode() == PPC::SELECT_QBRC || 10357 MI.getOpcode() == PPC::SELECT_SPE || 10358 MI.getOpcode() == PPC::SELECT_SPE4 || 10359 MI.getOpcode() == PPC::SELECT_VRRC || 10360 MI.getOpcode() == PPC::SELECT_VSFRC || 10361 MI.getOpcode() == PPC::SELECT_VSSRC || 10362 MI.getOpcode() == PPC::SELECT_VSRC) { 10363 // The incoming instruction knows the destination vreg to set, the 10364 // condition code register to branch on, the true/false values to 10365 // select between, and a branch opcode to use. 10366 10367 // thisMBB: 10368 // ... 10369 // TrueVal = ... 10370 // cmpTY ccX, r1, r2 10371 // bCC copy1MBB 10372 // fallthrough --> copy0MBB 10373 MachineBasicBlock *thisMBB = BB; 10374 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10375 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10376 DebugLoc dl = MI.getDebugLoc(); 10377 F->insert(It, copy0MBB); 10378 F->insert(It, sinkMBB); 10379 10380 // Transfer the remainder of BB and its successor edges to sinkMBB. 10381 sinkMBB->splice(sinkMBB->begin(), BB, 10382 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10383 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10384 10385 // Next, add the true and fallthrough blocks as its successors. 10386 BB->addSuccessor(copy0MBB); 10387 BB->addSuccessor(sinkMBB); 10388 10389 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10390 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10391 MI.getOpcode() == PPC::SELECT_F16 || 10392 MI.getOpcode() == PPC::SELECT_SPE4 || 10393 MI.getOpcode() == PPC::SELECT_SPE || 10394 MI.getOpcode() == PPC::SELECT_QFRC || 10395 MI.getOpcode() == PPC::SELECT_QSRC || 10396 MI.getOpcode() == PPC::SELECT_QBRC || 10397 MI.getOpcode() == PPC::SELECT_VRRC || 10398 MI.getOpcode() == PPC::SELECT_VSFRC || 10399 MI.getOpcode() == PPC::SELECT_VSSRC || 10400 MI.getOpcode() == PPC::SELECT_VSRC) { 10401 BuildMI(BB, dl, TII->get(PPC::BC)) 10402 .addReg(MI.getOperand(1).getReg()) 10403 .addMBB(sinkMBB); 10404 } else { 10405 unsigned SelectPred = MI.getOperand(4).getImm(); 10406 BuildMI(BB, dl, TII->get(PPC::BCC)) 10407 .addImm(SelectPred) 10408 .addReg(MI.getOperand(1).getReg()) 10409 .addMBB(sinkMBB); 10410 } 10411 10412 // copy0MBB: 10413 // %FalseValue = ... 10414 // # fallthrough to sinkMBB 10415 BB = copy0MBB; 10416 10417 // Update machine-CFG edges 10418 BB->addSuccessor(sinkMBB); 10419 10420 // sinkMBB: 10421 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10422 // ... 10423 BB = sinkMBB; 10424 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10425 .addReg(MI.getOperand(3).getReg()) 10426 .addMBB(copy0MBB) 10427 .addReg(MI.getOperand(2).getReg()) 10428 .addMBB(thisMBB); 10429 } else if (MI.getOpcode() == PPC::ReadTB) { 10430 // To read the 64-bit time-base register on a 32-bit target, we read the 10431 // two halves. Should the counter have wrapped while it was being read, we 10432 // need to try again. 10433 // ... 10434 // readLoop: 10435 // mfspr Rx,TBU # load from TBU 10436 // mfspr Ry,TB # load from TB 10437 // mfspr Rz,TBU # load from TBU 10438 // cmpw crX,Rx,Rz # check if 'old'='new' 10439 // bne readLoop # branch if they're not equal 10440 // ... 10441 10442 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10443 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10444 DebugLoc dl = MI.getDebugLoc(); 10445 F->insert(It, readMBB); 10446 F->insert(It, sinkMBB); 10447 10448 // Transfer the remainder of BB and its successor edges to sinkMBB. 10449 sinkMBB->splice(sinkMBB->begin(), BB, 10450 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10451 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10452 10453 BB->addSuccessor(readMBB); 10454 BB = readMBB; 10455 10456 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10457 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10458 unsigned LoReg = MI.getOperand(0).getReg(); 10459 unsigned HiReg = MI.getOperand(1).getReg(); 10460 10461 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10462 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10463 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10464 10465 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10466 10467 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10468 .addReg(HiReg).addReg(ReadAgainReg); 10469 BuildMI(BB, dl, TII->get(PPC::BCC)) 10470 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB); 10471 10472 BB->addSuccessor(readMBB); 10473 BB->addSuccessor(sinkMBB); 10474 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10475 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10476 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10477 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10478 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10479 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10480 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10481 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10482 10483 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10484 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10485 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10486 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10487 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10488 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10489 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10490 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10491 10492 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10493 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10494 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10495 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10496 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10497 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10498 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10499 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10500 10501 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10502 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10503 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10504 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10505 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10506 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10507 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10508 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10509 10510 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10511 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10512 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10513 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10514 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10515 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10516 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10517 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10518 10519 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10520 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10521 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10522 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10523 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10524 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10525 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10526 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10527 10528 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10529 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10530 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10531 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10532 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10533 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10534 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10535 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10536 10537 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10538 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10539 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10540 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10541 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10542 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10543 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10544 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10545 10546 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10547 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10548 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10549 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10550 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10551 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10552 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10553 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10554 10555 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10556 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10557 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10558 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10559 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10560 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10561 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10562 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10563 10564 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10565 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10566 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10567 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10568 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10569 BB = EmitAtomicBinary(MI, BB, 4, 0); 10570 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10571 BB = EmitAtomicBinary(MI, BB, 8, 0); 10572 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10573 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10574 (Subtarget.hasPartwordAtomics() && 10575 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10576 (Subtarget.hasPartwordAtomics() && 10577 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10578 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10579 10580 auto LoadMnemonic = PPC::LDARX; 10581 auto StoreMnemonic = PPC::STDCX; 10582 switch (MI.getOpcode()) { 10583 default: 10584 llvm_unreachable("Compare and swap of unknown size"); 10585 case PPC::ATOMIC_CMP_SWAP_I8: 10586 LoadMnemonic = PPC::LBARX; 10587 StoreMnemonic = PPC::STBCX; 10588 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10589 break; 10590 case PPC::ATOMIC_CMP_SWAP_I16: 10591 LoadMnemonic = PPC::LHARX; 10592 StoreMnemonic = PPC::STHCX; 10593 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10594 break; 10595 case PPC::ATOMIC_CMP_SWAP_I32: 10596 LoadMnemonic = PPC::LWARX; 10597 StoreMnemonic = PPC::STWCX; 10598 break; 10599 case PPC::ATOMIC_CMP_SWAP_I64: 10600 LoadMnemonic = PPC::LDARX; 10601 StoreMnemonic = PPC::STDCX; 10602 break; 10603 } 10604 unsigned dest = MI.getOperand(0).getReg(); 10605 unsigned ptrA = MI.getOperand(1).getReg(); 10606 unsigned ptrB = MI.getOperand(2).getReg(); 10607 unsigned oldval = MI.getOperand(3).getReg(); 10608 unsigned newval = MI.getOperand(4).getReg(); 10609 DebugLoc dl = MI.getDebugLoc(); 10610 10611 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10612 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10613 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10614 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10615 F->insert(It, loop1MBB); 10616 F->insert(It, loop2MBB); 10617 F->insert(It, midMBB); 10618 F->insert(It, exitMBB); 10619 exitMBB->splice(exitMBB->begin(), BB, 10620 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10621 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10622 10623 // thisMBB: 10624 // ... 10625 // fallthrough --> loopMBB 10626 BB->addSuccessor(loop1MBB); 10627 10628 // loop1MBB: 10629 // l[bhwd]arx dest, ptr 10630 // cmp[wd] dest, oldval 10631 // bne- midMBB 10632 // loop2MBB: 10633 // st[bhwd]cx. newval, ptr 10634 // bne- loopMBB 10635 // b exitBB 10636 // midMBB: 10637 // st[bhwd]cx. dest, ptr 10638 // exitBB: 10639 BB = loop1MBB; 10640 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10641 .addReg(ptrA).addReg(ptrB); 10642 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10643 .addReg(oldval).addReg(dest); 10644 BuildMI(BB, dl, TII->get(PPC::BCC)) 10645 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10646 BB->addSuccessor(loop2MBB); 10647 BB->addSuccessor(midMBB); 10648 10649 BB = loop2MBB; 10650 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10651 .addReg(newval).addReg(ptrA).addReg(ptrB); 10652 BuildMI(BB, dl, TII->get(PPC::BCC)) 10653 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10654 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10655 BB->addSuccessor(loop1MBB); 10656 BB->addSuccessor(exitMBB); 10657 10658 BB = midMBB; 10659 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10660 .addReg(dest).addReg(ptrA).addReg(ptrB); 10661 BB->addSuccessor(exitMBB); 10662 10663 // exitMBB: 10664 // ... 10665 BB = exitMBB; 10666 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 10667 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 10668 // We must use 64-bit registers for addresses when targeting 64-bit, 10669 // since we're actually doing arithmetic on them. Other registers 10670 // can be 32-bit. 10671 bool is64bit = Subtarget.isPPC64(); 10672 bool isLittleEndian = Subtarget.isLittleEndian(); 10673 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 10674 10675 unsigned dest = MI.getOperand(0).getReg(); 10676 unsigned ptrA = MI.getOperand(1).getReg(); 10677 unsigned ptrB = MI.getOperand(2).getReg(); 10678 unsigned oldval = MI.getOperand(3).getReg(); 10679 unsigned newval = MI.getOperand(4).getReg(); 10680 DebugLoc dl = MI.getDebugLoc(); 10681 10682 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10683 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10684 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10685 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10686 F->insert(It, loop1MBB); 10687 F->insert(It, loop2MBB); 10688 F->insert(It, midMBB); 10689 F->insert(It, exitMBB); 10690 exitMBB->splice(exitMBB->begin(), BB, 10691 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10692 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10693 10694 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10695 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 10696 : &PPC::GPRCRegClass; 10697 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10698 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 10699 unsigned ShiftReg = 10700 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 10701 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 10702 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 10703 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 10704 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 10705 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 10706 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 10707 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 10708 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 10709 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 10710 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 10711 unsigned Ptr1Reg; 10712 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 10713 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10714 // thisMBB: 10715 // ... 10716 // fallthrough --> loopMBB 10717 BB->addSuccessor(loop1MBB); 10718 10719 // The 4-byte load must be aligned, while a char or short may be 10720 // anywhere in the word. Hence all this nasty bookkeeping code. 10721 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10722 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10723 // xori shift, shift1, 24 [16] 10724 // rlwinm ptr, ptr1, 0, 0, 29 10725 // slw newval2, newval, shift 10726 // slw oldval2, oldval,shift 10727 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10728 // slw mask, mask2, shift 10729 // and newval3, newval2, mask 10730 // and oldval3, oldval2, mask 10731 // loop1MBB: 10732 // lwarx tmpDest, ptr 10733 // and tmp, tmpDest, mask 10734 // cmpw tmp, oldval3 10735 // bne- midMBB 10736 // loop2MBB: 10737 // andc tmp2, tmpDest, mask 10738 // or tmp4, tmp2, newval3 10739 // stwcx. tmp4, ptr 10740 // bne- loop1MBB 10741 // b exitBB 10742 // midMBB: 10743 // stwcx. tmpDest, ptr 10744 // exitBB: 10745 // srw dest, tmpDest, shift 10746 if (ptrA != ZeroReg) { 10747 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10748 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10749 .addReg(ptrA).addReg(ptrB); 10750 } else { 10751 Ptr1Reg = ptrB; 10752 } 10753 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 10754 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 10755 if (!isLittleEndian) 10756 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 10757 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 10758 if (is64bit) 10759 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10760 .addReg(Ptr1Reg).addImm(0).addImm(61); 10761 else 10762 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10763 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 10764 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 10765 .addReg(newval).addReg(ShiftReg); 10766 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 10767 .addReg(oldval).addReg(ShiftReg); 10768 if (is8bit) 10769 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10770 else { 10771 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10772 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10773 .addReg(Mask3Reg).addImm(65535); 10774 } 10775 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10776 .addReg(Mask2Reg).addReg(ShiftReg); 10777 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 10778 .addReg(NewVal2Reg).addReg(MaskReg); 10779 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 10780 .addReg(OldVal2Reg).addReg(MaskReg); 10781 10782 BB = loop1MBB; 10783 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10784 .addReg(ZeroReg).addReg(PtrReg); 10785 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 10786 .addReg(TmpDestReg).addReg(MaskReg); 10787 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 10788 .addReg(TmpReg).addReg(OldVal3Reg); 10789 BuildMI(BB, dl, TII->get(PPC::BCC)) 10790 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10791 BB->addSuccessor(loop2MBB); 10792 BB->addSuccessor(midMBB); 10793 10794 BB = loop2MBB; 10795 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 10796 .addReg(TmpDestReg).addReg(MaskReg); 10797 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 10798 .addReg(Tmp2Reg).addReg(NewVal3Reg); 10799 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 10800 .addReg(ZeroReg).addReg(PtrReg); 10801 BuildMI(BB, dl, TII->get(PPC::BCC)) 10802 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10803 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10804 BB->addSuccessor(loop1MBB); 10805 BB->addSuccessor(exitMBB); 10806 10807 BB = midMBB; 10808 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 10809 .addReg(ZeroReg).addReg(PtrReg); 10810 BB->addSuccessor(exitMBB); 10811 10812 // exitMBB: 10813 // ... 10814 BB = exitMBB; 10815 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 10816 .addReg(ShiftReg); 10817 } else if (MI.getOpcode() == PPC::FADDrtz) { 10818 // This pseudo performs an FADD with rounding mode temporarily forced 10819 // to round-to-zero. We emit this via custom inserter since the FPSCR 10820 // is not modeled at the SelectionDAG level. 10821 unsigned Dest = MI.getOperand(0).getReg(); 10822 unsigned Src1 = MI.getOperand(1).getReg(); 10823 unsigned Src2 = MI.getOperand(2).getReg(); 10824 DebugLoc dl = MI.getDebugLoc(); 10825 10826 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10827 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 10828 10829 // Save FPSCR value. 10830 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 10831 10832 // Set rounding mode to round-to-zero. 10833 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 10834 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 10835 10836 // Perform addition. 10837 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 10838 10839 // Restore FPSCR value. 10840 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 10841 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10842 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 10843 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10844 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 10845 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10846 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 10847 ? PPC::ANDIo8 10848 : PPC::ANDIo; 10849 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10850 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 10851 10852 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10853 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? 10854 &PPC::GPRCRegClass : 10855 &PPC::G8RCRegClass); 10856 10857 DebugLoc dl = MI.getDebugLoc(); 10858 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 10859 .addReg(MI.getOperand(1).getReg()) 10860 .addImm(1); 10861 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 10862 MI.getOperand(0).getReg()) 10863 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 10864 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 10865 DebugLoc Dl = MI.getDebugLoc(); 10866 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10867 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10868 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 10869 return BB; 10870 } else { 10871 llvm_unreachable("Unexpected instr type to insert"); 10872 } 10873 10874 MI.eraseFromParent(); // The pseudo instruction is gone now. 10875 return BB; 10876 } 10877 10878 //===----------------------------------------------------------------------===// 10879 // Target Optimization Hooks 10880 //===----------------------------------------------------------------------===// 10881 10882 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 10883 // For the estimates, convergence is quadratic, so we essentially double the 10884 // number of digits correct after every iteration. For both FRE and FRSQRTE, 10885 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 10886 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 10887 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 10888 if (VT.getScalarType() == MVT::f64) 10889 RefinementSteps++; 10890 return RefinementSteps; 10891 } 10892 10893 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 10894 int Enabled, int &RefinementSteps, 10895 bool &UseOneConstNR, 10896 bool Reciprocal) const { 10897 EVT VT = Operand.getValueType(); 10898 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 10899 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 10900 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10901 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10902 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10903 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10904 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10905 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10906 10907 UseOneConstNR = true; 10908 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 10909 } 10910 return SDValue(); 10911 } 10912 10913 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 10914 int Enabled, 10915 int &RefinementSteps) const { 10916 EVT VT = Operand.getValueType(); 10917 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 10918 (VT == MVT::f64 && Subtarget.hasFRE()) || 10919 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10920 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10921 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10922 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10923 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10924 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10925 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 10926 } 10927 return SDValue(); 10928 } 10929 10930 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 10931 // Note: This functionality is used only when unsafe-fp-math is enabled, and 10932 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 10933 // enabled for division), this functionality is redundant with the default 10934 // combiner logic (once the division -> reciprocal/multiply transformation 10935 // has taken place). As a result, this matters more for older cores than for 10936 // newer ones. 10937 10938 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10939 // reciprocal if there are two or more FDIVs (for embedded cores with only 10940 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 10941 switch (Subtarget.getDarwinDirective()) { 10942 default: 10943 return 3; 10944 case PPC::DIR_440: 10945 case PPC::DIR_A2: 10946 case PPC::DIR_E500: 10947 case PPC::DIR_E500mc: 10948 case PPC::DIR_E5500: 10949 return 2; 10950 } 10951 } 10952 10953 // isConsecutiveLSLoc needs to work even if all adds have not yet been 10954 // collapsed, and so we need to look through chains of them. 10955 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 10956 int64_t& Offset, SelectionDAG &DAG) { 10957 if (DAG.isBaseWithConstantOffset(Loc)) { 10958 Base = Loc.getOperand(0); 10959 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 10960 10961 // The base might itself be a base plus an offset, and if so, accumulate 10962 // that as well. 10963 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 10964 } 10965 } 10966 10967 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 10968 unsigned Bytes, int Dist, 10969 SelectionDAG &DAG) { 10970 if (VT.getSizeInBits() / 8 != Bytes) 10971 return false; 10972 10973 SDValue BaseLoc = Base->getBasePtr(); 10974 if (Loc.getOpcode() == ISD::FrameIndex) { 10975 if (BaseLoc.getOpcode() != ISD::FrameIndex) 10976 return false; 10977 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10978 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 10979 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 10980 int FS = MFI.getObjectSize(FI); 10981 int BFS = MFI.getObjectSize(BFI); 10982 if (FS != BFS || FS != (int)Bytes) return false; 10983 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 10984 } 10985 10986 SDValue Base1 = Loc, Base2 = BaseLoc; 10987 int64_t Offset1 = 0, Offset2 = 0; 10988 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 10989 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 10990 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 10991 return true; 10992 10993 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10994 const GlobalValue *GV1 = nullptr; 10995 const GlobalValue *GV2 = nullptr; 10996 Offset1 = 0; 10997 Offset2 = 0; 10998 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 10999 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 11000 if (isGA1 && isGA2 && GV1 == GV2) 11001 return Offset1 == (Offset2 + Dist*Bytes); 11002 return false; 11003 } 11004 11005 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11006 // not enforce equality of the chain operands. 11007 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11008 unsigned Bytes, int Dist, 11009 SelectionDAG &DAG) { 11010 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11011 EVT VT = LS->getMemoryVT(); 11012 SDValue Loc = LS->getBasePtr(); 11013 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11014 } 11015 11016 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11017 EVT VT; 11018 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11019 default: return false; 11020 case Intrinsic::ppc_qpx_qvlfd: 11021 case Intrinsic::ppc_qpx_qvlfda: 11022 VT = MVT::v4f64; 11023 break; 11024 case Intrinsic::ppc_qpx_qvlfs: 11025 case Intrinsic::ppc_qpx_qvlfsa: 11026 VT = MVT::v4f32; 11027 break; 11028 case Intrinsic::ppc_qpx_qvlfcd: 11029 case Intrinsic::ppc_qpx_qvlfcda: 11030 VT = MVT::v2f64; 11031 break; 11032 case Intrinsic::ppc_qpx_qvlfcs: 11033 case Intrinsic::ppc_qpx_qvlfcsa: 11034 VT = MVT::v2f32; 11035 break; 11036 case Intrinsic::ppc_qpx_qvlfiwa: 11037 case Intrinsic::ppc_qpx_qvlfiwz: 11038 case Intrinsic::ppc_altivec_lvx: 11039 case Intrinsic::ppc_altivec_lvxl: 11040 case Intrinsic::ppc_vsx_lxvw4x: 11041 case Intrinsic::ppc_vsx_lxvw4x_be: 11042 VT = MVT::v4i32; 11043 break; 11044 case Intrinsic::ppc_vsx_lxvd2x: 11045 case Intrinsic::ppc_vsx_lxvd2x_be: 11046 VT = MVT::v2f64; 11047 break; 11048 case Intrinsic::ppc_altivec_lvebx: 11049 VT = MVT::i8; 11050 break; 11051 case Intrinsic::ppc_altivec_lvehx: 11052 VT = MVT::i16; 11053 break; 11054 case Intrinsic::ppc_altivec_lvewx: 11055 VT = MVT::i32; 11056 break; 11057 } 11058 11059 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 11060 } 11061 11062 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 11063 EVT VT; 11064 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11065 default: return false; 11066 case Intrinsic::ppc_qpx_qvstfd: 11067 case Intrinsic::ppc_qpx_qvstfda: 11068 VT = MVT::v4f64; 11069 break; 11070 case Intrinsic::ppc_qpx_qvstfs: 11071 case Intrinsic::ppc_qpx_qvstfsa: 11072 VT = MVT::v4f32; 11073 break; 11074 case Intrinsic::ppc_qpx_qvstfcd: 11075 case Intrinsic::ppc_qpx_qvstfcda: 11076 VT = MVT::v2f64; 11077 break; 11078 case Intrinsic::ppc_qpx_qvstfcs: 11079 case Intrinsic::ppc_qpx_qvstfcsa: 11080 VT = MVT::v2f32; 11081 break; 11082 case Intrinsic::ppc_qpx_qvstfiw: 11083 case Intrinsic::ppc_qpx_qvstfiwa: 11084 case Intrinsic::ppc_altivec_stvx: 11085 case Intrinsic::ppc_altivec_stvxl: 11086 case Intrinsic::ppc_vsx_stxvw4x: 11087 VT = MVT::v4i32; 11088 break; 11089 case Intrinsic::ppc_vsx_stxvd2x: 11090 VT = MVT::v2f64; 11091 break; 11092 case Intrinsic::ppc_vsx_stxvw4x_be: 11093 VT = MVT::v4i32; 11094 break; 11095 case Intrinsic::ppc_vsx_stxvd2x_be: 11096 VT = MVT::v2f64; 11097 break; 11098 case Intrinsic::ppc_altivec_stvebx: 11099 VT = MVT::i8; 11100 break; 11101 case Intrinsic::ppc_altivec_stvehx: 11102 VT = MVT::i16; 11103 break; 11104 case Intrinsic::ppc_altivec_stvewx: 11105 VT = MVT::i32; 11106 break; 11107 } 11108 11109 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 11110 } 11111 11112 return false; 11113 } 11114 11115 // Return true is there is a nearyby consecutive load to the one provided 11116 // (regardless of alignment). We search up and down the chain, looking though 11117 // token factors and other loads (but nothing else). As a result, a true result 11118 // indicates that it is safe to create a new consecutive load adjacent to the 11119 // load provided. 11120 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 11121 SDValue Chain = LD->getChain(); 11122 EVT VT = LD->getMemoryVT(); 11123 11124 SmallSet<SDNode *, 16> LoadRoots; 11125 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 11126 SmallSet<SDNode *, 16> Visited; 11127 11128 // First, search up the chain, branching to follow all token-factor operands. 11129 // If we find a consecutive load, then we're done, otherwise, record all 11130 // nodes just above the top-level loads and token factors. 11131 while (!Queue.empty()) { 11132 SDNode *ChainNext = Queue.pop_back_val(); 11133 if (!Visited.insert(ChainNext).second) 11134 continue; 11135 11136 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 11137 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11138 return true; 11139 11140 if (!Visited.count(ChainLD->getChain().getNode())) 11141 Queue.push_back(ChainLD->getChain().getNode()); 11142 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 11143 for (const SDUse &O : ChainNext->ops()) 11144 if (!Visited.count(O.getNode())) 11145 Queue.push_back(O.getNode()); 11146 } else 11147 LoadRoots.insert(ChainNext); 11148 } 11149 11150 // Second, search down the chain, starting from the top-level nodes recorded 11151 // in the first phase. These top-level nodes are the nodes just above all 11152 // loads and token factors. Starting with their uses, recursively look though 11153 // all loads (just the chain uses) and token factors to find a consecutive 11154 // load. 11155 Visited.clear(); 11156 Queue.clear(); 11157 11158 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 11159 IE = LoadRoots.end(); I != IE; ++I) { 11160 Queue.push_back(*I); 11161 11162 while (!Queue.empty()) { 11163 SDNode *LoadRoot = Queue.pop_back_val(); 11164 if (!Visited.insert(LoadRoot).second) 11165 continue; 11166 11167 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 11168 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11169 return true; 11170 11171 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 11172 UE = LoadRoot->use_end(); UI != UE; ++UI) 11173 if (((isa<MemSDNode>(*UI) && 11174 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 11175 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 11176 Queue.push_back(*UI); 11177 } 11178 } 11179 11180 return false; 11181 } 11182 11183 /// This function is called when we have proved that a SETCC node can be replaced 11184 /// by subtraction (and other supporting instructions) so that the result of 11185 /// comparison is kept in a GPR instead of CR. This function is purely for 11186 /// codegen purposes and has some flags to guide the codegen process. 11187 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 11188 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 11189 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11190 11191 // Zero extend the operands to the largest legal integer. Originally, they 11192 // must be of a strictly smaller size. 11193 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 11194 DAG.getConstant(Size, DL, MVT::i32)); 11195 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 11196 DAG.getConstant(Size, DL, MVT::i32)); 11197 11198 // Swap if needed. Depends on the condition code. 11199 if (Swap) 11200 std::swap(Op0, Op1); 11201 11202 // Subtract extended integers. 11203 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 11204 11205 // Move the sign bit to the least significant position and zero out the rest. 11206 // Now the least significant bit carries the result of original comparison. 11207 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 11208 DAG.getConstant(Size - 1, DL, MVT::i32)); 11209 auto Final = Shifted; 11210 11211 // Complement the result if needed. Based on the condition code. 11212 if (Complement) 11213 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 11214 DAG.getConstant(1, DL, MVT::i64)); 11215 11216 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11217 } 11218 11219 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11220 DAGCombinerInfo &DCI) const { 11221 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11222 11223 SelectionDAG &DAG = DCI.DAG; 11224 SDLoc DL(N); 11225 11226 // Size of integers being compared has a critical role in the following 11227 // analysis, so we prefer to do this when all types are legal. 11228 if (!DCI.isAfterLegalizeDAG()) 11229 return SDValue(); 11230 11231 // If all users of SETCC extend its value to a legal integer type 11232 // then we replace SETCC with a subtraction 11233 for (SDNode::use_iterator UI = N->use_begin(), 11234 UE = N->use_end(); UI != UE; ++UI) { 11235 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11236 return SDValue(); 11237 } 11238 11239 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11240 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11241 11242 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11243 11244 if (OpSize < Size) { 11245 switch (CC) { 11246 default: break; 11247 case ISD::SETULT: 11248 return generateEquivalentSub(N, Size, false, false, DL, DAG); 11249 case ISD::SETULE: 11250 return generateEquivalentSub(N, Size, true, true, DL, DAG); 11251 case ISD::SETUGT: 11252 return generateEquivalentSub(N, Size, false, true, DL, DAG); 11253 case ISD::SETUGE: 11254 return generateEquivalentSub(N, Size, true, false, DL, DAG); 11255 } 11256 } 11257 11258 return SDValue(); 11259 } 11260 11261 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 11262 DAGCombinerInfo &DCI) const { 11263 SelectionDAG &DAG = DCI.DAG; 11264 SDLoc dl(N); 11265 11266 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11267 // If we're tracking CR bits, we need to be careful that we don't have: 11268 // trunc(binary-ops(zext(x), zext(y))) 11269 // or 11270 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11271 // such that we're unnecessarily moving things into GPRs when it would be 11272 // better to keep them in CR bits. 11273 11274 // Note that trunc here can be an actual i1 trunc, or can be the effective 11275 // truncation that comes from a setcc or select_cc. 11276 if (N->getOpcode() == ISD::TRUNCATE && 11277 N->getValueType(0) != MVT::i1) 11278 return SDValue(); 11279 11280 if (N->getOperand(0).getValueType() != MVT::i32 && 11281 N->getOperand(0).getValueType() != MVT::i64) 11282 return SDValue(); 11283 11284 if (N->getOpcode() == ISD::SETCC || 11285 N->getOpcode() == ISD::SELECT_CC) { 11286 // If we're looking at a comparison, then we need to make sure that the 11287 // high bits (all except for the first) don't matter the result. 11288 ISD::CondCode CC = 11289 cast<CondCodeSDNode>(N->getOperand( 11290 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11291 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11292 11293 if (ISD::isSignedIntSetCC(CC)) { 11294 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11295 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11296 return SDValue(); 11297 } else if (ISD::isUnsignedIntSetCC(CC)) { 11298 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11299 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11300 !DAG.MaskedValueIsZero(N->getOperand(1), 11301 APInt::getHighBitsSet(OpBits, OpBits-1))) 11302 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11303 : SDValue()); 11304 } else { 11305 // This is neither a signed nor an unsigned comparison, just make sure 11306 // that the high bits are equal. 11307 KnownBits Op1Known, Op2Known; 11308 DAG.computeKnownBits(N->getOperand(0), Op1Known); 11309 DAG.computeKnownBits(N->getOperand(1), Op2Known); 11310 11311 // We don't really care about what is known about the first bit (if 11312 // anything), so clear it in all masks prior to comparing them. 11313 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11314 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11315 11316 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11317 return SDValue(); 11318 } 11319 } 11320 11321 // We now know that the higher-order bits are irrelevant, we just need to 11322 // make sure that all of the intermediate operations are bit operations, and 11323 // all inputs are extensions. 11324 if (N->getOperand(0).getOpcode() != ISD::AND && 11325 N->getOperand(0).getOpcode() != ISD::OR && 11326 N->getOperand(0).getOpcode() != ISD::XOR && 11327 N->getOperand(0).getOpcode() != ISD::SELECT && 11328 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11329 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11330 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11331 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11332 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11333 return SDValue(); 11334 11335 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11336 N->getOperand(1).getOpcode() != ISD::AND && 11337 N->getOperand(1).getOpcode() != ISD::OR && 11338 N->getOperand(1).getOpcode() != ISD::XOR && 11339 N->getOperand(1).getOpcode() != ISD::SELECT && 11340 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11341 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11342 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11343 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11344 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11345 return SDValue(); 11346 11347 SmallVector<SDValue, 4> Inputs; 11348 SmallVector<SDValue, 8> BinOps, PromOps; 11349 SmallPtrSet<SDNode *, 16> Visited; 11350 11351 for (unsigned i = 0; i < 2; ++i) { 11352 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11353 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11354 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11355 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11356 isa<ConstantSDNode>(N->getOperand(i))) 11357 Inputs.push_back(N->getOperand(i)); 11358 else 11359 BinOps.push_back(N->getOperand(i)); 11360 11361 if (N->getOpcode() == ISD::TRUNCATE) 11362 break; 11363 } 11364 11365 // Visit all inputs, collect all binary operations (and, or, xor and 11366 // select) that are all fed by extensions. 11367 while (!BinOps.empty()) { 11368 SDValue BinOp = BinOps.back(); 11369 BinOps.pop_back(); 11370 11371 if (!Visited.insert(BinOp.getNode()).second) 11372 continue; 11373 11374 PromOps.push_back(BinOp); 11375 11376 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11377 // The condition of the select is not promoted. 11378 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11379 continue; 11380 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11381 continue; 11382 11383 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11384 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11385 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11386 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11387 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11388 Inputs.push_back(BinOp.getOperand(i)); 11389 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11390 BinOp.getOperand(i).getOpcode() == ISD::OR || 11391 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11392 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11393 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11394 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11395 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11396 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11397 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11398 BinOps.push_back(BinOp.getOperand(i)); 11399 } else { 11400 // We have an input that is not an extension or another binary 11401 // operation; we'll abort this transformation. 11402 return SDValue(); 11403 } 11404 } 11405 } 11406 11407 // Make sure that this is a self-contained cluster of operations (which 11408 // is not quite the same thing as saying that everything has only one 11409 // use). 11410 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11411 if (isa<ConstantSDNode>(Inputs[i])) 11412 continue; 11413 11414 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11415 UE = Inputs[i].getNode()->use_end(); 11416 UI != UE; ++UI) { 11417 SDNode *User = *UI; 11418 if (User != N && !Visited.count(User)) 11419 return SDValue(); 11420 11421 // Make sure that we're not going to promote the non-output-value 11422 // operand(s) or SELECT or SELECT_CC. 11423 // FIXME: Although we could sometimes handle this, and it does occur in 11424 // practice that one of the condition inputs to the select is also one of 11425 // the outputs, we currently can't deal with this. 11426 if (User->getOpcode() == ISD::SELECT) { 11427 if (User->getOperand(0) == Inputs[i]) 11428 return SDValue(); 11429 } else if (User->getOpcode() == ISD::SELECT_CC) { 11430 if (User->getOperand(0) == Inputs[i] || 11431 User->getOperand(1) == Inputs[i]) 11432 return SDValue(); 11433 } 11434 } 11435 } 11436 11437 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11438 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11439 UE = PromOps[i].getNode()->use_end(); 11440 UI != UE; ++UI) { 11441 SDNode *User = *UI; 11442 if (User != N && !Visited.count(User)) 11443 return SDValue(); 11444 11445 // Make sure that we're not going to promote the non-output-value 11446 // operand(s) or SELECT or SELECT_CC. 11447 // FIXME: Although we could sometimes handle this, and it does occur in 11448 // practice that one of the condition inputs to the select is also one of 11449 // the outputs, we currently can't deal with this. 11450 if (User->getOpcode() == ISD::SELECT) { 11451 if (User->getOperand(0) == PromOps[i]) 11452 return SDValue(); 11453 } else if (User->getOpcode() == ISD::SELECT_CC) { 11454 if (User->getOperand(0) == PromOps[i] || 11455 User->getOperand(1) == PromOps[i]) 11456 return SDValue(); 11457 } 11458 } 11459 } 11460 11461 // Replace all inputs with the extension operand. 11462 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11463 // Constants may have users outside the cluster of to-be-promoted nodes, 11464 // and so we need to replace those as we do the promotions. 11465 if (isa<ConstantSDNode>(Inputs[i])) 11466 continue; 11467 else 11468 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 11469 } 11470 11471 std::list<HandleSDNode> PromOpHandles; 11472 for (auto &PromOp : PromOps) 11473 PromOpHandles.emplace_back(PromOp); 11474 11475 // Replace all operations (these are all the same, but have a different 11476 // (i1) return type). DAG.getNode will validate that the types of 11477 // a binary operator match, so go through the list in reverse so that 11478 // we've likely promoted both operands first. Any intermediate truncations or 11479 // extensions disappear. 11480 while (!PromOpHandles.empty()) { 11481 SDValue PromOp = PromOpHandles.back().getValue(); 11482 PromOpHandles.pop_back(); 11483 11484 if (PromOp.getOpcode() == ISD::TRUNCATE || 11485 PromOp.getOpcode() == ISD::SIGN_EXTEND || 11486 PromOp.getOpcode() == ISD::ZERO_EXTEND || 11487 PromOp.getOpcode() == ISD::ANY_EXTEND) { 11488 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 11489 PromOp.getOperand(0).getValueType() != MVT::i1) { 11490 // The operand is not yet ready (see comment below). 11491 PromOpHandles.emplace_front(PromOp); 11492 continue; 11493 } 11494 11495 SDValue RepValue = PromOp.getOperand(0); 11496 if (isa<ConstantSDNode>(RepValue)) 11497 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 11498 11499 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 11500 continue; 11501 } 11502 11503 unsigned C; 11504 switch (PromOp.getOpcode()) { 11505 default: C = 0; break; 11506 case ISD::SELECT: C = 1; break; 11507 case ISD::SELECT_CC: C = 2; break; 11508 } 11509 11510 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11511 PromOp.getOperand(C).getValueType() != MVT::i1) || 11512 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11513 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 11514 // The to-be-promoted operands of this node have not yet been 11515 // promoted (this should be rare because we're going through the 11516 // list backward, but if one of the operands has several users in 11517 // this cluster of to-be-promoted nodes, it is possible). 11518 PromOpHandles.emplace_front(PromOp); 11519 continue; 11520 } 11521 11522 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11523 PromOp.getNode()->op_end()); 11524 11525 // If there are any constant inputs, make sure they're replaced now. 11526 for (unsigned i = 0; i < 2; ++i) 11527 if (isa<ConstantSDNode>(Ops[C+i])) 11528 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 11529 11530 DAG.ReplaceAllUsesOfValueWith(PromOp, 11531 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 11532 } 11533 11534 // Now we're left with the initial truncation itself. 11535 if (N->getOpcode() == ISD::TRUNCATE) 11536 return N->getOperand(0); 11537 11538 // Otherwise, this is a comparison. The operands to be compared have just 11539 // changed type (to i1), but everything else is the same. 11540 return SDValue(N, 0); 11541 } 11542 11543 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 11544 DAGCombinerInfo &DCI) const { 11545 SelectionDAG &DAG = DCI.DAG; 11546 SDLoc dl(N); 11547 11548 // If we're tracking CR bits, we need to be careful that we don't have: 11549 // zext(binary-ops(trunc(x), trunc(y))) 11550 // or 11551 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 11552 // such that we're unnecessarily moving things into CR bits that can more 11553 // efficiently stay in GPRs. Note that if we're not certain that the high 11554 // bits are set as required by the final extension, we still may need to do 11555 // some masking to get the proper behavior. 11556 11557 // This same functionality is important on PPC64 when dealing with 11558 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 11559 // the return values of functions. Because it is so similar, it is handled 11560 // here as well. 11561 11562 if (N->getValueType(0) != MVT::i32 && 11563 N->getValueType(0) != MVT::i64) 11564 return SDValue(); 11565 11566 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 11567 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 11568 return SDValue(); 11569 11570 if (N->getOperand(0).getOpcode() != ISD::AND && 11571 N->getOperand(0).getOpcode() != ISD::OR && 11572 N->getOperand(0).getOpcode() != ISD::XOR && 11573 N->getOperand(0).getOpcode() != ISD::SELECT && 11574 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 11575 return SDValue(); 11576 11577 SmallVector<SDValue, 4> Inputs; 11578 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 11579 SmallPtrSet<SDNode *, 16> Visited; 11580 11581 // Visit all inputs, collect all binary operations (and, or, xor and 11582 // select) that are all fed by truncations. 11583 while (!BinOps.empty()) { 11584 SDValue BinOp = BinOps.back(); 11585 BinOps.pop_back(); 11586 11587 if (!Visited.insert(BinOp.getNode()).second) 11588 continue; 11589 11590 PromOps.push_back(BinOp); 11591 11592 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11593 // The condition of the select is not promoted. 11594 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11595 continue; 11596 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11597 continue; 11598 11599 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11600 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11601 Inputs.push_back(BinOp.getOperand(i)); 11602 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11603 BinOp.getOperand(i).getOpcode() == ISD::OR || 11604 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11605 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11606 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 11607 BinOps.push_back(BinOp.getOperand(i)); 11608 } else { 11609 // We have an input that is not a truncation or another binary 11610 // operation; we'll abort this transformation. 11611 return SDValue(); 11612 } 11613 } 11614 } 11615 11616 // The operands of a select that must be truncated when the select is 11617 // promoted because the operand is actually part of the to-be-promoted set. 11618 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 11619 11620 // Make sure that this is a self-contained cluster of operations (which 11621 // is not quite the same thing as saying that everything has only one 11622 // use). 11623 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11624 if (isa<ConstantSDNode>(Inputs[i])) 11625 continue; 11626 11627 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11628 UE = Inputs[i].getNode()->use_end(); 11629 UI != UE; ++UI) { 11630 SDNode *User = *UI; 11631 if (User != N && !Visited.count(User)) 11632 return SDValue(); 11633 11634 // If we're going to promote the non-output-value operand(s) or SELECT or 11635 // SELECT_CC, record them for truncation. 11636 if (User->getOpcode() == ISD::SELECT) { 11637 if (User->getOperand(0) == Inputs[i]) 11638 SelectTruncOp[0].insert(std::make_pair(User, 11639 User->getOperand(0).getValueType())); 11640 } else if (User->getOpcode() == ISD::SELECT_CC) { 11641 if (User->getOperand(0) == Inputs[i]) 11642 SelectTruncOp[0].insert(std::make_pair(User, 11643 User->getOperand(0).getValueType())); 11644 if (User->getOperand(1) == Inputs[i]) 11645 SelectTruncOp[1].insert(std::make_pair(User, 11646 User->getOperand(1).getValueType())); 11647 } 11648 } 11649 } 11650 11651 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11652 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11653 UE = PromOps[i].getNode()->use_end(); 11654 UI != UE; ++UI) { 11655 SDNode *User = *UI; 11656 if (User != N && !Visited.count(User)) 11657 return SDValue(); 11658 11659 // If we're going to promote the non-output-value operand(s) or SELECT or 11660 // SELECT_CC, record them for truncation. 11661 if (User->getOpcode() == ISD::SELECT) { 11662 if (User->getOperand(0) == PromOps[i]) 11663 SelectTruncOp[0].insert(std::make_pair(User, 11664 User->getOperand(0).getValueType())); 11665 } else if (User->getOpcode() == ISD::SELECT_CC) { 11666 if (User->getOperand(0) == PromOps[i]) 11667 SelectTruncOp[0].insert(std::make_pair(User, 11668 User->getOperand(0).getValueType())); 11669 if (User->getOperand(1) == PromOps[i]) 11670 SelectTruncOp[1].insert(std::make_pair(User, 11671 User->getOperand(1).getValueType())); 11672 } 11673 } 11674 } 11675 11676 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 11677 bool ReallyNeedsExt = false; 11678 if (N->getOpcode() != ISD::ANY_EXTEND) { 11679 // If all of the inputs are not already sign/zero extended, then 11680 // we'll still need to do that at the end. 11681 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11682 if (isa<ConstantSDNode>(Inputs[i])) 11683 continue; 11684 11685 unsigned OpBits = 11686 Inputs[i].getOperand(0).getValueSizeInBits(); 11687 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 11688 11689 if ((N->getOpcode() == ISD::ZERO_EXTEND && 11690 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 11691 APInt::getHighBitsSet(OpBits, 11692 OpBits-PromBits))) || 11693 (N->getOpcode() == ISD::SIGN_EXTEND && 11694 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 11695 (OpBits-(PromBits-1)))) { 11696 ReallyNeedsExt = true; 11697 break; 11698 } 11699 } 11700 } 11701 11702 // Replace all inputs, either with the truncation operand, or a 11703 // truncation or extension to the final output type. 11704 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11705 // Constant inputs need to be replaced with the to-be-promoted nodes that 11706 // use them because they might have users outside of the cluster of 11707 // promoted nodes. 11708 if (isa<ConstantSDNode>(Inputs[i])) 11709 continue; 11710 11711 SDValue InSrc = Inputs[i].getOperand(0); 11712 if (Inputs[i].getValueType() == N->getValueType(0)) 11713 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 11714 else if (N->getOpcode() == ISD::SIGN_EXTEND) 11715 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11716 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 11717 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11718 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11719 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 11720 else 11721 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11722 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 11723 } 11724 11725 std::list<HandleSDNode> PromOpHandles; 11726 for (auto &PromOp : PromOps) 11727 PromOpHandles.emplace_back(PromOp); 11728 11729 // Replace all operations (these are all the same, but have a different 11730 // (promoted) return type). DAG.getNode will validate that the types of 11731 // a binary operator match, so go through the list in reverse so that 11732 // we've likely promoted both operands first. 11733 while (!PromOpHandles.empty()) { 11734 SDValue PromOp = PromOpHandles.back().getValue(); 11735 PromOpHandles.pop_back(); 11736 11737 unsigned C; 11738 switch (PromOp.getOpcode()) { 11739 default: C = 0; break; 11740 case ISD::SELECT: C = 1; break; 11741 case ISD::SELECT_CC: C = 2; break; 11742 } 11743 11744 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11745 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 11746 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11747 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 11748 // The to-be-promoted operands of this node have not yet been 11749 // promoted (this should be rare because we're going through the 11750 // list backward, but if one of the operands has several users in 11751 // this cluster of to-be-promoted nodes, it is possible). 11752 PromOpHandles.emplace_front(PromOp); 11753 continue; 11754 } 11755 11756 // For SELECT and SELECT_CC nodes, we do a similar check for any 11757 // to-be-promoted comparison inputs. 11758 if (PromOp.getOpcode() == ISD::SELECT || 11759 PromOp.getOpcode() == ISD::SELECT_CC) { 11760 if ((SelectTruncOp[0].count(PromOp.getNode()) && 11761 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 11762 (SelectTruncOp[1].count(PromOp.getNode()) && 11763 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 11764 PromOpHandles.emplace_front(PromOp); 11765 continue; 11766 } 11767 } 11768 11769 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11770 PromOp.getNode()->op_end()); 11771 11772 // If this node has constant inputs, then they'll need to be promoted here. 11773 for (unsigned i = 0; i < 2; ++i) { 11774 if (!isa<ConstantSDNode>(Ops[C+i])) 11775 continue; 11776 if (Ops[C+i].getValueType() == N->getValueType(0)) 11777 continue; 11778 11779 if (N->getOpcode() == ISD::SIGN_EXTEND) 11780 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11781 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11782 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11783 else 11784 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11785 } 11786 11787 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 11788 // truncate them again to the original value type. 11789 if (PromOp.getOpcode() == ISD::SELECT || 11790 PromOp.getOpcode() == ISD::SELECT_CC) { 11791 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 11792 if (SI0 != SelectTruncOp[0].end()) 11793 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 11794 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 11795 if (SI1 != SelectTruncOp[1].end()) 11796 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 11797 } 11798 11799 DAG.ReplaceAllUsesOfValueWith(PromOp, 11800 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 11801 } 11802 11803 // Now we're left with the initial extension itself. 11804 if (!ReallyNeedsExt) 11805 return N->getOperand(0); 11806 11807 // To zero extend, just mask off everything except for the first bit (in the 11808 // i1 case). 11809 if (N->getOpcode() == ISD::ZERO_EXTEND) 11810 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 11811 DAG.getConstant(APInt::getLowBitsSet( 11812 N->getValueSizeInBits(0), PromBits), 11813 dl, N->getValueType(0))); 11814 11815 assert(N->getOpcode() == ISD::SIGN_EXTEND && 11816 "Invalid extension type"); 11817 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 11818 SDValue ShiftCst = 11819 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 11820 return DAG.getNode( 11821 ISD::SRA, dl, N->getValueType(0), 11822 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 11823 ShiftCst); 11824 } 11825 11826 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 11827 DAGCombinerInfo &DCI) const { 11828 assert(N->getOpcode() == ISD::SETCC && 11829 "Should be called with a SETCC node"); 11830 11831 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11832 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 11833 SDValue LHS = N->getOperand(0); 11834 SDValue RHS = N->getOperand(1); 11835 11836 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 11837 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 11838 LHS.hasOneUse()) 11839 std::swap(LHS, RHS); 11840 11841 // x == 0-y --> x+y == 0 11842 // x != 0-y --> x+y != 0 11843 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 11844 RHS.hasOneUse()) { 11845 SDLoc DL(N); 11846 SelectionDAG &DAG = DCI.DAG; 11847 EVT VT = N->getValueType(0); 11848 EVT OpVT = LHS.getValueType(); 11849 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 11850 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 11851 } 11852 } 11853 11854 return DAGCombineTruncBoolExt(N, DCI); 11855 } 11856 11857 // Is this an extending load from an f32 to an f64? 11858 static bool isFPExtLoad(SDValue Op) { 11859 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 11860 return LD->getExtensionType() == ISD::EXTLOAD && 11861 Op.getValueType() == MVT::f64; 11862 return false; 11863 } 11864 11865 /// Reduces the number of fp-to-int conversion when building a vector. 11866 /// 11867 /// If this vector is built out of floating to integer conversions, 11868 /// transform it to a vector built out of floating point values followed by a 11869 /// single floating to integer conversion of the vector. 11870 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 11871 /// becomes (fptosi (build_vector ($A, $B, ...))) 11872 SDValue PPCTargetLowering:: 11873 combineElementTruncationToVectorTruncation(SDNode *N, 11874 DAGCombinerInfo &DCI) const { 11875 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11876 "Should be called with a BUILD_VECTOR node"); 11877 11878 SelectionDAG &DAG = DCI.DAG; 11879 SDLoc dl(N); 11880 11881 SDValue FirstInput = N->getOperand(0); 11882 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 11883 "The input operand must be an fp-to-int conversion."); 11884 11885 // This combine happens after legalization so the fp_to_[su]i nodes are 11886 // already converted to PPCSISD nodes. 11887 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 11888 if (FirstConversion == PPCISD::FCTIDZ || 11889 FirstConversion == PPCISD::FCTIDUZ || 11890 FirstConversion == PPCISD::FCTIWZ || 11891 FirstConversion == PPCISD::FCTIWUZ) { 11892 bool IsSplat = true; 11893 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 11894 FirstConversion == PPCISD::FCTIWUZ; 11895 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 11896 SmallVector<SDValue, 4> Ops; 11897 EVT TargetVT = N->getValueType(0); 11898 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11899 SDValue NextOp = N->getOperand(i); 11900 if (NextOp.getOpcode() != PPCISD::MFVSR) 11901 return SDValue(); 11902 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 11903 if (NextConversion != FirstConversion) 11904 return SDValue(); 11905 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 11906 // This is not valid if the input was originally double precision. It is 11907 // also not profitable to do unless this is an extending load in which 11908 // case doing this combine will allow us to combine consecutive loads. 11909 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 11910 return SDValue(); 11911 if (N->getOperand(i) != FirstInput) 11912 IsSplat = false; 11913 } 11914 11915 // If this is a splat, we leave it as-is since there will be only a single 11916 // fp-to-int conversion followed by a splat of the integer. This is better 11917 // for 32-bit and smaller ints and neutral for 64-bit ints. 11918 if (IsSplat) 11919 return SDValue(); 11920 11921 // Now that we know we have the right type of node, get its operands 11922 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11923 SDValue In = N->getOperand(i).getOperand(0); 11924 if (Is32Bit) { 11925 // For 32-bit values, we need to add an FP_ROUND node (if we made it 11926 // here, we know that all inputs are extending loads so this is safe). 11927 if (In.isUndef()) 11928 Ops.push_back(DAG.getUNDEF(SrcVT)); 11929 else { 11930 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 11931 MVT::f32, In.getOperand(0), 11932 DAG.getIntPtrConstant(1, dl)); 11933 Ops.push_back(Trunc); 11934 } 11935 } else 11936 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 11937 } 11938 11939 unsigned Opcode; 11940 if (FirstConversion == PPCISD::FCTIDZ || 11941 FirstConversion == PPCISD::FCTIWZ) 11942 Opcode = ISD::FP_TO_SINT; 11943 else 11944 Opcode = ISD::FP_TO_UINT; 11945 11946 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 11947 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 11948 return DAG.getNode(Opcode, dl, TargetVT, BV); 11949 } 11950 return SDValue(); 11951 } 11952 11953 /// Reduce the number of loads when building a vector. 11954 /// 11955 /// Building a vector out of multiple loads can be converted to a load 11956 /// of the vector type if the loads are consecutive. If the loads are 11957 /// consecutive but in descending order, a shuffle is added at the end 11958 /// to reorder the vector. 11959 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 11960 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11961 "Should be called with a BUILD_VECTOR node"); 11962 11963 SDLoc dl(N); 11964 bool InputsAreConsecutiveLoads = true; 11965 bool InputsAreReverseConsecutive = true; 11966 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8; 11967 SDValue FirstInput = N->getOperand(0); 11968 bool IsRoundOfExtLoad = false; 11969 11970 if (FirstInput.getOpcode() == ISD::FP_ROUND && 11971 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 11972 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 11973 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 11974 } 11975 // Not a build vector of (possibly fp_rounded) loads. 11976 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 11977 N->getNumOperands() == 1) 11978 return SDValue(); 11979 11980 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 11981 // If any inputs are fp_round(extload), they all must be. 11982 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 11983 return SDValue(); 11984 11985 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 11986 N->getOperand(i); 11987 if (NextInput.getOpcode() != ISD::LOAD) 11988 return SDValue(); 11989 11990 SDValue PreviousInput = 11991 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 11992 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 11993 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 11994 11995 // If any inputs are fp_round(extload), they all must be. 11996 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 11997 return SDValue(); 11998 11999 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 12000 InputsAreConsecutiveLoads = false; 12001 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 12002 InputsAreReverseConsecutive = false; 12003 12004 // Exit early if the loads are neither consecutive nor reverse consecutive. 12005 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12006 return SDValue(); 12007 } 12008 12009 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12010 "The loads cannot be both consecutive and reverse consecutive."); 12011 12012 SDValue FirstLoadOp = 12013 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12014 SDValue LastLoadOp = 12015 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12016 N->getOperand(N->getNumOperands()-1); 12017 12018 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12019 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12020 if (InputsAreConsecutiveLoads) { 12021 assert(LD1 && "Input needs to be a LoadSDNode."); 12022 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12023 LD1->getBasePtr(), LD1->getPointerInfo(), 12024 LD1->getAlignment()); 12025 } 12026 if (InputsAreReverseConsecutive) { 12027 assert(LDL && "Input needs to be a LoadSDNode."); 12028 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12029 LDL->getBasePtr(), LDL->getPointerInfo(), 12030 LDL->getAlignment()); 12031 SmallVector<int, 16> Ops; 12032 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12033 Ops.push_back(i); 12034 12035 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12036 DAG.getUNDEF(N->getValueType(0)), Ops); 12037 } 12038 return SDValue(); 12039 } 12040 12041 // This function adds the required vector_shuffle needed to get 12042 // the elements of the vector extract in the correct position 12043 // as specified by the CorrectElems encoding. 12044 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12045 SDValue Input, uint64_t Elems, 12046 uint64_t CorrectElems) { 12047 SDLoc dl(N); 12048 12049 unsigned NumElems = Input.getValueType().getVectorNumElements(); 12050 SmallVector<int, 16> ShuffleMask(NumElems, -1); 12051 12052 // Knowing the element indices being extracted from the original 12053 // vector and the order in which they're being inserted, just put 12054 // them at element indices required for the instruction. 12055 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12056 if (DAG.getDataLayout().isLittleEndian()) 12057 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 12058 else 12059 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 12060 CorrectElems = CorrectElems >> 8; 12061 Elems = Elems >> 8; 12062 } 12063 12064 SDValue Shuffle = 12065 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 12066 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 12067 12068 EVT Ty = N->getValueType(0); 12069 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 12070 return BV; 12071 } 12072 12073 // Look for build vector patterns where input operands come from sign 12074 // extended vector_extract elements of specific indices. If the correct indices 12075 // aren't used, add a vector shuffle to fix up the indices and create a new 12076 // PPCISD:SExtVElems node which selects the vector sign extend instructions 12077 // during instruction selection. 12078 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 12079 // This array encodes the indices that the vector sign extend instructions 12080 // extract from when extending from one type to another for both BE and LE. 12081 // The right nibble of each byte corresponds to the LE incides. 12082 // and the left nibble of each byte corresponds to the BE incides. 12083 // For example: 0x3074B8FC byte->word 12084 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 12085 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 12086 // For example: 0x000070F8 byte->double word 12087 // For LE: the allowed indices are: 0x0,0x8 12088 // For BE: the allowed indices are: 0x7,0xF 12089 uint64_t TargetElems[] = { 12090 0x3074B8FC, // b->w 12091 0x000070F8, // b->d 12092 0x10325476, // h->w 12093 0x00003074, // h->d 12094 0x00001032, // w->d 12095 }; 12096 12097 uint64_t Elems = 0; 12098 int Index; 12099 SDValue Input; 12100 12101 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 12102 if (!Op) 12103 return false; 12104 if (Op.getOpcode() != ISD::SIGN_EXTEND && 12105 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 12106 return false; 12107 12108 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 12109 // of the right width. 12110 SDValue Extract = Op.getOperand(0); 12111 if (Extract.getOpcode() == ISD::ANY_EXTEND) 12112 Extract = Extract.getOperand(0); 12113 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12114 return false; 12115 12116 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 12117 if (!ExtOp) 12118 return false; 12119 12120 Index = ExtOp->getZExtValue(); 12121 if (Input && Input != Extract.getOperand(0)) 12122 return false; 12123 12124 if (!Input) 12125 Input = Extract.getOperand(0); 12126 12127 Elems = Elems << 8; 12128 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 12129 Elems |= Index; 12130 12131 return true; 12132 }; 12133 12134 // If the build vector operands aren't sign extended vector extracts, 12135 // of the same input vector, then return. 12136 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12137 if (!isSExtOfVecExtract(N->getOperand(i))) { 12138 return SDValue(); 12139 } 12140 } 12141 12142 // If the vector extract indicies are not correct, add the appropriate 12143 // vector_shuffle. 12144 int TgtElemArrayIdx; 12145 int InputSize = Input.getValueType().getScalarSizeInBits(); 12146 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 12147 if (InputSize + OutputSize == 40) 12148 TgtElemArrayIdx = 0; 12149 else if (InputSize + OutputSize == 72) 12150 TgtElemArrayIdx = 1; 12151 else if (InputSize + OutputSize == 48) 12152 TgtElemArrayIdx = 2; 12153 else if (InputSize + OutputSize == 80) 12154 TgtElemArrayIdx = 3; 12155 else if (InputSize + OutputSize == 96) 12156 TgtElemArrayIdx = 4; 12157 else 12158 return SDValue(); 12159 12160 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 12161 CorrectElems = DAG.getDataLayout().isLittleEndian() 12162 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 12163 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 12164 if (Elems != CorrectElems) { 12165 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 12166 } 12167 12168 // Regular lowering will catch cases where a shuffle is not needed. 12169 return SDValue(); 12170 } 12171 12172 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 12173 DAGCombinerInfo &DCI) const { 12174 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12175 "Should be called with a BUILD_VECTOR node"); 12176 12177 SelectionDAG &DAG = DCI.DAG; 12178 SDLoc dl(N); 12179 12180 if (!Subtarget.hasVSX()) 12181 return SDValue(); 12182 12183 // The target independent DAG combiner will leave a build_vector of 12184 // float-to-int conversions intact. We can generate MUCH better code for 12185 // a float-to-int conversion of a vector of floats. 12186 SDValue FirstInput = N->getOperand(0); 12187 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 12188 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 12189 if (Reduced) 12190 return Reduced; 12191 } 12192 12193 // If we're building a vector out of consecutive loads, just load that 12194 // vector type. 12195 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 12196 if (Reduced) 12197 return Reduced; 12198 12199 // If we're building a vector out of extended elements from another vector 12200 // we have P9 vector integer extend instructions. The code assumes legal 12201 // input types (i.e. it can't handle things like v4i16) so do not run before 12202 // legalization. 12203 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 12204 Reduced = combineBVOfVecSExt(N, DAG); 12205 if (Reduced) 12206 return Reduced; 12207 } 12208 12209 12210 if (N->getValueType(0) != MVT::v2f64) 12211 return SDValue(); 12212 12213 // Looking for: 12214 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 12215 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 12216 FirstInput.getOpcode() != ISD::UINT_TO_FP) 12217 return SDValue(); 12218 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 12219 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 12220 return SDValue(); 12221 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 12222 return SDValue(); 12223 12224 SDValue Ext1 = FirstInput.getOperand(0); 12225 SDValue Ext2 = N->getOperand(1).getOperand(0); 12226 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12227 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12228 return SDValue(); 12229 12230 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 12231 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 12232 if (!Ext1Op || !Ext2Op) 12233 return SDValue(); 12234 if (Ext1.getValueType() != MVT::i32 || 12235 Ext2.getValueType() != MVT::i32) 12236 if (Ext1.getOperand(0) != Ext2.getOperand(0)) 12237 return SDValue(); 12238 12239 int FirstElem = Ext1Op->getZExtValue(); 12240 int SecondElem = Ext2Op->getZExtValue(); 12241 int SubvecIdx; 12242 if (FirstElem == 0 && SecondElem == 1) 12243 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 12244 else if (FirstElem == 2 && SecondElem == 3) 12245 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 12246 else 12247 return SDValue(); 12248 12249 SDValue SrcVec = Ext1.getOperand(0); 12250 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 12251 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 12252 return DAG.getNode(NodeType, dl, MVT::v2f64, 12253 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 12254 } 12255 12256 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 12257 DAGCombinerInfo &DCI) const { 12258 assert((N->getOpcode() == ISD::SINT_TO_FP || 12259 N->getOpcode() == ISD::UINT_TO_FP) && 12260 "Need an int -> FP conversion node here"); 12261 12262 if (useSoftFloat() || !Subtarget.has64BitSupport()) 12263 return SDValue(); 12264 12265 SelectionDAG &DAG = DCI.DAG; 12266 SDLoc dl(N); 12267 SDValue Op(N, 0); 12268 12269 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 12270 // from the hardware. 12271 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 12272 return SDValue(); 12273 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 12274 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 12275 return SDValue(); 12276 12277 SDValue FirstOperand(Op.getOperand(0)); 12278 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 12279 (FirstOperand.getValueType() == MVT::i8 || 12280 FirstOperand.getValueType() == MVT::i16); 12281 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 12282 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 12283 bool DstDouble = Op.getValueType() == MVT::f64; 12284 unsigned ConvOp = Signed ? 12285 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 12286 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 12287 SDValue WidthConst = 12288 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 12289 dl, false); 12290 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 12291 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 12292 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 12293 DAG.getVTList(MVT::f64, MVT::Other), 12294 Ops, MVT::i8, LDN->getMemOperand()); 12295 12296 // For signed conversion, we need to sign-extend the value in the VSR 12297 if (Signed) { 12298 SDValue ExtOps[] = { Ld, WidthConst }; 12299 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 12300 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 12301 } else 12302 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 12303 } 12304 12305 12306 // For i32 intermediate values, unfortunately, the conversion functions 12307 // leave the upper 32 bits of the value are undefined. Within the set of 12308 // scalar instructions, we have no method for zero- or sign-extending the 12309 // value. Thus, we cannot handle i32 intermediate values here. 12310 if (Op.getOperand(0).getValueType() == MVT::i32) 12311 return SDValue(); 12312 12313 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 12314 "UINT_TO_FP is supported only with FPCVT"); 12315 12316 // If we have FCFIDS, then use it when converting to single-precision. 12317 // Otherwise, convert to double-precision and then round. 12318 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12319 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12320 : PPCISD::FCFIDS) 12321 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12322 : PPCISD::FCFID); 12323 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12324 ? MVT::f32 12325 : MVT::f64; 12326 12327 // If we're converting from a float, to an int, and back to a float again, 12328 // then we don't need the store/load pair at all. 12329 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12330 Subtarget.hasFPCVT()) || 12331 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12332 SDValue Src = Op.getOperand(0).getOperand(0); 12333 if (Src.getValueType() == MVT::f32) { 12334 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12335 DCI.AddToWorklist(Src.getNode()); 12336 } else if (Src.getValueType() != MVT::f64) { 12337 // Make sure that we don't pick up a ppc_fp128 source value. 12338 return SDValue(); 12339 } 12340 12341 unsigned FCTOp = 12342 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12343 PPCISD::FCTIDUZ; 12344 12345 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12346 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12347 12348 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12349 FP = DAG.getNode(ISD::FP_ROUND, dl, 12350 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12351 DCI.AddToWorklist(FP.getNode()); 12352 } 12353 12354 return FP; 12355 } 12356 12357 return SDValue(); 12358 } 12359 12360 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12361 // builtins) into loads with swaps. 12362 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12363 DAGCombinerInfo &DCI) const { 12364 SelectionDAG &DAG = DCI.DAG; 12365 SDLoc dl(N); 12366 SDValue Chain; 12367 SDValue Base; 12368 MachineMemOperand *MMO; 12369 12370 switch (N->getOpcode()) { 12371 default: 12372 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12373 case ISD::LOAD: { 12374 LoadSDNode *LD = cast<LoadSDNode>(N); 12375 Chain = LD->getChain(); 12376 Base = LD->getBasePtr(); 12377 MMO = LD->getMemOperand(); 12378 // If the MMO suggests this isn't a load of a full vector, leave 12379 // things alone. For a built-in, we have to make the change for 12380 // correctness, so if there is a size problem that will be a bug. 12381 if (MMO->getSize() < 16) 12382 return SDValue(); 12383 break; 12384 } 12385 case ISD::INTRINSIC_W_CHAIN: { 12386 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12387 Chain = Intrin->getChain(); 12388 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12389 // us what we want. Get operand 2 instead. 12390 Base = Intrin->getOperand(2); 12391 MMO = Intrin->getMemOperand(); 12392 break; 12393 } 12394 } 12395 12396 MVT VecTy = N->getValueType(0).getSimpleVT(); 12397 12398 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12399 // aligned and the type is a vector with elements up to 4 bytes 12400 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12401 && VecTy.getScalarSizeInBits() <= 32 ) { 12402 return SDValue(); 12403 } 12404 12405 SDValue LoadOps[] = { Chain, Base }; 12406 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12407 DAG.getVTList(MVT::v2f64, MVT::Other), 12408 LoadOps, MVT::v2f64, MMO); 12409 12410 DCI.AddToWorklist(Load.getNode()); 12411 Chain = Load.getValue(1); 12412 SDValue Swap = DAG.getNode( 12413 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12414 DCI.AddToWorklist(Swap.getNode()); 12415 12416 // Add a bitcast if the resulting load type doesn't match v2f64. 12417 if (VecTy != MVT::v2f64) { 12418 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12419 DCI.AddToWorklist(N.getNode()); 12420 // Package {bitcast value, swap's chain} to match Load's shape. 12421 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12422 N, Swap.getValue(1)); 12423 } 12424 12425 return Swap; 12426 } 12427 12428 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12429 // builtins) into stores with swaps. 12430 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12431 DAGCombinerInfo &DCI) const { 12432 SelectionDAG &DAG = DCI.DAG; 12433 SDLoc dl(N); 12434 SDValue Chain; 12435 SDValue Base; 12436 unsigned SrcOpnd; 12437 MachineMemOperand *MMO; 12438 12439 switch (N->getOpcode()) { 12440 default: 12441 llvm_unreachable("Unexpected opcode for little endian VSX store"); 12442 case ISD::STORE: { 12443 StoreSDNode *ST = cast<StoreSDNode>(N); 12444 Chain = ST->getChain(); 12445 Base = ST->getBasePtr(); 12446 MMO = ST->getMemOperand(); 12447 SrcOpnd = 1; 12448 // If the MMO suggests this isn't a store of a full vector, leave 12449 // things alone. For a built-in, we have to make the change for 12450 // correctness, so if there is a size problem that will be a bug. 12451 if (MMO->getSize() < 16) 12452 return SDValue(); 12453 break; 12454 } 12455 case ISD::INTRINSIC_VOID: { 12456 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12457 Chain = Intrin->getChain(); 12458 // Intrin->getBasePtr() oddly does not get what we want. 12459 Base = Intrin->getOperand(3); 12460 MMO = Intrin->getMemOperand(); 12461 SrcOpnd = 2; 12462 break; 12463 } 12464 } 12465 12466 SDValue Src = N->getOperand(SrcOpnd); 12467 MVT VecTy = Src.getValueType().getSimpleVT(); 12468 12469 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 12470 // aligned and the type is a vector with elements up to 4 bytes 12471 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12472 && VecTy.getScalarSizeInBits() <= 32 ) { 12473 return SDValue(); 12474 } 12475 12476 // All stores are done as v2f64 and possible bit cast. 12477 if (VecTy != MVT::v2f64) { 12478 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 12479 DCI.AddToWorklist(Src.getNode()); 12480 } 12481 12482 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 12483 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 12484 DCI.AddToWorklist(Swap.getNode()); 12485 Chain = Swap.getValue(1); 12486 SDValue StoreOps[] = { Chain, Swap, Base }; 12487 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 12488 DAG.getVTList(MVT::Other), 12489 StoreOps, VecTy, MMO); 12490 DCI.AddToWorklist(Store.getNode()); 12491 return Store; 12492 } 12493 12494 // Handle DAG combine for STORE (FP_TO_INT F). 12495 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 12496 DAGCombinerInfo &DCI) const { 12497 12498 SelectionDAG &DAG = DCI.DAG; 12499 SDLoc dl(N); 12500 unsigned Opcode = N->getOperand(1).getOpcode(); 12501 12502 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 12503 && "Not a FP_TO_INT Instruction!"); 12504 12505 SDValue Val = N->getOperand(1).getOperand(0); 12506 EVT Op1VT = N->getOperand(1).getValueType(); 12507 EVT ResVT = Val.getValueType(); 12508 12509 // Floating point types smaller than 32 bits are not legal on Power. 12510 if (ResVT.getScalarSizeInBits() < 32) 12511 return SDValue(); 12512 12513 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 12514 bool ValidTypeForStoreFltAsInt = 12515 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 12516 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 12517 12518 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 12519 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 12520 return SDValue(); 12521 12522 // Extend f32 values to f64 12523 if (ResVT.getScalarSizeInBits() == 32) { 12524 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 12525 DCI.AddToWorklist(Val.getNode()); 12526 } 12527 12528 // Set signed or unsigned conversion opcode. 12529 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 12530 PPCISD::FP_TO_SINT_IN_VSR : 12531 PPCISD::FP_TO_UINT_IN_VSR; 12532 12533 Val = DAG.getNode(ConvOpcode, 12534 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 12535 DCI.AddToWorklist(Val.getNode()); 12536 12537 // Set number of bytes being converted. 12538 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 12539 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 12540 DAG.getIntPtrConstant(ByteSize, dl, false), 12541 DAG.getValueType(Op1VT) }; 12542 12543 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 12544 DAG.getVTList(MVT::Other), Ops, 12545 cast<StoreSDNode>(N)->getMemoryVT(), 12546 cast<StoreSDNode>(N)->getMemOperand()); 12547 12548 DCI.AddToWorklist(Val.getNode()); 12549 return Val; 12550 } 12551 12552 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 12553 DAGCombinerInfo &DCI) const { 12554 SelectionDAG &DAG = DCI.DAG; 12555 SDLoc dl(N); 12556 switch (N->getOpcode()) { 12557 default: break; 12558 case ISD::ADD: 12559 return combineADD(N, DCI); 12560 case ISD::SHL: 12561 return combineSHL(N, DCI); 12562 case ISD::SRA: 12563 return combineSRA(N, DCI); 12564 case ISD::SRL: 12565 return combineSRL(N, DCI); 12566 case PPCISD::SHL: 12567 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 12568 return N->getOperand(0); 12569 break; 12570 case PPCISD::SRL: 12571 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 12572 return N->getOperand(0); 12573 break; 12574 case PPCISD::SRA: 12575 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 12576 if (C->isNullValue() || // 0 >>s V -> 0. 12577 C->isAllOnesValue()) // -1 >>s V -> -1. 12578 return N->getOperand(0); 12579 } 12580 break; 12581 case ISD::SIGN_EXTEND: 12582 case ISD::ZERO_EXTEND: 12583 case ISD::ANY_EXTEND: 12584 return DAGCombineExtBoolTrunc(N, DCI); 12585 case ISD::TRUNCATE: 12586 return combineTRUNCATE(N, DCI); 12587 case ISD::SETCC: 12588 if (SDValue CSCC = combineSetCC(N, DCI)) 12589 return CSCC; 12590 LLVM_FALLTHROUGH; 12591 case ISD::SELECT_CC: 12592 return DAGCombineTruncBoolExt(N, DCI); 12593 case ISD::SINT_TO_FP: 12594 case ISD::UINT_TO_FP: 12595 return combineFPToIntToFP(N, DCI); 12596 case ISD::STORE: { 12597 12598 EVT Op1VT = N->getOperand(1).getValueType(); 12599 unsigned Opcode = N->getOperand(1).getOpcode(); 12600 12601 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 12602 SDValue Val= combineStoreFPToInt(N, DCI); 12603 if (Val) 12604 return Val; 12605 } 12606 12607 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 12608 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 12609 N->getOperand(1).getNode()->hasOneUse() && 12610 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 12611 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 12612 12613 // STBRX can only handle simple types. 12614 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 12615 if (mVT.isExtended()) 12616 break; 12617 12618 SDValue BSwapOp = N->getOperand(1).getOperand(0); 12619 // Do an any-extend to 32-bits if this is a half-word input. 12620 if (BSwapOp.getValueType() == MVT::i16) 12621 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 12622 12623 // If the type of BSWAP operand is wider than stored memory width 12624 // it need to be shifted to the right side before STBRX. 12625 if (Op1VT.bitsGT(mVT)) { 12626 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 12627 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 12628 DAG.getConstant(Shift, dl, MVT::i32)); 12629 // Need to truncate if this is a bswap of i64 stored as i32/i16. 12630 if (Op1VT == MVT::i64) 12631 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 12632 } 12633 12634 SDValue Ops[] = { 12635 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 12636 }; 12637 return 12638 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 12639 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 12640 cast<StoreSDNode>(N)->getMemOperand()); 12641 } 12642 12643 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 12644 // So it can increase the chance of CSE constant construction. 12645 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 12646 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 12647 // Need to sign-extended to 64-bits to handle negative values. 12648 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 12649 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 12650 MemVT.getSizeInBits()); 12651 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 12652 12653 // DAG.getTruncStore() can't be used here because it doesn't accept 12654 // the general (base + offset) addressing mode. 12655 // So we use UpdateNodeOperands and setTruncatingStore instead. 12656 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 12657 N->getOperand(3)); 12658 cast<StoreSDNode>(N)->setTruncatingStore(true); 12659 return SDValue(N, 0); 12660 } 12661 12662 // For little endian, VSX stores require generating xxswapd/lxvd2x. 12663 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12664 if (Op1VT.isSimple()) { 12665 MVT StoreVT = Op1VT.getSimpleVT(); 12666 if (Subtarget.needsSwapsForVSXMemOps() && 12667 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 12668 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 12669 return expandVSXStoreForLE(N, DCI); 12670 } 12671 break; 12672 } 12673 case ISD::LOAD: { 12674 LoadSDNode *LD = cast<LoadSDNode>(N); 12675 EVT VT = LD->getValueType(0); 12676 12677 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12678 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12679 if (VT.isSimple()) { 12680 MVT LoadVT = VT.getSimpleVT(); 12681 if (Subtarget.needsSwapsForVSXMemOps() && 12682 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 12683 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 12684 return expandVSXLoadForLE(N, DCI); 12685 } 12686 12687 // We sometimes end up with a 64-bit integer load, from which we extract 12688 // two single-precision floating-point numbers. This happens with 12689 // std::complex<float>, and other similar structures, because of the way we 12690 // canonicalize structure copies. However, if we lack direct moves, 12691 // then the final bitcasts from the extracted integer values to the 12692 // floating-point numbers turn into store/load pairs. Even with direct moves, 12693 // just loading the two floating-point numbers is likely better. 12694 auto ReplaceTwoFloatLoad = [&]() { 12695 if (VT != MVT::i64) 12696 return false; 12697 12698 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 12699 LD->isVolatile()) 12700 return false; 12701 12702 // We're looking for a sequence like this: 12703 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 12704 // t16: i64 = srl t13, Constant:i32<32> 12705 // t17: i32 = truncate t16 12706 // t18: f32 = bitcast t17 12707 // t19: i32 = truncate t13 12708 // t20: f32 = bitcast t19 12709 12710 if (!LD->hasNUsesOfValue(2, 0)) 12711 return false; 12712 12713 auto UI = LD->use_begin(); 12714 while (UI.getUse().getResNo() != 0) ++UI; 12715 SDNode *Trunc = *UI++; 12716 while (UI.getUse().getResNo() != 0) ++UI; 12717 SDNode *RightShift = *UI; 12718 if (Trunc->getOpcode() != ISD::TRUNCATE) 12719 std::swap(Trunc, RightShift); 12720 12721 if (Trunc->getOpcode() != ISD::TRUNCATE || 12722 Trunc->getValueType(0) != MVT::i32 || 12723 !Trunc->hasOneUse()) 12724 return false; 12725 if (RightShift->getOpcode() != ISD::SRL || 12726 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 12727 RightShift->getConstantOperandVal(1) != 32 || 12728 !RightShift->hasOneUse()) 12729 return false; 12730 12731 SDNode *Trunc2 = *RightShift->use_begin(); 12732 if (Trunc2->getOpcode() != ISD::TRUNCATE || 12733 Trunc2->getValueType(0) != MVT::i32 || 12734 !Trunc2->hasOneUse()) 12735 return false; 12736 12737 SDNode *Bitcast = *Trunc->use_begin(); 12738 SDNode *Bitcast2 = *Trunc2->use_begin(); 12739 12740 if (Bitcast->getOpcode() != ISD::BITCAST || 12741 Bitcast->getValueType(0) != MVT::f32) 12742 return false; 12743 if (Bitcast2->getOpcode() != ISD::BITCAST || 12744 Bitcast2->getValueType(0) != MVT::f32) 12745 return false; 12746 12747 if (Subtarget.isLittleEndian()) 12748 std::swap(Bitcast, Bitcast2); 12749 12750 // Bitcast has the second float (in memory-layout order) and Bitcast2 12751 // has the first one. 12752 12753 SDValue BasePtr = LD->getBasePtr(); 12754 if (LD->isIndexed()) { 12755 assert(LD->getAddressingMode() == ISD::PRE_INC && 12756 "Non-pre-inc AM on PPC?"); 12757 BasePtr = 12758 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 12759 LD->getOffset()); 12760 } 12761 12762 auto MMOFlags = 12763 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 12764 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 12765 LD->getPointerInfo(), LD->getAlignment(), 12766 MMOFlags, LD->getAAInfo()); 12767 SDValue AddPtr = 12768 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 12769 BasePtr, DAG.getIntPtrConstant(4, dl)); 12770 SDValue FloatLoad2 = DAG.getLoad( 12771 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 12772 LD->getPointerInfo().getWithOffset(4), 12773 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 12774 12775 if (LD->isIndexed()) { 12776 // Note that DAGCombine should re-form any pre-increment load(s) from 12777 // what is produced here if that makes sense. 12778 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 12779 } 12780 12781 DCI.CombineTo(Bitcast2, FloatLoad); 12782 DCI.CombineTo(Bitcast, FloatLoad2); 12783 12784 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 12785 SDValue(FloatLoad2.getNode(), 1)); 12786 return true; 12787 }; 12788 12789 if (ReplaceTwoFloatLoad()) 12790 return SDValue(N, 0); 12791 12792 EVT MemVT = LD->getMemoryVT(); 12793 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 12794 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 12795 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 12796 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 12797 if (LD->isUnindexed() && VT.isVector() && 12798 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 12799 // P8 and later hardware should just use LOAD. 12800 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 12801 VT == MVT::v4i32 || VT == MVT::v4f32)) || 12802 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 12803 LD->getAlignment() >= ScalarABIAlignment)) && 12804 LD->getAlignment() < ABIAlignment) { 12805 // This is a type-legal unaligned Altivec or QPX load. 12806 SDValue Chain = LD->getChain(); 12807 SDValue Ptr = LD->getBasePtr(); 12808 bool isLittleEndian = Subtarget.isLittleEndian(); 12809 12810 // This implements the loading of unaligned vectors as described in 12811 // the venerable Apple Velocity Engine overview. Specifically: 12812 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 12813 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 12814 // 12815 // The general idea is to expand a sequence of one or more unaligned 12816 // loads into an alignment-based permutation-control instruction (lvsl 12817 // or lvsr), a series of regular vector loads (which always truncate 12818 // their input address to an aligned address), and a series of 12819 // permutations. The results of these permutations are the requested 12820 // loaded values. The trick is that the last "extra" load is not taken 12821 // from the address you might suspect (sizeof(vector) bytes after the 12822 // last requested load), but rather sizeof(vector) - 1 bytes after the 12823 // last requested vector. The point of this is to avoid a page fault if 12824 // the base address happened to be aligned. This works because if the 12825 // base address is aligned, then adding less than a full vector length 12826 // will cause the last vector in the sequence to be (re)loaded. 12827 // Otherwise, the next vector will be fetched as you might suspect was 12828 // necessary. 12829 12830 // We might be able to reuse the permutation generation from 12831 // a different base address offset from this one by an aligned amount. 12832 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 12833 // optimization later. 12834 Intrinsic::ID Intr, IntrLD, IntrPerm; 12835 MVT PermCntlTy, PermTy, LDTy; 12836 if (Subtarget.hasAltivec()) { 12837 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 12838 Intrinsic::ppc_altivec_lvsl; 12839 IntrLD = Intrinsic::ppc_altivec_lvx; 12840 IntrPerm = Intrinsic::ppc_altivec_vperm; 12841 PermCntlTy = MVT::v16i8; 12842 PermTy = MVT::v4i32; 12843 LDTy = MVT::v4i32; 12844 } else { 12845 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 12846 Intrinsic::ppc_qpx_qvlpcls; 12847 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 12848 Intrinsic::ppc_qpx_qvlfs; 12849 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 12850 PermCntlTy = MVT::v4f64; 12851 PermTy = MVT::v4f64; 12852 LDTy = MemVT.getSimpleVT(); 12853 } 12854 12855 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 12856 12857 // Create the new MMO for the new base load. It is like the original MMO, 12858 // but represents an area in memory almost twice the vector size centered 12859 // on the original address. If the address is unaligned, we might start 12860 // reading up to (sizeof(vector)-1) bytes below the address of the 12861 // original unaligned load. 12862 MachineFunction &MF = DAG.getMachineFunction(); 12863 MachineMemOperand *BaseMMO = 12864 MF.getMachineMemOperand(LD->getMemOperand(), 12865 -(long)MemVT.getStoreSize()+1, 12866 2*MemVT.getStoreSize()-1); 12867 12868 // Create the new base load. 12869 SDValue LDXIntID = 12870 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 12871 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 12872 SDValue BaseLoad = 12873 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12874 DAG.getVTList(PermTy, MVT::Other), 12875 BaseLoadOps, LDTy, BaseMMO); 12876 12877 // Note that the value of IncOffset (which is provided to the next 12878 // load's pointer info offset value, and thus used to calculate the 12879 // alignment), and the value of IncValue (which is actually used to 12880 // increment the pointer value) are different! This is because we 12881 // require the next load to appear to be aligned, even though it 12882 // is actually offset from the base pointer by a lesser amount. 12883 int IncOffset = VT.getSizeInBits() / 8; 12884 int IncValue = IncOffset; 12885 12886 // Walk (both up and down) the chain looking for another load at the real 12887 // (aligned) offset (the alignment of the other load does not matter in 12888 // this case). If found, then do not use the offset reduction trick, as 12889 // that will prevent the loads from being later combined (as they would 12890 // otherwise be duplicates). 12891 if (!findConsecutiveLoad(LD, DAG)) 12892 --IncValue; 12893 12894 SDValue Increment = 12895 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 12896 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 12897 12898 MachineMemOperand *ExtraMMO = 12899 MF.getMachineMemOperand(LD->getMemOperand(), 12900 1, 2*MemVT.getStoreSize()-1); 12901 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 12902 SDValue ExtraLoad = 12903 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12904 DAG.getVTList(PermTy, MVT::Other), 12905 ExtraLoadOps, LDTy, ExtraMMO); 12906 12907 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 12908 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 12909 12910 // Because vperm has a big-endian bias, we must reverse the order 12911 // of the input vectors and complement the permute control vector 12912 // when generating little endian code. We have already handled the 12913 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 12914 // and ExtraLoad here. 12915 SDValue Perm; 12916 if (isLittleEndian) 12917 Perm = BuildIntrinsicOp(IntrPerm, 12918 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 12919 else 12920 Perm = BuildIntrinsicOp(IntrPerm, 12921 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 12922 12923 if (VT != PermTy) 12924 Perm = Subtarget.hasAltivec() ? 12925 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 12926 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 12927 DAG.getTargetConstant(1, dl, MVT::i64)); 12928 // second argument is 1 because this rounding 12929 // is always exact. 12930 12931 // The output of the permutation is our loaded result, the TokenFactor is 12932 // our new chain. 12933 DCI.CombineTo(N, Perm, TF); 12934 return SDValue(N, 0); 12935 } 12936 } 12937 break; 12938 case ISD::INTRINSIC_WO_CHAIN: { 12939 bool isLittleEndian = Subtarget.isLittleEndian(); 12940 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12941 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 12942 : Intrinsic::ppc_altivec_lvsl); 12943 if ((IID == Intr || 12944 IID == Intrinsic::ppc_qpx_qvlpcld || 12945 IID == Intrinsic::ppc_qpx_qvlpcls) && 12946 N->getOperand(1)->getOpcode() == ISD::ADD) { 12947 SDValue Add = N->getOperand(1); 12948 12949 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 12950 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 12951 12952 if (DAG.MaskedValueIsZero(Add->getOperand(1), 12953 APInt::getAllOnesValue(Bits /* alignment */) 12954 .zext(Add.getScalarValueSizeInBits()))) { 12955 SDNode *BasePtr = Add->getOperand(0).getNode(); 12956 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12957 UE = BasePtr->use_end(); 12958 UI != UE; ++UI) { 12959 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12960 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 12961 // We've found another LVSL/LVSR, and this address is an aligned 12962 // multiple of that one. The results will be the same, so use the 12963 // one we've just found instead. 12964 12965 return SDValue(*UI, 0); 12966 } 12967 } 12968 } 12969 12970 if (isa<ConstantSDNode>(Add->getOperand(1))) { 12971 SDNode *BasePtr = Add->getOperand(0).getNode(); 12972 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12973 UE = BasePtr->use_end(); UI != UE; ++UI) { 12974 if (UI->getOpcode() == ISD::ADD && 12975 isa<ConstantSDNode>(UI->getOperand(1)) && 12976 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 12977 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 12978 (1ULL << Bits) == 0) { 12979 SDNode *OtherAdd = *UI; 12980 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 12981 VE = OtherAdd->use_end(); VI != VE; ++VI) { 12982 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12983 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 12984 return SDValue(*VI, 0); 12985 } 12986 } 12987 } 12988 } 12989 } 12990 } 12991 } 12992 12993 break; 12994 case ISD::INTRINSIC_W_CHAIN: 12995 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12996 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12997 if (Subtarget.needsSwapsForVSXMemOps()) { 12998 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12999 default: 13000 break; 13001 case Intrinsic::ppc_vsx_lxvw4x: 13002 case Intrinsic::ppc_vsx_lxvd2x: 13003 return expandVSXLoadForLE(N, DCI); 13004 } 13005 } 13006 break; 13007 case ISD::INTRINSIC_VOID: 13008 // For little endian, VSX stores require generating xxswapd/stxvd2x. 13009 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13010 if (Subtarget.needsSwapsForVSXMemOps()) { 13011 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13012 default: 13013 break; 13014 case Intrinsic::ppc_vsx_stxvw4x: 13015 case Intrinsic::ppc_vsx_stxvd2x: 13016 return expandVSXStoreForLE(N, DCI); 13017 } 13018 } 13019 break; 13020 case ISD::BSWAP: 13021 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 13022 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 13023 N->getOperand(0).hasOneUse() && 13024 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 13025 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 13026 N->getValueType(0) == MVT::i64))) { 13027 SDValue Load = N->getOperand(0); 13028 LoadSDNode *LD = cast<LoadSDNode>(Load); 13029 // Create the byte-swapping load. 13030 SDValue Ops[] = { 13031 LD->getChain(), // Chain 13032 LD->getBasePtr(), // Ptr 13033 DAG.getValueType(N->getValueType(0)) // VT 13034 }; 13035 SDValue BSLoad = 13036 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 13037 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 13038 MVT::i64 : MVT::i32, MVT::Other), 13039 Ops, LD->getMemoryVT(), LD->getMemOperand()); 13040 13041 // If this is an i16 load, insert the truncate. 13042 SDValue ResVal = BSLoad; 13043 if (N->getValueType(0) == MVT::i16) 13044 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 13045 13046 // First, combine the bswap away. This makes the value produced by the 13047 // load dead. 13048 DCI.CombineTo(N, ResVal); 13049 13050 // Next, combine the load away, we give it a bogus result value but a real 13051 // chain result. The result value is dead because the bswap is dead. 13052 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 13053 13054 // Return N so it doesn't get rechecked! 13055 return SDValue(N, 0); 13056 } 13057 break; 13058 case PPCISD::VCMP: 13059 // If a VCMPo node already exists with exactly the same operands as this 13060 // node, use its result instead of this node (VCMPo computes both a CR6 and 13061 // a normal output). 13062 // 13063 if (!N->getOperand(0).hasOneUse() && 13064 !N->getOperand(1).hasOneUse() && 13065 !N->getOperand(2).hasOneUse()) { 13066 13067 // Scan all of the users of the LHS, looking for VCMPo's that match. 13068 SDNode *VCMPoNode = nullptr; 13069 13070 SDNode *LHSN = N->getOperand(0).getNode(); 13071 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 13072 UI != E; ++UI) 13073 if (UI->getOpcode() == PPCISD::VCMPo && 13074 UI->getOperand(1) == N->getOperand(1) && 13075 UI->getOperand(2) == N->getOperand(2) && 13076 UI->getOperand(0) == N->getOperand(0)) { 13077 VCMPoNode = *UI; 13078 break; 13079 } 13080 13081 // If there is no VCMPo node, or if the flag value has a single use, don't 13082 // transform this. 13083 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 13084 break; 13085 13086 // Look at the (necessarily single) use of the flag value. If it has a 13087 // chain, this transformation is more complex. Note that multiple things 13088 // could use the value result, which we should ignore. 13089 SDNode *FlagUser = nullptr; 13090 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 13091 FlagUser == nullptr; ++UI) { 13092 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 13093 SDNode *User = *UI; 13094 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 13095 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 13096 FlagUser = User; 13097 break; 13098 } 13099 } 13100 } 13101 13102 // If the user is a MFOCRF instruction, we know this is safe. 13103 // Otherwise we give up for right now. 13104 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 13105 return SDValue(VCMPoNode, 0); 13106 } 13107 break; 13108 case ISD::BRCOND: { 13109 SDValue Cond = N->getOperand(1); 13110 SDValue Target = N->getOperand(2); 13111 13112 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13113 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 13114 Intrinsic::ppc_is_decremented_ctr_nonzero) { 13115 13116 // We now need to make the intrinsic dead (it cannot be instruction 13117 // selected). 13118 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 13119 assert(Cond.getNode()->hasOneUse() && 13120 "Counter decrement has more than one use"); 13121 13122 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 13123 N->getOperand(0), Target); 13124 } 13125 } 13126 break; 13127 case ISD::BR_CC: { 13128 // If this is a branch on an altivec predicate comparison, lower this so 13129 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 13130 // lowering is done pre-legalize, because the legalizer lowers the predicate 13131 // compare down to code that is difficult to reassemble. 13132 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13133 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 13134 13135 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 13136 // value. If so, pass-through the AND to get to the intrinsic. 13137 if (LHS.getOpcode() == ISD::AND && 13138 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 13139 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 13140 Intrinsic::ppc_is_decremented_ctr_nonzero && 13141 isa<ConstantSDNode>(LHS.getOperand(1)) && 13142 !isNullConstant(LHS.getOperand(1))) 13143 LHS = LHS.getOperand(0); 13144 13145 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13146 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 13147 Intrinsic::ppc_is_decremented_ctr_nonzero && 13148 isa<ConstantSDNode>(RHS)) { 13149 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 13150 "Counter decrement comparison is not EQ or NE"); 13151 13152 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13153 bool isBDNZ = (CC == ISD::SETEQ && Val) || 13154 (CC == ISD::SETNE && !Val); 13155 13156 // We now need to make the intrinsic dead (it cannot be instruction 13157 // selected). 13158 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 13159 assert(LHS.getNode()->hasOneUse() && 13160 "Counter decrement has more than one use"); 13161 13162 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 13163 N->getOperand(0), N->getOperand(4)); 13164 } 13165 13166 int CompareOpc; 13167 bool isDot; 13168 13169 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13170 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 13171 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 13172 assert(isDot && "Can't compare against a vector result!"); 13173 13174 // If this is a comparison against something other than 0/1, then we know 13175 // that the condition is never/always true. 13176 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13177 if (Val != 0 && Val != 1) { 13178 if (CC == ISD::SETEQ) // Cond never true, remove branch. 13179 return N->getOperand(0); 13180 // Always !=, turn it into an unconditional branch. 13181 return DAG.getNode(ISD::BR, dl, MVT::Other, 13182 N->getOperand(0), N->getOperand(4)); 13183 } 13184 13185 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 13186 13187 // Create the PPCISD altivec 'dot' comparison node. 13188 SDValue Ops[] = { 13189 LHS.getOperand(2), // LHS of compare 13190 LHS.getOperand(3), // RHS of compare 13191 DAG.getConstant(CompareOpc, dl, MVT::i32) 13192 }; 13193 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 13194 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 13195 13196 // Unpack the result based on how the target uses it. 13197 PPC::Predicate CompOpc; 13198 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 13199 default: // Can't happen, don't crash on invalid number though. 13200 case 0: // Branch on the value of the EQ bit of CR6. 13201 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 13202 break; 13203 case 1: // Branch on the inverted value of the EQ bit of CR6. 13204 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 13205 break; 13206 case 2: // Branch on the value of the LT bit of CR6. 13207 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 13208 break; 13209 case 3: // Branch on the inverted value of the LT bit of CR6. 13210 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 13211 break; 13212 } 13213 13214 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 13215 DAG.getConstant(CompOpc, dl, MVT::i32), 13216 DAG.getRegister(PPC::CR6, MVT::i32), 13217 N->getOperand(4), CompNode.getValue(1)); 13218 } 13219 break; 13220 } 13221 case ISD::BUILD_VECTOR: 13222 return DAGCombineBuildVector(N, DCI); 13223 } 13224 13225 return SDValue(); 13226 } 13227 13228 SDValue 13229 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 13230 SelectionDAG &DAG, 13231 SmallVectorImpl<SDNode *> &Created) const { 13232 // fold (sdiv X, pow2) 13233 EVT VT = N->getValueType(0); 13234 if (VT == MVT::i64 && !Subtarget.isPPC64()) 13235 return SDValue(); 13236 if ((VT != MVT::i32 && VT != MVT::i64) || 13237 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 13238 return SDValue(); 13239 13240 SDLoc DL(N); 13241 SDValue N0 = N->getOperand(0); 13242 13243 bool IsNegPow2 = (-Divisor).isPowerOf2(); 13244 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 13245 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 13246 13247 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 13248 Created.push_back(Op.getNode()); 13249 13250 if (IsNegPow2) { 13251 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 13252 Created.push_back(Op.getNode()); 13253 } 13254 13255 return Op; 13256 } 13257 13258 //===----------------------------------------------------------------------===// 13259 // Inline Assembly Support 13260 //===----------------------------------------------------------------------===// 13261 13262 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13263 KnownBits &Known, 13264 const APInt &DemandedElts, 13265 const SelectionDAG &DAG, 13266 unsigned Depth) const { 13267 Known.resetAll(); 13268 switch (Op.getOpcode()) { 13269 default: break; 13270 case PPCISD::LBRX: { 13271 // lhbrx is known to have the top bits cleared out. 13272 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 13273 Known.Zero = 0xFFFF0000; 13274 break; 13275 } 13276 case ISD::INTRINSIC_WO_CHAIN: { 13277 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 13278 default: break; 13279 case Intrinsic::ppc_altivec_vcmpbfp_p: 13280 case Intrinsic::ppc_altivec_vcmpeqfp_p: 13281 case Intrinsic::ppc_altivec_vcmpequb_p: 13282 case Intrinsic::ppc_altivec_vcmpequh_p: 13283 case Intrinsic::ppc_altivec_vcmpequw_p: 13284 case Intrinsic::ppc_altivec_vcmpequd_p: 13285 case Intrinsic::ppc_altivec_vcmpgefp_p: 13286 case Intrinsic::ppc_altivec_vcmpgtfp_p: 13287 case Intrinsic::ppc_altivec_vcmpgtsb_p: 13288 case Intrinsic::ppc_altivec_vcmpgtsh_p: 13289 case Intrinsic::ppc_altivec_vcmpgtsw_p: 13290 case Intrinsic::ppc_altivec_vcmpgtsd_p: 13291 case Intrinsic::ppc_altivec_vcmpgtub_p: 13292 case Intrinsic::ppc_altivec_vcmpgtuh_p: 13293 case Intrinsic::ppc_altivec_vcmpgtuw_p: 13294 case Intrinsic::ppc_altivec_vcmpgtud_p: 13295 Known.Zero = ~1U; // All bits but the low one are known to be zero. 13296 break; 13297 } 13298 } 13299 } 13300 } 13301 13302 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 13303 switch (Subtarget.getDarwinDirective()) { 13304 default: break; 13305 case PPC::DIR_970: 13306 case PPC::DIR_PWR4: 13307 case PPC::DIR_PWR5: 13308 case PPC::DIR_PWR5X: 13309 case PPC::DIR_PWR6: 13310 case PPC::DIR_PWR6X: 13311 case PPC::DIR_PWR7: 13312 case PPC::DIR_PWR8: 13313 case PPC::DIR_PWR9: { 13314 if (!ML) 13315 break; 13316 13317 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 13318 13319 // For small loops (between 5 and 8 instructions), align to a 32-byte 13320 // boundary so that the entire loop fits in one instruction-cache line. 13321 uint64_t LoopSize = 0; 13322 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 13323 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 13324 LoopSize += TII->getInstSizeInBytes(*J); 13325 if (LoopSize > 32) 13326 break; 13327 } 13328 13329 if (LoopSize > 16 && LoopSize <= 32) 13330 return 5; 13331 13332 break; 13333 } 13334 } 13335 13336 return TargetLowering::getPrefLoopAlignment(ML); 13337 } 13338 13339 /// getConstraintType - Given a constraint, return the type of 13340 /// constraint it is for this target. 13341 PPCTargetLowering::ConstraintType 13342 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 13343 if (Constraint.size() == 1) { 13344 switch (Constraint[0]) { 13345 default: break; 13346 case 'b': 13347 case 'r': 13348 case 'f': 13349 case 'd': 13350 case 'v': 13351 case 'y': 13352 return C_RegisterClass; 13353 case 'Z': 13354 // FIXME: While Z does indicate a memory constraint, it specifically 13355 // indicates an r+r address (used in conjunction with the 'y' modifier 13356 // in the replacement string). Currently, we're forcing the base 13357 // register to be r0 in the asm printer (which is interpreted as zero) 13358 // and forming the complete address in the second register. This is 13359 // suboptimal. 13360 return C_Memory; 13361 } 13362 } else if (Constraint == "wc") { // individual CR bits. 13363 return C_RegisterClass; 13364 } else if (Constraint == "wa" || Constraint == "wd" || 13365 Constraint == "wf" || Constraint == "ws" || 13366 Constraint == "wi") { 13367 return C_RegisterClass; // VSX registers. 13368 } 13369 return TargetLowering::getConstraintType(Constraint); 13370 } 13371 13372 /// Examine constraint type and operand type and determine a weight value. 13373 /// This object must already have been set up with the operand type 13374 /// and the current alternative constraint selected. 13375 TargetLowering::ConstraintWeight 13376 PPCTargetLowering::getSingleConstraintMatchWeight( 13377 AsmOperandInfo &info, const char *constraint) const { 13378 ConstraintWeight weight = CW_Invalid; 13379 Value *CallOperandVal = info.CallOperandVal; 13380 // If we don't have a value, we can't do a match, 13381 // but allow it at the lowest weight. 13382 if (!CallOperandVal) 13383 return CW_Default; 13384 Type *type = CallOperandVal->getType(); 13385 13386 // Look at the constraint type. 13387 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 13388 return CW_Register; // an individual CR bit. 13389 else if ((StringRef(constraint) == "wa" || 13390 StringRef(constraint) == "wd" || 13391 StringRef(constraint) == "wf") && 13392 type->isVectorTy()) 13393 return CW_Register; 13394 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 13395 return CW_Register; 13396 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 13397 return CW_Register; // just hold 64-bit integers data. 13398 13399 switch (*constraint) { 13400 default: 13401 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13402 break; 13403 case 'b': 13404 if (type->isIntegerTy()) 13405 weight = CW_Register; 13406 break; 13407 case 'f': 13408 if (type->isFloatTy()) 13409 weight = CW_Register; 13410 break; 13411 case 'd': 13412 if (type->isDoubleTy()) 13413 weight = CW_Register; 13414 break; 13415 case 'v': 13416 if (type->isVectorTy()) 13417 weight = CW_Register; 13418 break; 13419 case 'y': 13420 weight = CW_Register; 13421 break; 13422 case 'Z': 13423 weight = CW_Memory; 13424 break; 13425 } 13426 return weight; 13427 } 13428 13429 std::pair<unsigned, const TargetRegisterClass *> 13430 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 13431 StringRef Constraint, 13432 MVT VT) const { 13433 if (Constraint.size() == 1) { 13434 // GCC RS6000 Constraint Letters 13435 switch (Constraint[0]) { 13436 case 'b': // R1-R31 13437 if (VT == MVT::i64 && Subtarget.isPPC64()) 13438 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 13439 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 13440 case 'r': // R0-R31 13441 if (VT == MVT::i64 && Subtarget.isPPC64()) 13442 return std::make_pair(0U, &PPC::G8RCRegClass); 13443 return std::make_pair(0U, &PPC::GPRCRegClass); 13444 // 'd' and 'f' constraints are both defined to be "the floating point 13445 // registers", where one is for 32-bit and the other for 64-bit. We don't 13446 // really care overly much here so just give them all the same reg classes. 13447 case 'd': 13448 case 'f': 13449 if (Subtarget.hasSPE()) { 13450 if (VT == MVT::f32 || VT == MVT::i32) 13451 return std::make_pair(0U, &PPC::SPE4RCRegClass); 13452 if (VT == MVT::f64 || VT == MVT::i64) 13453 return std::make_pair(0U, &PPC::SPERCRegClass); 13454 } else { 13455 if (VT == MVT::f32 || VT == MVT::i32) 13456 return std::make_pair(0U, &PPC::F4RCRegClass); 13457 if (VT == MVT::f64 || VT == MVT::i64) 13458 return std::make_pair(0U, &PPC::F8RCRegClass); 13459 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13460 return std::make_pair(0U, &PPC::QFRCRegClass); 13461 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13462 return std::make_pair(0U, &PPC::QSRCRegClass); 13463 } 13464 break; 13465 case 'v': 13466 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13467 return std::make_pair(0U, &PPC::QFRCRegClass); 13468 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13469 return std::make_pair(0U, &PPC::QSRCRegClass); 13470 if (Subtarget.hasAltivec()) 13471 return std::make_pair(0U, &PPC::VRRCRegClass); 13472 break; 13473 case 'y': // crrc 13474 return std::make_pair(0U, &PPC::CRRCRegClass); 13475 } 13476 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 13477 // An individual CR bit. 13478 return std::make_pair(0U, &PPC::CRBITRCRegClass); 13479 } else if ((Constraint == "wa" || Constraint == "wd" || 13480 Constraint == "wf" || Constraint == "wi") && 13481 Subtarget.hasVSX()) { 13482 return std::make_pair(0U, &PPC::VSRCRegClass); 13483 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 13484 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 13485 return std::make_pair(0U, &PPC::VSSRCRegClass); 13486 else 13487 return std::make_pair(0U, &PPC::VSFRCRegClass); 13488 } 13489 13490 std::pair<unsigned, const TargetRegisterClass *> R = 13491 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13492 13493 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 13494 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 13495 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 13496 // register. 13497 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 13498 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 13499 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 13500 PPC::GPRCRegClass.contains(R.first)) 13501 return std::make_pair(TRI->getMatchingSuperReg(R.first, 13502 PPC::sub_32, &PPC::G8RCRegClass), 13503 &PPC::G8RCRegClass); 13504 13505 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 13506 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 13507 R.first = PPC::CR0; 13508 R.second = &PPC::CRRCRegClass; 13509 } 13510 13511 return R; 13512 } 13513 13514 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13515 /// vector. If it is invalid, don't add anything to Ops. 13516 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13517 std::string &Constraint, 13518 std::vector<SDValue>&Ops, 13519 SelectionDAG &DAG) const { 13520 SDValue Result; 13521 13522 // Only support length 1 constraints. 13523 if (Constraint.length() > 1) return; 13524 13525 char Letter = Constraint[0]; 13526 switch (Letter) { 13527 default: break; 13528 case 'I': 13529 case 'J': 13530 case 'K': 13531 case 'L': 13532 case 'M': 13533 case 'N': 13534 case 'O': 13535 case 'P': { 13536 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 13537 if (!CST) return; // Must be an immediate to match. 13538 SDLoc dl(Op); 13539 int64_t Value = CST->getSExtValue(); 13540 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 13541 // numbers are printed as such. 13542 switch (Letter) { 13543 default: llvm_unreachable("Unknown constraint letter!"); 13544 case 'I': // "I" is a signed 16-bit constant. 13545 if (isInt<16>(Value)) 13546 Result = DAG.getTargetConstant(Value, dl, TCVT); 13547 break; 13548 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 13549 if (isShiftedUInt<16, 16>(Value)) 13550 Result = DAG.getTargetConstant(Value, dl, TCVT); 13551 break; 13552 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 13553 if (isShiftedInt<16, 16>(Value)) 13554 Result = DAG.getTargetConstant(Value, dl, TCVT); 13555 break; 13556 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 13557 if (isUInt<16>(Value)) 13558 Result = DAG.getTargetConstant(Value, dl, TCVT); 13559 break; 13560 case 'M': // "M" is a constant that is greater than 31. 13561 if (Value > 31) 13562 Result = DAG.getTargetConstant(Value, dl, TCVT); 13563 break; 13564 case 'N': // "N" is a positive constant that is an exact power of two. 13565 if (Value > 0 && isPowerOf2_64(Value)) 13566 Result = DAG.getTargetConstant(Value, dl, TCVT); 13567 break; 13568 case 'O': // "O" is the constant zero. 13569 if (Value == 0) 13570 Result = DAG.getTargetConstant(Value, dl, TCVT); 13571 break; 13572 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 13573 if (isInt<16>(-Value)) 13574 Result = DAG.getTargetConstant(Value, dl, TCVT); 13575 break; 13576 } 13577 break; 13578 } 13579 } 13580 13581 if (Result.getNode()) { 13582 Ops.push_back(Result); 13583 return; 13584 } 13585 13586 // Handle standard constraint letters. 13587 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13588 } 13589 13590 // isLegalAddressingMode - Return true if the addressing mode represented 13591 // by AM is legal for this target, for a load/store of the specified type. 13592 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13593 const AddrMode &AM, Type *Ty, 13594 unsigned AS, Instruction *I) const { 13595 // PPC does not allow r+i addressing modes for vectors! 13596 if (Ty->isVectorTy() && AM.BaseOffs != 0) 13597 return false; 13598 13599 // PPC allows a sign-extended 16-bit immediate field. 13600 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 13601 return false; 13602 13603 // No global is ever allowed as a base. 13604 if (AM.BaseGV) 13605 return false; 13606 13607 // PPC only support r+r, 13608 switch (AM.Scale) { 13609 case 0: // "r+i" or just "i", depending on HasBaseReg. 13610 break; 13611 case 1: 13612 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 13613 return false; 13614 // Otherwise we have r+r or r+i. 13615 break; 13616 case 2: 13617 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 13618 return false; 13619 // Allow 2*r as r+r. 13620 break; 13621 default: 13622 // No other scales are supported. 13623 return false; 13624 } 13625 13626 return true; 13627 } 13628 13629 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 13630 SelectionDAG &DAG) const { 13631 MachineFunction &MF = DAG.getMachineFunction(); 13632 MachineFrameInfo &MFI = MF.getFrameInfo(); 13633 MFI.setReturnAddressIsTaken(true); 13634 13635 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 13636 return SDValue(); 13637 13638 SDLoc dl(Op); 13639 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13640 13641 // Make sure the function does not optimize away the store of the RA to 13642 // the stack. 13643 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 13644 FuncInfo->setLRStoreRequired(); 13645 bool isPPC64 = Subtarget.isPPC64(); 13646 auto PtrVT = getPointerTy(MF.getDataLayout()); 13647 13648 if (Depth > 0) { 13649 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 13650 SDValue Offset = 13651 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 13652 isPPC64 ? MVT::i64 : MVT::i32); 13653 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 13654 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 13655 MachinePointerInfo()); 13656 } 13657 13658 // Just load the return address off the stack. 13659 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 13660 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 13661 MachinePointerInfo()); 13662 } 13663 13664 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 13665 SelectionDAG &DAG) const { 13666 SDLoc dl(Op); 13667 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13668 13669 MachineFunction &MF = DAG.getMachineFunction(); 13670 MachineFrameInfo &MFI = MF.getFrameInfo(); 13671 MFI.setFrameAddressIsTaken(true); 13672 13673 EVT PtrVT = getPointerTy(MF.getDataLayout()); 13674 bool isPPC64 = PtrVT == MVT::i64; 13675 13676 // Naked functions never have a frame pointer, and so we use r1. For all 13677 // other functions, this decision must be delayed until during PEI. 13678 unsigned FrameReg; 13679 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 13680 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 13681 else 13682 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 13683 13684 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 13685 PtrVT); 13686 while (Depth--) 13687 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 13688 FrameAddr, MachinePointerInfo()); 13689 return FrameAddr; 13690 } 13691 13692 // FIXME? Maybe this could be a TableGen attribute on some registers and 13693 // this table could be generated automatically from RegInfo. 13694 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 13695 SelectionDAG &DAG) const { 13696 bool isPPC64 = Subtarget.isPPC64(); 13697 bool isDarwinABI = Subtarget.isDarwinABI(); 13698 13699 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 13700 (!isPPC64 && VT != MVT::i32)) 13701 report_fatal_error("Invalid register global variable type"); 13702 13703 bool is64Bit = isPPC64 && VT == MVT::i64; 13704 unsigned Reg = StringSwitch<unsigned>(RegName) 13705 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 13706 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 13707 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 13708 (is64Bit ? PPC::X13 : PPC::R13)) 13709 .Default(0); 13710 13711 if (Reg) 13712 return Reg; 13713 report_fatal_error("Invalid register name global variable"); 13714 } 13715 13716 bool 13717 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13718 // The PowerPC target isn't yet aware of offsets. 13719 return false; 13720 } 13721 13722 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13723 const CallInst &I, 13724 MachineFunction &MF, 13725 unsigned Intrinsic) const { 13726 switch (Intrinsic) { 13727 case Intrinsic::ppc_qpx_qvlfd: 13728 case Intrinsic::ppc_qpx_qvlfs: 13729 case Intrinsic::ppc_qpx_qvlfcd: 13730 case Intrinsic::ppc_qpx_qvlfcs: 13731 case Intrinsic::ppc_qpx_qvlfiwa: 13732 case Intrinsic::ppc_qpx_qvlfiwz: 13733 case Intrinsic::ppc_altivec_lvx: 13734 case Intrinsic::ppc_altivec_lvxl: 13735 case Intrinsic::ppc_altivec_lvebx: 13736 case Intrinsic::ppc_altivec_lvehx: 13737 case Intrinsic::ppc_altivec_lvewx: 13738 case Intrinsic::ppc_vsx_lxvd2x: 13739 case Intrinsic::ppc_vsx_lxvw4x: { 13740 EVT VT; 13741 switch (Intrinsic) { 13742 case Intrinsic::ppc_altivec_lvebx: 13743 VT = MVT::i8; 13744 break; 13745 case Intrinsic::ppc_altivec_lvehx: 13746 VT = MVT::i16; 13747 break; 13748 case Intrinsic::ppc_altivec_lvewx: 13749 VT = MVT::i32; 13750 break; 13751 case Intrinsic::ppc_vsx_lxvd2x: 13752 VT = MVT::v2f64; 13753 break; 13754 case Intrinsic::ppc_qpx_qvlfd: 13755 VT = MVT::v4f64; 13756 break; 13757 case Intrinsic::ppc_qpx_qvlfs: 13758 VT = MVT::v4f32; 13759 break; 13760 case Intrinsic::ppc_qpx_qvlfcd: 13761 VT = MVT::v2f64; 13762 break; 13763 case Intrinsic::ppc_qpx_qvlfcs: 13764 VT = MVT::v2f32; 13765 break; 13766 default: 13767 VT = MVT::v4i32; 13768 break; 13769 } 13770 13771 Info.opc = ISD::INTRINSIC_W_CHAIN; 13772 Info.memVT = VT; 13773 Info.ptrVal = I.getArgOperand(0); 13774 Info.offset = -VT.getStoreSize()+1; 13775 Info.size = 2*VT.getStoreSize()-1; 13776 Info.align = 1; 13777 Info.flags = MachineMemOperand::MOLoad; 13778 return true; 13779 } 13780 case Intrinsic::ppc_qpx_qvlfda: 13781 case Intrinsic::ppc_qpx_qvlfsa: 13782 case Intrinsic::ppc_qpx_qvlfcda: 13783 case Intrinsic::ppc_qpx_qvlfcsa: 13784 case Intrinsic::ppc_qpx_qvlfiwaa: 13785 case Intrinsic::ppc_qpx_qvlfiwza: { 13786 EVT VT; 13787 switch (Intrinsic) { 13788 case Intrinsic::ppc_qpx_qvlfda: 13789 VT = MVT::v4f64; 13790 break; 13791 case Intrinsic::ppc_qpx_qvlfsa: 13792 VT = MVT::v4f32; 13793 break; 13794 case Intrinsic::ppc_qpx_qvlfcda: 13795 VT = MVT::v2f64; 13796 break; 13797 case Intrinsic::ppc_qpx_qvlfcsa: 13798 VT = MVT::v2f32; 13799 break; 13800 default: 13801 VT = MVT::v4i32; 13802 break; 13803 } 13804 13805 Info.opc = ISD::INTRINSIC_W_CHAIN; 13806 Info.memVT = VT; 13807 Info.ptrVal = I.getArgOperand(0); 13808 Info.offset = 0; 13809 Info.size = VT.getStoreSize(); 13810 Info.align = 1; 13811 Info.flags = MachineMemOperand::MOLoad; 13812 return true; 13813 } 13814 case Intrinsic::ppc_qpx_qvstfd: 13815 case Intrinsic::ppc_qpx_qvstfs: 13816 case Intrinsic::ppc_qpx_qvstfcd: 13817 case Intrinsic::ppc_qpx_qvstfcs: 13818 case Intrinsic::ppc_qpx_qvstfiw: 13819 case Intrinsic::ppc_altivec_stvx: 13820 case Intrinsic::ppc_altivec_stvxl: 13821 case Intrinsic::ppc_altivec_stvebx: 13822 case Intrinsic::ppc_altivec_stvehx: 13823 case Intrinsic::ppc_altivec_stvewx: 13824 case Intrinsic::ppc_vsx_stxvd2x: 13825 case Intrinsic::ppc_vsx_stxvw4x: { 13826 EVT VT; 13827 switch (Intrinsic) { 13828 case Intrinsic::ppc_altivec_stvebx: 13829 VT = MVT::i8; 13830 break; 13831 case Intrinsic::ppc_altivec_stvehx: 13832 VT = MVT::i16; 13833 break; 13834 case Intrinsic::ppc_altivec_stvewx: 13835 VT = MVT::i32; 13836 break; 13837 case Intrinsic::ppc_vsx_stxvd2x: 13838 VT = MVT::v2f64; 13839 break; 13840 case Intrinsic::ppc_qpx_qvstfd: 13841 VT = MVT::v4f64; 13842 break; 13843 case Intrinsic::ppc_qpx_qvstfs: 13844 VT = MVT::v4f32; 13845 break; 13846 case Intrinsic::ppc_qpx_qvstfcd: 13847 VT = MVT::v2f64; 13848 break; 13849 case Intrinsic::ppc_qpx_qvstfcs: 13850 VT = MVT::v2f32; 13851 break; 13852 default: 13853 VT = MVT::v4i32; 13854 break; 13855 } 13856 13857 Info.opc = ISD::INTRINSIC_VOID; 13858 Info.memVT = VT; 13859 Info.ptrVal = I.getArgOperand(1); 13860 Info.offset = -VT.getStoreSize()+1; 13861 Info.size = 2*VT.getStoreSize()-1; 13862 Info.align = 1; 13863 Info.flags = MachineMemOperand::MOStore; 13864 return true; 13865 } 13866 case Intrinsic::ppc_qpx_qvstfda: 13867 case Intrinsic::ppc_qpx_qvstfsa: 13868 case Intrinsic::ppc_qpx_qvstfcda: 13869 case Intrinsic::ppc_qpx_qvstfcsa: 13870 case Intrinsic::ppc_qpx_qvstfiwa: { 13871 EVT VT; 13872 switch (Intrinsic) { 13873 case Intrinsic::ppc_qpx_qvstfda: 13874 VT = MVT::v4f64; 13875 break; 13876 case Intrinsic::ppc_qpx_qvstfsa: 13877 VT = MVT::v4f32; 13878 break; 13879 case Intrinsic::ppc_qpx_qvstfcda: 13880 VT = MVT::v2f64; 13881 break; 13882 case Intrinsic::ppc_qpx_qvstfcsa: 13883 VT = MVT::v2f32; 13884 break; 13885 default: 13886 VT = MVT::v4i32; 13887 break; 13888 } 13889 13890 Info.opc = ISD::INTRINSIC_VOID; 13891 Info.memVT = VT; 13892 Info.ptrVal = I.getArgOperand(1); 13893 Info.offset = 0; 13894 Info.size = VT.getStoreSize(); 13895 Info.align = 1; 13896 Info.flags = MachineMemOperand::MOStore; 13897 return true; 13898 } 13899 default: 13900 break; 13901 } 13902 13903 return false; 13904 } 13905 13906 /// getOptimalMemOpType - Returns the target specific optimal type for load 13907 /// and store operations as a result of memset, memcpy, and memmove 13908 /// lowering. If DstAlign is zero that means it's safe to destination 13909 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 13910 /// means there isn't a need to check it against alignment requirement, 13911 /// probably because the source does not need to be loaded. If 'IsMemset' is 13912 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 13913 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 13914 /// source is constant so it does not need to be loaded. 13915 /// It returns EVT::Other if the type should be determined using generic 13916 /// target-independent logic. 13917 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 13918 unsigned DstAlign, unsigned SrcAlign, 13919 bool IsMemset, bool ZeroMemset, 13920 bool MemcpyStrSrc, 13921 MachineFunction &MF) const { 13922 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 13923 const Function &F = MF.getFunction(); 13924 // When expanding a memset, require at least two QPX instructions to cover 13925 // the cost of loading the value to be stored from the constant pool. 13926 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 13927 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 13928 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 13929 return MVT::v4f64; 13930 } 13931 13932 // We should use Altivec/VSX loads and stores when available. For unaligned 13933 // addresses, unaligned VSX loads are only fast starting with the P8. 13934 if (Subtarget.hasAltivec() && Size >= 16 && 13935 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 13936 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 13937 return MVT::v4i32; 13938 } 13939 13940 if (Subtarget.isPPC64()) { 13941 return MVT::i64; 13942 } 13943 13944 return MVT::i32; 13945 } 13946 13947 /// Returns true if it is beneficial to convert a load of a constant 13948 /// to just the constant itself. 13949 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13950 Type *Ty) const { 13951 assert(Ty->isIntegerTy()); 13952 13953 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 13954 return !(BitSize == 0 || BitSize > 64); 13955 } 13956 13957 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 13958 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13959 return false; 13960 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 13961 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 13962 return NumBits1 == 64 && NumBits2 == 32; 13963 } 13964 13965 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 13966 if (!VT1.isInteger() || !VT2.isInteger()) 13967 return false; 13968 unsigned NumBits1 = VT1.getSizeInBits(); 13969 unsigned NumBits2 = VT2.getSizeInBits(); 13970 return NumBits1 == 64 && NumBits2 == 32; 13971 } 13972 13973 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13974 // Generally speaking, zexts are not free, but they are free when they can be 13975 // folded with other operations. 13976 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 13977 EVT MemVT = LD->getMemoryVT(); 13978 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 13979 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 13980 (LD->getExtensionType() == ISD::NON_EXTLOAD || 13981 LD->getExtensionType() == ISD::ZEXTLOAD)) 13982 return true; 13983 } 13984 13985 // FIXME: Add other cases... 13986 // - 32-bit shifts with a zext to i64 13987 // - zext after ctlz, bswap, etc. 13988 // - zext after and by a constant mask 13989 13990 return TargetLowering::isZExtFree(Val, VT2); 13991 } 13992 13993 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 13994 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 13995 "invalid fpext types"); 13996 // Extending to float128 is not free. 13997 if (DestVT == MVT::f128) 13998 return false; 13999 return true; 14000 } 14001 14002 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14003 return isInt<16>(Imm) || isUInt<16>(Imm); 14004 } 14005 14006 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14007 return isInt<16>(Imm) || isUInt<16>(Imm); 14008 } 14009 14010 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 14011 unsigned, 14012 unsigned, 14013 bool *Fast) const { 14014 if (DisablePPCUnaligned) 14015 return false; 14016 14017 // PowerPC supports unaligned memory access for simple non-vector types. 14018 // Although accessing unaligned addresses is not as efficient as accessing 14019 // aligned addresses, it is generally more efficient than manual expansion, 14020 // and generally only traps for software emulation when crossing page 14021 // boundaries. 14022 14023 if (!VT.isSimple()) 14024 return false; 14025 14026 if (VT.getSimpleVT().isVector()) { 14027 if (Subtarget.hasVSX()) { 14028 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 14029 VT != MVT::v4f32 && VT != MVT::v4i32) 14030 return false; 14031 } else { 14032 return false; 14033 } 14034 } 14035 14036 if (VT == MVT::ppcf128) 14037 return false; 14038 14039 if (Fast) 14040 *Fast = true; 14041 14042 return true; 14043 } 14044 14045 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 14046 VT = VT.getScalarType(); 14047 14048 if (!VT.isSimple()) 14049 return false; 14050 14051 switch (VT.getSimpleVT().SimpleTy) { 14052 case MVT::f32: 14053 case MVT::f64: 14054 return true; 14055 case MVT::f128: 14056 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 14057 default: 14058 break; 14059 } 14060 14061 return false; 14062 } 14063 14064 const MCPhysReg * 14065 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 14066 // LR is a callee-save register, but we must treat it as clobbered by any call 14067 // site. Hence we include LR in the scratch registers, which are in turn added 14068 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 14069 // to CTR, which is used by any indirect call. 14070 static const MCPhysReg ScratchRegs[] = { 14071 PPC::X12, PPC::LR8, PPC::CTR8, 0 14072 }; 14073 14074 return ScratchRegs; 14075 } 14076 14077 unsigned PPCTargetLowering::getExceptionPointerRegister( 14078 const Constant *PersonalityFn) const { 14079 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 14080 } 14081 14082 unsigned PPCTargetLowering::getExceptionSelectorRegister( 14083 const Constant *PersonalityFn) const { 14084 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 14085 } 14086 14087 bool 14088 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 14089 EVT VT , unsigned DefinedValues) const { 14090 if (VT == MVT::v2i64) 14091 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 14092 14093 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 14094 return true; 14095 14096 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 14097 } 14098 14099 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 14100 if (DisableILPPref || Subtarget.enableMachineScheduler()) 14101 return TargetLowering::getSchedulingPreference(N); 14102 14103 return Sched::ILP; 14104 } 14105 14106 // Create a fast isel object. 14107 FastISel * 14108 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 14109 const TargetLibraryInfo *LibInfo) const { 14110 return PPC::createFastISel(FuncInfo, LibInfo); 14111 } 14112 14113 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14114 if (Subtarget.isDarwinABI()) return; 14115 if (!Subtarget.isPPC64()) return; 14116 14117 // Update IsSplitCSR in PPCFunctionInfo 14118 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 14119 PFI->setIsSplitCSR(true); 14120 } 14121 14122 void PPCTargetLowering::insertCopiesSplitCSR( 14123 MachineBasicBlock *Entry, 14124 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14125 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 14126 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14127 if (!IStart) 14128 return; 14129 14130 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 14131 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14132 MachineBasicBlock::iterator MBBI = Entry->begin(); 14133 for (const MCPhysReg *I = IStart; *I; ++I) { 14134 const TargetRegisterClass *RC = nullptr; 14135 if (PPC::G8RCRegClass.contains(*I)) 14136 RC = &PPC::G8RCRegClass; 14137 else if (PPC::F8RCRegClass.contains(*I)) 14138 RC = &PPC::F8RCRegClass; 14139 else if (PPC::CRRCRegClass.contains(*I)) 14140 RC = &PPC::CRRCRegClass; 14141 else if (PPC::VRRCRegClass.contains(*I)) 14142 RC = &PPC::VRRCRegClass; 14143 else 14144 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14145 14146 unsigned NewVR = MRI->createVirtualRegister(RC); 14147 // Create copy from CSR to a virtual register. 14148 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14149 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14150 // nounwind. If we want to generalize this later, we may need to emit 14151 // CFI pseudo-instructions. 14152 assert(Entry->getParent()->getFunction().hasFnAttribute( 14153 Attribute::NoUnwind) && 14154 "Function should be nounwind in insertCopiesSplitCSR!"); 14155 Entry->addLiveIn(*I); 14156 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14157 .addReg(*I); 14158 14159 // Insert the copy-back instructions right before the terminator 14160 for (auto *Exit : Exits) 14161 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14162 TII->get(TargetOpcode::COPY), *I) 14163 .addReg(NewVR); 14164 } 14165 } 14166 14167 // Override to enable LOAD_STACK_GUARD lowering on Linux. 14168 bool PPCTargetLowering::useLoadStackGuardNode() const { 14169 if (!Subtarget.isTargetLinux()) 14170 return TargetLowering::useLoadStackGuardNode(); 14171 return true; 14172 } 14173 14174 // Override to disable global variable loading on Linux. 14175 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 14176 if (!Subtarget.isTargetLinux()) 14177 return TargetLowering::insertSSPDeclarations(M); 14178 } 14179 14180 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 14181 if (!VT.isSimple() || !Subtarget.hasVSX()) 14182 return false; 14183 14184 switch(VT.getSimpleVT().SimpleTy) { 14185 default: 14186 // For FP types that are currently not supported by PPC backend, return 14187 // false. Examples: f16, f80. 14188 return false; 14189 case MVT::f32: 14190 case MVT::f64: 14191 case MVT::ppcf128: 14192 return Imm.isPosZero(); 14193 } 14194 } 14195 14196 // For vector shift operation op, fold 14197 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 14198 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 14199 SelectionDAG &DAG) { 14200 SDValue N0 = N->getOperand(0); 14201 SDValue N1 = N->getOperand(1); 14202 EVT VT = N0.getValueType(); 14203 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 14204 unsigned Opcode = N->getOpcode(); 14205 unsigned TargetOpcode; 14206 14207 switch (Opcode) { 14208 default: 14209 llvm_unreachable("Unexpected shift operation"); 14210 case ISD::SHL: 14211 TargetOpcode = PPCISD::SHL; 14212 break; 14213 case ISD::SRL: 14214 TargetOpcode = PPCISD::SRL; 14215 break; 14216 case ISD::SRA: 14217 TargetOpcode = PPCISD::SRA; 14218 break; 14219 } 14220 14221 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 14222 N1->getOpcode() == ISD::AND) 14223 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 14224 if (Mask->getZExtValue() == OpSizeInBits - 1) 14225 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 14226 14227 return SDValue(); 14228 } 14229 14230 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 14231 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14232 return Value; 14233 14234 SDValue N0 = N->getOperand(0); 14235 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14236 if (!Subtarget.isISA3_0() || 14237 N0.getOpcode() != ISD::SIGN_EXTEND || 14238 N0.getOperand(0).getValueType() != MVT::i32 || 14239 CN1 == nullptr || N->getValueType(0) != MVT::i64) 14240 return SDValue(); 14241 14242 // We can't save an operation here if the value is already extended, and 14243 // the existing shift is easier to combine. 14244 SDValue ExtsSrc = N0.getOperand(0); 14245 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 14246 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 14247 return SDValue(); 14248 14249 SDLoc DL(N0); 14250 SDValue ShiftBy = SDValue(CN1, 0); 14251 // We want the shift amount to be i32 on the extswli, but the shift could 14252 // have an i64. 14253 if (ShiftBy.getValueType() == MVT::i64) 14254 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 14255 14256 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 14257 ShiftBy); 14258 } 14259 14260 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 14261 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14262 return Value; 14263 14264 return SDValue(); 14265 } 14266 14267 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 14268 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14269 return Value; 14270 14271 return SDValue(); 14272 } 14273 14274 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 14275 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 14276 // When C is zero, the equation (addi Z, -C) can be simplified to Z 14277 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 14278 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 14279 const PPCSubtarget &Subtarget) { 14280 if (!Subtarget.isPPC64()) 14281 return SDValue(); 14282 14283 SDValue LHS = N->getOperand(0); 14284 SDValue RHS = N->getOperand(1); 14285 14286 auto isZextOfCompareWithConstant = [](SDValue Op) { 14287 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 14288 Op.getValueType() != MVT::i64) 14289 return false; 14290 14291 SDValue Cmp = Op.getOperand(0); 14292 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 14293 Cmp.getOperand(0).getValueType() != MVT::i64) 14294 return false; 14295 14296 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 14297 int64_t NegConstant = 0 - Constant->getSExtValue(); 14298 // Due to the limitations of the addi instruction, 14299 // -C is required to be [-32768, 32767]. 14300 return isInt<16>(NegConstant); 14301 } 14302 14303 return false; 14304 }; 14305 14306 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 14307 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 14308 14309 // If there is a pattern, canonicalize a zext operand to the RHS. 14310 if (LHSHasPattern && !RHSHasPattern) 14311 std::swap(LHS, RHS); 14312 else if (!LHSHasPattern && !RHSHasPattern) 14313 return SDValue(); 14314 14315 SDLoc DL(N); 14316 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i64); 14317 SDValue Cmp = RHS.getOperand(0); 14318 SDValue Z = Cmp.getOperand(0); 14319 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 14320 14321 assert(Constant && "Constant Should not be a null pointer."); 14322 int64_t NegConstant = 0 - Constant->getSExtValue(); 14323 14324 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 14325 default: break; 14326 case ISD::SETNE: { 14327 // when C == 0 14328 // --> addze X, (addic Z, -1).carry 14329 // / 14330 // add X, (zext(setne Z, C))-- 14331 // \ when -32768 <= -C <= 32767 && C != 0 14332 // --> addze X, (addic (addi Z, -C), -1).carry 14333 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14334 DAG.getConstant(NegConstant, DL, MVT::i64)); 14335 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14336 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14337 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 14338 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14339 SDValue(Addc.getNode(), 1)); 14340 } 14341 case ISD::SETEQ: { 14342 // when C == 0 14343 // --> addze X, (subfic Z, 0).carry 14344 // / 14345 // add X, (zext(sete Z, C))-- 14346 // \ when -32768 <= -C <= 32767 && C != 0 14347 // --> addze X, (subfic (addi Z, -C), 0).carry 14348 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14349 DAG.getConstant(NegConstant, DL, MVT::i64)); 14350 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14351 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14352 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 14353 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14354 SDValue(Subc.getNode(), 1)); 14355 } 14356 } 14357 14358 return SDValue(); 14359 } 14360 14361 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 14362 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 14363 return Value; 14364 14365 return SDValue(); 14366 } 14367 14368 // Detect TRUNCATE operations on bitcasts of float128 values. 14369 // What we are looking for here is the situtation where we extract a subset 14370 // of bits from a 128 bit float. 14371 // This can be of two forms: 14372 // 1) BITCAST of f128 feeding TRUNCATE 14373 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 14374 // The reason this is required is because we do not have a legal i128 type 14375 // and so we want to prevent having to store the f128 and then reload part 14376 // of it. 14377 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 14378 DAGCombinerInfo &DCI) const { 14379 // If we are using CRBits then try that first. 14380 if (Subtarget.useCRBits()) { 14381 // Check if CRBits did anything and return that if it did. 14382 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 14383 return CRTruncValue; 14384 } 14385 14386 SDLoc dl(N); 14387 SDValue Op0 = N->getOperand(0); 14388 14389 // Looking for a truncate of i128 to i64. 14390 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 14391 return SDValue(); 14392 14393 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 14394 14395 // SRL feeding TRUNCATE. 14396 if (Op0.getOpcode() == ISD::SRL) { 14397 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 14398 // The right shift has to be by 64 bits. 14399 if (!ConstNode || ConstNode->getZExtValue() != 64) 14400 return SDValue(); 14401 14402 // Switch the element number to extract. 14403 EltToExtract = EltToExtract ? 0 : 1; 14404 // Update Op0 past the SRL. 14405 Op0 = Op0.getOperand(0); 14406 } 14407 14408 // BITCAST feeding a TRUNCATE possibly via SRL. 14409 if (Op0.getOpcode() == ISD::BITCAST && 14410 Op0.getValueType() == MVT::i128 && 14411 Op0.getOperand(0).getValueType() == MVT::f128) { 14412 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 14413 return DCI.DAG.getNode( 14414 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 14415 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 14416 } 14417 return SDValue(); 14418 } 14419 14420 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 14421 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 14422 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 14423 return false; 14424 14425 // If not a tail call then no need to proceed. 14426 if (!CI->isTailCall()) 14427 return false; 14428 14429 // If tail calls are disabled for the caller then we are done. 14430 const Function *Caller = CI->getParent()->getParent(); 14431 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 14432 if (Attr.getValueAsString() == "true") 14433 return false; 14434 14435 // If sibling calls have been disabled and tail-calls aren't guaranteed 14436 // there is no reason to duplicate. 14437 auto &TM = getTargetMachine(); 14438 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 14439 return false; 14440 14441 // Can't tail call a function called indirectly, or if it has variadic args. 14442 const Function *Callee = CI->getCalledFunction(); 14443 if (!Callee || Callee->isVarArg()) 14444 return false; 14445 14446 // Make sure the callee and caller calling conventions are eligible for tco. 14447 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 14448 CI->getCallingConv())) 14449 return false; 14450 14451 // If the function is local then we have a good chance at tail-calling it 14452 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 14453 } 14454 14455 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 14456 if (!Subtarget.hasVSX()) 14457 return false; 14458 if (Subtarget.hasP9Vector() && VT == MVT::f128) 14459 return true; 14460 return VT == MVT::f32 || VT == MVT::f64 || 14461 VT == MVT::v4f32 || VT == MVT::v2f64; 14462 } 14463 14464 bool PPCTargetLowering:: 14465 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 14466 const Value *Mask = AndI.getOperand(1); 14467 // If the mask is suitable for andi. or andis. we should sink the and. 14468 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 14469 // Can't handle constants wider than 64-bits. 14470 if (CI->getBitWidth() > 64) 14471 return false; 14472 int64_t ConstVal = CI->getZExtValue(); 14473 return isUInt<16>(ConstVal) || 14474 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 14475 } 14476 14477 // For non-constant masks, we can always use the record-form and. 14478 return true; 14479 } 14480