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 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 255 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 256 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 257 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 258 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 259 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 260 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 261 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 262 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 263 264 // We don't support sin/cos/sqrt/fmod/pow 265 setOperationAction(ISD::FSIN , MVT::f64, Expand); 266 setOperationAction(ISD::FCOS , MVT::f64, Expand); 267 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 268 setOperationAction(ISD::FREM , MVT::f64, Expand); 269 setOperationAction(ISD::FPOW , MVT::f64, Expand); 270 setOperationAction(ISD::FSIN , MVT::f32, Expand); 271 setOperationAction(ISD::FCOS , MVT::f32, Expand); 272 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 273 setOperationAction(ISD::FREM , MVT::f32, Expand); 274 setOperationAction(ISD::FPOW , MVT::f32, Expand); 275 if (Subtarget.hasSPE()) { 276 setOperationAction(ISD::FMA , MVT::f64, Expand); 277 setOperationAction(ISD::FMA , MVT::f32, Expand); 278 } else { 279 setOperationAction(ISD::FMA , MVT::f64, Legal); 280 setOperationAction(ISD::FMA , MVT::f32, Legal); 281 } 282 283 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 284 285 // If we're enabling GP optimizations, use hardware square root 286 if (!Subtarget.hasFSQRT() && 287 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 288 Subtarget.hasFRE())) 289 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 290 291 if (!Subtarget.hasFSQRT() && 292 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 293 Subtarget.hasFRES())) 294 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 295 296 if (Subtarget.hasFCPSGN()) { 297 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 298 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 299 } else { 300 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 301 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 302 } 303 304 if (Subtarget.hasFPRND()) { 305 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 306 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 307 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 308 setOperationAction(ISD::FROUND, MVT::f64, Legal); 309 310 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 311 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 312 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 313 setOperationAction(ISD::FROUND, MVT::f32, Legal); 314 } 315 316 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 317 // to speed up scalar BSWAP64. 318 // CTPOP or CTTZ were introduced in P8/P9 respectively 319 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 320 if (Subtarget.hasP9Vector()) 321 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 322 else 323 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 324 if (Subtarget.isISA3_0()) { 325 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 326 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 327 } else { 328 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 329 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 330 } 331 332 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 333 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 334 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 335 } else { 336 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 337 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 338 } 339 340 // PowerPC does not have ROTR 341 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 342 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 343 344 if (!Subtarget.useCRBits()) { 345 // PowerPC does not have Select 346 setOperationAction(ISD::SELECT, MVT::i32, Expand); 347 setOperationAction(ISD::SELECT, MVT::i64, Expand); 348 setOperationAction(ISD::SELECT, MVT::f32, Expand); 349 setOperationAction(ISD::SELECT, MVT::f64, Expand); 350 } 351 352 // PowerPC wants to turn select_cc of FP into fsel when possible. 353 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 354 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 355 356 // PowerPC wants to optimize integer setcc a bit 357 if (!Subtarget.useCRBits()) 358 setOperationAction(ISD::SETCC, MVT::i32, Custom); 359 360 // PowerPC does not have BRCOND which requires SetCC 361 if (!Subtarget.useCRBits()) 362 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 363 364 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 365 366 if (Subtarget.hasSPE()) { 367 // SPE has built-in conversions 368 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 369 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 370 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 371 } else { 372 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 373 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 374 375 // PowerPC does not have [U|S]INT_TO_FP 376 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 377 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 378 } 379 380 if (Subtarget.hasDirectMove() && isPPC64) { 381 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 382 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 383 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 384 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 385 } else { 386 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 387 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 388 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 389 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 390 } 391 392 // We cannot sextinreg(i1). Expand to shifts. 393 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 394 395 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 396 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 397 // support continuation, user-level threading, and etc.. As a result, no 398 // other SjLj exception interfaces are implemented and please don't build 399 // your own exception handling based on them. 400 // LLVM/Clang supports zero-cost DWARF exception handling. 401 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 402 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 403 404 // We want to legalize GlobalAddress and ConstantPool nodes into the 405 // appropriate instructions to materialize the address. 406 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 407 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 408 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 409 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 410 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 411 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 412 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 413 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 414 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 415 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 416 417 // TRAP is legal. 418 setOperationAction(ISD::TRAP, MVT::Other, Legal); 419 420 // TRAMPOLINE is custom lowered. 421 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 422 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 423 424 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 425 setOperationAction(ISD::VASTART , MVT::Other, Custom); 426 427 if (Subtarget.isSVR4ABI()) { 428 if (isPPC64) { 429 // VAARG always uses double-word chunks, so promote anything smaller. 430 setOperationAction(ISD::VAARG, MVT::i1, Promote); 431 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 432 setOperationAction(ISD::VAARG, MVT::i8, Promote); 433 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 434 setOperationAction(ISD::VAARG, MVT::i16, Promote); 435 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 436 setOperationAction(ISD::VAARG, MVT::i32, Promote); 437 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 438 setOperationAction(ISD::VAARG, MVT::Other, Expand); 439 } else { 440 // VAARG is custom lowered with the 32-bit SVR4 ABI. 441 setOperationAction(ISD::VAARG, MVT::Other, Custom); 442 setOperationAction(ISD::VAARG, MVT::i64, Custom); 443 } 444 } else 445 setOperationAction(ISD::VAARG, MVT::Other, Expand); 446 447 if (Subtarget.isSVR4ABI() && !isPPC64) 448 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 449 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 450 else 451 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 452 453 // Use the default implementation. 454 setOperationAction(ISD::VAEND , MVT::Other, Expand); 455 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 456 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 457 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 458 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 459 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 460 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 461 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 462 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 463 464 // We want to custom lower some of our intrinsics. 465 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 466 467 // To handle counter-based loop conditions. 468 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 469 470 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 471 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 472 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 473 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 474 475 // Comparisons that require checking two conditions. 476 if (Subtarget.hasSPE()) { 477 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 478 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 479 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 480 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 481 } 482 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 483 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 484 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 485 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 486 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 487 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 488 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 489 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 490 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 491 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 492 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 493 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 494 495 if (Subtarget.has64BitSupport()) { 496 // They also have instructions for converting between i64 and fp. 497 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 498 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 499 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 500 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 501 // This is just the low 32 bits of a (signed) fp->i64 conversion. 502 // We cannot do this with Promote because i64 is not a legal type. 503 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 504 505 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 506 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 507 } else { 508 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 509 if (Subtarget.hasSPE()) 510 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 511 else 512 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 513 } 514 515 // With the instructions enabled under FPCVT, we can do everything. 516 if (Subtarget.hasFPCVT()) { 517 if (Subtarget.has64BitSupport()) { 518 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 519 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 520 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 521 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 522 } 523 524 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 525 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 526 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 527 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 528 } 529 530 if (Subtarget.use64BitRegs()) { 531 // 64-bit PowerPC implementations can support i64 types directly 532 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 533 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 534 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 535 // 64-bit PowerPC wants to expand i128 shifts itself. 536 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 537 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 538 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 539 } else { 540 // 32-bit PowerPC wants to expand i64 shifts itself. 541 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 542 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 543 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 544 } 545 546 if (Subtarget.hasAltivec()) { 547 // First set operation action for all vector types to expand. Then we 548 // will selectively turn on ones that can be effectively codegen'd. 549 for (MVT VT : MVT::vector_valuetypes()) { 550 // add/sub are legal for all supported vector VT's. 551 setOperationAction(ISD::ADD, VT, Legal); 552 setOperationAction(ISD::SUB, VT, Legal); 553 setOperationAction(ISD::ABS, VT, Custom); 554 555 // Vector instructions introduced in P8 556 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 557 setOperationAction(ISD::CTPOP, VT, Legal); 558 setOperationAction(ISD::CTLZ, VT, Legal); 559 } 560 else { 561 setOperationAction(ISD::CTPOP, VT, Expand); 562 setOperationAction(ISD::CTLZ, VT, Expand); 563 } 564 565 // Vector instructions introduced in P9 566 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 567 setOperationAction(ISD::CTTZ, VT, Legal); 568 else 569 setOperationAction(ISD::CTTZ, VT, Expand); 570 571 // We promote all shuffles to v16i8. 572 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 573 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 574 575 // We promote all non-typed operations to v4i32. 576 setOperationAction(ISD::AND , VT, Promote); 577 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 578 setOperationAction(ISD::OR , VT, Promote); 579 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 580 setOperationAction(ISD::XOR , VT, Promote); 581 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 582 setOperationAction(ISD::LOAD , VT, Promote); 583 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 584 setOperationAction(ISD::SELECT, VT, Promote); 585 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 586 setOperationAction(ISD::VSELECT, VT, Legal); 587 setOperationAction(ISD::SELECT_CC, VT, Promote); 588 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 589 setOperationAction(ISD::STORE, VT, Promote); 590 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 591 592 // No other operations are legal. 593 setOperationAction(ISD::MUL , VT, Expand); 594 setOperationAction(ISD::SDIV, VT, Expand); 595 setOperationAction(ISD::SREM, VT, Expand); 596 setOperationAction(ISD::UDIV, VT, Expand); 597 setOperationAction(ISD::UREM, VT, Expand); 598 setOperationAction(ISD::FDIV, VT, Expand); 599 setOperationAction(ISD::FREM, VT, Expand); 600 setOperationAction(ISD::FNEG, VT, Expand); 601 setOperationAction(ISD::FSQRT, VT, Expand); 602 setOperationAction(ISD::FLOG, VT, Expand); 603 setOperationAction(ISD::FLOG10, VT, Expand); 604 setOperationAction(ISD::FLOG2, VT, Expand); 605 setOperationAction(ISD::FEXP, VT, Expand); 606 setOperationAction(ISD::FEXP2, VT, Expand); 607 setOperationAction(ISD::FSIN, VT, Expand); 608 setOperationAction(ISD::FCOS, VT, Expand); 609 setOperationAction(ISD::FABS, VT, Expand); 610 setOperationAction(ISD::FFLOOR, VT, Expand); 611 setOperationAction(ISD::FCEIL, VT, Expand); 612 setOperationAction(ISD::FTRUNC, VT, Expand); 613 setOperationAction(ISD::FRINT, VT, Expand); 614 setOperationAction(ISD::FNEARBYINT, VT, Expand); 615 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 616 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 617 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 618 setOperationAction(ISD::MULHU, VT, Expand); 619 setOperationAction(ISD::MULHS, VT, Expand); 620 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 621 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 622 setOperationAction(ISD::UDIVREM, VT, Expand); 623 setOperationAction(ISD::SDIVREM, VT, Expand); 624 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 625 setOperationAction(ISD::FPOW, VT, Expand); 626 setOperationAction(ISD::BSWAP, VT, Expand); 627 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 628 setOperationAction(ISD::ROTL, VT, Expand); 629 setOperationAction(ISD::ROTR, VT, Expand); 630 631 for (MVT InnerVT : MVT::vector_valuetypes()) { 632 setTruncStoreAction(VT, InnerVT, Expand); 633 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 634 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 635 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 636 } 637 } 638 639 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 640 // with merges, splats, etc. 641 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 642 643 setOperationAction(ISD::AND , MVT::v4i32, Legal); 644 setOperationAction(ISD::OR , MVT::v4i32, Legal); 645 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 646 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 647 setOperationAction(ISD::SELECT, MVT::v4i32, 648 Subtarget.useCRBits() ? Legal : Expand); 649 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 650 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 651 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 652 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 653 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 654 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 655 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 656 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 657 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 658 659 // Without hasP8Altivec set, v2i64 SMAX isn't available. 660 // But ABS custom lowering requires SMAX support. 661 if (!Subtarget.hasP8Altivec()) 662 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 663 664 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 665 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 666 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 667 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 668 669 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 670 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 671 672 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 673 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 674 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 675 } 676 677 if (Subtarget.hasP8Altivec()) 678 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 679 else 680 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 681 682 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 683 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 684 685 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 686 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 687 688 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 689 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 690 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 691 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 692 693 // Altivec does not contain unordered floating-point compare instructions 694 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 695 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 696 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 697 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 698 699 if (Subtarget.hasVSX()) { 700 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 701 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 702 if (Subtarget.hasP8Vector()) { 703 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 704 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 705 } 706 if (Subtarget.hasDirectMove() && isPPC64) { 707 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 708 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 709 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 710 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 711 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 713 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 714 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 715 } 716 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 717 718 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 719 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 720 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 721 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 722 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 723 724 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 725 726 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 727 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 728 729 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 730 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 731 732 // Share the Altivec comparison restrictions. 733 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 734 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 735 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 736 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 737 738 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 739 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 740 741 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 742 743 if (Subtarget.hasP8Vector()) 744 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 745 746 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 747 748 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 749 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 750 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 751 752 if (Subtarget.hasP8Altivec()) { 753 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 754 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 755 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 756 757 // 128 bit shifts can be accomplished via 3 instructions for SHL and 758 // SRL, but not for SRA because of the instructions available: 759 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 760 // doing 761 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 762 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 763 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 764 765 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 766 } 767 else { 768 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 769 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 770 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 771 772 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 773 774 // VSX v2i64 only supports non-arithmetic operations. 775 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 776 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 777 } 778 779 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 780 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 781 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 782 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 783 784 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 785 786 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 787 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 788 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 789 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 790 791 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 792 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 793 794 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 795 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 796 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 797 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 798 799 if (Subtarget.hasDirectMove()) 800 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 801 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 802 803 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 804 } 805 806 if (Subtarget.hasP8Altivec()) { 807 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 808 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 809 } 810 811 if (Subtarget.hasP9Vector()) { 812 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 813 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 814 815 // 128 bit shifts can be accomplished via 3 instructions for SHL and 816 // SRL, but not for SRA because of the instructions available: 817 // VS{RL} and VS{RL}O. 818 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 819 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 820 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 821 822 if (EnableQuadPrecision) { 823 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 824 setOperationAction(ISD::FADD, MVT::f128, Legal); 825 setOperationAction(ISD::FSUB, MVT::f128, Legal); 826 setOperationAction(ISD::FDIV, MVT::f128, Legal); 827 setOperationAction(ISD::FMUL, MVT::f128, Legal); 828 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 829 // No extending loads to f128 on PPC. 830 for (MVT FPT : MVT::fp_valuetypes()) 831 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 832 setOperationAction(ISD::FMA, MVT::f128, Legal); 833 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 834 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 835 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 836 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 837 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 838 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 839 840 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 841 setOperationAction(ISD::FRINT, MVT::f128, Legal); 842 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 843 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 844 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 845 setOperationAction(ISD::FROUND, MVT::f128, Legal); 846 847 setOperationAction(ISD::SELECT, MVT::f128, Expand); 848 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 849 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 850 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 851 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 852 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 853 // No implementation for these ops for PowerPC. 854 setOperationAction(ISD::FSIN , MVT::f128, Expand); 855 setOperationAction(ISD::FCOS , MVT::f128, Expand); 856 setOperationAction(ISD::FPOW, MVT::f128, Expand); 857 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 858 setOperationAction(ISD::FREM, MVT::f128, Expand); 859 } 860 861 } 862 863 if (Subtarget.hasP9Altivec()) { 864 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 865 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 866 } 867 } 868 869 if (Subtarget.hasQPX()) { 870 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 871 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 872 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 873 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 874 875 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 876 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 877 878 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 879 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 880 881 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 882 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 883 884 if (!Subtarget.useCRBits()) 885 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 886 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 887 888 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 889 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 890 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 891 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 892 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 893 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 894 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 895 896 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 897 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 898 899 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 900 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 901 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 902 903 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 904 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 905 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 906 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 907 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 908 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 909 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 910 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 911 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 912 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 913 914 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 915 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 916 917 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 918 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 919 920 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 921 922 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 923 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 924 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 925 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 926 927 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 928 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 929 930 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 931 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 932 933 if (!Subtarget.useCRBits()) 934 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 935 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 936 937 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 938 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 939 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 940 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 941 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 942 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 943 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 944 945 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 946 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 947 948 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 949 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 950 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 951 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 952 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 953 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 954 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 955 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 956 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 957 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 958 959 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 960 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 961 962 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 963 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 964 965 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 966 967 setOperationAction(ISD::AND , MVT::v4i1, Legal); 968 setOperationAction(ISD::OR , MVT::v4i1, Legal); 969 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 970 971 if (!Subtarget.useCRBits()) 972 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 973 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 974 975 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 976 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 977 978 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 979 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 980 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 981 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 982 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 983 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 984 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 985 986 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 987 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 988 989 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 990 991 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 992 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 993 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 994 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 995 996 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 997 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 998 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 999 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1000 1001 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1002 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1003 1004 // These need to set FE_INEXACT, and so cannot be vectorized here. 1005 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1006 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1007 1008 if (TM.Options.UnsafeFPMath) { 1009 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1010 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1011 1012 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1013 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1014 } else { 1015 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1016 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1017 1018 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1019 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1020 } 1021 } 1022 1023 if (Subtarget.has64BitSupport()) 1024 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1025 1026 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1027 1028 if (!isPPC64) { 1029 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1030 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1031 } 1032 1033 setBooleanContents(ZeroOrOneBooleanContent); 1034 1035 if (Subtarget.hasAltivec()) { 1036 // Altivec instructions set fields to all zeros or all ones. 1037 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1038 } 1039 1040 if (!isPPC64) { 1041 // These libcalls are not available in 32-bit. 1042 setLibcallName(RTLIB::SHL_I128, nullptr); 1043 setLibcallName(RTLIB::SRL_I128, nullptr); 1044 setLibcallName(RTLIB::SRA_I128, nullptr); 1045 } 1046 1047 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1048 1049 // We have target-specific dag combine patterns for the following nodes: 1050 setTargetDAGCombine(ISD::ADD); 1051 setTargetDAGCombine(ISD::SHL); 1052 setTargetDAGCombine(ISD::SRA); 1053 setTargetDAGCombine(ISD::SRL); 1054 setTargetDAGCombine(ISD::SINT_TO_FP); 1055 setTargetDAGCombine(ISD::BUILD_VECTOR); 1056 if (Subtarget.hasFPCVT()) 1057 setTargetDAGCombine(ISD::UINT_TO_FP); 1058 setTargetDAGCombine(ISD::LOAD); 1059 setTargetDAGCombine(ISD::STORE); 1060 setTargetDAGCombine(ISD::BR_CC); 1061 if (Subtarget.useCRBits()) 1062 setTargetDAGCombine(ISD::BRCOND); 1063 setTargetDAGCombine(ISD::BSWAP); 1064 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1065 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1066 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1067 1068 setTargetDAGCombine(ISD::SIGN_EXTEND); 1069 setTargetDAGCombine(ISD::ZERO_EXTEND); 1070 setTargetDAGCombine(ISD::ANY_EXTEND); 1071 1072 setTargetDAGCombine(ISD::TRUNCATE); 1073 1074 if (Subtarget.useCRBits()) { 1075 setTargetDAGCombine(ISD::TRUNCATE); 1076 setTargetDAGCombine(ISD::SETCC); 1077 setTargetDAGCombine(ISD::SELECT_CC); 1078 } 1079 1080 // Use reciprocal estimates. 1081 if (TM.Options.UnsafeFPMath) { 1082 setTargetDAGCombine(ISD::FDIV); 1083 setTargetDAGCombine(ISD::FSQRT); 1084 } 1085 1086 if (Subtarget.hasP9Altivec()) { 1087 setTargetDAGCombine(ISD::ABS); 1088 setTargetDAGCombine(ISD::VSELECT); 1089 } 1090 1091 // Darwin long double math library functions have $LDBL128 appended. 1092 if (Subtarget.isDarwin()) { 1093 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1094 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1095 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1096 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1097 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1098 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1099 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1100 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1101 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1102 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1103 } 1104 1105 if (EnableQuadPrecision) { 1106 setLibcallName(RTLIB::LOG_F128, "logf128"); 1107 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1108 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1109 setLibcallName(RTLIB::EXP_F128, "expf128"); 1110 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1111 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1112 setLibcallName(RTLIB::COS_F128, "cosf128"); 1113 setLibcallName(RTLIB::POW_F128, "powf128"); 1114 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1115 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1116 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1117 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1118 } 1119 1120 // With 32 condition bits, we don't need to sink (and duplicate) compares 1121 // aggressively in CodeGenPrep. 1122 if (Subtarget.useCRBits()) { 1123 setHasMultipleConditionRegisters(); 1124 setJumpIsExpensive(); 1125 } 1126 1127 setMinFunctionAlignment(2); 1128 if (Subtarget.isDarwin()) 1129 setPrefFunctionAlignment(4); 1130 1131 switch (Subtarget.getDarwinDirective()) { 1132 default: break; 1133 case PPC::DIR_970: 1134 case PPC::DIR_A2: 1135 case PPC::DIR_E500: 1136 case PPC::DIR_E500mc: 1137 case PPC::DIR_E5500: 1138 case PPC::DIR_PWR4: 1139 case PPC::DIR_PWR5: 1140 case PPC::DIR_PWR5X: 1141 case PPC::DIR_PWR6: 1142 case PPC::DIR_PWR6X: 1143 case PPC::DIR_PWR7: 1144 case PPC::DIR_PWR8: 1145 case PPC::DIR_PWR9: 1146 setPrefFunctionAlignment(4); 1147 setPrefLoopAlignment(4); 1148 break; 1149 } 1150 1151 if (Subtarget.enableMachineScheduler()) 1152 setSchedulingPreference(Sched::Source); 1153 else 1154 setSchedulingPreference(Sched::Hybrid); 1155 1156 computeRegisterProperties(STI.getRegisterInfo()); 1157 1158 // The Freescale cores do better with aggressive inlining of memcpy and 1159 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1160 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1161 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1162 MaxStoresPerMemset = 32; 1163 MaxStoresPerMemsetOptSize = 16; 1164 MaxStoresPerMemcpy = 32; 1165 MaxStoresPerMemcpyOptSize = 8; 1166 MaxStoresPerMemmove = 32; 1167 MaxStoresPerMemmoveOptSize = 8; 1168 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1169 // The A2 also benefits from (very) aggressive inlining of memcpy and 1170 // friends. The overhead of a the function call, even when warm, can be 1171 // over one hundred cycles. 1172 MaxStoresPerMemset = 128; 1173 MaxStoresPerMemcpy = 128; 1174 MaxStoresPerMemmove = 128; 1175 MaxLoadsPerMemcmp = 128; 1176 } else { 1177 MaxLoadsPerMemcmp = 8; 1178 MaxLoadsPerMemcmpOptSize = 4; 1179 } 1180 } 1181 1182 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1183 /// the desired ByVal argument alignment. 1184 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1185 unsigned MaxMaxAlign) { 1186 if (MaxAlign == MaxMaxAlign) 1187 return; 1188 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1189 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1190 MaxAlign = 32; 1191 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1192 MaxAlign = 16; 1193 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1194 unsigned EltAlign = 0; 1195 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1196 if (EltAlign > MaxAlign) 1197 MaxAlign = EltAlign; 1198 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1199 for (auto *EltTy : STy->elements()) { 1200 unsigned EltAlign = 0; 1201 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1202 if (EltAlign > MaxAlign) 1203 MaxAlign = EltAlign; 1204 if (MaxAlign == MaxMaxAlign) 1205 break; 1206 } 1207 } 1208 } 1209 1210 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1211 /// function arguments in the caller parameter area. 1212 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1213 const DataLayout &DL) const { 1214 // Darwin passes everything on 4 byte boundary. 1215 if (Subtarget.isDarwin()) 1216 return 4; 1217 1218 // 16byte and wider vectors are passed on 16byte boundary. 1219 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1220 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1221 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1222 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1223 return Align; 1224 } 1225 1226 unsigned PPCTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1227 CallingConv:: ID CC, 1228 EVT VT) const { 1229 if (Subtarget.hasSPE() && VT == MVT::f64) 1230 return 2; 1231 return PPCTargetLowering::getNumRegisters(Context, VT); 1232 } 1233 1234 MVT PPCTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1235 CallingConv:: ID CC, 1236 EVT VT) const { 1237 if (Subtarget.hasSPE() && VT == MVT::f64) 1238 return MVT::i32; 1239 return PPCTargetLowering::getRegisterType(Context, VT); 1240 } 1241 1242 bool PPCTargetLowering::useSoftFloat() const { 1243 return Subtarget.useSoftFloat(); 1244 } 1245 1246 bool PPCTargetLowering::hasSPE() const { 1247 return Subtarget.hasSPE(); 1248 } 1249 1250 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1251 switch ((PPCISD::NodeType)Opcode) { 1252 case PPCISD::FIRST_NUMBER: break; 1253 case PPCISD::FSEL: return "PPCISD::FSEL"; 1254 case PPCISD::FCFID: return "PPCISD::FCFID"; 1255 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1256 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1257 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1258 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1259 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1260 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1261 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1262 case PPCISD::FP_TO_UINT_IN_VSR: 1263 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1264 case PPCISD::FP_TO_SINT_IN_VSR: 1265 return "PPCISD::FP_TO_SINT_IN_VSR"; 1266 case PPCISD::FRE: return "PPCISD::FRE"; 1267 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1268 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1269 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1270 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1271 case PPCISD::VPERM: return "PPCISD::VPERM"; 1272 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1273 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1274 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1275 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1276 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1277 case PPCISD::CMPB: return "PPCISD::CMPB"; 1278 case PPCISD::Hi: return "PPCISD::Hi"; 1279 case PPCISD::Lo: return "PPCISD::Lo"; 1280 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1281 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1282 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1283 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1284 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1285 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1286 case PPCISD::SRL: return "PPCISD::SRL"; 1287 case PPCISD::SRA: return "PPCISD::SRA"; 1288 case PPCISD::SHL: return "PPCISD::SHL"; 1289 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1290 case PPCISD::CALL: return "PPCISD::CALL"; 1291 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1292 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1293 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1294 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1295 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1296 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1297 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1298 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1299 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1300 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1301 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1302 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1303 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1304 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1305 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1306 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1307 case PPCISD::VCMP: return "PPCISD::VCMP"; 1308 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1309 case PPCISD::LBRX: return "PPCISD::LBRX"; 1310 case PPCISD::STBRX: return "PPCISD::STBRX"; 1311 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1312 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1313 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1314 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1315 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1316 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1317 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1318 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1319 case PPCISD::ST_VSR_SCAL_INT: 1320 return "PPCISD::ST_VSR_SCAL_INT"; 1321 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1322 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1323 case PPCISD::BDZ: return "PPCISD::BDZ"; 1324 case PPCISD::MFFS: return "PPCISD::MFFS"; 1325 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1326 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1327 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1328 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1329 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1330 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1331 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1332 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1333 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1334 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1335 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1336 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1337 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1338 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1339 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1340 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1341 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1342 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1343 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1344 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1345 case PPCISD::SC: return "PPCISD::SC"; 1346 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1347 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1348 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1349 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1350 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1351 case PPCISD::VABSD: return "PPCISD::VABSD"; 1352 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1353 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1354 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1355 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1356 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1357 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1358 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1359 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1360 } 1361 return nullptr; 1362 } 1363 1364 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1365 EVT VT) const { 1366 if (!VT.isVector()) 1367 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1368 1369 if (Subtarget.hasQPX()) 1370 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1371 1372 return VT.changeVectorElementTypeToInteger(); 1373 } 1374 1375 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1376 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1377 return true; 1378 } 1379 1380 //===----------------------------------------------------------------------===// 1381 // Node matching predicates, for use by the tblgen matching code. 1382 //===----------------------------------------------------------------------===// 1383 1384 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1385 static bool isFloatingPointZero(SDValue Op) { 1386 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1387 return CFP->getValueAPF().isZero(); 1388 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1389 // Maybe this has already been legalized into the constant pool? 1390 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1391 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1392 return CFP->getValueAPF().isZero(); 1393 } 1394 return false; 1395 } 1396 1397 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1398 /// true if Op is undef or if it matches the specified value. 1399 static bool isConstantOrUndef(int Op, int Val) { 1400 return Op < 0 || Op == Val; 1401 } 1402 1403 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1404 /// VPKUHUM instruction. 1405 /// The ShuffleKind distinguishes between big-endian operations with 1406 /// two different inputs (0), either-endian operations with two identical 1407 /// inputs (1), and little-endian operations with two different inputs (2). 1408 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1409 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1410 SelectionDAG &DAG) { 1411 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1412 if (ShuffleKind == 0) { 1413 if (IsLE) 1414 return false; 1415 for (unsigned i = 0; i != 16; ++i) 1416 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1417 return false; 1418 } else if (ShuffleKind == 2) { 1419 if (!IsLE) 1420 return false; 1421 for (unsigned i = 0; i != 16; ++i) 1422 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1423 return false; 1424 } else if (ShuffleKind == 1) { 1425 unsigned j = IsLE ? 0 : 1; 1426 for (unsigned i = 0; i != 8; ++i) 1427 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1428 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1429 return false; 1430 } 1431 return true; 1432 } 1433 1434 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1435 /// VPKUWUM instruction. 1436 /// The ShuffleKind distinguishes between big-endian operations with 1437 /// two different inputs (0), either-endian operations with two identical 1438 /// inputs (1), and little-endian operations with two different inputs (2). 1439 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1440 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1441 SelectionDAG &DAG) { 1442 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1443 if (ShuffleKind == 0) { 1444 if (IsLE) 1445 return false; 1446 for (unsigned i = 0; i != 16; i += 2) 1447 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1448 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1449 return false; 1450 } else if (ShuffleKind == 2) { 1451 if (!IsLE) 1452 return false; 1453 for (unsigned i = 0; i != 16; i += 2) 1454 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1455 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1456 return false; 1457 } else if (ShuffleKind == 1) { 1458 unsigned j = IsLE ? 0 : 2; 1459 for (unsigned i = 0; i != 8; i += 2) 1460 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1461 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1462 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1463 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1464 return false; 1465 } 1466 return true; 1467 } 1468 1469 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1470 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1471 /// current subtarget. 1472 /// 1473 /// The ShuffleKind distinguishes between big-endian operations with 1474 /// two different inputs (0), either-endian operations with two identical 1475 /// inputs (1), and little-endian operations with two different inputs (2). 1476 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1477 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1478 SelectionDAG &DAG) { 1479 const PPCSubtarget& Subtarget = 1480 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1481 if (!Subtarget.hasP8Vector()) 1482 return false; 1483 1484 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1485 if (ShuffleKind == 0) { 1486 if (IsLE) 1487 return false; 1488 for (unsigned i = 0; i != 16; i += 4) 1489 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1490 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1491 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1492 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1493 return false; 1494 } else if (ShuffleKind == 2) { 1495 if (!IsLE) 1496 return false; 1497 for (unsigned i = 0; i != 16; i += 4) 1498 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1499 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1500 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1501 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1502 return false; 1503 } else if (ShuffleKind == 1) { 1504 unsigned j = IsLE ? 0 : 4; 1505 for (unsigned i = 0; i != 8; i += 4) 1506 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1507 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1508 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1509 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1510 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1511 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1512 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1513 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1514 return false; 1515 } 1516 return true; 1517 } 1518 1519 /// isVMerge - Common function, used to match vmrg* shuffles. 1520 /// 1521 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1522 unsigned LHSStart, unsigned RHSStart) { 1523 if (N->getValueType(0) != MVT::v16i8) 1524 return false; 1525 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1526 "Unsupported merge size!"); 1527 1528 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1529 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1530 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1531 LHSStart+j+i*UnitSize) || 1532 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1533 RHSStart+j+i*UnitSize)) 1534 return false; 1535 } 1536 return true; 1537 } 1538 1539 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1540 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1541 /// The ShuffleKind distinguishes between big-endian merges with two 1542 /// different inputs (0), either-endian merges with two identical inputs (1), 1543 /// and little-endian merges with two different inputs (2). For the latter, 1544 /// the input operands are swapped (see PPCInstrAltivec.td). 1545 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1546 unsigned ShuffleKind, SelectionDAG &DAG) { 1547 if (DAG.getDataLayout().isLittleEndian()) { 1548 if (ShuffleKind == 1) // unary 1549 return isVMerge(N, UnitSize, 0, 0); 1550 else if (ShuffleKind == 2) // swapped 1551 return isVMerge(N, UnitSize, 0, 16); 1552 else 1553 return false; 1554 } else { 1555 if (ShuffleKind == 1) // unary 1556 return isVMerge(N, UnitSize, 8, 8); 1557 else if (ShuffleKind == 0) // normal 1558 return isVMerge(N, UnitSize, 8, 24); 1559 else 1560 return false; 1561 } 1562 } 1563 1564 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1565 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1566 /// The ShuffleKind distinguishes between big-endian merges with two 1567 /// different inputs (0), either-endian merges with two identical inputs (1), 1568 /// and little-endian merges with two different inputs (2). For the latter, 1569 /// the input operands are swapped (see PPCInstrAltivec.td). 1570 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1571 unsigned ShuffleKind, SelectionDAG &DAG) { 1572 if (DAG.getDataLayout().isLittleEndian()) { 1573 if (ShuffleKind == 1) // unary 1574 return isVMerge(N, UnitSize, 8, 8); 1575 else if (ShuffleKind == 2) // swapped 1576 return isVMerge(N, UnitSize, 8, 24); 1577 else 1578 return false; 1579 } else { 1580 if (ShuffleKind == 1) // unary 1581 return isVMerge(N, UnitSize, 0, 0); 1582 else if (ShuffleKind == 0) // normal 1583 return isVMerge(N, UnitSize, 0, 16); 1584 else 1585 return false; 1586 } 1587 } 1588 1589 /** 1590 * Common function used to match vmrgew and vmrgow shuffles 1591 * 1592 * The indexOffset determines whether to look for even or odd words in 1593 * the shuffle mask. This is based on the of the endianness of the target 1594 * machine. 1595 * - Little Endian: 1596 * - Use offset of 0 to check for odd elements 1597 * - Use offset of 4 to check for even elements 1598 * - Big Endian: 1599 * - Use offset of 0 to check for even elements 1600 * - Use offset of 4 to check for odd elements 1601 * A detailed description of the vector element ordering for little endian and 1602 * big endian can be found at 1603 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1604 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1605 * compiler differences mean to you 1606 * 1607 * The mask to the shuffle vector instruction specifies the indices of the 1608 * elements from the two input vectors to place in the result. The elements are 1609 * numbered in array-access order, starting with the first vector. These vectors 1610 * are always of type v16i8, thus each vector will contain 16 elements of size 1611 * 8. More info on the shuffle vector can be found in the 1612 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1613 * Language Reference. 1614 * 1615 * The RHSStartValue indicates whether the same input vectors are used (unary) 1616 * or two different input vectors are used, based on the following: 1617 * - If the instruction uses the same vector for both inputs, the range of the 1618 * indices will be 0 to 15. In this case, the RHSStart value passed should 1619 * be 0. 1620 * - If the instruction has two different vectors then the range of the 1621 * indices will be 0 to 31. In this case, the RHSStart value passed should 1622 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1623 * to 31 specify elements in the second vector). 1624 * 1625 * \param[in] N The shuffle vector SD Node to analyze 1626 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1627 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1628 * vector to the shuffle_vector instruction 1629 * \return true iff this shuffle vector represents an even or odd word merge 1630 */ 1631 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1632 unsigned RHSStartValue) { 1633 if (N->getValueType(0) != MVT::v16i8) 1634 return false; 1635 1636 for (unsigned i = 0; i < 2; ++i) 1637 for (unsigned j = 0; j < 4; ++j) 1638 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1639 i*RHSStartValue+j+IndexOffset) || 1640 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1641 i*RHSStartValue+j+IndexOffset+8)) 1642 return false; 1643 return true; 1644 } 1645 1646 /** 1647 * Determine if the specified shuffle mask is suitable for the vmrgew or 1648 * vmrgow instructions. 1649 * 1650 * \param[in] N The shuffle vector SD Node to analyze 1651 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1652 * \param[in] ShuffleKind Identify the type of merge: 1653 * - 0 = big-endian merge with two different inputs; 1654 * - 1 = either-endian merge with two identical inputs; 1655 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1656 * little-endian merges). 1657 * \param[in] DAG The current SelectionDAG 1658 * \return true iff this shuffle mask 1659 */ 1660 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1661 unsigned ShuffleKind, SelectionDAG &DAG) { 1662 if (DAG.getDataLayout().isLittleEndian()) { 1663 unsigned indexOffset = CheckEven ? 4 : 0; 1664 if (ShuffleKind == 1) // Unary 1665 return isVMerge(N, indexOffset, 0); 1666 else if (ShuffleKind == 2) // swapped 1667 return isVMerge(N, indexOffset, 16); 1668 else 1669 return false; 1670 } 1671 else { 1672 unsigned indexOffset = CheckEven ? 0 : 4; 1673 if (ShuffleKind == 1) // Unary 1674 return isVMerge(N, indexOffset, 0); 1675 else if (ShuffleKind == 0) // Normal 1676 return isVMerge(N, indexOffset, 16); 1677 else 1678 return false; 1679 } 1680 return false; 1681 } 1682 1683 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1684 /// amount, otherwise return -1. 1685 /// The ShuffleKind distinguishes between big-endian operations with two 1686 /// different inputs (0), either-endian operations with two identical inputs 1687 /// (1), and little-endian operations with two different inputs (2). For the 1688 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1689 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1690 SelectionDAG &DAG) { 1691 if (N->getValueType(0) != MVT::v16i8) 1692 return -1; 1693 1694 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1695 1696 // Find the first non-undef value in the shuffle mask. 1697 unsigned i; 1698 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1699 /*search*/; 1700 1701 if (i == 16) return -1; // all undef. 1702 1703 // Otherwise, check to see if the rest of the elements are consecutively 1704 // numbered from this value. 1705 unsigned ShiftAmt = SVOp->getMaskElt(i); 1706 if (ShiftAmt < i) return -1; 1707 1708 ShiftAmt -= i; 1709 bool isLE = DAG.getDataLayout().isLittleEndian(); 1710 1711 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1712 // Check the rest of the elements to see if they are consecutive. 1713 for (++i; i != 16; ++i) 1714 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1715 return -1; 1716 } else if (ShuffleKind == 1) { 1717 // Check the rest of the elements to see if they are consecutive. 1718 for (++i; i != 16; ++i) 1719 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1720 return -1; 1721 } else 1722 return -1; 1723 1724 if (isLE) 1725 ShiftAmt = 16 - ShiftAmt; 1726 1727 return ShiftAmt; 1728 } 1729 1730 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1731 /// specifies a splat of a single element that is suitable for input to 1732 /// VSPLTB/VSPLTH/VSPLTW. 1733 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1734 assert(N->getValueType(0) == MVT::v16i8 && 1735 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1736 1737 // The consecutive indices need to specify an element, not part of two 1738 // different elements. So abandon ship early if this isn't the case. 1739 if (N->getMaskElt(0) % EltSize != 0) 1740 return false; 1741 1742 // This is a splat operation if each element of the permute is the same, and 1743 // if the value doesn't reference the second vector. 1744 unsigned ElementBase = N->getMaskElt(0); 1745 1746 // FIXME: Handle UNDEF elements too! 1747 if (ElementBase >= 16) 1748 return false; 1749 1750 // Check that the indices are consecutive, in the case of a multi-byte element 1751 // splatted with a v16i8 mask. 1752 for (unsigned i = 1; i != EltSize; ++i) 1753 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1754 return false; 1755 1756 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1757 if (N->getMaskElt(i) < 0) continue; 1758 for (unsigned j = 0; j != EltSize; ++j) 1759 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1760 return false; 1761 } 1762 return true; 1763 } 1764 1765 /// Check that the mask is shuffling N byte elements. Within each N byte 1766 /// element of the mask, the indices could be either in increasing or 1767 /// decreasing order as long as they are consecutive. 1768 /// \param[in] N the shuffle vector SD Node to analyze 1769 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1770 /// Word/DoubleWord/QuadWord). 1771 /// \param[in] StepLen the delta indices number among the N byte element, if 1772 /// the mask is in increasing/decreasing order then it is 1/-1. 1773 /// \return true iff the mask is shuffling N byte elements. 1774 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1775 int StepLen) { 1776 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1777 "Unexpected element width."); 1778 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1779 1780 unsigned NumOfElem = 16 / Width; 1781 unsigned MaskVal[16]; // Width is never greater than 16 1782 for (unsigned i = 0; i < NumOfElem; ++i) { 1783 MaskVal[0] = N->getMaskElt(i * Width); 1784 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1785 return false; 1786 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1787 return false; 1788 } 1789 1790 for (unsigned int j = 1; j < Width; ++j) { 1791 MaskVal[j] = N->getMaskElt(i * Width + j); 1792 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1793 return false; 1794 } 1795 } 1796 } 1797 1798 return true; 1799 } 1800 1801 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1802 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1803 if (!isNByteElemShuffleMask(N, 4, 1)) 1804 return false; 1805 1806 // Now we look at mask elements 0,4,8,12 1807 unsigned M0 = N->getMaskElt(0) / 4; 1808 unsigned M1 = N->getMaskElt(4) / 4; 1809 unsigned M2 = N->getMaskElt(8) / 4; 1810 unsigned M3 = N->getMaskElt(12) / 4; 1811 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1812 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1813 1814 // Below, let H and L be arbitrary elements of the shuffle mask 1815 // where H is in the range [4,7] and L is in the range [0,3]. 1816 // H, 1, 2, 3 or L, 5, 6, 7 1817 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1818 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1819 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1820 InsertAtByte = IsLE ? 12 : 0; 1821 Swap = M0 < 4; 1822 return true; 1823 } 1824 // 0, H, 2, 3 or 4, L, 6, 7 1825 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1826 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1827 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1828 InsertAtByte = IsLE ? 8 : 4; 1829 Swap = M1 < 4; 1830 return true; 1831 } 1832 // 0, 1, H, 3 or 4, 5, L, 7 1833 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1834 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1835 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1836 InsertAtByte = IsLE ? 4 : 8; 1837 Swap = M2 < 4; 1838 return true; 1839 } 1840 // 0, 1, 2, H or 4, 5, 6, L 1841 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1842 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1843 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1844 InsertAtByte = IsLE ? 0 : 12; 1845 Swap = M3 < 4; 1846 return true; 1847 } 1848 1849 // If both vector operands for the shuffle are the same vector, the mask will 1850 // contain only elements from the first one and the second one will be undef. 1851 if (N->getOperand(1).isUndef()) { 1852 ShiftElts = 0; 1853 Swap = true; 1854 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1855 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1856 InsertAtByte = IsLE ? 12 : 0; 1857 return true; 1858 } 1859 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1860 InsertAtByte = IsLE ? 8 : 4; 1861 return true; 1862 } 1863 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1864 InsertAtByte = IsLE ? 4 : 8; 1865 return true; 1866 } 1867 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1868 InsertAtByte = IsLE ? 0 : 12; 1869 return true; 1870 } 1871 } 1872 1873 return false; 1874 } 1875 1876 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1877 bool &Swap, bool IsLE) { 1878 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1879 // Ensure each byte index of the word is consecutive. 1880 if (!isNByteElemShuffleMask(N, 4, 1)) 1881 return false; 1882 1883 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1884 unsigned M0 = N->getMaskElt(0) / 4; 1885 unsigned M1 = N->getMaskElt(4) / 4; 1886 unsigned M2 = N->getMaskElt(8) / 4; 1887 unsigned M3 = N->getMaskElt(12) / 4; 1888 1889 // If both vector operands for the shuffle are the same vector, the mask will 1890 // contain only elements from the first one and the second one will be undef. 1891 if (N->getOperand(1).isUndef()) { 1892 assert(M0 < 4 && "Indexing into an undef vector?"); 1893 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1894 return false; 1895 1896 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1897 Swap = false; 1898 return true; 1899 } 1900 1901 // Ensure each word index of the ShuffleVector Mask is consecutive. 1902 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1903 return false; 1904 1905 if (IsLE) { 1906 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1907 // Input vectors don't need to be swapped if the leading element 1908 // of the result is one of the 3 left elements of the second vector 1909 // (or if there is no shift to be done at all). 1910 Swap = false; 1911 ShiftElts = (8 - M0) % 8; 1912 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1913 // Input vectors need to be swapped if the leading element 1914 // of the result is one of the 3 left elements of the first vector 1915 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1916 Swap = true; 1917 ShiftElts = (4 - M0) % 4; 1918 } 1919 1920 return true; 1921 } else { // BE 1922 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1923 // Input vectors don't need to be swapped if the leading element 1924 // of the result is one of the 4 elements of the first vector. 1925 Swap = false; 1926 ShiftElts = M0; 1927 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1928 // Input vectors need to be swapped if the leading element 1929 // of the result is one of the 4 elements of the right vector. 1930 Swap = true; 1931 ShiftElts = M0 - 4; 1932 } 1933 1934 return true; 1935 } 1936 } 1937 1938 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1939 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1940 1941 if (!isNByteElemShuffleMask(N, Width, -1)) 1942 return false; 1943 1944 for (int i = 0; i < 16; i += Width) 1945 if (N->getMaskElt(i) != i + Width - 1) 1946 return false; 1947 1948 return true; 1949 } 1950 1951 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1952 return isXXBRShuffleMaskHelper(N, 2); 1953 } 1954 1955 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1956 return isXXBRShuffleMaskHelper(N, 4); 1957 } 1958 1959 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 1960 return isXXBRShuffleMaskHelper(N, 8); 1961 } 1962 1963 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 1964 return isXXBRShuffleMaskHelper(N, 16); 1965 } 1966 1967 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 1968 /// if the inputs to the instruction should be swapped and set \p DM to the 1969 /// value for the immediate. 1970 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 1971 /// AND element 0 of the result comes from the first input (LE) or second input 1972 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 1973 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 1974 /// mask. 1975 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 1976 bool &Swap, bool IsLE) { 1977 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1978 1979 // Ensure each byte index of the double word is consecutive. 1980 if (!isNByteElemShuffleMask(N, 8, 1)) 1981 return false; 1982 1983 unsigned M0 = N->getMaskElt(0) / 8; 1984 unsigned M1 = N->getMaskElt(8) / 8; 1985 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 1986 1987 // If both vector operands for the shuffle are the same vector, the mask will 1988 // contain only elements from the first one and the second one will be undef. 1989 if (N->getOperand(1).isUndef()) { 1990 if ((M0 | M1) < 2) { 1991 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 1992 Swap = false; 1993 return true; 1994 } else 1995 return false; 1996 } 1997 1998 if (IsLE) { 1999 if (M0 > 1 && M1 < 2) { 2000 Swap = false; 2001 } else if (M0 < 2 && M1 > 1) { 2002 M0 = (M0 + 2) % 4; 2003 M1 = (M1 + 2) % 4; 2004 Swap = true; 2005 } else 2006 return false; 2007 2008 // Note: if control flow comes here that means Swap is already set above 2009 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2010 return true; 2011 } else { // BE 2012 if (M0 < 2 && M1 > 1) { 2013 Swap = false; 2014 } else if (M0 > 1 && M1 < 2) { 2015 M0 = (M0 + 2) % 4; 2016 M1 = (M1 + 2) % 4; 2017 Swap = true; 2018 } else 2019 return false; 2020 2021 // Note: if control flow comes here that means Swap is already set above 2022 DM = (M0 << 1) + (M1 & 1); 2023 return true; 2024 } 2025 } 2026 2027 2028 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 2029 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 2030 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 2031 SelectionDAG &DAG) { 2032 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2033 assert(isSplatShuffleMask(SVOp, EltSize)); 2034 if (DAG.getDataLayout().isLittleEndian()) 2035 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2036 else 2037 return SVOp->getMaskElt(0) / EltSize; 2038 } 2039 2040 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2041 /// by using a vspltis[bhw] instruction of the specified element size, return 2042 /// the constant being splatted. The ByteSize field indicates the number of 2043 /// bytes of each element [124] -> [bhw]. 2044 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2045 SDValue OpVal(nullptr, 0); 2046 2047 // If ByteSize of the splat is bigger than the element size of the 2048 // build_vector, then we have a case where we are checking for a splat where 2049 // multiple elements of the buildvector are folded together into a single 2050 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2051 unsigned EltSize = 16/N->getNumOperands(); 2052 if (EltSize < ByteSize) { 2053 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2054 SDValue UniquedVals[4]; 2055 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2056 2057 // See if all of the elements in the buildvector agree across. 2058 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2059 if (N->getOperand(i).isUndef()) continue; 2060 // If the element isn't a constant, bail fully out. 2061 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2062 2063 if (!UniquedVals[i&(Multiple-1)].getNode()) 2064 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2065 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2066 return SDValue(); // no match. 2067 } 2068 2069 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2070 // either constant or undef values that are identical for each chunk. See 2071 // if these chunks can form into a larger vspltis*. 2072 2073 // Check to see if all of the leading entries are either 0 or -1. If 2074 // neither, then this won't fit into the immediate field. 2075 bool LeadingZero = true; 2076 bool LeadingOnes = true; 2077 for (unsigned i = 0; i != Multiple-1; ++i) { 2078 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2079 2080 LeadingZero &= isNullConstant(UniquedVals[i]); 2081 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2082 } 2083 // Finally, check the least significant entry. 2084 if (LeadingZero) { 2085 if (!UniquedVals[Multiple-1].getNode()) 2086 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2087 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2088 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2089 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2090 } 2091 if (LeadingOnes) { 2092 if (!UniquedVals[Multiple-1].getNode()) 2093 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2094 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2095 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2096 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2097 } 2098 2099 return SDValue(); 2100 } 2101 2102 // Check to see if this buildvec has a single non-undef value in its elements. 2103 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2104 if (N->getOperand(i).isUndef()) continue; 2105 if (!OpVal.getNode()) 2106 OpVal = N->getOperand(i); 2107 else if (OpVal != N->getOperand(i)) 2108 return SDValue(); 2109 } 2110 2111 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2112 2113 unsigned ValSizeInBytes = EltSize; 2114 uint64_t Value = 0; 2115 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2116 Value = CN->getZExtValue(); 2117 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2118 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2119 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2120 } 2121 2122 // If the splat value is larger than the element value, then we can never do 2123 // this splat. The only case that we could fit the replicated bits into our 2124 // immediate field for would be zero, and we prefer to use vxor for it. 2125 if (ValSizeInBytes < ByteSize) return SDValue(); 2126 2127 // If the element value is larger than the splat value, check if it consists 2128 // of a repeated bit pattern of size ByteSize. 2129 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2130 return SDValue(); 2131 2132 // Properly sign extend the value. 2133 int MaskVal = SignExtend32(Value, ByteSize * 8); 2134 2135 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2136 if (MaskVal == 0) return SDValue(); 2137 2138 // Finally, if this value fits in a 5 bit sext field, return it 2139 if (SignExtend32<5>(MaskVal) == MaskVal) 2140 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2141 return SDValue(); 2142 } 2143 2144 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2145 /// amount, otherwise return -1. 2146 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2147 EVT VT = N->getValueType(0); 2148 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2149 return -1; 2150 2151 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2152 2153 // Find the first non-undef value in the shuffle mask. 2154 unsigned i; 2155 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2156 /*search*/; 2157 2158 if (i == 4) return -1; // all undef. 2159 2160 // Otherwise, check to see if the rest of the elements are consecutively 2161 // numbered from this value. 2162 unsigned ShiftAmt = SVOp->getMaskElt(i); 2163 if (ShiftAmt < i) return -1; 2164 ShiftAmt -= i; 2165 2166 // Check the rest of the elements to see if they are consecutive. 2167 for (++i; i != 4; ++i) 2168 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2169 return -1; 2170 2171 return ShiftAmt; 2172 } 2173 2174 //===----------------------------------------------------------------------===// 2175 // Addressing Mode Selection 2176 //===----------------------------------------------------------------------===// 2177 2178 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2179 /// or 64-bit immediate, and if the value can be accurately represented as a 2180 /// sign extension from a 16-bit value. If so, this returns true and the 2181 /// immediate. 2182 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2183 if (!isa<ConstantSDNode>(N)) 2184 return false; 2185 2186 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2187 if (N->getValueType(0) == MVT::i32) 2188 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2189 else 2190 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2191 } 2192 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2193 return isIntS16Immediate(Op.getNode(), Imm); 2194 } 2195 2196 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2197 /// can be represented as an indexed [r+r] operation. Returns false if it 2198 /// can be more efficiently represented with [r+imm]. 2199 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2200 SDValue &Index, 2201 SelectionDAG &DAG) const { 2202 int16_t imm = 0; 2203 if (N.getOpcode() == ISD::ADD) { 2204 if (isIntS16Immediate(N.getOperand(1), imm)) 2205 return false; // r+i 2206 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2207 return false; // r+i 2208 2209 Base = N.getOperand(0); 2210 Index = N.getOperand(1); 2211 return true; 2212 } else if (N.getOpcode() == ISD::OR) { 2213 if (isIntS16Immediate(N.getOperand(1), imm)) 2214 return false; // r+i can fold it if we can. 2215 2216 // If this is an or of disjoint bitfields, we can codegen this as an add 2217 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2218 // disjoint. 2219 KnownBits LHSKnown, RHSKnown; 2220 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2221 2222 if (LHSKnown.Zero.getBoolValue()) { 2223 DAG.computeKnownBits(N.getOperand(1), RHSKnown); 2224 // If all of the bits are known zero on the LHS or RHS, the add won't 2225 // carry. 2226 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2227 Base = N.getOperand(0); 2228 Index = N.getOperand(1); 2229 return true; 2230 } 2231 } 2232 } 2233 2234 return false; 2235 } 2236 2237 // If we happen to be doing an i64 load or store into a stack slot that has 2238 // less than a 4-byte alignment, then the frame-index elimination may need to 2239 // use an indexed load or store instruction (because the offset may not be a 2240 // multiple of 4). The extra register needed to hold the offset comes from the 2241 // register scavenger, and it is possible that the scavenger will need to use 2242 // an emergency spill slot. As a result, we need to make sure that a spill slot 2243 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2244 // stack slot. 2245 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2246 // FIXME: This does not handle the LWA case. 2247 if (VT != MVT::i64) 2248 return; 2249 2250 // NOTE: We'll exclude negative FIs here, which come from argument 2251 // lowering, because there are no known test cases triggering this problem 2252 // using packed structures (or similar). We can remove this exclusion if 2253 // we find such a test case. The reason why this is so test-case driven is 2254 // because this entire 'fixup' is only to prevent crashes (from the 2255 // register scavenger) on not-really-valid inputs. For example, if we have: 2256 // %a = alloca i1 2257 // %b = bitcast i1* %a to i64* 2258 // store i64* a, i64 b 2259 // then the store should really be marked as 'align 1', but is not. If it 2260 // were marked as 'align 1' then the indexed form would have been 2261 // instruction-selected initially, and the problem this 'fixup' is preventing 2262 // won't happen regardless. 2263 if (FrameIdx < 0) 2264 return; 2265 2266 MachineFunction &MF = DAG.getMachineFunction(); 2267 MachineFrameInfo &MFI = MF.getFrameInfo(); 2268 2269 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2270 if (Align >= 4) 2271 return; 2272 2273 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2274 FuncInfo->setHasNonRISpills(); 2275 } 2276 2277 /// Returns true if the address N can be represented by a base register plus 2278 /// a signed 16-bit displacement [r+imm], and if it is not better 2279 /// represented as reg+reg. If \p Alignment is non-zero, only accept 2280 /// displacements that are multiples of that value. 2281 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2282 SDValue &Base, 2283 SelectionDAG &DAG, 2284 unsigned Alignment) const { 2285 // FIXME dl should come from parent load or store, not from address 2286 SDLoc dl(N); 2287 // If this can be more profitably realized as r+r, fail. 2288 if (SelectAddressRegReg(N, Disp, Base, DAG)) 2289 return false; 2290 2291 if (N.getOpcode() == ISD::ADD) { 2292 int16_t imm = 0; 2293 if (isIntS16Immediate(N.getOperand(1), imm) && 2294 (!Alignment || (imm % Alignment) == 0)) { 2295 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2296 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2297 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2298 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2299 } else { 2300 Base = N.getOperand(0); 2301 } 2302 return true; // [r+i] 2303 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2304 // Match LOAD (ADD (X, Lo(G))). 2305 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2306 && "Cannot handle constant offsets yet!"); 2307 Disp = N.getOperand(1).getOperand(0); // The global address. 2308 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2309 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2310 Disp.getOpcode() == ISD::TargetConstantPool || 2311 Disp.getOpcode() == ISD::TargetJumpTable); 2312 Base = N.getOperand(0); 2313 return true; // [&g+r] 2314 } 2315 } else if (N.getOpcode() == ISD::OR) { 2316 int16_t imm = 0; 2317 if (isIntS16Immediate(N.getOperand(1), imm) && 2318 (!Alignment || (imm % Alignment) == 0)) { 2319 // If this is an or of disjoint bitfields, we can codegen this as an add 2320 // (for better address arithmetic) if the LHS and RHS of the OR are 2321 // provably disjoint. 2322 KnownBits LHSKnown; 2323 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2324 2325 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2326 // If all of the bits are known zero on the LHS or RHS, the add won't 2327 // carry. 2328 if (FrameIndexSDNode *FI = 2329 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2330 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2331 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2332 } else { 2333 Base = N.getOperand(0); 2334 } 2335 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2336 return true; 2337 } 2338 } 2339 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2340 // Loading from a constant address. 2341 2342 // If this address fits entirely in a 16-bit sext immediate field, codegen 2343 // this as "d, 0" 2344 int16_t Imm; 2345 if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) { 2346 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2347 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2348 CN->getValueType(0)); 2349 return true; 2350 } 2351 2352 // Handle 32-bit sext immediates with LIS + addr mode. 2353 if ((CN->getValueType(0) == MVT::i32 || 2354 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2355 (!Alignment || (CN->getZExtValue() % Alignment) == 0)) { 2356 int Addr = (int)CN->getZExtValue(); 2357 2358 // Otherwise, break this down into an LIS + disp. 2359 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2360 2361 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2362 MVT::i32); 2363 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2364 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2365 return true; 2366 } 2367 } 2368 2369 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2370 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2371 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2372 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2373 } else 2374 Base = N; 2375 return true; // [r+0] 2376 } 2377 2378 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2379 /// represented as an indexed [r+r] operation. 2380 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2381 SDValue &Index, 2382 SelectionDAG &DAG) const { 2383 // Check to see if we can easily represent this as an [r+r] address. This 2384 // will fail if it thinks that the address is more profitably represented as 2385 // reg+imm, e.g. where imm = 0. 2386 if (SelectAddressRegReg(N, Base, Index, DAG)) 2387 return true; 2388 2389 // If the address is the result of an add, we will utilize the fact that the 2390 // address calculation includes an implicit add. However, we can reduce 2391 // register pressure if we do not materialize a constant just for use as the 2392 // index register. We only get rid of the add if it is not an add of a 2393 // value and a 16-bit signed constant and both have a single use. 2394 int16_t imm = 0; 2395 if (N.getOpcode() == ISD::ADD && 2396 (!isIntS16Immediate(N.getOperand(1), imm) || 2397 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2398 Base = N.getOperand(0); 2399 Index = N.getOperand(1); 2400 return true; 2401 } 2402 2403 // Otherwise, do it the hard way, using R0 as the base register. 2404 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2405 N.getValueType()); 2406 Index = N; 2407 return true; 2408 } 2409 2410 /// Returns true if we should use a direct load into vector instruction 2411 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2412 static bool usePartialVectorLoads(SDNode *N) { 2413 if (!N->hasOneUse()) 2414 return false; 2415 2416 // If there are any other uses other than scalar to vector, then we should 2417 // keep it as a scalar load -> direct move pattern to prevent multiple 2418 // loads. Currently, only check for i64 since we have lxsd/lfd to do this 2419 // efficiently, but no update equivalent. 2420 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2421 EVT MemVT = LD->getMemoryVT(); 2422 if (MemVT.isSimple() && MemVT.getSimpleVT().SimpleTy == MVT::i64) { 2423 SDNode *User = *(LD->use_begin()); 2424 if (User->getOpcode() == ISD::SCALAR_TO_VECTOR) 2425 return true; 2426 } 2427 } 2428 2429 return false; 2430 } 2431 2432 /// getPreIndexedAddressParts - returns true by value, base pointer and 2433 /// offset pointer and addressing mode by reference if the node's address 2434 /// can be legally represented as pre-indexed load / store address. 2435 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2436 SDValue &Offset, 2437 ISD::MemIndexedMode &AM, 2438 SelectionDAG &DAG) const { 2439 if (DisablePPCPreinc) return false; 2440 2441 bool isLoad = true; 2442 SDValue Ptr; 2443 EVT VT; 2444 unsigned Alignment; 2445 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2446 Ptr = LD->getBasePtr(); 2447 VT = LD->getMemoryVT(); 2448 Alignment = LD->getAlignment(); 2449 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2450 Ptr = ST->getBasePtr(); 2451 VT = ST->getMemoryVT(); 2452 Alignment = ST->getAlignment(); 2453 isLoad = false; 2454 } else 2455 return false; 2456 2457 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2458 // instructions because we can fold these into a more efficient instruction 2459 // instead, (such as LXSD). 2460 if (isLoad && usePartialVectorLoads(N)) { 2461 return false; 2462 } 2463 2464 // PowerPC doesn't have preinc load/store instructions for vectors (except 2465 // for QPX, which does have preinc r+r forms). 2466 if (VT.isVector()) { 2467 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2468 return false; 2469 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2470 AM = ISD::PRE_INC; 2471 return true; 2472 } 2473 } 2474 2475 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2476 // Common code will reject creating a pre-inc form if the base pointer 2477 // is a frame index, or if N is a store and the base pointer is either 2478 // the same as or a predecessor of the value being stored. Check for 2479 // those situations here, and try with swapped Base/Offset instead. 2480 bool Swap = false; 2481 2482 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2483 Swap = true; 2484 else if (!isLoad) { 2485 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2486 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2487 Swap = true; 2488 } 2489 2490 if (Swap) 2491 std::swap(Base, Offset); 2492 2493 AM = ISD::PRE_INC; 2494 return true; 2495 } 2496 2497 // LDU/STU can only handle immediates that are a multiple of 4. 2498 if (VT != MVT::i64) { 2499 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2500 return false; 2501 } else { 2502 // LDU/STU need an address with at least 4-byte alignment. 2503 if (Alignment < 4) 2504 return false; 2505 2506 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2507 return false; 2508 } 2509 2510 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2511 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2512 // sext i32 to i64 when addr mode is r+i. 2513 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2514 LD->getExtensionType() == ISD::SEXTLOAD && 2515 isa<ConstantSDNode>(Offset)) 2516 return false; 2517 } 2518 2519 AM = ISD::PRE_INC; 2520 return true; 2521 } 2522 2523 //===----------------------------------------------------------------------===// 2524 // LowerOperation implementation 2525 //===----------------------------------------------------------------------===// 2526 2527 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2528 /// and LoOpFlags to the target MO flags. 2529 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2530 unsigned &HiOpFlags, unsigned &LoOpFlags, 2531 const GlobalValue *GV = nullptr) { 2532 HiOpFlags = PPCII::MO_HA; 2533 LoOpFlags = PPCII::MO_LO; 2534 2535 // Don't use the pic base if not in PIC relocation model. 2536 if (IsPIC) { 2537 HiOpFlags |= PPCII::MO_PIC_FLAG; 2538 LoOpFlags |= PPCII::MO_PIC_FLAG; 2539 } 2540 2541 // If this is a reference to a global value that requires a non-lazy-ptr, make 2542 // sure that instruction lowering adds it. 2543 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2544 HiOpFlags |= PPCII::MO_NLP_FLAG; 2545 LoOpFlags |= PPCII::MO_NLP_FLAG; 2546 2547 if (GV->hasHiddenVisibility()) { 2548 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2549 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2550 } 2551 } 2552 } 2553 2554 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2555 SelectionDAG &DAG) { 2556 SDLoc DL(HiPart); 2557 EVT PtrVT = HiPart.getValueType(); 2558 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2559 2560 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2561 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2562 2563 // With PIC, the first instruction is actually "GR+hi(&G)". 2564 if (isPIC) 2565 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2566 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2567 2568 // Generate non-pic code that has direct accesses to the constant pool. 2569 // The address of the global is just (hi(&g)+lo(&g)). 2570 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2571 } 2572 2573 static void setUsesTOCBasePtr(MachineFunction &MF) { 2574 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2575 FuncInfo->setUsesTOCBasePtr(); 2576 } 2577 2578 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2579 setUsesTOCBasePtr(DAG.getMachineFunction()); 2580 } 2581 2582 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2583 SDValue GA) { 2584 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2585 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2586 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2587 2588 SDValue Ops[] = { GA, Reg }; 2589 return DAG.getMemIntrinsicNode( 2590 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2591 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2592 MachineMemOperand::MOLoad); 2593 } 2594 2595 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2596 SelectionDAG &DAG) const { 2597 EVT PtrVT = Op.getValueType(); 2598 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2599 const Constant *C = CP->getConstVal(); 2600 2601 // 64-bit SVR4 ABI code is always position-independent. 2602 // The actual address of the GlobalValue is stored in the TOC. 2603 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2604 setUsesTOCBasePtr(DAG); 2605 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2606 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2607 } 2608 2609 unsigned MOHiFlag, MOLoFlag; 2610 bool IsPIC = isPositionIndependent(); 2611 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2612 2613 if (IsPIC && Subtarget.isSVR4ABI()) { 2614 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2615 PPCII::MO_PIC_FLAG); 2616 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2617 } 2618 2619 SDValue CPIHi = 2620 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2621 SDValue CPILo = 2622 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2623 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2624 } 2625 2626 // For 64-bit PowerPC, prefer the more compact relative encodings. 2627 // This trades 32 bits per jump table entry for one or two instructions 2628 // on the jump site. 2629 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2630 if (isJumpTableRelative()) 2631 return MachineJumpTableInfo::EK_LabelDifference32; 2632 2633 return TargetLowering::getJumpTableEncoding(); 2634 } 2635 2636 bool PPCTargetLowering::isJumpTableRelative() const { 2637 if (Subtarget.isPPC64()) 2638 return true; 2639 return TargetLowering::isJumpTableRelative(); 2640 } 2641 2642 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2643 SelectionDAG &DAG) const { 2644 if (!Subtarget.isPPC64()) 2645 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2646 2647 switch (getTargetMachine().getCodeModel()) { 2648 case CodeModel::Small: 2649 case CodeModel::Medium: 2650 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2651 default: 2652 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2653 getPointerTy(DAG.getDataLayout())); 2654 } 2655 } 2656 2657 const MCExpr * 2658 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2659 unsigned JTI, 2660 MCContext &Ctx) const { 2661 if (!Subtarget.isPPC64()) 2662 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2663 2664 switch (getTargetMachine().getCodeModel()) { 2665 case CodeModel::Small: 2666 case CodeModel::Medium: 2667 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2668 default: 2669 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2670 } 2671 } 2672 2673 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2674 EVT PtrVT = Op.getValueType(); 2675 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2676 2677 // 64-bit SVR4 ABI code is always position-independent. 2678 // The actual address of the GlobalValue is stored in the TOC. 2679 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2680 setUsesTOCBasePtr(DAG); 2681 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2682 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2683 } 2684 2685 unsigned MOHiFlag, MOLoFlag; 2686 bool IsPIC = isPositionIndependent(); 2687 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2688 2689 if (IsPIC && Subtarget.isSVR4ABI()) { 2690 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2691 PPCII::MO_PIC_FLAG); 2692 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2693 } 2694 2695 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2696 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2697 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2698 } 2699 2700 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2701 SelectionDAG &DAG) const { 2702 EVT PtrVT = Op.getValueType(); 2703 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2704 const BlockAddress *BA = BASDN->getBlockAddress(); 2705 2706 // 64-bit SVR4 ABI code is always position-independent. 2707 // The actual BlockAddress is stored in the TOC. 2708 if (Subtarget.isSVR4ABI() && 2709 (Subtarget.isPPC64() || isPositionIndependent())) { 2710 if (Subtarget.isPPC64()) 2711 setUsesTOCBasePtr(DAG); 2712 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2713 return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA); 2714 } 2715 2716 unsigned MOHiFlag, MOLoFlag; 2717 bool IsPIC = isPositionIndependent(); 2718 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2719 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2720 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2721 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2722 } 2723 2724 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2725 SelectionDAG &DAG) const { 2726 // FIXME: TLS addresses currently use medium model code sequences, 2727 // which is the most useful form. Eventually support for small and 2728 // large models could be added if users need it, at the cost of 2729 // additional complexity. 2730 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2731 if (DAG.getTarget().useEmulatedTLS()) 2732 return LowerToTLSEmulatedModel(GA, DAG); 2733 2734 SDLoc dl(GA); 2735 const GlobalValue *GV = GA->getGlobal(); 2736 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2737 bool is64bit = Subtarget.isPPC64(); 2738 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2739 PICLevel::Level picLevel = M->getPICLevel(); 2740 2741 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 2742 2743 if (Model == TLSModel::LocalExec) { 2744 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2745 PPCII::MO_TPREL_HA); 2746 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2747 PPCII::MO_TPREL_LO); 2748 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2749 : DAG.getRegister(PPC::R2, MVT::i32); 2750 2751 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2752 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2753 } 2754 2755 if (Model == TLSModel::InitialExec) { 2756 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2757 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2758 PPCII::MO_TLS); 2759 SDValue GOTPtr; 2760 if (is64bit) { 2761 setUsesTOCBasePtr(DAG); 2762 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2763 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2764 PtrVT, GOTReg, TGA); 2765 } else 2766 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2767 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2768 PtrVT, TGA, GOTPtr); 2769 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2770 } 2771 2772 if (Model == TLSModel::GeneralDynamic) { 2773 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2774 SDValue GOTPtr; 2775 if (is64bit) { 2776 setUsesTOCBasePtr(DAG); 2777 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2778 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2779 GOTReg, TGA); 2780 } else { 2781 if (picLevel == PICLevel::SmallPIC) 2782 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2783 else 2784 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2785 } 2786 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2787 GOTPtr, TGA, TGA); 2788 } 2789 2790 if (Model == TLSModel::LocalDynamic) { 2791 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2792 SDValue GOTPtr; 2793 if (is64bit) { 2794 setUsesTOCBasePtr(DAG); 2795 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2796 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2797 GOTReg, TGA); 2798 } else { 2799 if (picLevel == PICLevel::SmallPIC) 2800 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2801 else 2802 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2803 } 2804 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2805 PtrVT, GOTPtr, TGA, TGA); 2806 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2807 PtrVT, TLSAddr, TGA); 2808 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2809 } 2810 2811 llvm_unreachable("Unknown TLS model!"); 2812 } 2813 2814 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2815 SelectionDAG &DAG) const { 2816 EVT PtrVT = Op.getValueType(); 2817 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2818 SDLoc DL(GSDN); 2819 const GlobalValue *GV = GSDN->getGlobal(); 2820 2821 // 64-bit SVR4 ABI code is always position-independent. 2822 // The actual address of the GlobalValue is stored in the TOC. 2823 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2824 setUsesTOCBasePtr(DAG); 2825 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2826 return getTOCEntry(DAG, DL, true, GA); 2827 } 2828 2829 unsigned MOHiFlag, MOLoFlag; 2830 bool IsPIC = isPositionIndependent(); 2831 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2832 2833 if (IsPIC && Subtarget.isSVR4ABI()) { 2834 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2835 GSDN->getOffset(), 2836 PPCII::MO_PIC_FLAG); 2837 return getTOCEntry(DAG, DL, false, GA); 2838 } 2839 2840 SDValue GAHi = 2841 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2842 SDValue GALo = 2843 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2844 2845 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2846 2847 // If the global reference is actually to a non-lazy-pointer, we have to do an 2848 // extra load to get the address of the global. 2849 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2850 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2851 return Ptr; 2852 } 2853 2854 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2855 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2856 SDLoc dl(Op); 2857 2858 if (Op.getValueType() == MVT::v2i64) { 2859 // When the operands themselves are v2i64 values, we need to do something 2860 // special because VSX has no underlying comparison operations for these. 2861 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2862 // Equality can be handled by casting to the legal type for Altivec 2863 // comparisons, everything else needs to be expanded. 2864 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2865 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2866 DAG.getSetCC(dl, MVT::v4i32, 2867 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2868 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2869 CC)); 2870 } 2871 2872 return SDValue(); 2873 } 2874 2875 // We handle most of these in the usual way. 2876 return Op; 2877 } 2878 2879 // If we're comparing for equality to zero, expose the fact that this is 2880 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2881 // fold the new nodes. 2882 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2883 return V; 2884 2885 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2886 // Leave comparisons against 0 and -1 alone for now, since they're usually 2887 // optimized. FIXME: revisit this when we can custom lower all setcc 2888 // optimizations. 2889 if (C->isAllOnesValue() || C->isNullValue()) 2890 return SDValue(); 2891 } 2892 2893 // If we have an integer seteq/setne, turn it into a compare against zero 2894 // by xor'ing the rhs with the lhs, which is faster than setting a 2895 // condition register, reading it back out, and masking the correct bit. The 2896 // normal approach here uses sub to do this instead of xor. Using xor exposes 2897 // the result to other bit-twiddling opportunities. 2898 EVT LHSVT = Op.getOperand(0).getValueType(); 2899 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2900 EVT VT = Op.getValueType(); 2901 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2902 Op.getOperand(1)); 2903 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2904 } 2905 return SDValue(); 2906 } 2907 2908 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2909 SDNode *Node = Op.getNode(); 2910 EVT VT = Node->getValueType(0); 2911 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2912 SDValue InChain = Node->getOperand(0); 2913 SDValue VAListPtr = Node->getOperand(1); 2914 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2915 SDLoc dl(Node); 2916 2917 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2918 2919 // gpr_index 2920 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2921 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2922 InChain = GprIndex.getValue(1); 2923 2924 if (VT == MVT::i64) { 2925 // Check if GprIndex is even 2926 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2927 DAG.getConstant(1, dl, MVT::i32)); 2928 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2929 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2930 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2931 DAG.getConstant(1, dl, MVT::i32)); 2932 // Align GprIndex to be even if it isn't 2933 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2934 GprIndex); 2935 } 2936 2937 // fpr index is 1 byte after gpr 2938 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2939 DAG.getConstant(1, dl, MVT::i32)); 2940 2941 // fpr 2942 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2943 FprPtr, MachinePointerInfo(SV), MVT::i8); 2944 InChain = FprIndex.getValue(1); 2945 2946 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2947 DAG.getConstant(8, dl, MVT::i32)); 2948 2949 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2950 DAG.getConstant(4, dl, MVT::i32)); 2951 2952 // areas 2953 SDValue OverflowArea = 2954 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 2955 InChain = OverflowArea.getValue(1); 2956 2957 SDValue RegSaveArea = 2958 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 2959 InChain = RegSaveArea.getValue(1); 2960 2961 // select overflow_area if index > 8 2962 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2963 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 2964 2965 // adjustment constant gpr_index * 4/8 2966 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2967 VT.isInteger() ? GprIndex : FprIndex, 2968 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 2969 MVT::i32)); 2970 2971 // OurReg = RegSaveArea + RegConstant 2972 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2973 RegConstant); 2974 2975 // Floating types are 32 bytes into RegSaveArea 2976 if (VT.isFloatingPoint()) 2977 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 2978 DAG.getConstant(32, dl, MVT::i32)); 2979 2980 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 2981 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 2982 VT.isInteger() ? GprIndex : FprIndex, 2983 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 2984 MVT::i32)); 2985 2986 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 2987 VT.isInteger() ? VAListPtr : FprPtr, 2988 MachinePointerInfo(SV), MVT::i8); 2989 2990 // determine if we should load from reg_save_area or overflow_area 2991 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 2992 2993 // increase overflow_area by 4/8 if gpr/fpr > 8 2994 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 2995 DAG.getConstant(VT.isInteger() ? 4 : 8, 2996 dl, MVT::i32)); 2997 2998 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 2999 OverflowAreaPlusN); 3000 3001 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3002 MachinePointerInfo(), MVT::i32); 3003 3004 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3005 } 3006 3007 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3008 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3009 3010 // We have to copy the entire va_list struct: 3011 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3012 return DAG.getMemcpy(Op.getOperand(0), Op, 3013 Op.getOperand(1), Op.getOperand(2), 3014 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3015 false, MachinePointerInfo(), MachinePointerInfo()); 3016 } 3017 3018 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3019 SelectionDAG &DAG) const { 3020 return Op.getOperand(0); 3021 } 3022 3023 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3024 SelectionDAG &DAG) const { 3025 SDValue Chain = Op.getOperand(0); 3026 SDValue Trmp = Op.getOperand(1); // trampoline 3027 SDValue FPtr = Op.getOperand(2); // nested function 3028 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3029 SDLoc dl(Op); 3030 3031 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3032 bool isPPC64 = (PtrVT == MVT::i64); 3033 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3034 3035 TargetLowering::ArgListTy Args; 3036 TargetLowering::ArgListEntry Entry; 3037 3038 Entry.Ty = IntPtrTy; 3039 Entry.Node = Trmp; Args.push_back(Entry); 3040 3041 // TrampSize == (isPPC64 ? 48 : 40); 3042 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3043 isPPC64 ? MVT::i64 : MVT::i32); 3044 Args.push_back(Entry); 3045 3046 Entry.Node = FPtr; Args.push_back(Entry); 3047 Entry.Node = Nest; Args.push_back(Entry); 3048 3049 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3050 TargetLowering::CallLoweringInfo CLI(DAG); 3051 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3052 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3053 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3054 3055 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3056 return CallResult.second; 3057 } 3058 3059 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3060 MachineFunction &MF = DAG.getMachineFunction(); 3061 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3062 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3063 3064 SDLoc dl(Op); 3065 3066 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3067 // vastart just stores the address of the VarArgsFrameIndex slot into the 3068 // memory location argument. 3069 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3070 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3071 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3072 MachinePointerInfo(SV)); 3073 } 3074 3075 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3076 // We suppose the given va_list is already allocated. 3077 // 3078 // typedef struct { 3079 // char gpr; /* index into the array of 8 GPRs 3080 // * stored in the register save area 3081 // * gpr=0 corresponds to r3, 3082 // * gpr=1 to r4, etc. 3083 // */ 3084 // char fpr; /* index into the array of 8 FPRs 3085 // * stored in the register save area 3086 // * fpr=0 corresponds to f1, 3087 // * fpr=1 to f2, etc. 3088 // */ 3089 // char *overflow_arg_area; 3090 // /* location on stack that holds 3091 // * the next overflow argument 3092 // */ 3093 // char *reg_save_area; 3094 // /* where r3:r10 and f1:f8 (if saved) 3095 // * are stored 3096 // */ 3097 // } va_list[1]; 3098 3099 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3100 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3101 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3102 PtrVT); 3103 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3104 PtrVT); 3105 3106 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3107 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3108 3109 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3110 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3111 3112 uint64_t FPROffset = 1; 3113 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3114 3115 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3116 3117 // Store first byte : number of int regs 3118 SDValue firstStore = 3119 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3120 MachinePointerInfo(SV), MVT::i8); 3121 uint64_t nextOffset = FPROffset; 3122 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3123 ConstFPROffset); 3124 3125 // Store second byte : number of float regs 3126 SDValue secondStore = 3127 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3128 MachinePointerInfo(SV, nextOffset), MVT::i8); 3129 nextOffset += StackOffset; 3130 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3131 3132 // Store second word : arguments given on stack 3133 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3134 MachinePointerInfo(SV, nextOffset)); 3135 nextOffset += FrameOffset; 3136 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3137 3138 // Store third word : arguments given in registers 3139 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3140 MachinePointerInfo(SV, nextOffset)); 3141 } 3142 3143 #include "PPCGenCallingConv.inc" 3144 3145 // Function whose sole purpose is to kill compiler warnings 3146 // stemming from unused functions included from PPCGenCallingConv.inc. 3147 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { 3148 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; 3149 } 3150 3151 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 3152 CCValAssign::LocInfo &LocInfo, 3153 ISD::ArgFlagsTy &ArgFlags, 3154 CCState &State) { 3155 return true; 3156 } 3157 3158 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 3159 MVT &LocVT, 3160 CCValAssign::LocInfo &LocInfo, 3161 ISD::ArgFlagsTy &ArgFlags, 3162 CCState &State) { 3163 static const MCPhysReg ArgRegs[] = { 3164 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3165 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3166 }; 3167 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3168 3169 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3170 3171 // Skip one register if the first unallocated register has an even register 3172 // number and there are still argument registers available which have not been 3173 // allocated yet. RegNum is actually an index into ArgRegs, which means we 3174 // need to skip a register if RegNum is odd. 3175 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 3176 State.AllocateReg(ArgRegs[RegNum]); 3177 } 3178 3179 // Always return false here, as this function only makes sure that the first 3180 // unallocated register has an odd register number and does not actually 3181 // allocate a register for the current argument. 3182 return false; 3183 } 3184 3185 bool 3186 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT, 3187 MVT &LocVT, 3188 CCValAssign::LocInfo &LocInfo, 3189 ISD::ArgFlagsTy &ArgFlags, 3190 CCState &State) { 3191 static const MCPhysReg ArgRegs[] = { 3192 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3193 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3194 }; 3195 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3196 3197 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3198 int RegsLeft = NumArgRegs - RegNum; 3199 3200 // Skip if there is not enough registers left for long double type (4 gpr regs 3201 // in soft float mode) and put long double argument on the stack. 3202 if (RegNum != NumArgRegs && RegsLeft < 4) { 3203 for (int i = 0; i < RegsLeft; i++) { 3204 State.AllocateReg(ArgRegs[RegNum + i]); 3205 } 3206 } 3207 3208 return false; 3209 } 3210 3211 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 3212 MVT &LocVT, 3213 CCValAssign::LocInfo &LocInfo, 3214 ISD::ArgFlagsTy &ArgFlags, 3215 CCState &State) { 3216 static const MCPhysReg ArgRegs[] = { 3217 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3218 PPC::F8 3219 }; 3220 3221 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3222 3223 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3224 3225 // If there is only one Floating-point register left we need to put both f64 3226 // values of a split ppc_fp128 value on the stack. 3227 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 3228 State.AllocateReg(ArgRegs[RegNum]); 3229 } 3230 3231 // Always return false here, as this function only makes sure that the two f64 3232 // values a ppc_fp128 value is split into are both passed in registers or both 3233 // passed on the stack and does not actually allocate a register for the 3234 // current argument. 3235 return false; 3236 } 3237 3238 /// FPR - The set of FP registers that should be allocated for arguments, 3239 /// on Darwin. 3240 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3241 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3242 PPC::F11, PPC::F12, PPC::F13}; 3243 3244 /// QFPR - The set of QPX registers that should be allocated for arguments. 3245 static const MCPhysReg QFPR[] = { 3246 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3247 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3248 3249 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3250 /// the stack. 3251 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3252 unsigned PtrByteSize) { 3253 unsigned ArgSize = ArgVT.getStoreSize(); 3254 if (Flags.isByVal()) 3255 ArgSize = Flags.getByValSize(); 3256 3257 // Round up to multiples of the pointer size, except for array members, 3258 // which are always packed. 3259 if (!Flags.isInConsecutiveRegs()) 3260 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3261 3262 return ArgSize; 3263 } 3264 3265 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3266 /// on the stack. 3267 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3268 ISD::ArgFlagsTy Flags, 3269 unsigned PtrByteSize) { 3270 unsigned Align = PtrByteSize; 3271 3272 // Altivec parameters are padded to a 16 byte boundary. 3273 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3274 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3275 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3276 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3277 Align = 16; 3278 // QPX vector types stored in double-precision are padded to a 32 byte 3279 // boundary. 3280 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3281 Align = 32; 3282 3283 // ByVal parameters are aligned as requested. 3284 if (Flags.isByVal()) { 3285 unsigned BVAlign = Flags.getByValAlign(); 3286 if (BVAlign > PtrByteSize) { 3287 if (BVAlign % PtrByteSize != 0) 3288 llvm_unreachable( 3289 "ByVal alignment is not a multiple of the pointer size"); 3290 3291 Align = BVAlign; 3292 } 3293 } 3294 3295 // Array members are always packed to their original alignment. 3296 if (Flags.isInConsecutiveRegs()) { 3297 // If the array member was split into multiple registers, the first 3298 // needs to be aligned to the size of the full type. (Except for 3299 // ppcf128, which is only aligned as its f64 components.) 3300 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3301 Align = OrigVT.getStoreSize(); 3302 else 3303 Align = ArgVT.getStoreSize(); 3304 } 3305 3306 return Align; 3307 } 3308 3309 /// CalculateStackSlotUsed - Return whether this argument will use its 3310 /// stack slot (instead of being passed in registers). ArgOffset, 3311 /// AvailableFPRs, and AvailableVRs must hold the current argument 3312 /// position, and will be updated to account for this argument. 3313 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3314 ISD::ArgFlagsTy Flags, 3315 unsigned PtrByteSize, 3316 unsigned LinkageSize, 3317 unsigned ParamAreaSize, 3318 unsigned &ArgOffset, 3319 unsigned &AvailableFPRs, 3320 unsigned &AvailableVRs, bool HasQPX) { 3321 bool UseMemory = false; 3322 3323 // Respect alignment of argument on the stack. 3324 unsigned Align = 3325 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3326 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3327 // If there's no space left in the argument save area, we must 3328 // use memory (this check also catches zero-sized arguments). 3329 if (ArgOffset >= LinkageSize + ParamAreaSize) 3330 UseMemory = true; 3331 3332 // Allocate argument on the stack. 3333 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3334 if (Flags.isInConsecutiveRegsLast()) 3335 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3336 // If we overran the argument save area, we must use memory 3337 // (this check catches arguments passed partially in memory) 3338 if (ArgOffset > LinkageSize + ParamAreaSize) 3339 UseMemory = true; 3340 3341 // However, if the argument is actually passed in an FPR or a VR, 3342 // we don't use memory after all. 3343 if (!Flags.isByVal()) { 3344 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3345 // QPX registers overlap with the scalar FP registers. 3346 (HasQPX && (ArgVT == MVT::v4f32 || 3347 ArgVT == MVT::v4f64 || 3348 ArgVT == MVT::v4i1))) 3349 if (AvailableFPRs > 0) { 3350 --AvailableFPRs; 3351 return false; 3352 } 3353 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3354 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3355 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3356 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3357 if (AvailableVRs > 0) { 3358 --AvailableVRs; 3359 return false; 3360 } 3361 } 3362 3363 return UseMemory; 3364 } 3365 3366 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3367 /// ensure minimum alignment required for target. 3368 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3369 unsigned NumBytes) { 3370 unsigned TargetAlign = Lowering->getStackAlignment(); 3371 unsigned AlignMask = TargetAlign - 1; 3372 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3373 return NumBytes; 3374 } 3375 3376 SDValue PPCTargetLowering::LowerFormalArguments( 3377 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3378 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3379 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3380 if (Subtarget.isSVR4ABI()) { 3381 if (Subtarget.isPPC64()) 3382 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3383 dl, DAG, InVals); 3384 else 3385 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3386 dl, DAG, InVals); 3387 } else { 3388 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3389 dl, DAG, InVals); 3390 } 3391 } 3392 3393 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3394 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3395 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3396 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3397 3398 // 32-bit SVR4 ABI Stack Frame Layout: 3399 // +-----------------------------------+ 3400 // +--> | Back chain | 3401 // | +-----------------------------------+ 3402 // | | Floating-point register save area | 3403 // | +-----------------------------------+ 3404 // | | General register save area | 3405 // | +-----------------------------------+ 3406 // | | CR save word | 3407 // | +-----------------------------------+ 3408 // | | VRSAVE save word | 3409 // | +-----------------------------------+ 3410 // | | Alignment padding | 3411 // | +-----------------------------------+ 3412 // | | Vector register save area | 3413 // | +-----------------------------------+ 3414 // | | Local variable space | 3415 // | +-----------------------------------+ 3416 // | | Parameter list area | 3417 // | +-----------------------------------+ 3418 // | | LR save word | 3419 // | +-----------------------------------+ 3420 // SP--> +--- | Back chain | 3421 // +-----------------------------------+ 3422 // 3423 // Specifications: 3424 // System V Application Binary Interface PowerPC Processor Supplement 3425 // AltiVec Technology Programming Interface Manual 3426 3427 MachineFunction &MF = DAG.getMachineFunction(); 3428 MachineFrameInfo &MFI = MF.getFrameInfo(); 3429 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3430 3431 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3432 // Potential tail calls could cause overwriting of argument stack slots. 3433 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3434 (CallConv == CallingConv::Fast)); 3435 unsigned PtrByteSize = 4; 3436 3437 // Assign locations to all of the incoming arguments. 3438 SmallVector<CCValAssign, 16> ArgLocs; 3439 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3440 *DAG.getContext()); 3441 3442 // Reserve space for the linkage area on the stack. 3443 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3444 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3445 if (useSoftFloat() || hasSPE()) 3446 CCInfo.PreAnalyzeFormalArguments(Ins); 3447 3448 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3449 CCInfo.clearWasPPCF128(); 3450 3451 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3452 CCValAssign &VA = ArgLocs[i]; 3453 3454 // Arguments stored in registers. 3455 if (VA.isRegLoc()) { 3456 const TargetRegisterClass *RC; 3457 EVT ValVT = VA.getValVT(); 3458 3459 switch (ValVT.getSimpleVT().SimpleTy) { 3460 default: 3461 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3462 case MVT::i1: 3463 case MVT::i32: 3464 RC = &PPC::GPRCRegClass; 3465 break; 3466 case MVT::f32: 3467 if (Subtarget.hasP8Vector()) 3468 RC = &PPC::VSSRCRegClass; 3469 else if (Subtarget.hasSPE()) 3470 RC = &PPC::SPE4RCRegClass; 3471 else 3472 RC = &PPC::F4RCRegClass; 3473 break; 3474 case MVT::f64: 3475 if (Subtarget.hasVSX()) 3476 RC = &PPC::VSFRCRegClass; 3477 else if (Subtarget.hasSPE()) 3478 RC = &PPC::SPERCRegClass; 3479 else 3480 RC = &PPC::F8RCRegClass; 3481 break; 3482 case MVT::v16i8: 3483 case MVT::v8i16: 3484 case MVT::v4i32: 3485 RC = &PPC::VRRCRegClass; 3486 break; 3487 case MVT::v4f32: 3488 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3489 break; 3490 case MVT::v2f64: 3491 case MVT::v2i64: 3492 RC = &PPC::VRRCRegClass; 3493 break; 3494 case MVT::v4f64: 3495 RC = &PPC::QFRCRegClass; 3496 break; 3497 case MVT::v4i1: 3498 RC = &PPC::QBRCRegClass; 3499 break; 3500 } 3501 3502 // Transform the arguments stored in physical registers into virtual ones. 3503 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3504 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3505 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3506 3507 if (ValVT == MVT::i1) 3508 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3509 3510 InVals.push_back(ArgValue); 3511 } else { 3512 // Argument stored in memory. 3513 assert(VA.isMemLoc()); 3514 3515 // Get the extended size of the argument type in stack 3516 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3517 // Get the actual size of the argument type 3518 unsigned ObjSize = VA.getValVT().getStoreSize(); 3519 unsigned ArgOffset = VA.getLocMemOffset(); 3520 // Stack objects in PPC32 are right justified. 3521 ArgOffset += ArgSize - ObjSize; 3522 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3523 3524 // Create load nodes to retrieve arguments from the stack. 3525 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3526 InVals.push_back( 3527 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3528 } 3529 } 3530 3531 // Assign locations to all of the incoming aggregate by value arguments. 3532 // Aggregates passed by value are stored in the local variable space of the 3533 // caller's stack frame, right above the parameter list area. 3534 SmallVector<CCValAssign, 16> ByValArgLocs; 3535 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3536 ByValArgLocs, *DAG.getContext()); 3537 3538 // Reserve stack space for the allocations in CCInfo. 3539 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3540 3541 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3542 3543 // Area that is at least reserved in the caller of this function. 3544 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3545 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3546 3547 // Set the size that is at least reserved in caller of this function. Tail 3548 // call optimized function's reserved stack space needs to be aligned so that 3549 // taking the difference between two stack areas will result in an aligned 3550 // stack. 3551 MinReservedArea = 3552 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3553 FuncInfo->setMinReservedArea(MinReservedArea); 3554 3555 SmallVector<SDValue, 8> MemOps; 3556 3557 // If the function takes variable number of arguments, make a frame index for 3558 // the start of the first vararg value... for expansion of llvm.va_start. 3559 if (isVarArg) { 3560 static const MCPhysReg GPArgRegs[] = { 3561 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3562 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3563 }; 3564 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3565 3566 static const MCPhysReg FPArgRegs[] = { 3567 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3568 PPC::F8 3569 }; 3570 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3571 3572 if (useSoftFloat() || hasSPE()) 3573 NumFPArgRegs = 0; 3574 3575 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3576 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3577 3578 // Make room for NumGPArgRegs and NumFPArgRegs. 3579 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3580 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3581 3582 FuncInfo->setVarArgsStackOffset( 3583 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3584 CCInfo.getNextStackOffset(), true)); 3585 3586 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3587 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3588 3589 // The fixed integer arguments of a variadic function are stored to the 3590 // VarArgsFrameIndex on the stack so that they may be loaded by 3591 // dereferencing the result of va_next. 3592 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3593 // Get an existing live-in vreg, or add a new one. 3594 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3595 if (!VReg) 3596 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3597 3598 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3599 SDValue Store = 3600 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3601 MemOps.push_back(Store); 3602 // Increment the address by four for the next argument to store 3603 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3604 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3605 } 3606 3607 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3608 // is set. 3609 // The double arguments are stored to the VarArgsFrameIndex 3610 // on the stack. 3611 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3612 // Get an existing live-in vreg, or add a new one. 3613 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3614 if (!VReg) 3615 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3616 3617 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3618 SDValue Store = 3619 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3620 MemOps.push_back(Store); 3621 // Increment the address by eight for the next argument to store 3622 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3623 PtrVT); 3624 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3625 } 3626 } 3627 3628 if (!MemOps.empty()) 3629 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3630 3631 return Chain; 3632 } 3633 3634 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3635 // value to MVT::i64 and then truncate to the correct register size. 3636 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3637 EVT ObjectVT, SelectionDAG &DAG, 3638 SDValue ArgVal, 3639 const SDLoc &dl) const { 3640 if (Flags.isSExt()) 3641 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3642 DAG.getValueType(ObjectVT)); 3643 else if (Flags.isZExt()) 3644 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3645 DAG.getValueType(ObjectVT)); 3646 3647 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3648 } 3649 3650 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3651 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3652 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3653 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3654 // TODO: add description of PPC stack frame format, or at least some docs. 3655 // 3656 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3657 bool isLittleEndian = Subtarget.isLittleEndian(); 3658 MachineFunction &MF = DAG.getMachineFunction(); 3659 MachineFrameInfo &MFI = MF.getFrameInfo(); 3660 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3661 3662 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3663 "fastcc not supported on varargs functions"); 3664 3665 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3666 // Potential tail calls could cause overwriting of argument stack slots. 3667 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3668 (CallConv == CallingConv::Fast)); 3669 unsigned PtrByteSize = 8; 3670 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3671 3672 static const MCPhysReg GPR[] = { 3673 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3674 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3675 }; 3676 static const MCPhysReg VR[] = { 3677 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3678 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3679 }; 3680 3681 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3682 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3683 const unsigned Num_VR_Regs = array_lengthof(VR); 3684 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3685 3686 // Do a first pass over the arguments to determine whether the ABI 3687 // guarantees that our caller has allocated the parameter save area 3688 // on its stack frame. In the ELFv1 ABI, this is always the case; 3689 // in the ELFv2 ABI, it is true if this is a vararg function or if 3690 // any parameter is located in a stack slot. 3691 3692 bool HasParameterArea = !isELFv2ABI || isVarArg; 3693 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3694 unsigned NumBytes = LinkageSize; 3695 unsigned AvailableFPRs = Num_FPR_Regs; 3696 unsigned AvailableVRs = Num_VR_Regs; 3697 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3698 if (Ins[i].Flags.isNest()) 3699 continue; 3700 3701 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3702 PtrByteSize, LinkageSize, ParamAreaSize, 3703 NumBytes, AvailableFPRs, AvailableVRs, 3704 Subtarget.hasQPX())) 3705 HasParameterArea = true; 3706 } 3707 3708 // Add DAG nodes to load the arguments or copy them out of registers. On 3709 // entry to a function on PPC, the arguments start after the linkage area, 3710 // although the first ones are often in registers. 3711 3712 unsigned ArgOffset = LinkageSize; 3713 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3714 unsigned &QFPR_idx = FPR_idx; 3715 SmallVector<SDValue, 8> MemOps; 3716 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3717 unsigned CurArgIdx = 0; 3718 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3719 SDValue ArgVal; 3720 bool needsLoad = false; 3721 EVT ObjectVT = Ins[ArgNo].VT; 3722 EVT OrigVT = Ins[ArgNo].ArgVT; 3723 unsigned ObjSize = ObjectVT.getStoreSize(); 3724 unsigned ArgSize = ObjSize; 3725 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3726 if (Ins[ArgNo].isOrigArg()) { 3727 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3728 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3729 } 3730 // We re-align the argument offset for each argument, except when using the 3731 // fast calling convention, when we need to make sure we do that only when 3732 // we'll actually use a stack slot. 3733 unsigned CurArgOffset, Align; 3734 auto ComputeArgOffset = [&]() { 3735 /* Respect alignment of argument on the stack. */ 3736 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3737 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3738 CurArgOffset = ArgOffset; 3739 }; 3740 3741 if (CallConv != CallingConv::Fast) { 3742 ComputeArgOffset(); 3743 3744 /* Compute GPR index associated with argument offset. */ 3745 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3746 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3747 } 3748 3749 // FIXME the codegen can be much improved in some cases. 3750 // We do not have to keep everything in memory. 3751 if (Flags.isByVal()) { 3752 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3753 3754 if (CallConv == CallingConv::Fast) 3755 ComputeArgOffset(); 3756 3757 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3758 ObjSize = Flags.getByValSize(); 3759 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3760 // Empty aggregate parameters do not take up registers. Examples: 3761 // struct { } a; 3762 // union { } b; 3763 // int c[0]; 3764 // etc. However, we have to provide a place-holder in InVals, so 3765 // pretend we have an 8-byte item at the current address for that 3766 // purpose. 3767 if (!ObjSize) { 3768 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3769 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3770 InVals.push_back(FIN); 3771 continue; 3772 } 3773 3774 // Create a stack object covering all stack doublewords occupied 3775 // by the argument. If the argument is (fully or partially) on 3776 // the stack, or if the argument is fully in registers but the 3777 // caller has allocated the parameter save anyway, we can refer 3778 // directly to the caller's stack frame. Otherwise, create a 3779 // local copy in our own frame. 3780 int FI; 3781 if (HasParameterArea || 3782 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3783 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3784 else 3785 FI = MFI.CreateStackObject(ArgSize, Align, false); 3786 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3787 3788 // Handle aggregates smaller than 8 bytes. 3789 if (ObjSize < PtrByteSize) { 3790 // The value of the object is its address, which differs from the 3791 // address of the enclosing doubleword on big-endian systems. 3792 SDValue Arg = FIN; 3793 if (!isLittleEndian) { 3794 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3795 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3796 } 3797 InVals.push_back(Arg); 3798 3799 if (GPR_idx != Num_GPR_Regs) { 3800 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3801 FuncInfo->addLiveInAttr(VReg, Flags); 3802 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3803 SDValue Store; 3804 3805 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3806 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3807 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3808 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3809 MachinePointerInfo(&*FuncArg), ObjType); 3810 } else { 3811 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3812 // store the whole register as-is to the parameter save area 3813 // slot. 3814 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3815 MachinePointerInfo(&*FuncArg)); 3816 } 3817 3818 MemOps.push_back(Store); 3819 } 3820 // Whether we copied from a register or not, advance the offset 3821 // into the parameter save area by a full doubleword. 3822 ArgOffset += PtrByteSize; 3823 continue; 3824 } 3825 3826 // The value of the object is its address, which is the address of 3827 // its first stack doubleword. 3828 InVals.push_back(FIN); 3829 3830 // Store whatever pieces of the object are in registers to memory. 3831 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3832 if (GPR_idx == Num_GPR_Regs) 3833 break; 3834 3835 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3836 FuncInfo->addLiveInAttr(VReg, Flags); 3837 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3838 SDValue Addr = FIN; 3839 if (j) { 3840 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3841 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3842 } 3843 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3844 MachinePointerInfo(&*FuncArg, j)); 3845 MemOps.push_back(Store); 3846 ++GPR_idx; 3847 } 3848 ArgOffset += ArgSize; 3849 continue; 3850 } 3851 3852 switch (ObjectVT.getSimpleVT().SimpleTy) { 3853 default: llvm_unreachable("Unhandled argument type!"); 3854 case MVT::i1: 3855 case MVT::i32: 3856 case MVT::i64: 3857 if (Flags.isNest()) { 3858 // The 'nest' parameter, if any, is passed in R11. 3859 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3860 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3861 3862 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3863 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3864 3865 break; 3866 } 3867 3868 // These can be scalar arguments or elements of an integer array type 3869 // passed directly. Clang may use those instead of "byval" aggregate 3870 // types to avoid forcing arguments to memory unnecessarily. 3871 if (GPR_idx != Num_GPR_Regs) { 3872 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3873 FuncInfo->addLiveInAttr(VReg, Flags); 3874 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3875 3876 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3877 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3878 // value to MVT::i64 and then truncate to the correct register size. 3879 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3880 } else { 3881 if (CallConv == CallingConv::Fast) 3882 ComputeArgOffset(); 3883 3884 needsLoad = true; 3885 ArgSize = PtrByteSize; 3886 } 3887 if (CallConv != CallingConv::Fast || needsLoad) 3888 ArgOffset += 8; 3889 break; 3890 3891 case MVT::f32: 3892 case MVT::f64: 3893 // These can be scalar arguments or elements of a float array type 3894 // passed directly. The latter are used to implement ELFv2 homogenous 3895 // float aggregates. 3896 if (FPR_idx != Num_FPR_Regs) { 3897 unsigned VReg; 3898 3899 if (ObjectVT == MVT::f32) 3900 VReg = MF.addLiveIn(FPR[FPR_idx], 3901 Subtarget.hasP8Vector() 3902 ? &PPC::VSSRCRegClass 3903 : &PPC::F4RCRegClass); 3904 else 3905 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3906 ? &PPC::VSFRCRegClass 3907 : &PPC::F8RCRegClass); 3908 3909 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3910 ++FPR_idx; 3911 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3912 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3913 // once we support fp <-> gpr moves. 3914 3915 // This can only ever happen in the presence of f32 array types, 3916 // since otherwise we never run out of FPRs before running out 3917 // of GPRs. 3918 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3919 FuncInfo->addLiveInAttr(VReg, Flags); 3920 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3921 3922 if (ObjectVT == MVT::f32) { 3923 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3924 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3925 DAG.getConstant(32, dl, MVT::i32)); 3926 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3927 } 3928 3929 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3930 } else { 3931 if (CallConv == CallingConv::Fast) 3932 ComputeArgOffset(); 3933 3934 needsLoad = true; 3935 } 3936 3937 // When passing an array of floats, the array occupies consecutive 3938 // space in the argument area; only round up to the next doubleword 3939 // at the end of the array. Otherwise, each float takes 8 bytes. 3940 if (CallConv != CallingConv::Fast || needsLoad) { 3941 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3942 ArgOffset += ArgSize; 3943 if (Flags.isInConsecutiveRegsLast()) 3944 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3945 } 3946 break; 3947 case MVT::v4f32: 3948 case MVT::v4i32: 3949 case MVT::v8i16: 3950 case MVT::v16i8: 3951 case MVT::v2f64: 3952 case MVT::v2i64: 3953 case MVT::v1i128: 3954 case MVT::f128: 3955 if (!Subtarget.hasQPX()) { 3956 // These can be scalar arguments or elements of a vector array type 3957 // passed directly. The latter are used to implement ELFv2 homogenous 3958 // vector aggregates. 3959 if (VR_idx != Num_VR_Regs) { 3960 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3961 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3962 ++VR_idx; 3963 } else { 3964 if (CallConv == CallingConv::Fast) 3965 ComputeArgOffset(); 3966 needsLoad = true; 3967 } 3968 if (CallConv != CallingConv::Fast || needsLoad) 3969 ArgOffset += 16; 3970 break; 3971 } // not QPX 3972 3973 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3974 "Invalid QPX parameter type"); 3975 LLVM_FALLTHROUGH; 3976 3977 case MVT::v4f64: 3978 case MVT::v4i1: 3979 // QPX vectors are treated like their scalar floating-point subregisters 3980 // (except that they're larger). 3981 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3982 if (QFPR_idx != Num_QFPR_Regs) { 3983 const TargetRegisterClass *RC; 3984 switch (ObjectVT.getSimpleVT().SimpleTy) { 3985 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3986 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3987 default: RC = &PPC::QBRCRegClass; break; 3988 } 3989 3990 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3991 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3992 ++QFPR_idx; 3993 } else { 3994 if (CallConv == CallingConv::Fast) 3995 ComputeArgOffset(); 3996 needsLoad = true; 3997 } 3998 if (CallConv != CallingConv::Fast || needsLoad) 3999 ArgOffset += Sz; 4000 break; 4001 } 4002 4003 // We need to load the argument to a virtual register if we determined 4004 // above that we ran out of physical registers of the appropriate type. 4005 if (needsLoad) { 4006 if (ObjSize < ArgSize && !isLittleEndian) 4007 CurArgOffset += ArgSize - ObjSize; 4008 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4009 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4010 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4011 } 4012 4013 InVals.push_back(ArgVal); 4014 } 4015 4016 // Area that is at least reserved in the caller of this function. 4017 unsigned MinReservedArea; 4018 if (HasParameterArea) 4019 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4020 else 4021 MinReservedArea = LinkageSize; 4022 4023 // Set the size that is at least reserved in caller of this function. Tail 4024 // call optimized functions' reserved stack space needs to be aligned so that 4025 // taking the difference between two stack areas will result in an aligned 4026 // stack. 4027 MinReservedArea = 4028 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4029 FuncInfo->setMinReservedArea(MinReservedArea); 4030 4031 // If the function takes variable number of arguments, make a frame index for 4032 // the start of the first vararg value... for expansion of llvm.va_start. 4033 if (isVarArg) { 4034 int Depth = ArgOffset; 4035 4036 FuncInfo->setVarArgsFrameIndex( 4037 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4038 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4039 4040 // If this function is vararg, store any remaining integer argument regs 4041 // to their spots on the stack so that they may be loaded by dereferencing 4042 // the result of va_next. 4043 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4044 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4045 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4046 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4047 SDValue Store = 4048 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4049 MemOps.push_back(Store); 4050 // Increment the address by four for the next argument to store 4051 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4052 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4053 } 4054 } 4055 4056 if (!MemOps.empty()) 4057 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4058 4059 return Chain; 4060 } 4061 4062 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4063 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4064 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4065 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4066 // TODO: add description of PPC stack frame format, or at least some docs. 4067 // 4068 MachineFunction &MF = DAG.getMachineFunction(); 4069 MachineFrameInfo &MFI = MF.getFrameInfo(); 4070 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4071 4072 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4073 bool isPPC64 = PtrVT == MVT::i64; 4074 // Potential tail calls could cause overwriting of argument stack slots. 4075 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4076 (CallConv == CallingConv::Fast)); 4077 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4078 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4079 unsigned ArgOffset = LinkageSize; 4080 // Area that is at least reserved in caller of this function. 4081 unsigned MinReservedArea = ArgOffset; 4082 4083 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4084 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4085 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4086 }; 4087 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4088 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4089 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4090 }; 4091 static const MCPhysReg VR[] = { 4092 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4093 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4094 }; 4095 4096 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4097 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4098 const unsigned Num_VR_Regs = array_lengthof( VR); 4099 4100 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4101 4102 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4103 4104 // In 32-bit non-varargs functions, the stack space for vectors is after the 4105 // stack space for non-vectors. We do not use this space unless we have 4106 // too many vectors to fit in registers, something that only occurs in 4107 // constructed examples:), but we have to walk the arglist to figure 4108 // that out...for the pathological case, compute VecArgOffset as the 4109 // start of the vector parameter area. Computing VecArgOffset is the 4110 // entire point of the following loop. 4111 unsigned VecArgOffset = ArgOffset; 4112 if (!isVarArg && !isPPC64) { 4113 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4114 ++ArgNo) { 4115 EVT ObjectVT = Ins[ArgNo].VT; 4116 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4117 4118 if (Flags.isByVal()) { 4119 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4120 unsigned ObjSize = Flags.getByValSize(); 4121 unsigned ArgSize = 4122 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4123 VecArgOffset += ArgSize; 4124 continue; 4125 } 4126 4127 switch(ObjectVT.getSimpleVT().SimpleTy) { 4128 default: llvm_unreachable("Unhandled argument type!"); 4129 case MVT::i1: 4130 case MVT::i32: 4131 case MVT::f32: 4132 VecArgOffset += 4; 4133 break; 4134 case MVT::i64: // PPC64 4135 case MVT::f64: 4136 // FIXME: We are guaranteed to be !isPPC64 at this point. 4137 // Does MVT::i64 apply? 4138 VecArgOffset += 8; 4139 break; 4140 case MVT::v4f32: 4141 case MVT::v4i32: 4142 case MVT::v8i16: 4143 case MVT::v16i8: 4144 // Nothing to do, we're only looking at Nonvector args here. 4145 break; 4146 } 4147 } 4148 } 4149 // We've found where the vector parameter area in memory is. Skip the 4150 // first 12 parameters; these don't use that memory. 4151 VecArgOffset = ((VecArgOffset+15)/16)*16; 4152 VecArgOffset += 12*16; 4153 4154 // Add DAG nodes to load the arguments or copy them out of registers. On 4155 // entry to a function on PPC, the arguments start after the linkage area, 4156 // although the first ones are often in registers. 4157 4158 SmallVector<SDValue, 8> MemOps; 4159 unsigned nAltivecParamsAtEnd = 0; 4160 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4161 unsigned CurArgIdx = 0; 4162 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4163 SDValue ArgVal; 4164 bool needsLoad = false; 4165 EVT ObjectVT = Ins[ArgNo].VT; 4166 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4167 unsigned ArgSize = ObjSize; 4168 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4169 if (Ins[ArgNo].isOrigArg()) { 4170 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4171 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4172 } 4173 unsigned CurArgOffset = ArgOffset; 4174 4175 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4176 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4177 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4178 if (isVarArg || isPPC64) { 4179 MinReservedArea = ((MinReservedArea+15)/16)*16; 4180 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4181 Flags, 4182 PtrByteSize); 4183 } else nAltivecParamsAtEnd++; 4184 } else 4185 // Calculate min reserved area. 4186 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4187 Flags, 4188 PtrByteSize); 4189 4190 // FIXME the codegen can be much improved in some cases. 4191 // We do not have to keep everything in memory. 4192 if (Flags.isByVal()) { 4193 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4194 4195 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4196 ObjSize = Flags.getByValSize(); 4197 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4198 // Objects of size 1 and 2 are right justified, everything else is 4199 // left justified. This means the memory address is adjusted forwards. 4200 if (ObjSize==1 || ObjSize==2) { 4201 CurArgOffset = CurArgOffset + (4 - ObjSize); 4202 } 4203 // The value of the object is its address. 4204 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4205 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4206 InVals.push_back(FIN); 4207 if (ObjSize==1 || ObjSize==2) { 4208 if (GPR_idx != Num_GPR_Regs) { 4209 unsigned VReg; 4210 if (isPPC64) 4211 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4212 else 4213 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4214 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4215 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4216 SDValue Store = 4217 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4218 MachinePointerInfo(&*FuncArg), ObjType); 4219 MemOps.push_back(Store); 4220 ++GPR_idx; 4221 } 4222 4223 ArgOffset += PtrByteSize; 4224 4225 continue; 4226 } 4227 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4228 // Store whatever pieces of the object are in registers 4229 // to memory. ArgOffset will be the address of the beginning 4230 // of the object. 4231 if (GPR_idx != Num_GPR_Regs) { 4232 unsigned VReg; 4233 if (isPPC64) 4234 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4235 else 4236 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4237 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4238 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4239 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4240 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4241 MachinePointerInfo(&*FuncArg, j)); 4242 MemOps.push_back(Store); 4243 ++GPR_idx; 4244 ArgOffset += PtrByteSize; 4245 } else { 4246 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4247 break; 4248 } 4249 } 4250 continue; 4251 } 4252 4253 switch (ObjectVT.getSimpleVT().SimpleTy) { 4254 default: llvm_unreachable("Unhandled argument type!"); 4255 case MVT::i1: 4256 case MVT::i32: 4257 if (!isPPC64) { 4258 if (GPR_idx != Num_GPR_Regs) { 4259 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4260 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4261 4262 if (ObjectVT == MVT::i1) 4263 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4264 4265 ++GPR_idx; 4266 } else { 4267 needsLoad = true; 4268 ArgSize = PtrByteSize; 4269 } 4270 // All int arguments reserve stack space in the Darwin ABI. 4271 ArgOffset += PtrByteSize; 4272 break; 4273 } 4274 LLVM_FALLTHROUGH; 4275 case MVT::i64: // PPC64 4276 if (GPR_idx != Num_GPR_Regs) { 4277 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4278 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4279 4280 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4281 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4282 // value to MVT::i64 and then truncate to the correct register size. 4283 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4284 4285 ++GPR_idx; 4286 } else { 4287 needsLoad = true; 4288 ArgSize = PtrByteSize; 4289 } 4290 // All int arguments reserve stack space in the Darwin ABI. 4291 ArgOffset += 8; 4292 break; 4293 4294 case MVT::f32: 4295 case MVT::f64: 4296 // Every 4 bytes of argument space consumes one of the GPRs available for 4297 // argument passing. 4298 if (GPR_idx != Num_GPR_Regs) { 4299 ++GPR_idx; 4300 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4301 ++GPR_idx; 4302 } 4303 if (FPR_idx != Num_FPR_Regs) { 4304 unsigned VReg; 4305 4306 if (ObjectVT == MVT::f32) 4307 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4308 else 4309 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4310 4311 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4312 ++FPR_idx; 4313 } else { 4314 needsLoad = true; 4315 } 4316 4317 // All FP arguments reserve stack space in the Darwin ABI. 4318 ArgOffset += isPPC64 ? 8 : ObjSize; 4319 break; 4320 case MVT::v4f32: 4321 case MVT::v4i32: 4322 case MVT::v8i16: 4323 case MVT::v16i8: 4324 // Note that vector arguments in registers don't reserve stack space, 4325 // except in varargs functions. 4326 if (VR_idx != Num_VR_Regs) { 4327 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4328 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4329 if (isVarArg) { 4330 while ((ArgOffset % 16) != 0) { 4331 ArgOffset += PtrByteSize; 4332 if (GPR_idx != Num_GPR_Regs) 4333 GPR_idx++; 4334 } 4335 ArgOffset += 16; 4336 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4337 } 4338 ++VR_idx; 4339 } else { 4340 if (!isVarArg && !isPPC64) { 4341 // Vectors go after all the nonvectors. 4342 CurArgOffset = VecArgOffset; 4343 VecArgOffset += 16; 4344 } else { 4345 // Vectors are aligned. 4346 ArgOffset = ((ArgOffset+15)/16)*16; 4347 CurArgOffset = ArgOffset; 4348 ArgOffset += 16; 4349 } 4350 needsLoad = true; 4351 } 4352 break; 4353 } 4354 4355 // We need to load the argument to a virtual register if we determined above 4356 // that we ran out of physical registers of the appropriate type. 4357 if (needsLoad) { 4358 int FI = MFI.CreateFixedObject(ObjSize, 4359 CurArgOffset + (ArgSize - ObjSize), 4360 isImmutable); 4361 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4362 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4363 } 4364 4365 InVals.push_back(ArgVal); 4366 } 4367 4368 // Allow for Altivec parameters at the end, if needed. 4369 if (nAltivecParamsAtEnd) { 4370 MinReservedArea = ((MinReservedArea+15)/16)*16; 4371 MinReservedArea += 16*nAltivecParamsAtEnd; 4372 } 4373 4374 // Area that is at least reserved in the caller of this function. 4375 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4376 4377 // Set the size that is at least reserved in caller of this function. Tail 4378 // call optimized functions' reserved stack space needs to be aligned so that 4379 // taking the difference between two stack areas will result in an aligned 4380 // stack. 4381 MinReservedArea = 4382 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4383 FuncInfo->setMinReservedArea(MinReservedArea); 4384 4385 // If the function takes variable number of arguments, make a frame index for 4386 // the start of the first vararg value... for expansion of llvm.va_start. 4387 if (isVarArg) { 4388 int Depth = ArgOffset; 4389 4390 FuncInfo->setVarArgsFrameIndex( 4391 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4392 Depth, true)); 4393 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4394 4395 // If this function is vararg, store any remaining integer argument regs 4396 // to their spots on the stack so that they may be loaded by dereferencing 4397 // the result of va_next. 4398 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4399 unsigned VReg; 4400 4401 if (isPPC64) 4402 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4403 else 4404 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4405 4406 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4407 SDValue Store = 4408 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4409 MemOps.push_back(Store); 4410 // Increment the address by four for the next argument to store 4411 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4412 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4413 } 4414 } 4415 4416 if (!MemOps.empty()) 4417 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4418 4419 return Chain; 4420 } 4421 4422 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4423 /// adjusted to accommodate the arguments for the tailcall. 4424 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4425 unsigned ParamSize) { 4426 4427 if (!isTailCall) return 0; 4428 4429 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4430 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4431 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4432 // Remember only if the new adjustment is bigger. 4433 if (SPDiff < FI->getTailCallSPDelta()) 4434 FI->setTailCallSPDelta(SPDiff); 4435 4436 return SPDiff; 4437 } 4438 4439 static bool isFunctionGlobalAddress(SDValue Callee); 4440 4441 static bool 4442 callsShareTOCBase(const Function *Caller, SDValue Callee, 4443 const TargetMachine &TM) { 4444 // If !G, Callee can be an external symbol. 4445 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4446 if (!G) 4447 return false; 4448 4449 // The medium and large code models are expected to provide a sufficiently 4450 // large TOC to provide all data addressing needs of a module with a 4451 // single TOC. Since each module will be addressed with a single TOC then we 4452 // only need to check that caller and callee don't cross dso boundaries. 4453 if (CodeModel::Medium == TM.getCodeModel() || 4454 CodeModel::Large == TM.getCodeModel()) 4455 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal()); 4456 4457 // Otherwise we need to ensure callee and caller are in the same section, 4458 // since the linker may allocate multiple TOCs, and we don't know which 4459 // sections will belong to the same TOC base. 4460 4461 const GlobalValue *GV = G->getGlobal(); 4462 if (!GV->isStrongDefinitionForLinker()) 4463 return false; 4464 4465 // Any explicitly-specified sections and section prefixes must also match. 4466 // Also, if we're using -ffunction-sections, then each function is always in 4467 // a different section (the same is true for COMDAT functions). 4468 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4469 GV->getSection() != Caller->getSection()) 4470 return false; 4471 if (const auto *F = dyn_cast<Function>(GV)) { 4472 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4473 return false; 4474 } 4475 4476 // If the callee might be interposed, then we can't assume the ultimate call 4477 // target will be in the same section. Even in cases where we can assume that 4478 // interposition won't happen, in any case where the linker might insert a 4479 // stub to allow for interposition, we must generate code as though 4480 // interposition might occur. To understand why this matters, consider a 4481 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4482 // in the same section, but a is in a different module (i.e. has a different 4483 // TOC base pointer). If the linker allows for interposition between b and c, 4484 // then it will generate a stub for the call edge between b and c which will 4485 // save the TOC pointer into the designated stack slot allocated by b. If we 4486 // return true here, and therefore allow a tail call between b and c, that 4487 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4488 // pointer into the stack slot allocated by a (where the a -> b stub saved 4489 // a's TOC base pointer). If we're not considering a tail call, but rather, 4490 // whether a nop is needed after the call instruction in b, because the linker 4491 // will insert a stub, it might complain about a missing nop if we omit it 4492 // (although many don't complain in this case). 4493 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4494 return false; 4495 4496 return true; 4497 } 4498 4499 static bool 4500 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4501 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4502 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4503 4504 const unsigned PtrByteSize = 8; 4505 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4506 4507 static const MCPhysReg GPR[] = { 4508 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4509 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4510 }; 4511 static const MCPhysReg VR[] = { 4512 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4513 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4514 }; 4515 4516 const unsigned NumGPRs = array_lengthof(GPR); 4517 const unsigned NumFPRs = 13; 4518 const unsigned NumVRs = array_lengthof(VR); 4519 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4520 4521 unsigned NumBytes = LinkageSize; 4522 unsigned AvailableFPRs = NumFPRs; 4523 unsigned AvailableVRs = NumVRs; 4524 4525 for (const ISD::OutputArg& Param : Outs) { 4526 if (Param.Flags.isNest()) continue; 4527 4528 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4529 PtrByteSize, LinkageSize, ParamAreaSize, 4530 NumBytes, AvailableFPRs, AvailableVRs, 4531 Subtarget.hasQPX())) 4532 return true; 4533 } 4534 return false; 4535 } 4536 4537 static bool 4538 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4539 if (CS.arg_size() != CallerFn->arg_size()) 4540 return false; 4541 4542 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4543 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4544 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4545 4546 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4547 const Value* CalleeArg = *CalleeArgIter; 4548 const Value* CallerArg = &(*CallerArgIter); 4549 if (CalleeArg == CallerArg) 4550 continue; 4551 4552 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4553 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4554 // } 4555 // 1st argument of callee is undef and has the same type as caller. 4556 if (CalleeArg->getType() == CallerArg->getType() && 4557 isa<UndefValue>(CalleeArg)) 4558 continue; 4559 4560 return false; 4561 } 4562 4563 return true; 4564 } 4565 4566 // Returns true if TCO is possible between the callers and callees 4567 // calling conventions. 4568 static bool 4569 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4570 CallingConv::ID CalleeCC) { 4571 // Tail calls are possible with fastcc and ccc. 4572 auto isTailCallableCC = [] (CallingConv::ID CC){ 4573 return CC == CallingConv::C || CC == CallingConv::Fast; 4574 }; 4575 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4576 return false; 4577 4578 // We can safely tail call both fastcc and ccc callees from a c calling 4579 // convention caller. If the caller is fastcc, we may have less stack space 4580 // than a non-fastcc caller with the same signature so disable tail-calls in 4581 // that case. 4582 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4583 } 4584 4585 bool 4586 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4587 SDValue Callee, 4588 CallingConv::ID CalleeCC, 4589 ImmutableCallSite CS, 4590 bool isVarArg, 4591 const SmallVectorImpl<ISD::OutputArg> &Outs, 4592 const SmallVectorImpl<ISD::InputArg> &Ins, 4593 SelectionDAG& DAG) const { 4594 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4595 4596 if (DisableSCO && !TailCallOpt) return false; 4597 4598 // Variadic argument functions are not supported. 4599 if (isVarArg) return false; 4600 4601 auto &Caller = DAG.getMachineFunction().getFunction(); 4602 // Check that the calling conventions are compatible for tco. 4603 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4604 return false; 4605 4606 // Caller contains any byval parameter is not supported. 4607 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4608 return false; 4609 4610 // Callee contains any byval parameter is not supported, too. 4611 // Note: This is a quick work around, because in some cases, e.g. 4612 // caller's stack size > callee's stack size, we are still able to apply 4613 // sibling call optimization. For example, gcc is able to do SCO for caller1 4614 // in the following example, but not for caller2. 4615 // struct test { 4616 // long int a; 4617 // char ary[56]; 4618 // } gTest; 4619 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4620 // b->a = v.a; 4621 // return 0; 4622 // } 4623 // void caller1(struct test a, struct test c, struct test *b) { 4624 // callee(gTest, b); } 4625 // void caller2(struct test *b) { callee(gTest, b); } 4626 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4627 return false; 4628 4629 // If callee and caller use different calling conventions, we cannot pass 4630 // parameters on stack since offsets for the parameter area may be different. 4631 if (Caller.getCallingConv() != CalleeCC && 4632 needStackSlotPassParameters(Subtarget, Outs)) 4633 return false; 4634 4635 // No TCO/SCO on indirect call because Caller have to restore its TOC 4636 if (!isFunctionGlobalAddress(Callee) && 4637 !isa<ExternalSymbolSDNode>(Callee)) 4638 return false; 4639 4640 // If the caller and callee potentially have different TOC bases then we 4641 // cannot tail call since we need to restore the TOC pointer after the call. 4642 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4643 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4644 return false; 4645 4646 // TCO allows altering callee ABI, so we don't have to check further. 4647 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4648 return true; 4649 4650 if (DisableSCO) return false; 4651 4652 // If callee use the same argument list that caller is using, then we can 4653 // apply SCO on this case. If it is not, then we need to check if callee needs 4654 // stack for passing arguments. 4655 if (!hasSameArgumentList(&Caller, CS) && 4656 needStackSlotPassParameters(Subtarget, Outs)) { 4657 return false; 4658 } 4659 4660 return true; 4661 } 4662 4663 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4664 /// for tail call optimization. Targets which want to do tail call 4665 /// optimization should implement this function. 4666 bool 4667 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4668 CallingConv::ID CalleeCC, 4669 bool isVarArg, 4670 const SmallVectorImpl<ISD::InputArg> &Ins, 4671 SelectionDAG& DAG) const { 4672 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4673 return false; 4674 4675 // Variable argument functions are not supported. 4676 if (isVarArg) 4677 return false; 4678 4679 MachineFunction &MF = DAG.getMachineFunction(); 4680 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4681 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4682 // Functions containing by val parameters are not supported. 4683 for (unsigned i = 0; i != Ins.size(); i++) { 4684 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4685 if (Flags.isByVal()) return false; 4686 } 4687 4688 // Non-PIC/GOT tail calls are supported. 4689 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4690 return true; 4691 4692 // At the moment we can only do local tail calls (in same module, hidden 4693 // or protected) if we are generating PIC. 4694 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4695 return G->getGlobal()->hasHiddenVisibility() 4696 || G->getGlobal()->hasProtectedVisibility(); 4697 } 4698 4699 return false; 4700 } 4701 4702 /// isCallCompatibleAddress - Return the immediate to use if the specified 4703 /// 32-bit value is representable in the immediate field of a BxA instruction. 4704 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4705 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4706 if (!C) return nullptr; 4707 4708 int Addr = C->getZExtValue(); 4709 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4710 SignExtend32<26>(Addr) != Addr) 4711 return nullptr; // Top 6 bits have to be sext of immediate. 4712 4713 return DAG 4714 .getConstant( 4715 (int)C->getZExtValue() >> 2, SDLoc(Op), 4716 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4717 .getNode(); 4718 } 4719 4720 namespace { 4721 4722 struct TailCallArgumentInfo { 4723 SDValue Arg; 4724 SDValue FrameIdxOp; 4725 int FrameIdx = 0; 4726 4727 TailCallArgumentInfo() = default; 4728 }; 4729 4730 } // end anonymous namespace 4731 4732 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4733 static void StoreTailCallArgumentsToStackSlot( 4734 SelectionDAG &DAG, SDValue Chain, 4735 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4736 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4737 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4738 SDValue Arg = TailCallArgs[i].Arg; 4739 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4740 int FI = TailCallArgs[i].FrameIdx; 4741 // Store relative to framepointer. 4742 MemOpChains.push_back(DAG.getStore( 4743 Chain, dl, Arg, FIN, 4744 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4745 } 4746 } 4747 4748 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4749 /// the appropriate stack slot for the tail call optimized function call. 4750 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4751 SDValue OldRetAddr, SDValue OldFP, 4752 int SPDiff, const SDLoc &dl) { 4753 if (SPDiff) { 4754 // Calculate the new stack slot for the return address. 4755 MachineFunction &MF = DAG.getMachineFunction(); 4756 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4757 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4758 bool isPPC64 = Subtarget.isPPC64(); 4759 int SlotSize = isPPC64 ? 8 : 4; 4760 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4761 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4762 NewRetAddrLoc, true); 4763 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4764 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4765 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4766 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4767 4768 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4769 // slot as the FP is never overwritten. 4770 if (Subtarget.isDarwinABI()) { 4771 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4772 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4773 true); 4774 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4775 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4776 MachinePointerInfo::getFixedStack( 4777 DAG.getMachineFunction(), NewFPIdx)); 4778 } 4779 } 4780 return Chain; 4781 } 4782 4783 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4784 /// the position of the argument. 4785 static void 4786 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4787 SDValue Arg, int SPDiff, unsigned ArgOffset, 4788 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4789 int Offset = ArgOffset + SPDiff; 4790 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4791 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4792 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4793 SDValue FIN = DAG.getFrameIndex(FI, VT); 4794 TailCallArgumentInfo Info; 4795 Info.Arg = Arg; 4796 Info.FrameIdxOp = FIN; 4797 Info.FrameIdx = FI; 4798 TailCallArguments.push_back(Info); 4799 } 4800 4801 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4802 /// stack slot. Returns the chain as result and the loaded frame pointers in 4803 /// LROpOut/FPOpout. Used when tail calling. 4804 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4805 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4806 SDValue &FPOpOut, const SDLoc &dl) const { 4807 if (SPDiff) { 4808 // Load the LR and FP stack slot for later adjusting. 4809 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4810 LROpOut = getReturnAddrFrameIndex(DAG); 4811 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4812 Chain = SDValue(LROpOut.getNode(), 1); 4813 4814 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4815 // slot as the FP is never overwritten. 4816 if (Subtarget.isDarwinABI()) { 4817 FPOpOut = getFramePointerFrameIndex(DAG); 4818 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4819 Chain = SDValue(FPOpOut.getNode(), 1); 4820 } 4821 } 4822 return Chain; 4823 } 4824 4825 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4826 /// by "Src" to address "Dst" of size "Size". Alignment information is 4827 /// specified by the specific parameter attribute. The copy will be passed as 4828 /// a byval function parameter. 4829 /// Sometimes what we are copying is the end of a larger object, the part that 4830 /// does not fit in registers. 4831 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4832 SDValue Chain, ISD::ArgFlagsTy Flags, 4833 SelectionDAG &DAG, const SDLoc &dl) { 4834 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4835 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4836 false, false, false, MachinePointerInfo(), 4837 MachinePointerInfo()); 4838 } 4839 4840 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4841 /// tail calls. 4842 static void LowerMemOpCallTo( 4843 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4844 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4845 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4846 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4847 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4848 if (!isTailCall) { 4849 if (isVector) { 4850 SDValue StackPtr; 4851 if (isPPC64) 4852 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4853 else 4854 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4855 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4856 DAG.getConstant(ArgOffset, dl, PtrVT)); 4857 } 4858 MemOpChains.push_back( 4859 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4860 // Calculate and remember argument location. 4861 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4862 TailCallArguments); 4863 } 4864 4865 static void 4866 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4867 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4868 SDValue FPOp, 4869 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4870 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4871 // might overwrite each other in case of tail call optimization. 4872 SmallVector<SDValue, 8> MemOpChains2; 4873 // Do not flag preceding copytoreg stuff together with the following stuff. 4874 InFlag = SDValue(); 4875 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4876 MemOpChains2, dl); 4877 if (!MemOpChains2.empty()) 4878 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4879 4880 // Store the return address to the appropriate stack slot. 4881 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4882 4883 // Emit callseq_end just before tailcall node. 4884 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4885 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4886 InFlag = Chain.getValue(1); 4887 } 4888 4889 // Is this global address that of a function that can be called by name? (as 4890 // opposed to something that must hold a descriptor for an indirect call). 4891 static bool isFunctionGlobalAddress(SDValue Callee) { 4892 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4893 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4894 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4895 return false; 4896 4897 return G->getGlobal()->getValueType()->isFunctionTy(); 4898 } 4899 4900 return false; 4901 } 4902 4903 static unsigned 4904 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4905 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4906 bool isPatchPoint, bool hasNest, 4907 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4908 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4909 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4910 bool isPPC64 = Subtarget.isPPC64(); 4911 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4912 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4913 4914 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4915 NodeTys.push_back(MVT::Other); // Returns a chain 4916 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4917 4918 unsigned CallOpc = PPCISD::CALL; 4919 4920 bool needIndirectCall = true; 4921 if (!isSVR4ABI || !isPPC64) 4922 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4923 // If this is an absolute destination address, use the munged value. 4924 Callee = SDValue(Dest, 0); 4925 needIndirectCall = false; 4926 } 4927 4928 // PC-relative references to external symbols should go through $stub, unless 4929 // we're building with the leopard linker or later, which automatically 4930 // synthesizes these stubs. 4931 const TargetMachine &TM = DAG.getTarget(); 4932 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4933 const GlobalValue *GV = nullptr; 4934 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4935 GV = G->getGlobal(); 4936 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4937 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4938 4939 if (isFunctionGlobalAddress(Callee)) { 4940 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4941 // A call to a TLS address is actually an indirect call to a 4942 // thread-specific pointer. 4943 unsigned OpFlags = 0; 4944 if (UsePlt) 4945 OpFlags = PPCII::MO_PLT; 4946 4947 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4948 // every direct call is) turn it into a TargetGlobalAddress / 4949 // TargetExternalSymbol node so that legalize doesn't hack it. 4950 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4951 Callee.getValueType(), 0, OpFlags); 4952 needIndirectCall = false; 4953 } 4954 4955 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4956 unsigned char OpFlags = 0; 4957 4958 if (UsePlt) 4959 OpFlags = PPCII::MO_PLT; 4960 4961 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4962 OpFlags); 4963 needIndirectCall = false; 4964 } 4965 4966 if (isPatchPoint) { 4967 // We'll form an invalid direct call when lowering a patchpoint; the full 4968 // sequence for an indirect call is complicated, and many of the 4969 // instructions introduced might have side effects (and, thus, can't be 4970 // removed later). The call itself will be removed as soon as the 4971 // argument/return lowering is complete, so the fact that it has the wrong 4972 // kind of operands should not really matter. 4973 needIndirectCall = false; 4974 } 4975 4976 if (needIndirectCall) { 4977 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4978 // to do the call, we can't use PPCISD::CALL. 4979 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4980 4981 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4982 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4983 // entry point, but to the function descriptor (the function entry point 4984 // address is part of the function descriptor though). 4985 // The function descriptor is a three doubleword structure with the 4986 // following fields: function entry point, TOC base address and 4987 // environment pointer. 4988 // Thus for a call through a function pointer, the following actions need 4989 // to be performed: 4990 // 1. Save the TOC of the caller in the TOC save area of its stack 4991 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4992 // 2. Load the address of the function entry point from the function 4993 // descriptor. 4994 // 3. Load the TOC of the callee from the function descriptor into r2. 4995 // 4. Load the environment pointer from the function descriptor into 4996 // r11. 4997 // 5. Branch to the function entry point address. 4998 // 6. On return of the callee, the TOC of the caller needs to be 4999 // restored (this is done in FinishCall()). 5000 // 5001 // The loads are scheduled at the beginning of the call sequence, and the 5002 // register copies are flagged together to ensure that no other 5003 // operations can be scheduled in between. E.g. without flagging the 5004 // copies together, a TOC access in the caller could be scheduled between 5005 // the assignment of the callee TOC and the branch to the callee, which 5006 // results in the TOC access going through the TOC of the callee instead 5007 // of going through the TOC of the caller, which leads to incorrect code. 5008 5009 // Load the address of the function entry point from the function 5010 // descriptor. 5011 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 5012 if (LDChain.getValueType() == MVT::Glue) 5013 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 5014 5015 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5016 ? (MachineMemOperand::MODereferenceable | 5017 MachineMemOperand::MOInvariant) 5018 : MachineMemOperand::MONone; 5019 5020 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5021 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 5022 /* Alignment = */ 8, MMOFlags); 5023 5024 // Load environment pointer into r11. 5025 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 5026 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 5027 SDValue LoadEnvPtr = 5028 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 5029 /* Alignment = */ 8, MMOFlags); 5030 5031 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 5032 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 5033 SDValue TOCPtr = 5034 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 5035 /* Alignment = */ 8, MMOFlags); 5036 5037 setUsesTOCBasePtr(DAG); 5038 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 5039 InFlag); 5040 Chain = TOCVal.getValue(0); 5041 InFlag = TOCVal.getValue(1); 5042 5043 // If the function call has an explicit 'nest' parameter, it takes the 5044 // place of the environment pointer. 5045 if (!hasNest) { 5046 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 5047 InFlag); 5048 5049 Chain = EnvVal.getValue(0); 5050 InFlag = EnvVal.getValue(1); 5051 } 5052 5053 MTCTROps[0] = Chain; 5054 MTCTROps[1] = LoadFuncPtr; 5055 MTCTROps[2] = InFlag; 5056 } 5057 5058 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 5059 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 5060 InFlag = Chain.getValue(1); 5061 5062 NodeTys.clear(); 5063 NodeTys.push_back(MVT::Other); 5064 NodeTys.push_back(MVT::Glue); 5065 Ops.push_back(Chain); 5066 CallOpc = PPCISD::BCTRL; 5067 Callee.setNode(nullptr); 5068 // Add use of X11 (holding environment pointer) 5069 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 5070 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 5071 // Add CTR register as callee so a bctr can be emitted later. 5072 if (isTailCall) 5073 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 5074 } 5075 5076 // If this is a direct call, pass the chain and the callee. 5077 if (Callee.getNode()) { 5078 Ops.push_back(Chain); 5079 Ops.push_back(Callee); 5080 } 5081 // If this is a tail call add stack pointer delta. 5082 if (isTailCall) 5083 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5084 5085 // Add argument registers to the end of the list so that they are known live 5086 // into the call. 5087 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5088 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5089 RegsToPass[i].second.getValueType())); 5090 5091 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 5092 // into the call. 5093 if (isSVR4ABI && isPPC64 && !isPatchPoint) { 5094 setUsesTOCBasePtr(DAG); 5095 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 5096 } 5097 5098 return CallOpc; 5099 } 5100 5101 SDValue PPCTargetLowering::LowerCallResult( 5102 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5103 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5104 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5105 SmallVector<CCValAssign, 16> RVLocs; 5106 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5107 *DAG.getContext()); 5108 5109 CCRetInfo.AnalyzeCallResult( 5110 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5111 ? RetCC_PPC_Cold 5112 : RetCC_PPC); 5113 5114 // Copy all of the result registers out of their specified physreg. 5115 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5116 CCValAssign &VA = RVLocs[i]; 5117 assert(VA.isRegLoc() && "Can only return in registers!"); 5118 5119 SDValue Val = DAG.getCopyFromReg(Chain, dl, 5120 VA.getLocReg(), VA.getLocVT(), InFlag); 5121 Chain = Val.getValue(1); 5122 InFlag = Val.getValue(2); 5123 5124 switch (VA.getLocInfo()) { 5125 default: llvm_unreachable("Unknown loc info!"); 5126 case CCValAssign::Full: break; 5127 case CCValAssign::AExt: 5128 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5129 break; 5130 case CCValAssign::ZExt: 5131 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5132 DAG.getValueType(VA.getValVT())); 5133 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5134 break; 5135 case CCValAssign::SExt: 5136 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5137 DAG.getValueType(VA.getValVT())); 5138 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5139 break; 5140 } 5141 5142 InVals.push_back(Val); 5143 } 5144 5145 return Chain; 5146 } 5147 5148 SDValue PPCTargetLowering::FinishCall( 5149 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5150 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5151 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 5152 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5153 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5154 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5155 std::vector<EVT> NodeTys; 5156 SmallVector<SDValue, 8> Ops; 5157 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 5158 SPDiff, isTailCall, isPatchPoint, hasNest, 5159 RegsToPass, Ops, NodeTys, CS, Subtarget); 5160 5161 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5162 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5163 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5164 5165 // When performing tail call optimization the callee pops its arguments off 5166 // the stack. Account for this here so these bytes can be pushed back on in 5167 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5168 int BytesCalleePops = 5169 (CallConv == CallingConv::Fast && 5170 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5171 5172 // Add a register mask operand representing the call-preserved registers. 5173 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5174 const uint32_t *Mask = 5175 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5176 assert(Mask && "Missing call preserved mask for calling convention"); 5177 Ops.push_back(DAG.getRegisterMask(Mask)); 5178 5179 if (InFlag.getNode()) 5180 Ops.push_back(InFlag); 5181 5182 // Emit tail call. 5183 if (isTailCall) { 5184 assert(((Callee.getOpcode() == ISD::Register && 5185 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5186 Callee.getOpcode() == ISD::TargetExternalSymbol || 5187 Callee.getOpcode() == ISD::TargetGlobalAddress || 5188 isa<ConstantSDNode>(Callee)) && 5189 "Expecting an global address, external symbol, absolute value or register"); 5190 5191 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5192 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5193 } 5194 5195 // Add a NOP immediately after the branch instruction when using the 64-bit 5196 // SVR4 ABI. At link time, if caller and callee are in a different module and 5197 // thus have a different TOC, the call will be replaced with a call to a stub 5198 // function which saves the current TOC, loads the TOC of the callee and 5199 // branches to the callee. The NOP will be replaced with a load instruction 5200 // which restores the TOC of the caller from the TOC save slot of the current 5201 // stack frame. If caller and callee belong to the same module (and have the 5202 // same TOC), the NOP will remain unchanged. 5203 5204 MachineFunction &MF = DAG.getMachineFunction(); 5205 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 5206 !isPatchPoint) { 5207 if (CallOpc == PPCISD::BCTRL) { 5208 // This is a call through a function pointer. 5209 // Restore the caller TOC from the save area into R2. 5210 // See PrepareCall() for more information about calls through function 5211 // pointers in the 64-bit SVR4 ABI. 5212 // We are using a target-specific load with r2 hard coded, because the 5213 // result of a target-independent load would never go directly into r2, 5214 // since r2 is a reserved register (which prevents the register allocator 5215 // from allocating it), resulting in an additional register being 5216 // allocated and an unnecessary move instruction being generated. 5217 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5218 5219 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5220 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5221 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5222 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5223 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5224 5225 // The address needs to go after the chain input but before the flag (or 5226 // any other variadic arguments). 5227 Ops.insert(std::next(Ops.begin()), AddTOC); 5228 } else if (CallOpc == PPCISD::CALL && 5229 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5230 // Otherwise insert NOP for non-local calls. 5231 CallOpc = PPCISD::CALL_NOP; 5232 } 5233 } 5234 5235 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5236 InFlag = Chain.getValue(1); 5237 5238 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5239 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5240 InFlag, dl); 5241 if (!Ins.empty()) 5242 InFlag = Chain.getValue(1); 5243 5244 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5245 Ins, dl, DAG, InVals); 5246 } 5247 5248 SDValue 5249 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5250 SmallVectorImpl<SDValue> &InVals) const { 5251 SelectionDAG &DAG = CLI.DAG; 5252 SDLoc &dl = CLI.DL; 5253 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5254 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5255 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5256 SDValue Chain = CLI.Chain; 5257 SDValue Callee = CLI.Callee; 5258 bool &isTailCall = CLI.IsTailCall; 5259 CallingConv::ID CallConv = CLI.CallConv; 5260 bool isVarArg = CLI.IsVarArg; 5261 bool isPatchPoint = CLI.IsPatchPoint; 5262 ImmutableCallSite CS = CLI.CS; 5263 5264 if (isTailCall) { 5265 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5266 isTailCall = false; 5267 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5268 isTailCall = 5269 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5270 isVarArg, Outs, Ins, DAG); 5271 else 5272 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5273 Ins, DAG); 5274 if (isTailCall) { 5275 ++NumTailCalls; 5276 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5277 ++NumSiblingCalls; 5278 5279 assert(isa<GlobalAddressSDNode>(Callee) && 5280 "Callee should be an llvm::Function object."); 5281 LLVM_DEBUG( 5282 const GlobalValue *GV = 5283 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5284 const unsigned Width = 5285 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5286 dbgs() << "TCO caller: " 5287 << left_justify(DAG.getMachineFunction().getName(), Width) 5288 << ", callee linkage: " << GV->getVisibility() << ", " 5289 << GV->getLinkage() << "\n"); 5290 } 5291 } 5292 5293 if (!isTailCall && CS && CS.isMustTailCall()) 5294 report_fatal_error("failed to perform tail call elimination on a call " 5295 "site marked musttail"); 5296 5297 // When long calls (i.e. indirect calls) are always used, calls are always 5298 // made via function pointer. If we have a function name, first translate it 5299 // into a pointer. 5300 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5301 !isTailCall) 5302 Callee = LowerGlobalAddress(Callee, DAG); 5303 5304 if (Subtarget.isSVR4ABI()) { 5305 if (Subtarget.isPPC64()) 5306 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5307 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5308 dl, DAG, InVals, CS); 5309 else 5310 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5311 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5312 dl, DAG, InVals, CS); 5313 } 5314 5315 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5316 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5317 dl, DAG, InVals, CS); 5318 } 5319 5320 SDValue PPCTargetLowering::LowerCall_32SVR4( 5321 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5322 bool isTailCall, bool isPatchPoint, 5323 const SmallVectorImpl<ISD::OutputArg> &Outs, 5324 const SmallVectorImpl<SDValue> &OutVals, 5325 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5326 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5327 ImmutableCallSite CS) const { 5328 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5329 // of the 32-bit SVR4 ABI stack frame layout. 5330 5331 assert((CallConv == CallingConv::C || 5332 CallConv == CallingConv::Cold || 5333 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5334 5335 unsigned PtrByteSize = 4; 5336 5337 MachineFunction &MF = DAG.getMachineFunction(); 5338 5339 // Mark this function as potentially containing a function that contains a 5340 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5341 // and restoring the callers stack pointer in this functions epilog. This is 5342 // done because by tail calling the called function might overwrite the value 5343 // in this function's (MF) stack pointer stack slot 0(SP). 5344 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5345 CallConv == CallingConv::Fast) 5346 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5347 5348 // Count how many bytes are to be pushed on the stack, including the linkage 5349 // area, parameter list area and the part of the local variable space which 5350 // contains copies of aggregates which are passed by value. 5351 5352 // Assign locations to all of the outgoing arguments. 5353 SmallVector<CCValAssign, 16> ArgLocs; 5354 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5355 5356 // Reserve space for the linkage area on the stack. 5357 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5358 PtrByteSize); 5359 if (useSoftFloat()) 5360 CCInfo.PreAnalyzeCallOperands(Outs); 5361 5362 if (isVarArg) { 5363 // Handle fixed and variable vector arguments differently. 5364 // Fixed vector arguments go into registers as long as registers are 5365 // available. Variable vector arguments always go into memory. 5366 unsigned NumArgs = Outs.size(); 5367 5368 for (unsigned i = 0; i != NumArgs; ++i) { 5369 MVT ArgVT = Outs[i].VT; 5370 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5371 bool Result; 5372 5373 if (Outs[i].IsFixed) { 5374 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5375 CCInfo); 5376 } else { 5377 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5378 ArgFlags, CCInfo); 5379 } 5380 5381 if (Result) { 5382 #ifndef NDEBUG 5383 errs() << "Call operand #" << i << " has unhandled type " 5384 << EVT(ArgVT).getEVTString() << "\n"; 5385 #endif 5386 llvm_unreachable(nullptr); 5387 } 5388 } 5389 } else { 5390 // All arguments are treated the same. 5391 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5392 } 5393 CCInfo.clearWasPPCF128(); 5394 5395 // Assign locations to all of the outgoing aggregate by value arguments. 5396 SmallVector<CCValAssign, 16> ByValArgLocs; 5397 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5398 5399 // Reserve stack space for the allocations in CCInfo. 5400 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5401 5402 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5403 5404 // Size of the linkage area, parameter list area and the part of the local 5405 // space variable where copies of aggregates which are passed by value are 5406 // stored. 5407 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5408 5409 // Calculate by how many bytes the stack has to be adjusted in case of tail 5410 // call optimization. 5411 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5412 5413 // Adjust the stack pointer for the new arguments... 5414 // These operations are automatically eliminated by the prolog/epilog pass 5415 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5416 SDValue CallSeqStart = Chain; 5417 5418 // Load the return address and frame pointer so it can be moved somewhere else 5419 // later. 5420 SDValue LROp, FPOp; 5421 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5422 5423 // Set up a copy of the stack pointer for use loading and storing any 5424 // arguments that may not fit in the registers available for argument 5425 // passing. 5426 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5427 5428 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5429 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5430 SmallVector<SDValue, 8> MemOpChains; 5431 5432 bool seenFloatArg = false; 5433 // Walk the register/memloc assignments, inserting copies/loads. 5434 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 5435 i != e; 5436 ++i) { 5437 CCValAssign &VA = ArgLocs[i]; 5438 SDValue Arg = OutVals[i]; 5439 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5440 5441 if (Flags.isByVal()) { 5442 // Argument is an aggregate which is passed by value, thus we need to 5443 // create a copy of it in the local variable space of the current stack 5444 // frame (which is the stack frame of the caller) and pass the address of 5445 // this copy to the callee. 5446 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5447 CCValAssign &ByValVA = ByValArgLocs[j++]; 5448 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5449 5450 // Memory reserved in the local variable space of the callers stack frame. 5451 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5452 5453 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5454 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5455 StackPtr, PtrOff); 5456 5457 // Create a copy of the argument in the local area of the current 5458 // stack frame. 5459 SDValue MemcpyCall = 5460 CreateCopyOfByValArgument(Arg, PtrOff, 5461 CallSeqStart.getNode()->getOperand(0), 5462 Flags, DAG, dl); 5463 5464 // This must go outside the CALLSEQ_START..END. 5465 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5466 SDLoc(MemcpyCall)); 5467 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5468 NewCallSeqStart.getNode()); 5469 Chain = CallSeqStart = NewCallSeqStart; 5470 5471 // Pass the address of the aggregate copy on the stack either in a 5472 // physical register or in the parameter list area of the current stack 5473 // frame to the callee. 5474 Arg = PtrOff; 5475 } 5476 5477 // When useCRBits() is true, there can be i1 arguments. 5478 // It is because getRegisterType(MVT::i1) => MVT::i1, 5479 // and for other integer types getRegisterType() => MVT::i32. 5480 // Extend i1 and ensure callee will get i32. 5481 if (Arg.getValueType() == MVT::i1) 5482 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5483 dl, MVT::i32, Arg); 5484 5485 if (VA.isRegLoc()) { 5486 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5487 // Put argument in a physical register. 5488 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5489 } else { 5490 // Put argument in the parameter list area of the current stack frame. 5491 assert(VA.isMemLoc()); 5492 unsigned LocMemOffset = VA.getLocMemOffset(); 5493 5494 if (!isTailCall) { 5495 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5496 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5497 StackPtr, PtrOff); 5498 5499 MemOpChains.push_back( 5500 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5501 } else { 5502 // Calculate and remember argument location. 5503 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5504 TailCallArguments); 5505 } 5506 } 5507 } 5508 5509 if (!MemOpChains.empty()) 5510 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5511 5512 // Build a sequence of copy-to-reg nodes chained together with token chain 5513 // and flag operands which copy the outgoing args into the appropriate regs. 5514 SDValue InFlag; 5515 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5516 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5517 RegsToPass[i].second, InFlag); 5518 InFlag = Chain.getValue(1); 5519 } 5520 5521 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5522 // registers. 5523 if (isVarArg) { 5524 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5525 SDValue Ops[] = { Chain, InFlag }; 5526 5527 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5528 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5529 5530 InFlag = Chain.getValue(1); 5531 } 5532 5533 if (isTailCall) 5534 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5535 TailCallArguments); 5536 5537 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5538 /* unused except on PPC64 ELFv1 */ false, DAG, 5539 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5540 NumBytes, Ins, InVals, CS); 5541 } 5542 5543 // Copy an argument into memory, being careful to do this outside the 5544 // call sequence for the call to which the argument belongs. 5545 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5546 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5547 SelectionDAG &DAG, const SDLoc &dl) const { 5548 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5549 CallSeqStart.getNode()->getOperand(0), 5550 Flags, DAG, dl); 5551 // The MEMCPY must go outside the CALLSEQ_START..END. 5552 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5553 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5554 SDLoc(MemcpyCall)); 5555 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5556 NewCallSeqStart.getNode()); 5557 return NewCallSeqStart; 5558 } 5559 5560 SDValue PPCTargetLowering::LowerCall_64SVR4( 5561 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5562 bool isTailCall, bool isPatchPoint, 5563 const SmallVectorImpl<ISD::OutputArg> &Outs, 5564 const SmallVectorImpl<SDValue> &OutVals, 5565 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5566 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5567 ImmutableCallSite CS) const { 5568 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5569 bool isLittleEndian = Subtarget.isLittleEndian(); 5570 unsigned NumOps = Outs.size(); 5571 bool hasNest = false; 5572 bool IsSibCall = false; 5573 5574 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5575 unsigned PtrByteSize = 8; 5576 5577 MachineFunction &MF = DAG.getMachineFunction(); 5578 5579 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5580 IsSibCall = true; 5581 5582 // Mark this function as potentially containing a function that contains a 5583 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5584 // and restoring the callers stack pointer in this functions epilog. This is 5585 // done because by tail calling the called function might overwrite the value 5586 // in this function's (MF) stack pointer stack slot 0(SP). 5587 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5588 CallConv == CallingConv::Fast) 5589 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5590 5591 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5592 "fastcc not supported on varargs functions"); 5593 5594 // Count how many bytes are to be pushed on the stack, including the linkage 5595 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5596 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5597 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5598 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5599 unsigned NumBytes = LinkageSize; 5600 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5601 unsigned &QFPR_idx = FPR_idx; 5602 5603 static const MCPhysReg GPR[] = { 5604 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5605 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5606 }; 5607 static const MCPhysReg VR[] = { 5608 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5609 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5610 }; 5611 5612 const unsigned NumGPRs = array_lengthof(GPR); 5613 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5614 const unsigned NumVRs = array_lengthof(VR); 5615 const unsigned NumQFPRs = NumFPRs; 5616 5617 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5618 // can be passed to the callee in registers. 5619 // For the fast calling convention, there is another check below. 5620 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5621 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5622 if (!HasParameterArea) { 5623 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5624 unsigned AvailableFPRs = NumFPRs; 5625 unsigned AvailableVRs = NumVRs; 5626 unsigned NumBytesTmp = NumBytes; 5627 for (unsigned i = 0; i != NumOps; ++i) { 5628 if (Outs[i].Flags.isNest()) continue; 5629 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5630 PtrByteSize, LinkageSize, ParamAreaSize, 5631 NumBytesTmp, AvailableFPRs, AvailableVRs, 5632 Subtarget.hasQPX())) 5633 HasParameterArea = true; 5634 } 5635 } 5636 5637 // When using the fast calling convention, we don't provide backing for 5638 // arguments that will be in registers. 5639 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5640 5641 // Avoid allocating parameter area for fastcc functions if all the arguments 5642 // can be passed in the registers. 5643 if (CallConv == CallingConv::Fast) 5644 HasParameterArea = false; 5645 5646 // Add up all the space actually used. 5647 for (unsigned i = 0; i != NumOps; ++i) { 5648 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5649 EVT ArgVT = Outs[i].VT; 5650 EVT OrigVT = Outs[i].ArgVT; 5651 5652 if (Flags.isNest()) 5653 continue; 5654 5655 if (CallConv == CallingConv::Fast) { 5656 if (Flags.isByVal()) { 5657 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5658 if (NumGPRsUsed > NumGPRs) 5659 HasParameterArea = true; 5660 } else { 5661 switch (ArgVT.getSimpleVT().SimpleTy) { 5662 default: llvm_unreachable("Unexpected ValueType for argument!"); 5663 case MVT::i1: 5664 case MVT::i32: 5665 case MVT::i64: 5666 if (++NumGPRsUsed <= NumGPRs) 5667 continue; 5668 break; 5669 case MVT::v4i32: 5670 case MVT::v8i16: 5671 case MVT::v16i8: 5672 case MVT::v2f64: 5673 case MVT::v2i64: 5674 case MVT::v1i128: 5675 case MVT::f128: 5676 if (++NumVRsUsed <= NumVRs) 5677 continue; 5678 break; 5679 case MVT::v4f32: 5680 // When using QPX, this is handled like a FP register, otherwise, it 5681 // is an Altivec register. 5682 if (Subtarget.hasQPX()) { 5683 if (++NumFPRsUsed <= NumFPRs) 5684 continue; 5685 } else { 5686 if (++NumVRsUsed <= NumVRs) 5687 continue; 5688 } 5689 break; 5690 case MVT::f32: 5691 case MVT::f64: 5692 case MVT::v4f64: // QPX 5693 case MVT::v4i1: // QPX 5694 if (++NumFPRsUsed <= NumFPRs) 5695 continue; 5696 break; 5697 } 5698 HasParameterArea = true; 5699 } 5700 } 5701 5702 /* Respect alignment of argument on the stack. */ 5703 unsigned Align = 5704 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5705 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5706 5707 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5708 if (Flags.isInConsecutiveRegsLast()) 5709 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5710 } 5711 5712 unsigned NumBytesActuallyUsed = NumBytes; 5713 5714 // In the old ELFv1 ABI, 5715 // the prolog code of the callee may store up to 8 GPR argument registers to 5716 // the stack, allowing va_start to index over them in memory if its varargs. 5717 // Because we cannot tell if this is needed on the caller side, we have to 5718 // conservatively assume that it is needed. As such, make sure we have at 5719 // least enough stack space for the caller to store the 8 GPRs. 5720 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5721 // really requires memory operands, e.g. a vararg function. 5722 if (HasParameterArea) 5723 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5724 else 5725 NumBytes = LinkageSize; 5726 5727 // Tail call needs the stack to be aligned. 5728 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5729 CallConv == CallingConv::Fast) 5730 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5731 5732 int SPDiff = 0; 5733 5734 // Calculate by how many bytes the stack has to be adjusted in case of tail 5735 // call optimization. 5736 if (!IsSibCall) 5737 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5738 5739 // To protect arguments on the stack from being clobbered in a tail call, 5740 // force all the loads to happen before doing any other lowering. 5741 if (isTailCall) 5742 Chain = DAG.getStackArgumentTokenFactor(Chain); 5743 5744 // Adjust the stack pointer for the new arguments... 5745 // These operations are automatically eliminated by the prolog/epilog pass 5746 if (!IsSibCall) 5747 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5748 SDValue CallSeqStart = Chain; 5749 5750 // Load the return address and frame pointer so it can be move somewhere else 5751 // later. 5752 SDValue LROp, FPOp; 5753 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5754 5755 // Set up a copy of the stack pointer for use loading and storing any 5756 // arguments that may not fit in the registers available for argument 5757 // passing. 5758 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5759 5760 // Figure out which arguments are going to go in registers, and which in 5761 // memory. Also, if this is a vararg function, floating point operations 5762 // must be stored to our stack, and loaded into integer regs as well, if 5763 // any integer regs are available for argument passing. 5764 unsigned ArgOffset = LinkageSize; 5765 5766 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5767 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5768 5769 SmallVector<SDValue, 8> MemOpChains; 5770 for (unsigned i = 0; i != NumOps; ++i) { 5771 SDValue Arg = OutVals[i]; 5772 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5773 EVT ArgVT = Outs[i].VT; 5774 EVT OrigVT = Outs[i].ArgVT; 5775 5776 // PtrOff will be used to store the current argument to the stack if a 5777 // register cannot be found for it. 5778 SDValue PtrOff; 5779 5780 // We re-align the argument offset for each argument, except when using the 5781 // fast calling convention, when we need to make sure we do that only when 5782 // we'll actually use a stack slot. 5783 auto ComputePtrOff = [&]() { 5784 /* Respect alignment of argument on the stack. */ 5785 unsigned Align = 5786 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5787 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5788 5789 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5790 5791 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5792 }; 5793 5794 if (CallConv != CallingConv::Fast) { 5795 ComputePtrOff(); 5796 5797 /* Compute GPR index associated with argument offset. */ 5798 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5799 GPR_idx = std::min(GPR_idx, NumGPRs); 5800 } 5801 5802 // Promote integers to 64-bit values. 5803 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5804 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5805 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5806 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5807 } 5808 5809 // FIXME memcpy is used way more than necessary. Correctness first. 5810 // Note: "by value" is code for passing a structure by value, not 5811 // basic types. 5812 if (Flags.isByVal()) { 5813 // Note: Size includes alignment padding, so 5814 // struct x { short a; char b; } 5815 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5816 // These are the proper values we need for right-justifying the 5817 // aggregate in a parameter register. 5818 unsigned Size = Flags.getByValSize(); 5819 5820 // An empty aggregate parameter takes up no storage and no 5821 // registers. 5822 if (Size == 0) 5823 continue; 5824 5825 if (CallConv == CallingConv::Fast) 5826 ComputePtrOff(); 5827 5828 // All aggregates smaller than 8 bytes must be passed right-justified. 5829 if (Size==1 || Size==2 || Size==4) { 5830 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5831 if (GPR_idx != NumGPRs) { 5832 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5833 MachinePointerInfo(), VT); 5834 MemOpChains.push_back(Load.getValue(1)); 5835 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5836 5837 ArgOffset += PtrByteSize; 5838 continue; 5839 } 5840 } 5841 5842 if (GPR_idx == NumGPRs && Size < 8) { 5843 SDValue AddPtr = PtrOff; 5844 if (!isLittleEndian) { 5845 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5846 PtrOff.getValueType()); 5847 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5848 } 5849 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5850 CallSeqStart, 5851 Flags, DAG, dl); 5852 ArgOffset += PtrByteSize; 5853 continue; 5854 } 5855 // Copy entire object into memory. There are cases where gcc-generated 5856 // code assumes it is there, even if it could be put entirely into 5857 // registers. (This is not what the doc says.) 5858 5859 // FIXME: The above statement is likely due to a misunderstanding of the 5860 // documents. All arguments must be copied into the parameter area BY 5861 // THE CALLEE in the event that the callee takes the address of any 5862 // formal argument. That has not yet been implemented. However, it is 5863 // reasonable to use the stack area as a staging area for the register 5864 // load. 5865 5866 // Skip this for small aggregates, as we will use the same slot for a 5867 // right-justified copy, below. 5868 if (Size >= 8) 5869 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5870 CallSeqStart, 5871 Flags, DAG, dl); 5872 5873 // When a register is available, pass a small aggregate right-justified. 5874 if (Size < 8 && GPR_idx != NumGPRs) { 5875 // The easiest way to get this right-justified in a register 5876 // is to copy the structure into the rightmost portion of a 5877 // local variable slot, then load the whole slot into the 5878 // register. 5879 // FIXME: The memcpy seems to produce pretty awful code for 5880 // small aggregates, particularly for packed ones. 5881 // FIXME: It would be preferable to use the slot in the 5882 // parameter save area instead of a new local variable. 5883 SDValue AddPtr = PtrOff; 5884 if (!isLittleEndian) { 5885 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5886 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5887 } 5888 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5889 CallSeqStart, 5890 Flags, DAG, dl); 5891 5892 // Load the slot into the register. 5893 SDValue Load = 5894 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5895 MemOpChains.push_back(Load.getValue(1)); 5896 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5897 5898 // Done with this argument. 5899 ArgOffset += PtrByteSize; 5900 continue; 5901 } 5902 5903 // For aggregates larger than PtrByteSize, copy the pieces of the 5904 // object that fit into registers from the parameter save area. 5905 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5906 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5907 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5908 if (GPR_idx != NumGPRs) { 5909 SDValue Load = 5910 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5911 MemOpChains.push_back(Load.getValue(1)); 5912 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5913 ArgOffset += PtrByteSize; 5914 } else { 5915 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5916 break; 5917 } 5918 } 5919 continue; 5920 } 5921 5922 switch (Arg.getSimpleValueType().SimpleTy) { 5923 default: llvm_unreachable("Unexpected ValueType for argument!"); 5924 case MVT::i1: 5925 case MVT::i32: 5926 case MVT::i64: 5927 if (Flags.isNest()) { 5928 // The 'nest' parameter, if any, is passed in R11. 5929 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5930 hasNest = true; 5931 break; 5932 } 5933 5934 // These can be scalar arguments or elements of an integer array type 5935 // passed directly. Clang may use those instead of "byval" aggregate 5936 // types to avoid forcing arguments to memory unnecessarily. 5937 if (GPR_idx != NumGPRs) { 5938 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5939 } else { 5940 if (CallConv == CallingConv::Fast) 5941 ComputePtrOff(); 5942 5943 assert(HasParameterArea && 5944 "Parameter area must exist to pass an argument in memory."); 5945 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5946 true, isTailCall, false, MemOpChains, 5947 TailCallArguments, dl); 5948 if (CallConv == CallingConv::Fast) 5949 ArgOffset += PtrByteSize; 5950 } 5951 if (CallConv != CallingConv::Fast) 5952 ArgOffset += PtrByteSize; 5953 break; 5954 case MVT::f32: 5955 case MVT::f64: { 5956 // These can be scalar arguments or elements of a float array type 5957 // passed directly. The latter are used to implement ELFv2 homogenous 5958 // float aggregates. 5959 5960 // Named arguments go into FPRs first, and once they overflow, the 5961 // remaining arguments go into GPRs and then the parameter save area. 5962 // Unnamed arguments for vararg functions always go to GPRs and 5963 // then the parameter save area. For now, put all arguments to vararg 5964 // routines always in both locations (FPR *and* GPR or stack slot). 5965 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5966 bool NeededLoad = false; 5967 5968 // First load the argument into the next available FPR. 5969 if (FPR_idx != NumFPRs) 5970 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5971 5972 // Next, load the argument into GPR or stack slot if needed. 5973 if (!NeedGPROrStack) 5974 ; 5975 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5976 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5977 // once we support fp <-> gpr moves. 5978 5979 // In the non-vararg case, this can only ever happen in the 5980 // presence of f32 array types, since otherwise we never run 5981 // out of FPRs before running out of GPRs. 5982 SDValue ArgVal; 5983 5984 // Double values are always passed in a single GPR. 5985 if (Arg.getValueType() != MVT::f32) { 5986 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5987 5988 // Non-array float values are extended and passed in a GPR. 5989 } else if (!Flags.isInConsecutiveRegs()) { 5990 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5991 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5992 5993 // If we have an array of floats, we collect every odd element 5994 // together with its predecessor into one GPR. 5995 } else if (ArgOffset % PtrByteSize != 0) { 5996 SDValue Lo, Hi; 5997 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5998 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5999 if (!isLittleEndian) 6000 std::swap(Lo, Hi); 6001 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6002 6003 // The final element, if even, goes into the first half of a GPR. 6004 } else if (Flags.isInConsecutiveRegsLast()) { 6005 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6006 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6007 if (!isLittleEndian) 6008 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6009 DAG.getConstant(32, dl, MVT::i32)); 6010 6011 // Non-final even elements are skipped; they will be handled 6012 // together the with subsequent argument on the next go-around. 6013 } else 6014 ArgVal = SDValue(); 6015 6016 if (ArgVal.getNode()) 6017 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6018 } else { 6019 if (CallConv == CallingConv::Fast) 6020 ComputePtrOff(); 6021 6022 // Single-precision floating-point values are mapped to the 6023 // second (rightmost) word of the stack doubleword. 6024 if (Arg.getValueType() == MVT::f32 && 6025 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6026 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6027 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6028 } 6029 6030 assert(HasParameterArea && 6031 "Parameter area must exist to pass an argument in memory."); 6032 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6033 true, isTailCall, false, MemOpChains, 6034 TailCallArguments, dl); 6035 6036 NeededLoad = true; 6037 } 6038 // When passing an array of floats, the array occupies consecutive 6039 // space in the argument area; only round up to the next doubleword 6040 // at the end of the array. Otherwise, each float takes 8 bytes. 6041 if (CallConv != CallingConv::Fast || NeededLoad) { 6042 ArgOffset += (Arg.getValueType() == MVT::f32 && 6043 Flags.isInConsecutiveRegs()) ? 4 : 8; 6044 if (Flags.isInConsecutiveRegsLast()) 6045 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6046 } 6047 break; 6048 } 6049 case MVT::v4f32: 6050 case MVT::v4i32: 6051 case MVT::v8i16: 6052 case MVT::v16i8: 6053 case MVT::v2f64: 6054 case MVT::v2i64: 6055 case MVT::v1i128: 6056 case MVT::f128: 6057 if (!Subtarget.hasQPX()) { 6058 // These can be scalar arguments or elements of a vector array type 6059 // passed directly. The latter are used to implement ELFv2 homogenous 6060 // vector aggregates. 6061 6062 // For a varargs call, named arguments go into VRs or on the stack as 6063 // usual; unnamed arguments always go to the stack or the corresponding 6064 // GPRs when within range. For now, we always put the value in both 6065 // locations (or even all three). 6066 if (isVarArg) { 6067 assert(HasParameterArea && 6068 "Parameter area must exist if we have a varargs call."); 6069 // We could elide this store in the case where the object fits 6070 // entirely in R registers. Maybe later. 6071 SDValue Store = 6072 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6073 MemOpChains.push_back(Store); 6074 if (VR_idx != NumVRs) { 6075 SDValue Load = 6076 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6077 MemOpChains.push_back(Load.getValue(1)); 6078 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6079 } 6080 ArgOffset += 16; 6081 for (unsigned i=0; i<16; i+=PtrByteSize) { 6082 if (GPR_idx == NumGPRs) 6083 break; 6084 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6085 DAG.getConstant(i, dl, PtrVT)); 6086 SDValue Load = 6087 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6088 MemOpChains.push_back(Load.getValue(1)); 6089 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6090 } 6091 break; 6092 } 6093 6094 // Non-varargs Altivec params go into VRs or on the stack. 6095 if (VR_idx != NumVRs) { 6096 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6097 } else { 6098 if (CallConv == CallingConv::Fast) 6099 ComputePtrOff(); 6100 6101 assert(HasParameterArea && 6102 "Parameter area must exist to pass an argument in memory."); 6103 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6104 true, isTailCall, true, MemOpChains, 6105 TailCallArguments, dl); 6106 if (CallConv == CallingConv::Fast) 6107 ArgOffset += 16; 6108 } 6109 6110 if (CallConv != CallingConv::Fast) 6111 ArgOffset += 16; 6112 break; 6113 } // not QPX 6114 6115 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6116 "Invalid QPX parameter type"); 6117 6118 LLVM_FALLTHROUGH; 6119 case MVT::v4f64: 6120 case MVT::v4i1: { 6121 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6122 if (isVarArg) { 6123 assert(HasParameterArea && 6124 "Parameter area must exist if we have a varargs call."); 6125 // We could elide this store in the case where the object fits 6126 // entirely in R registers. Maybe later. 6127 SDValue Store = 6128 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6129 MemOpChains.push_back(Store); 6130 if (QFPR_idx != NumQFPRs) { 6131 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6132 PtrOff, MachinePointerInfo()); 6133 MemOpChains.push_back(Load.getValue(1)); 6134 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6135 } 6136 ArgOffset += (IsF32 ? 16 : 32); 6137 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6138 if (GPR_idx == NumGPRs) 6139 break; 6140 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6141 DAG.getConstant(i, dl, PtrVT)); 6142 SDValue Load = 6143 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6144 MemOpChains.push_back(Load.getValue(1)); 6145 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6146 } 6147 break; 6148 } 6149 6150 // Non-varargs QPX params go into registers or on the stack. 6151 if (QFPR_idx != NumQFPRs) { 6152 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6153 } else { 6154 if (CallConv == CallingConv::Fast) 6155 ComputePtrOff(); 6156 6157 assert(HasParameterArea && 6158 "Parameter area must exist to pass an argument in memory."); 6159 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6160 true, isTailCall, true, MemOpChains, 6161 TailCallArguments, dl); 6162 if (CallConv == CallingConv::Fast) 6163 ArgOffset += (IsF32 ? 16 : 32); 6164 } 6165 6166 if (CallConv != CallingConv::Fast) 6167 ArgOffset += (IsF32 ? 16 : 32); 6168 break; 6169 } 6170 } 6171 } 6172 6173 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6174 "mismatch in size of parameter area"); 6175 (void)NumBytesActuallyUsed; 6176 6177 if (!MemOpChains.empty()) 6178 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6179 6180 // Check if this is an indirect call (MTCTR/BCTRL). 6181 // See PrepareCall() for more information about calls through function 6182 // pointers in the 64-bit SVR4 ABI. 6183 if (!isTailCall && !isPatchPoint && 6184 !isFunctionGlobalAddress(Callee) && 6185 !isa<ExternalSymbolSDNode>(Callee)) { 6186 // Load r2 into a virtual register and store it to the TOC save area. 6187 setUsesTOCBasePtr(DAG); 6188 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6189 // TOC save area offset. 6190 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6191 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6192 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6193 Chain = DAG.getStore( 6194 Val.getValue(1), dl, Val, AddPtr, 6195 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6196 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6197 // This does not mean the MTCTR instruction must use R12; it's easier 6198 // to model this as an extra parameter, so do that. 6199 if (isELFv2ABI && !isPatchPoint) 6200 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6201 } 6202 6203 // Build a sequence of copy-to-reg nodes chained together with token chain 6204 // and flag operands which copy the outgoing args into the appropriate regs. 6205 SDValue InFlag; 6206 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6207 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6208 RegsToPass[i].second, InFlag); 6209 InFlag = Chain.getValue(1); 6210 } 6211 6212 if (isTailCall && !IsSibCall) 6213 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6214 TailCallArguments); 6215 6216 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6217 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6218 SPDiff, NumBytes, Ins, InVals, CS); 6219 } 6220 6221 SDValue PPCTargetLowering::LowerCall_Darwin( 6222 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6223 bool isTailCall, bool isPatchPoint, 6224 const SmallVectorImpl<ISD::OutputArg> &Outs, 6225 const SmallVectorImpl<SDValue> &OutVals, 6226 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6227 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6228 ImmutableCallSite CS) const { 6229 unsigned NumOps = Outs.size(); 6230 6231 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6232 bool isPPC64 = PtrVT == MVT::i64; 6233 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6234 6235 MachineFunction &MF = DAG.getMachineFunction(); 6236 6237 // Mark this function as potentially containing a function that contains a 6238 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6239 // and restoring the callers stack pointer in this functions epilog. This is 6240 // done because by tail calling the called function might overwrite the value 6241 // in this function's (MF) stack pointer stack slot 0(SP). 6242 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6243 CallConv == CallingConv::Fast) 6244 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6245 6246 // Count how many bytes are to be pushed on the stack, including the linkage 6247 // area, and parameter passing area. We start with 24/48 bytes, which is 6248 // prereserved space for [SP][CR][LR][3 x unused]. 6249 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6250 unsigned NumBytes = LinkageSize; 6251 6252 // Add up all the space actually used. 6253 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6254 // they all go in registers, but we must reserve stack space for them for 6255 // possible use by the caller. In varargs or 64-bit calls, parameters are 6256 // assigned stack space in order, with padding so Altivec parameters are 6257 // 16-byte aligned. 6258 unsigned nAltivecParamsAtEnd = 0; 6259 for (unsigned i = 0; i != NumOps; ++i) { 6260 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6261 EVT ArgVT = Outs[i].VT; 6262 // Varargs Altivec parameters are padded to a 16 byte boundary. 6263 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6264 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6265 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6266 if (!isVarArg && !isPPC64) { 6267 // Non-varargs Altivec parameters go after all the non-Altivec 6268 // parameters; handle those later so we know how much padding we need. 6269 nAltivecParamsAtEnd++; 6270 continue; 6271 } 6272 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6273 NumBytes = ((NumBytes+15)/16)*16; 6274 } 6275 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6276 } 6277 6278 // Allow for Altivec parameters at the end, if needed. 6279 if (nAltivecParamsAtEnd) { 6280 NumBytes = ((NumBytes+15)/16)*16; 6281 NumBytes += 16*nAltivecParamsAtEnd; 6282 } 6283 6284 // The prolog code of the callee may store up to 8 GPR argument registers to 6285 // the stack, allowing va_start to index over them in memory if its varargs. 6286 // Because we cannot tell if this is needed on the caller side, we have to 6287 // conservatively assume that it is needed. As such, make sure we have at 6288 // least enough stack space for the caller to store the 8 GPRs. 6289 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6290 6291 // Tail call needs the stack to be aligned. 6292 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6293 CallConv == CallingConv::Fast) 6294 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6295 6296 // Calculate by how many bytes the stack has to be adjusted in case of tail 6297 // call optimization. 6298 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6299 6300 // To protect arguments on the stack from being clobbered in a tail call, 6301 // force all the loads to happen before doing any other lowering. 6302 if (isTailCall) 6303 Chain = DAG.getStackArgumentTokenFactor(Chain); 6304 6305 // Adjust the stack pointer for the new arguments... 6306 // These operations are automatically eliminated by the prolog/epilog pass 6307 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6308 SDValue CallSeqStart = Chain; 6309 6310 // Load the return address and frame pointer so it can be move somewhere else 6311 // later. 6312 SDValue LROp, FPOp; 6313 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6314 6315 // Set up a copy of the stack pointer for use loading and storing any 6316 // arguments that may not fit in the registers available for argument 6317 // passing. 6318 SDValue StackPtr; 6319 if (isPPC64) 6320 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6321 else 6322 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6323 6324 // Figure out which arguments are going to go in registers, and which in 6325 // memory. Also, if this is a vararg function, floating point operations 6326 // must be stored to our stack, and loaded into integer regs as well, if 6327 // any integer regs are available for argument passing. 6328 unsigned ArgOffset = LinkageSize; 6329 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6330 6331 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6332 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6333 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6334 }; 6335 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6336 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6337 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6338 }; 6339 static const MCPhysReg VR[] = { 6340 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6341 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6342 }; 6343 const unsigned NumGPRs = array_lengthof(GPR_32); 6344 const unsigned NumFPRs = 13; 6345 const unsigned NumVRs = array_lengthof(VR); 6346 6347 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6348 6349 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6350 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6351 6352 SmallVector<SDValue, 8> MemOpChains; 6353 for (unsigned i = 0; i != NumOps; ++i) { 6354 SDValue Arg = OutVals[i]; 6355 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6356 6357 // PtrOff will be used to store the current argument to the stack if a 6358 // register cannot be found for it. 6359 SDValue PtrOff; 6360 6361 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6362 6363 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6364 6365 // On PPC64, promote integers to 64-bit values. 6366 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6367 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6368 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6369 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6370 } 6371 6372 // FIXME memcpy is used way more than necessary. Correctness first. 6373 // Note: "by value" is code for passing a structure by value, not 6374 // basic types. 6375 if (Flags.isByVal()) { 6376 unsigned Size = Flags.getByValSize(); 6377 // Very small objects are passed right-justified. Everything else is 6378 // passed left-justified. 6379 if (Size==1 || Size==2) { 6380 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6381 if (GPR_idx != NumGPRs) { 6382 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6383 MachinePointerInfo(), VT); 6384 MemOpChains.push_back(Load.getValue(1)); 6385 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6386 6387 ArgOffset += PtrByteSize; 6388 } else { 6389 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6390 PtrOff.getValueType()); 6391 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6392 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6393 CallSeqStart, 6394 Flags, DAG, dl); 6395 ArgOffset += PtrByteSize; 6396 } 6397 continue; 6398 } 6399 // Copy entire object into memory. There are cases where gcc-generated 6400 // code assumes it is there, even if it could be put entirely into 6401 // registers. (This is not what the doc says.) 6402 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6403 CallSeqStart, 6404 Flags, DAG, dl); 6405 6406 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6407 // copy the pieces of the object that fit into registers from the 6408 // parameter save area. 6409 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6410 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6411 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6412 if (GPR_idx != NumGPRs) { 6413 SDValue Load = 6414 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6415 MemOpChains.push_back(Load.getValue(1)); 6416 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6417 ArgOffset += PtrByteSize; 6418 } else { 6419 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6420 break; 6421 } 6422 } 6423 continue; 6424 } 6425 6426 switch (Arg.getSimpleValueType().SimpleTy) { 6427 default: llvm_unreachable("Unexpected ValueType for argument!"); 6428 case MVT::i1: 6429 case MVT::i32: 6430 case MVT::i64: 6431 if (GPR_idx != NumGPRs) { 6432 if (Arg.getValueType() == MVT::i1) 6433 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6434 6435 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6436 } else { 6437 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6438 isPPC64, isTailCall, false, MemOpChains, 6439 TailCallArguments, dl); 6440 } 6441 ArgOffset += PtrByteSize; 6442 break; 6443 case MVT::f32: 6444 case MVT::f64: 6445 if (FPR_idx != NumFPRs) { 6446 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6447 6448 if (isVarArg) { 6449 SDValue Store = 6450 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6451 MemOpChains.push_back(Store); 6452 6453 // Float varargs are always shadowed in available integer registers 6454 if (GPR_idx != NumGPRs) { 6455 SDValue Load = 6456 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6457 MemOpChains.push_back(Load.getValue(1)); 6458 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6459 } 6460 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6461 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6462 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6463 SDValue Load = 6464 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6465 MemOpChains.push_back(Load.getValue(1)); 6466 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6467 } 6468 } else { 6469 // If we have any FPRs remaining, we may also have GPRs remaining. 6470 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6471 // GPRs. 6472 if (GPR_idx != NumGPRs) 6473 ++GPR_idx; 6474 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6475 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6476 ++GPR_idx; 6477 } 6478 } else 6479 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6480 isPPC64, isTailCall, false, MemOpChains, 6481 TailCallArguments, dl); 6482 if (isPPC64) 6483 ArgOffset += 8; 6484 else 6485 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6486 break; 6487 case MVT::v4f32: 6488 case MVT::v4i32: 6489 case MVT::v8i16: 6490 case MVT::v16i8: 6491 if (isVarArg) { 6492 // These go aligned on the stack, or in the corresponding R registers 6493 // when within range. The Darwin PPC ABI doc claims they also go in 6494 // V registers; in fact gcc does this only for arguments that are 6495 // prototyped, not for those that match the ... We do it for all 6496 // arguments, seems to work. 6497 while (ArgOffset % 16 !=0) { 6498 ArgOffset += PtrByteSize; 6499 if (GPR_idx != NumGPRs) 6500 GPR_idx++; 6501 } 6502 // We could elide this store in the case where the object fits 6503 // entirely in R registers. Maybe later. 6504 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6505 DAG.getConstant(ArgOffset, dl, PtrVT)); 6506 SDValue Store = 6507 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6508 MemOpChains.push_back(Store); 6509 if (VR_idx != NumVRs) { 6510 SDValue Load = 6511 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6512 MemOpChains.push_back(Load.getValue(1)); 6513 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6514 } 6515 ArgOffset += 16; 6516 for (unsigned i=0; i<16; i+=PtrByteSize) { 6517 if (GPR_idx == NumGPRs) 6518 break; 6519 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6520 DAG.getConstant(i, dl, PtrVT)); 6521 SDValue Load = 6522 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6523 MemOpChains.push_back(Load.getValue(1)); 6524 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6525 } 6526 break; 6527 } 6528 6529 // Non-varargs Altivec params generally go in registers, but have 6530 // stack space allocated at the end. 6531 if (VR_idx != NumVRs) { 6532 // Doesn't have GPR space allocated. 6533 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6534 } else if (nAltivecParamsAtEnd==0) { 6535 // We are emitting Altivec params in order. 6536 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6537 isPPC64, isTailCall, true, MemOpChains, 6538 TailCallArguments, dl); 6539 ArgOffset += 16; 6540 } 6541 break; 6542 } 6543 } 6544 // If all Altivec parameters fit in registers, as they usually do, 6545 // they get stack space following the non-Altivec parameters. We 6546 // don't track this here because nobody below needs it. 6547 // If there are more Altivec parameters than fit in registers emit 6548 // the stores here. 6549 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6550 unsigned j = 0; 6551 // Offset is aligned; skip 1st 12 params which go in V registers. 6552 ArgOffset = ((ArgOffset+15)/16)*16; 6553 ArgOffset += 12*16; 6554 for (unsigned i = 0; i != NumOps; ++i) { 6555 SDValue Arg = OutVals[i]; 6556 EVT ArgType = Outs[i].VT; 6557 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6558 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6559 if (++j > NumVRs) { 6560 SDValue PtrOff; 6561 // We are emitting Altivec params in order. 6562 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6563 isPPC64, isTailCall, true, MemOpChains, 6564 TailCallArguments, dl); 6565 ArgOffset += 16; 6566 } 6567 } 6568 } 6569 } 6570 6571 if (!MemOpChains.empty()) 6572 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6573 6574 // On Darwin, R12 must contain the address of an indirect callee. This does 6575 // not mean the MTCTR instruction must use R12; it's easier to model this as 6576 // an extra parameter, so do that. 6577 if (!isTailCall && 6578 !isFunctionGlobalAddress(Callee) && 6579 !isa<ExternalSymbolSDNode>(Callee) && 6580 !isBLACompatibleAddress(Callee, DAG)) 6581 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6582 PPC::R12), Callee)); 6583 6584 // Build a sequence of copy-to-reg nodes chained together with token chain 6585 // and flag operands which copy the outgoing args into the appropriate regs. 6586 SDValue InFlag; 6587 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6588 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6589 RegsToPass[i].second, InFlag); 6590 InFlag = Chain.getValue(1); 6591 } 6592 6593 if (isTailCall) 6594 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6595 TailCallArguments); 6596 6597 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6598 /* unused except on PPC64 ELFv1 */ false, DAG, 6599 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6600 NumBytes, Ins, InVals, CS); 6601 } 6602 6603 bool 6604 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6605 MachineFunction &MF, bool isVarArg, 6606 const SmallVectorImpl<ISD::OutputArg> &Outs, 6607 LLVMContext &Context) const { 6608 SmallVector<CCValAssign, 16> RVLocs; 6609 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6610 return CCInfo.CheckReturn( 6611 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6612 ? RetCC_PPC_Cold 6613 : RetCC_PPC); 6614 } 6615 6616 SDValue 6617 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6618 bool isVarArg, 6619 const SmallVectorImpl<ISD::OutputArg> &Outs, 6620 const SmallVectorImpl<SDValue> &OutVals, 6621 const SDLoc &dl, SelectionDAG &DAG) const { 6622 SmallVector<CCValAssign, 16> RVLocs; 6623 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6624 *DAG.getContext()); 6625 CCInfo.AnalyzeReturn(Outs, 6626 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6627 ? RetCC_PPC_Cold 6628 : RetCC_PPC); 6629 6630 SDValue Flag; 6631 SmallVector<SDValue, 4> RetOps(1, Chain); 6632 6633 // Copy the result values into the output registers. 6634 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6635 CCValAssign &VA = RVLocs[i]; 6636 assert(VA.isRegLoc() && "Can only return in registers!"); 6637 6638 SDValue Arg = OutVals[i]; 6639 6640 switch (VA.getLocInfo()) { 6641 default: llvm_unreachable("Unknown loc info!"); 6642 case CCValAssign::Full: break; 6643 case CCValAssign::AExt: 6644 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6645 break; 6646 case CCValAssign::ZExt: 6647 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6648 break; 6649 case CCValAssign::SExt: 6650 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6651 break; 6652 } 6653 6654 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6655 Flag = Chain.getValue(1); 6656 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6657 } 6658 6659 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6660 const MCPhysReg *I = 6661 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6662 if (I) { 6663 for (; *I; ++I) { 6664 6665 if (PPC::G8RCRegClass.contains(*I)) 6666 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6667 else if (PPC::F8RCRegClass.contains(*I)) 6668 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6669 else if (PPC::CRRCRegClass.contains(*I)) 6670 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6671 else if (PPC::VRRCRegClass.contains(*I)) 6672 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6673 else 6674 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6675 } 6676 } 6677 6678 RetOps[0] = Chain; // Update chain. 6679 6680 // Add the flag if we have it. 6681 if (Flag.getNode()) 6682 RetOps.push_back(Flag); 6683 6684 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6685 } 6686 6687 SDValue 6688 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6689 SelectionDAG &DAG) const { 6690 SDLoc dl(Op); 6691 6692 // Get the correct type for integers. 6693 EVT IntVT = Op.getValueType(); 6694 6695 // Get the inputs. 6696 SDValue Chain = Op.getOperand(0); 6697 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6698 // Build a DYNAREAOFFSET node. 6699 SDValue Ops[2] = {Chain, FPSIdx}; 6700 SDVTList VTs = DAG.getVTList(IntVT); 6701 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6702 } 6703 6704 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6705 SelectionDAG &DAG) const { 6706 // When we pop the dynamic allocation we need to restore the SP link. 6707 SDLoc dl(Op); 6708 6709 // Get the correct type for pointers. 6710 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6711 6712 // Construct the stack pointer operand. 6713 bool isPPC64 = Subtarget.isPPC64(); 6714 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6715 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6716 6717 // Get the operands for the STACKRESTORE. 6718 SDValue Chain = Op.getOperand(0); 6719 SDValue SaveSP = Op.getOperand(1); 6720 6721 // Load the old link SP. 6722 SDValue LoadLinkSP = 6723 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6724 6725 // Restore the stack pointer. 6726 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6727 6728 // Store the old link SP. 6729 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6730 } 6731 6732 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6733 MachineFunction &MF = DAG.getMachineFunction(); 6734 bool isPPC64 = Subtarget.isPPC64(); 6735 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6736 6737 // Get current frame pointer save index. The users of this index will be 6738 // primarily DYNALLOC instructions. 6739 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6740 int RASI = FI->getReturnAddrSaveIndex(); 6741 6742 // If the frame pointer save index hasn't been defined yet. 6743 if (!RASI) { 6744 // Find out what the fix offset of the frame pointer save area. 6745 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6746 // Allocate the frame index for frame pointer save area. 6747 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6748 // Save the result. 6749 FI->setReturnAddrSaveIndex(RASI); 6750 } 6751 return DAG.getFrameIndex(RASI, PtrVT); 6752 } 6753 6754 SDValue 6755 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6756 MachineFunction &MF = DAG.getMachineFunction(); 6757 bool isPPC64 = Subtarget.isPPC64(); 6758 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6759 6760 // Get current frame pointer save index. The users of this index will be 6761 // primarily DYNALLOC instructions. 6762 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6763 int FPSI = FI->getFramePointerSaveIndex(); 6764 6765 // If the frame pointer save index hasn't been defined yet. 6766 if (!FPSI) { 6767 // Find out what the fix offset of the frame pointer save area. 6768 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6769 // Allocate the frame index for frame pointer save area. 6770 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6771 // Save the result. 6772 FI->setFramePointerSaveIndex(FPSI); 6773 } 6774 return DAG.getFrameIndex(FPSI, PtrVT); 6775 } 6776 6777 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6778 SelectionDAG &DAG) const { 6779 // Get the inputs. 6780 SDValue Chain = Op.getOperand(0); 6781 SDValue Size = Op.getOperand(1); 6782 SDLoc dl(Op); 6783 6784 // Get the correct type for pointers. 6785 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6786 // Negate the size. 6787 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6788 DAG.getConstant(0, dl, PtrVT), Size); 6789 // Construct a node for the frame pointer save index. 6790 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6791 // Build a DYNALLOC node. 6792 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6793 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6794 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6795 } 6796 6797 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6798 SelectionDAG &DAG) const { 6799 MachineFunction &MF = DAG.getMachineFunction(); 6800 6801 bool isPPC64 = Subtarget.isPPC64(); 6802 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6803 6804 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6805 return DAG.getFrameIndex(FI, PtrVT); 6806 } 6807 6808 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6809 SelectionDAG &DAG) const { 6810 SDLoc DL(Op); 6811 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6812 DAG.getVTList(MVT::i32, MVT::Other), 6813 Op.getOperand(0), Op.getOperand(1)); 6814 } 6815 6816 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6817 SelectionDAG &DAG) const { 6818 SDLoc DL(Op); 6819 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6820 Op.getOperand(0), Op.getOperand(1)); 6821 } 6822 6823 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6824 if (Op.getValueType().isVector()) 6825 return LowerVectorLoad(Op, DAG); 6826 6827 assert(Op.getValueType() == MVT::i1 && 6828 "Custom lowering only for i1 loads"); 6829 6830 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6831 6832 SDLoc dl(Op); 6833 LoadSDNode *LD = cast<LoadSDNode>(Op); 6834 6835 SDValue Chain = LD->getChain(); 6836 SDValue BasePtr = LD->getBasePtr(); 6837 MachineMemOperand *MMO = LD->getMemOperand(); 6838 6839 SDValue NewLD = 6840 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6841 BasePtr, MVT::i8, MMO); 6842 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6843 6844 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6845 return DAG.getMergeValues(Ops, dl); 6846 } 6847 6848 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6849 if (Op.getOperand(1).getValueType().isVector()) 6850 return LowerVectorStore(Op, DAG); 6851 6852 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6853 "Custom lowering only for i1 stores"); 6854 6855 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6856 6857 SDLoc dl(Op); 6858 StoreSDNode *ST = cast<StoreSDNode>(Op); 6859 6860 SDValue Chain = ST->getChain(); 6861 SDValue BasePtr = ST->getBasePtr(); 6862 SDValue Value = ST->getValue(); 6863 MachineMemOperand *MMO = ST->getMemOperand(); 6864 6865 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6866 Value); 6867 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6868 } 6869 6870 // FIXME: Remove this once the ANDI glue bug is fixed: 6871 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6872 assert(Op.getValueType() == MVT::i1 && 6873 "Custom lowering only for i1 results"); 6874 6875 SDLoc DL(Op); 6876 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6877 Op.getOperand(0)); 6878 } 6879 6880 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6881 /// possible. 6882 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6883 // Not FP? Not a fsel. 6884 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6885 !Op.getOperand(2).getValueType().isFloatingPoint()) 6886 return Op; 6887 6888 // We might be able to do better than this under some circumstances, but in 6889 // general, fsel-based lowering of select is a finite-math-only optimization. 6890 // For more information, see section F.3 of the 2.06 ISA specification. 6891 if (!DAG.getTarget().Options.NoInfsFPMath || 6892 !DAG.getTarget().Options.NoNaNsFPMath) 6893 return Op; 6894 // TODO: Propagate flags from the select rather than global settings. 6895 SDNodeFlags Flags; 6896 Flags.setNoInfs(true); 6897 Flags.setNoNaNs(true); 6898 6899 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6900 6901 EVT ResVT = Op.getValueType(); 6902 EVT CmpVT = Op.getOperand(0).getValueType(); 6903 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6904 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6905 SDLoc dl(Op); 6906 6907 // If the RHS of the comparison is a 0.0, we don't need to do the 6908 // subtraction at all. 6909 SDValue Sel1; 6910 if (isFloatingPointZero(RHS)) 6911 switch (CC) { 6912 default: break; // SETUO etc aren't handled by fsel. 6913 case ISD::SETNE: 6914 std::swap(TV, FV); 6915 LLVM_FALLTHROUGH; 6916 case ISD::SETEQ: 6917 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6918 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6919 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6920 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6921 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6922 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6923 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6924 case ISD::SETULT: 6925 case ISD::SETLT: 6926 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6927 LLVM_FALLTHROUGH; 6928 case ISD::SETOGE: 6929 case ISD::SETGE: 6930 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6931 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6932 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6933 case ISD::SETUGT: 6934 case ISD::SETGT: 6935 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6936 LLVM_FALLTHROUGH; 6937 case ISD::SETOLE: 6938 case ISD::SETLE: 6939 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6940 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6941 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6942 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6943 } 6944 6945 SDValue Cmp; 6946 switch (CC) { 6947 default: break; // SETUO etc aren't handled by fsel. 6948 case ISD::SETNE: 6949 std::swap(TV, FV); 6950 LLVM_FALLTHROUGH; 6951 case ISD::SETEQ: 6952 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6953 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6954 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6955 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6956 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6957 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6958 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6959 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6960 case ISD::SETULT: 6961 case ISD::SETLT: 6962 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6963 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6964 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6965 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6966 case ISD::SETOGE: 6967 case ISD::SETGE: 6968 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6969 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6970 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6971 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6972 case ISD::SETUGT: 6973 case ISD::SETGT: 6974 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6975 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6976 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6977 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6978 case ISD::SETOLE: 6979 case ISD::SETLE: 6980 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6981 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6982 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6983 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6984 } 6985 return Op; 6986 } 6987 6988 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 6989 SelectionDAG &DAG, 6990 const SDLoc &dl) const { 6991 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6992 SDValue Src = Op.getOperand(0); 6993 if (Src.getValueType() == MVT::f32) 6994 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6995 6996 SDValue Tmp; 6997 switch (Op.getSimpleValueType().SimpleTy) { 6998 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6999 case MVT::i32: 7000 Tmp = DAG.getNode( 7001 Op.getOpcode() == ISD::FP_TO_SINT 7002 ? PPCISD::FCTIWZ 7003 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7004 dl, MVT::f64, Src); 7005 break; 7006 case MVT::i64: 7007 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7008 "i64 FP_TO_UINT is supported only with FPCVT"); 7009 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7010 PPCISD::FCTIDUZ, 7011 dl, MVT::f64, Src); 7012 break; 7013 } 7014 7015 // Convert the FP value to an int value through memory. 7016 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7017 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7018 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7019 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7020 MachinePointerInfo MPI = 7021 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7022 7023 // Emit a store to the stack slot. 7024 SDValue Chain; 7025 if (i32Stack) { 7026 MachineFunction &MF = DAG.getMachineFunction(); 7027 MachineMemOperand *MMO = 7028 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7029 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7030 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7031 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7032 } else 7033 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7034 7035 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7036 // add in a bias on big endian. 7037 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7038 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7039 DAG.getConstant(4, dl, FIPtr.getValueType())); 7040 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7041 } 7042 7043 RLI.Chain = Chain; 7044 RLI.Ptr = FIPtr; 7045 RLI.MPI = MPI; 7046 } 7047 7048 /// Custom lowers floating point to integer conversions to use 7049 /// the direct move instructions available in ISA 2.07 to avoid the 7050 /// need for load/store combinations. 7051 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7052 SelectionDAG &DAG, 7053 const SDLoc &dl) const { 7054 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7055 SDValue Src = Op.getOperand(0); 7056 7057 if (Src.getValueType() == MVT::f32) 7058 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7059 7060 SDValue Tmp; 7061 switch (Op.getSimpleValueType().SimpleTy) { 7062 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7063 case MVT::i32: 7064 Tmp = DAG.getNode( 7065 Op.getOpcode() == ISD::FP_TO_SINT 7066 ? PPCISD::FCTIWZ 7067 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7068 dl, MVT::f64, Src); 7069 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7070 break; 7071 case MVT::i64: 7072 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7073 "i64 FP_TO_UINT is supported only with FPCVT"); 7074 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7075 PPCISD::FCTIDUZ, 7076 dl, MVT::f64, Src); 7077 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7078 break; 7079 } 7080 return Tmp; 7081 } 7082 7083 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7084 const SDLoc &dl) const { 7085 7086 // FP to INT conversions are legal for f128. 7087 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7088 return Op; 7089 7090 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7091 // PPC (the libcall is not available). 7092 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7093 if (Op.getValueType() == MVT::i32) { 7094 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7095 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7096 MVT::f64, Op.getOperand(0), 7097 DAG.getIntPtrConstant(0, dl)); 7098 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7099 MVT::f64, Op.getOperand(0), 7100 DAG.getIntPtrConstant(1, dl)); 7101 7102 // Add the two halves of the long double in round-to-zero mode. 7103 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7104 7105 // Now use a smaller FP_TO_SINT. 7106 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7107 } 7108 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7109 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7110 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7111 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7112 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7113 // FIXME: generated code sucks. 7114 // TODO: Are there fast-math-flags to propagate to this FSUB? 7115 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7116 Op.getOperand(0), Tmp); 7117 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7118 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7119 DAG.getConstant(0x80000000, dl, MVT::i32)); 7120 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7121 Op.getOperand(0)); 7122 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7123 ISD::SETGE); 7124 } 7125 } 7126 7127 return SDValue(); 7128 } 7129 7130 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7131 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7132 7133 ReuseLoadInfo RLI; 7134 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7135 7136 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7137 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7138 } 7139 7140 // We're trying to insert a regular store, S, and then a load, L. If the 7141 // incoming value, O, is a load, we might just be able to have our load use the 7142 // address used by O. However, we don't know if anything else will store to 7143 // that address before we can load from it. To prevent this situation, we need 7144 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7145 // the same chain operand as O, we create a token factor from the chain results 7146 // of O and L, and we replace all uses of O's chain result with that token 7147 // factor (see spliceIntoChain below for this last part). 7148 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7149 ReuseLoadInfo &RLI, 7150 SelectionDAG &DAG, 7151 ISD::LoadExtType ET) const { 7152 SDLoc dl(Op); 7153 if (ET == ISD::NON_EXTLOAD && 7154 (Op.getOpcode() == ISD::FP_TO_UINT || 7155 Op.getOpcode() == ISD::FP_TO_SINT) && 7156 isOperationLegalOrCustom(Op.getOpcode(), 7157 Op.getOperand(0).getValueType())) { 7158 7159 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7160 return true; 7161 } 7162 7163 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7164 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7165 LD->isNonTemporal()) 7166 return false; 7167 if (LD->getMemoryVT() != MemVT) 7168 return false; 7169 7170 RLI.Ptr = LD->getBasePtr(); 7171 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7172 assert(LD->getAddressingMode() == ISD::PRE_INC && 7173 "Non-pre-inc AM on PPC?"); 7174 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7175 LD->getOffset()); 7176 } 7177 7178 RLI.Chain = LD->getChain(); 7179 RLI.MPI = LD->getPointerInfo(); 7180 RLI.IsDereferenceable = LD->isDereferenceable(); 7181 RLI.IsInvariant = LD->isInvariant(); 7182 RLI.Alignment = LD->getAlignment(); 7183 RLI.AAInfo = LD->getAAInfo(); 7184 RLI.Ranges = LD->getRanges(); 7185 7186 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7187 return true; 7188 } 7189 7190 // Given the head of the old chain, ResChain, insert a token factor containing 7191 // it and NewResChain, and make users of ResChain now be users of that token 7192 // factor. 7193 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7194 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7195 SDValue NewResChain, 7196 SelectionDAG &DAG) const { 7197 if (!ResChain) 7198 return; 7199 7200 SDLoc dl(NewResChain); 7201 7202 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7203 NewResChain, DAG.getUNDEF(MVT::Other)); 7204 assert(TF.getNode() != NewResChain.getNode() && 7205 "A new TF really is required here"); 7206 7207 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7208 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7209 } 7210 7211 /// Analyze profitability of direct move 7212 /// prefer float load to int load plus direct move 7213 /// when there is no integer use of int load 7214 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7215 SDNode *Origin = Op.getOperand(0).getNode(); 7216 if (Origin->getOpcode() != ISD::LOAD) 7217 return true; 7218 7219 // If there is no LXSIBZX/LXSIHZX, like Power8, 7220 // prefer direct move if the memory size is 1 or 2 bytes. 7221 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7222 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7223 return true; 7224 7225 for (SDNode::use_iterator UI = Origin->use_begin(), 7226 UE = Origin->use_end(); 7227 UI != UE; ++UI) { 7228 7229 // Only look at the users of the loaded value. 7230 if (UI.getUse().get().getResNo() != 0) 7231 continue; 7232 7233 if (UI->getOpcode() != ISD::SINT_TO_FP && 7234 UI->getOpcode() != ISD::UINT_TO_FP) 7235 return true; 7236 } 7237 7238 return false; 7239 } 7240 7241 /// Custom lowers integer to floating point conversions to use 7242 /// the direct move instructions available in ISA 2.07 to avoid the 7243 /// need for load/store combinations. 7244 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7245 SelectionDAG &DAG, 7246 const SDLoc &dl) const { 7247 assert((Op.getValueType() == MVT::f32 || 7248 Op.getValueType() == MVT::f64) && 7249 "Invalid floating point type as target of conversion"); 7250 assert(Subtarget.hasFPCVT() && 7251 "Int to FP conversions with direct moves require FPCVT"); 7252 SDValue FP; 7253 SDValue Src = Op.getOperand(0); 7254 bool SinglePrec = Op.getValueType() == MVT::f32; 7255 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7256 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7257 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7258 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7259 7260 if (WordInt) { 7261 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7262 dl, MVT::f64, Src); 7263 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7264 } 7265 else { 7266 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7267 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7268 } 7269 7270 return FP; 7271 } 7272 7273 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7274 7275 EVT VecVT = Vec.getValueType(); 7276 assert(VecVT.isVector() && "Expected a vector type."); 7277 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7278 7279 EVT EltVT = VecVT.getVectorElementType(); 7280 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7281 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7282 7283 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7284 SmallVector<SDValue, 16> Ops(NumConcat); 7285 Ops[0] = Vec; 7286 SDValue UndefVec = DAG.getUNDEF(VecVT); 7287 for (unsigned i = 1; i < NumConcat; ++i) 7288 Ops[i] = UndefVec; 7289 7290 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7291 } 7292 7293 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, 7294 SelectionDAG &DAG, 7295 const SDLoc &dl) const { 7296 7297 unsigned Opc = Op.getOpcode(); 7298 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7299 "Unexpected conversion type"); 7300 assert(Op.getValueType() == MVT::v2f64 && "Supports v2f64 only."); 7301 7302 // CPU's prior to P9 don't have a way to sign-extend in vectors. 7303 bool SignedConv = Opc == ISD::SINT_TO_FP; 7304 if (SignedConv && !Subtarget.hasP9Altivec()) 7305 return SDValue(); 7306 7307 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7308 EVT WideVT = Wide.getValueType(); 7309 unsigned WideNumElts = WideVT.getVectorNumElements(); 7310 7311 SmallVector<int, 16> ShuffV; 7312 for (unsigned i = 0; i < WideNumElts; ++i) 7313 ShuffV.push_back(i + WideNumElts); 7314 7315 if (Subtarget.isLittleEndian()) { 7316 ShuffV[0] = 0; 7317 ShuffV[WideNumElts / 2] = 1; 7318 } 7319 else { 7320 ShuffV[WideNumElts / 2 - 1] = 0; 7321 ShuffV[WideNumElts - 1] = 1; 7322 } 7323 7324 SDValue ShuffleSrc2 = SignedConv ? DAG.getUNDEF(WideVT) : 7325 DAG.getConstant(0, dl, WideVT); 7326 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7327 unsigned ExtendOp = SignedConv ? (unsigned) PPCISD::SExtVElems : 7328 (unsigned) ISD::BITCAST; 7329 SDValue Extend = DAG.getNode(ExtendOp, dl, MVT::v2i64, Arrange); 7330 7331 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7332 } 7333 7334 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7335 SelectionDAG &DAG) const { 7336 SDLoc dl(Op); 7337 7338 if (Op.getValueType() == MVT::v2f64 && 7339 Op.getOperand(0).getValueType() == MVT::v2i16) 7340 return LowerINT_TO_FPVector(Op, DAG, dl); 7341 7342 // Conversions to f128 are legal. 7343 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7344 return Op; 7345 7346 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7347 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7348 return SDValue(); 7349 7350 SDValue Value = Op.getOperand(0); 7351 // The values are now known to be -1 (false) or 1 (true). To convert this 7352 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7353 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7354 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7355 7356 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7357 7358 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7359 7360 if (Op.getValueType() != MVT::v4f64) 7361 Value = DAG.getNode(ISD::FP_ROUND, dl, 7362 Op.getValueType(), Value, 7363 DAG.getIntPtrConstant(1, dl)); 7364 return Value; 7365 } 7366 7367 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7368 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7369 return SDValue(); 7370 7371 if (Op.getOperand(0).getValueType() == MVT::i1) 7372 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7373 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7374 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7375 7376 // If we have direct moves, we can do all the conversion, skip the store/load 7377 // however, without FPCVT we can't do most conversions. 7378 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7379 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7380 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7381 7382 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7383 "UINT_TO_FP is supported only with FPCVT"); 7384 7385 // If we have FCFIDS, then use it when converting to single-precision. 7386 // Otherwise, convert to double-precision and then round. 7387 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7388 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7389 : PPCISD::FCFIDS) 7390 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7391 : PPCISD::FCFID); 7392 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7393 ? MVT::f32 7394 : MVT::f64; 7395 7396 if (Op.getOperand(0).getValueType() == MVT::i64) { 7397 SDValue SINT = Op.getOperand(0); 7398 // When converting to single-precision, we actually need to convert 7399 // to double-precision first and then round to single-precision. 7400 // To avoid double-rounding effects during that operation, we have 7401 // to prepare the input operand. Bits that might be truncated when 7402 // converting to double-precision are replaced by a bit that won't 7403 // be lost at this stage, but is below the single-precision rounding 7404 // position. 7405 // 7406 // However, if -enable-unsafe-fp-math is in effect, accept double 7407 // rounding to avoid the extra overhead. 7408 if (Op.getValueType() == MVT::f32 && 7409 !Subtarget.hasFPCVT() && 7410 !DAG.getTarget().Options.UnsafeFPMath) { 7411 7412 // Twiddle input to make sure the low 11 bits are zero. (If this 7413 // is the case, we are guaranteed the value will fit into the 53 bit 7414 // mantissa of an IEEE double-precision value without rounding.) 7415 // If any of those low 11 bits were not zero originally, make sure 7416 // bit 12 (value 2048) is set instead, so that the final rounding 7417 // to single-precision gets the correct result. 7418 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7419 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7420 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7421 Round, DAG.getConstant(2047, dl, MVT::i64)); 7422 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7423 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7424 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7425 7426 // However, we cannot use that value unconditionally: if the magnitude 7427 // of the input value is small, the bit-twiddling we did above might 7428 // end up visibly changing the output. Fortunately, in that case, we 7429 // don't need to twiddle bits since the original input will convert 7430 // exactly to double-precision floating-point already. Therefore, 7431 // construct a conditional to use the original value if the top 11 7432 // bits are all sign-bit copies, and use the rounded value computed 7433 // above otherwise. 7434 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7435 SINT, DAG.getConstant(53, dl, MVT::i32)); 7436 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7437 Cond, DAG.getConstant(1, dl, MVT::i64)); 7438 Cond = DAG.getSetCC(dl, MVT::i32, 7439 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7440 7441 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7442 } 7443 7444 ReuseLoadInfo RLI; 7445 SDValue Bits; 7446 7447 MachineFunction &MF = DAG.getMachineFunction(); 7448 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7449 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7450 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7451 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7452 } else if (Subtarget.hasLFIWAX() && 7453 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7454 MachineMemOperand *MMO = 7455 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7456 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7457 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7458 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7459 DAG.getVTList(MVT::f64, MVT::Other), 7460 Ops, MVT::i32, MMO); 7461 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7462 } else if (Subtarget.hasFPCVT() && 7463 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7464 MachineMemOperand *MMO = 7465 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7466 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7467 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7468 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7469 DAG.getVTList(MVT::f64, MVT::Other), 7470 Ops, MVT::i32, MMO); 7471 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7472 } else if (((Subtarget.hasLFIWAX() && 7473 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7474 (Subtarget.hasFPCVT() && 7475 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7476 SINT.getOperand(0).getValueType() == MVT::i32) { 7477 MachineFrameInfo &MFI = MF.getFrameInfo(); 7478 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7479 7480 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7481 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7482 7483 SDValue Store = 7484 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7485 MachinePointerInfo::getFixedStack( 7486 DAG.getMachineFunction(), FrameIdx)); 7487 7488 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7489 "Expected an i32 store"); 7490 7491 RLI.Ptr = FIdx; 7492 RLI.Chain = Store; 7493 RLI.MPI = 7494 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7495 RLI.Alignment = 4; 7496 7497 MachineMemOperand *MMO = 7498 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7499 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7500 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7501 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7502 PPCISD::LFIWZX : PPCISD::LFIWAX, 7503 dl, DAG.getVTList(MVT::f64, MVT::Other), 7504 Ops, MVT::i32, MMO); 7505 } else 7506 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7507 7508 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7509 7510 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7511 FP = DAG.getNode(ISD::FP_ROUND, dl, 7512 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7513 return FP; 7514 } 7515 7516 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7517 "Unhandled INT_TO_FP type in custom expander!"); 7518 // Since we only generate this in 64-bit mode, we can take advantage of 7519 // 64-bit registers. In particular, sign extend the input value into the 7520 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7521 // then lfd it and fcfid it. 7522 MachineFunction &MF = DAG.getMachineFunction(); 7523 MachineFrameInfo &MFI = MF.getFrameInfo(); 7524 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7525 7526 SDValue Ld; 7527 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7528 ReuseLoadInfo RLI; 7529 bool ReusingLoad; 7530 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7531 DAG))) { 7532 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7533 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7534 7535 SDValue Store = 7536 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7537 MachinePointerInfo::getFixedStack( 7538 DAG.getMachineFunction(), FrameIdx)); 7539 7540 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7541 "Expected an i32 store"); 7542 7543 RLI.Ptr = FIdx; 7544 RLI.Chain = Store; 7545 RLI.MPI = 7546 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7547 RLI.Alignment = 4; 7548 } 7549 7550 MachineMemOperand *MMO = 7551 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7552 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7553 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7554 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7555 PPCISD::LFIWZX : PPCISD::LFIWAX, 7556 dl, DAG.getVTList(MVT::f64, MVT::Other), 7557 Ops, MVT::i32, MMO); 7558 if (ReusingLoad) 7559 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7560 } else { 7561 assert(Subtarget.isPPC64() && 7562 "i32->FP without LFIWAX supported only on PPC64"); 7563 7564 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7565 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7566 7567 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7568 Op.getOperand(0)); 7569 7570 // STD the extended value into the stack slot. 7571 SDValue Store = DAG.getStore( 7572 DAG.getEntryNode(), dl, Ext64, FIdx, 7573 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7574 7575 // Load the value as a double. 7576 Ld = DAG.getLoad( 7577 MVT::f64, dl, Store, FIdx, 7578 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7579 } 7580 7581 // FCFID it and return it. 7582 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7583 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7584 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7585 DAG.getIntPtrConstant(0, dl)); 7586 return FP; 7587 } 7588 7589 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7590 SelectionDAG &DAG) const { 7591 SDLoc dl(Op); 7592 /* 7593 The rounding mode is in bits 30:31 of FPSR, and has the following 7594 settings: 7595 00 Round to nearest 7596 01 Round to 0 7597 10 Round to +inf 7598 11 Round to -inf 7599 7600 FLT_ROUNDS, on the other hand, expects the following: 7601 -1 Undefined 7602 0 Round to 0 7603 1 Round to nearest 7604 2 Round to +inf 7605 3 Round to -inf 7606 7607 To perform the conversion, we do: 7608 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7609 */ 7610 7611 MachineFunction &MF = DAG.getMachineFunction(); 7612 EVT VT = Op.getValueType(); 7613 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7614 7615 // Save FP Control Word to register 7616 EVT NodeTys[] = { 7617 MVT::f64, // return register 7618 MVT::Glue // unused in this context 7619 }; 7620 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7621 7622 // Save FP register to stack slot 7623 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7624 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7625 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7626 MachinePointerInfo()); 7627 7628 // Load FP Control Word from low 32 bits of stack slot. 7629 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7630 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7631 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7632 7633 // Transform as necessary 7634 SDValue CWD1 = 7635 DAG.getNode(ISD::AND, dl, MVT::i32, 7636 CWD, DAG.getConstant(3, dl, MVT::i32)); 7637 SDValue CWD2 = 7638 DAG.getNode(ISD::SRL, dl, MVT::i32, 7639 DAG.getNode(ISD::AND, dl, MVT::i32, 7640 DAG.getNode(ISD::XOR, dl, MVT::i32, 7641 CWD, DAG.getConstant(3, dl, MVT::i32)), 7642 DAG.getConstant(3, dl, MVT::i32)), 7643 DAG.getConstant(1, dl, MVT::i32)); 7644 7645 SDValue RetVal = 7646 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7647 7648 return DAG.getNode((VT.getSizeInBits() < 16 ? 7649 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7650 } 7651 7652 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7653 EVT VT = Op.getValueType(); 7654 unsigned BitWidth = VT.getSizeInBits(); 7655 SDLoc dl(Op); 7656 assert(Op.getNumOperands() == 3 && 7657 VT == Op.getOperand(1).getValueType() && 7658 "Unexpected SHL!"); 7659 7660 // Expand into a bunch of logical ops. Note that these ops 7661 // depend on the PPC behavior for oversized shift amounts. 7662 SDValue Lo = Op.getOperand(0); 7663 SDValue Hi = Op.getOperand(1); 7664 SDValue Amt = Op.getOperand(2); 7665 EVT AmtVT = Amt.getValueType(); 7666 7667 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7668 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7669 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7670 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7671 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7672 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7673 DAG.getConstant(-BitWidth, dl, AmtVT)); 7674 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7675 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7676 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7677 SDValue OutOps[] = { OutLo, OutHi }; 7678 return DAG.getMergeValues(OutOps, dl); 7679 } 7680 7681 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7682 EVT VT = Op.getValueType(); 7683 SDLoc dl(Op); 7684 unsigned BitWidth = VT.getSizeInBits(); 7685 assert(Op.getNumOperands() == 3 && 7686 VT == Op.getOperand(1).getValueType() && 7687 "Unexpected SRL!"); 7688 7689 // Expand into a bunch of logical ops. Note that these ops 7690 // depend on the PPC behavior for oversized shift amounts. 7691 SDValue Lo = Op.getOperand(0); 7692 SDValue Hi = Op.getOperand(1); 7693 SDValue Amt = Op.getOperand(2); 7694 EVT AmtVT = Amt.getValueType(); 7695 7696 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7697 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7698 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7699 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7700 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7701 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7702 DAG.getConstant(-BitWidth, dl, AmtVT)); 7703 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7704 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7705 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7706 SDValue OutOps[] = { OutLo, OutHi }; 7707 return DAG.getMergeValues(OutOps, dl); 7708 } 7709 7710 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7711 SDLoc dl(Op); 7712 EVT VT = Op.getValueType(); 7713 unsigned BitWidth = VT.getSizeInBits(); 7714 assert(Op.getNumOperands() == 3 && 7715 VT == Op.getOperand(1).getValueType() && 7716 "Unexpected SRA!"); 7717 7718 // Expand into a bunch of logical ops, followed by a select_cc. 7719 SDValue Lo = Op.getOperand(0); 7720 SDValue Hi = Op.getOperand(1); 7721 SDValue Amt = Op.getOperand(2); 7722 EVT AmtVT = Amt.getValueType(); 7723 7724 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7725 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7726 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7727 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7728 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7729 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7730 DAG.getConstant(-BitWidth, dl, AmtVT)); 7731 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7732 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7733 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7734 Tmp4, Tmp6, ISD::SETLE); 7735 SDValue OutOps[] = { OutLo, OutHi }; 7736 return DAG.getMergeValues(OutOps, dl); 7737 } 7738 7739 //===----------------------------------------------------------------------===// 7740 // Vector related lowering. 7741 // 7742 7743 /// BuildSplatI - Build a canonical splati of Val with an element size of 7744 /// SplatSize. Cast the result to VT. 7745 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7746 SelectionDAG &DAG, const SDLoc &dl) { 7747 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7748 7749 static const MVT VTys[] = { // canonical VT to use for each size. 7750 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7751 }; 7752 7753 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7754 7755 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7756 if (Val == -1) 7757 SplatSize = 1; 7758 7759 EVT CanonicalVT = VTys[SplatSize-1]; 7760 7761 // Build a canonical splat for this value. 7762 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7763 } 7764 7765 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7766 /// specified intrinsic ID. 7767 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7768 const SDLoc &dl, EVT DestVT = MVT::Other) { 7769 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7770 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7771 DAG.getConstant(IID, dl, MVT::i32), Op); 7772 } 7773 7774 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7775 /// specified intrinsic ID. 7776 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7777 SelectionDAG &DAG, const SDLoc &dl, 7778 EVT DestVT = MVT::Other) { 7779 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7780 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7781 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7782 } 7783 7784 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7785 /// specified intrinsic ID. 7786 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7787 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7788 EVT DestVT = MVT::Other) { 7789 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7790 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7791 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7792 } 7793 7794 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7795 /// amount. The result has the specified value type. 7796 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7797 SelectionDAG &DAG, const SDLoc &dl) { 7798 // Force LHS/RHS to be the right type. 7799 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7800 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7801 7802 int Ops[16]; 7803 for (unsigned i = 0; i != 16; ++i) 7804 Ops[i] = i + Amt; 7805 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7806 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7807 } 7808 7809 /// Do we have an efficient pattern in a .td file for this node? 7810 /// 7811 /// \param V - pointer to the BuildVectorSDNode being matched 7812 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7813 /// 7814 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7815 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7816 /// the opposite is true (expansion is beneficial) are: 7817 /// - The node builds a vector out of integers that are not 32 or 64-bits 7818 /// - The node builds a vector out of constants 7819 /// - The node is a "load-and-splat" 7820 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7821 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7822 bool HasDirectMove, 7823 bool HasP8Vector) { 7824 EVT VecVT = V->getValueType(0); 7825 bool RightType = VecVT == MVT::v2f64 || 7826 (HasP8Vector && VecVT == MVT::v4f32) || 7827 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7828 if (!RightType) 7829 return false; 7830 7831 bool IsSplat = true; 7832 bool IsLoad = false; 7833 SDValue Op0 = V->getOperand(0); 7834 7835 // This function is called in a block that confirms the node is not a constant 7836 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7837 // different constants. 7838 if (V->isConstant()) 7839 return false; 7840 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7841 if (V->getOperand(i).isUndef()) 7842 return false; 7843 // We want to expand nodes that represent load-and-splat even if the 7844 // loaded value is a floating point truncation or conversion to int. 7845 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7846 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7847 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7848 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7849 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7850 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7851 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7852 IsLoad = true; 7853 // If the operands are different or the input is not a load and has more 7854 // uses than just this BV node, then it isn't a splat. 7855 if (V->getOperand(i) != Op0 || 7856 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7857 IsSplat = false; 7858 } 7859 return !(IsSplat && IsLoad); 7860 } 7861 7862 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 7863 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 7864 7865 SDLoc dl(Op); 7866 SDValue Op0 = Op->getOperand(0); 7867 7868 if (!EnableQuadPrecision || 7869 (Op.getValueType() != MVT::f128 ) || 7870 (Op0.getOpcode() != ISD::BUILD_PAIR) || 7871 (Op0.getOperand(0).getValueType() != MVT::i64) || 7872 (Op0.getOperand(1).getValueType() != MVT::i64)) 7873 return SDValue(); 7874 7875 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 7876 Op0.getOperand(1)); 7877 } 7878 7879 // If this is a case we can't handle, return null and let the default 7880 // expansion code take care of it. If we CAN select this case, and if it 7881 // selects to a single instruction, return Op. Otherwise, if we can codegen 7882 // this case more efficiently than a constant pool load, lower it to the 7883 // sequence of ops that should be used. 7884 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7885 SelectionDAG &DAG) const { 7886 SDLoc dl(Op); 7887 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7888 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7889 7890 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7891 // We first build an i32 vector, load it into a QPX register, 7892 // then convert it to a floating-point vector and compare it 7893 // to a zero vector to get the boolean result. 7894 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7895 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7896 MachinePointerInfo PtrInfo = 7897 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7898 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7899 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7900 7901 assert(BVN->getNumOperands() == 4 && 7902 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7903 7904 bool IsConst = true; 7905 for (unsigned i = 0; i < 4; ++i) { 7906 if (BVN->getOperand(i).isUndef()) continue; 7907 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7908 IsConst = false; 7909 break; 7910 } 7911 } 7912 7913 if (IsConst) { 7914 Constant *One = 7915 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7916 Constant *NegOne = 7917 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7918 7919 Constant *CV[4]; 7920 for (unsigned i = 0; i < 4; ++i) { 7921 if (BVN->getOperand(i).isUndef()) 7922 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7923 else if (isNullConstant(BVN->getOperand(i))) 7924 CV[i] = NegOne; 7925 else 7926 CV[i] = One; 7927 } 7928 7929 Constant *CP = ConstantVector::get(CV); 7930 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7931 16 /* alignment */); 7932 7933 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7934 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7935 return DAG.getMemIntrinsicNode( 7936 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7937 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7938 } 7939 7940 SmallVector<SDValue, 4> Stores; 7941 for (unsigned i = 0; i < 4; ++i) { 7942 if (BVN->getOperand(i).isUndef()) continue; 7943 7944 unsigned Offset = 4*i; 7945 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7946 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7947 7948 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7949 if (StoreSize > 4) { 7950 Stores.push_back( 7951 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7952 PtrInfo.getWithOffset(Offset), MVT::i32)); 7953 } else { 7954 SDValue StoreValue = BVN->getOperand(i); 7955 if (StoreSize < 4) 7956 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7957 7958 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7959 PtrInfo.getWithOffset(Offset))); 7960 } 7961 } 7962 7963 SDValue StoreChain; 7964 if (!Stores.empty()) 7965 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7966 else 7967 StoreChain = DAG.getEntryNode(); 7968 7969 // Now load from v4i32 into the QPX register; this will extend it to 7970 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7971 // is typed as v4f64 because the QPX register integer states are not 7972 // explicitly represented. 7973 7974 SDValue Ops[] = {StoreChain, 7975 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7976 FIdx}; 7977 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7978 7979 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 7980 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7981 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7982 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 7983 LoadedVect); 7984 7985 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 7986 7987 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 7988 } 7989 7990 // All other QPX vectors are handled by generic code. 7991 if (Subtarget.hasQPX()) 7992 return SDValue(); 7993 7994 // Check if this is a splat of a constant value. 7995 APInt APSplatBits, APSplatUndef; 7996 unsigned SplatBitSize; 7997 bool HasAnyUndefs; 7998 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 7999 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8000 SplatBitSize > 32) { 8001 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8002 // lowered to VSX instructions under certain conditions. 8003 // Without VSX, there is no pattern more efficient than expanding the node. 8004 if (Subtarget.hasVSX() && 8005 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8006 Subtarget.hasP8Vector())) 8007 return Op; 8008 return SDValue(); 8009 } 8010 8011 unsigned SplatBits = APSplatBits.getZExtValue(); 8012 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8013 unsigned SplatSize = SplatBitSize / 8; 8014 8015 // First, handle single instruction cases. 8016 8017 // All zeros? 8018 if (SplatBits == 0) { 8019 // Canonicalize all zero vectors to be v4i32. 8020 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8021 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8022 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8023 } 8024 return Op; 8025 } 8026 8027 // We have XXSPLTIB for constant splats one byte wide 8028 if (Subtarget.hasP9Vector() && SplatSize == 1) { 8029 // This is a splat of 1-byte elements with some elements potentially undef. 8030 // Rather than trying to match undef in the SDAG patterns, ensure that all 8031 // elements are the same constant. 8032 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 8033 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 8034 dl, MVT::i32)); 8035 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 8036 if (Op.getValueType() != MVT::v16i8) 8037 return DAG.getBitcast(Op.getValueType(), NewBV); 8038 return NewBV; 8039 } 8040 8041 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 8042 // detect that constant splats like v8i16: 0xABAB are really just splats 8043 // of a 1-byte constant. In this case, we need to convert the node to a 8044 // splat of v16i8 and a bitcast. 8045 if (Op.getValueType() != MVT::v16i8) 8046 return DAG.getBitcast(Op.getValueType(), 8047 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 8048 8049 return Op; 8050 } 8051 8052 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8053 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8054 (32-SplatBitSize)); 8055 if (SextVal >= -16 && SextVal <= 15) 8056 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8057 8058 // Two instruction sequences. 8059 8060 // If this value is in the range [-32,30] and is even, use: 8061 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8062 // If this value is in the range [17,31] and is odd, use: 8063 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8064 // If this value is in the range [-31,-17] and is odd, use: 8065 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8066 // Note the last two are three-instruction sequences. 8067 if (SextVal >= -32 && SextVal <= 31) { 8068 // To avoid having these optimizations undone by constant folding, 8069 // we convert to a pseudo that will be expanded later into one of 8070 // the above forms. 8071 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8072 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8073 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8074 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8075 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8076 if (VT == Op.getValueType()) 8077 return RetVal; 8078 else 8079 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8080 } 8081 8082 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8083 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8084 // for fneg/fabs. 8085 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8086 // Make -1 and vspltisw -1: 8087 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8088 8089 // Make the VSLW intrinsic, computing 0x8000_0000. 8090 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8091 OnesV, DAG, dl); 8092 8093 // xor by OnesV to invert it. 8094 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8095 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8096 } 8097 8098 // Check to see if this is a wide variety of vsplti*, binop self cases. 8099 static const signed char SplatCsts[] = { 8100 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8101 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8102 }; 8103 8104 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8105 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8106 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8107 int i = SplatCsts[idx]; 8108 8109 // Figure out what shift amount will be used by altivec if shifted by i in 8110 // this splat size. 8111 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8112 8113 // vsplti + shl self. 8114 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8115 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8116 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8117 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8118 Intrinsic::ppc_altivec_vslw 8119 }; 8120 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8121 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8122 } 8123 8124 // vsplti + srl self. 8125 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8126 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8127 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8128 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8129 Intrinsic::ppc_altivec_vsrw 8130 }; 8131 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8132 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8133 } 8134 8135 // vsplti + sra self. 8136 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8137 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8138 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8139 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8140 Intrinsic::ppc_altivec_vsraw 8141 }; 8142 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8143 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8144 } 8145 8146 // vsplti + rol self. 8147 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8148 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8149 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8150 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8151 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8152 Intrinsic::ppc_altivec_vrlw 8153 }; 8154 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8155 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8156 } 8157 8158 // t = vsplti c, result = vsldoi t, t, 1 8159 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8160 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8161 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8162 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8163 } 8164 // t = vsplti c, result = vsldoi t, t, 2 8165 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8166 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8167 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8168 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8169 } 8170 // t = vsplti c, result = vsldoi t, t, 3 8171 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8172 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8173 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8174 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8175 } 8176 } 8177 8178 return SDValue(); 8179 } 8180 8181 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8182 /// the specified operations to build the shuffle. 8183 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8184 SDValue RHS, SelectionDAG &DAG, 8185 const SDLoc &dl) { 8186 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8187 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8188 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8189 8190 enum { 8191 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8192 OP_VMRGHW, 8193 OP_VMRGLW, 8194 OP_VSPLTISW0, 8195 OP_VSPLTISW1, 8196 OP_VSPLTISW2, 8197 OP_VSPLTISW3, 8198 OP_VSLDOI4, 8199 OP_VSLDOI8, 8200 OP_VSLDOI12 8201 }; 8202 8203 if (OpNum == OP_COPY) { 8204 if (LHSID == (1*9+2)*9+3) return LHS; 8205 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8206 return RHS; 8207 } 8208 8209 SDValue OpLHS, OpRHS; 8210 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8211 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8212 8213 int ShufIdxs[16]; 8214 switch (OpNum) { 8215 default: llvm_unreachable("Unknown i32 permute!"); 8216 case OP_VMRGHW: 8217 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8218 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8219 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8220 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8221 break; 8222 case OP_VMRGLW: 8223 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8224 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8225 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8226 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8227 break; 8228 case OP_VSPLTISW0: 8229 for (unsigned i = 0; i != 16; ++i) 8230 ShufIdxs[i] = (i&3)+0; 8231 break; 8232 case OP_VSPLTISW1: 8233 for (unsigned i = 0; i != 16; ++i) 8234 ShufIdxs[i] = (i&3)+4; 8235 break; 8236 case OP_VSPLTISW2: 8237 for (unsigned i = 0; i != 16; ++i) 8238 ShufIdxs[i] = (i&3)+8; 8239 break; 8240 case OP_VSPLTISW3: 8241 for (unsigned i = 0; i != 16; ++i) 8242 ShufIdxs[i] = (i&3)+12; 8243 break; 8244 case OP_VSLDOI4: 8245 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8246 case OP_VSLDOI8: 8247 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8248 case OP_VSLDOI12: 8249 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8250 } 8251 EVT VT = OpLHS.getValueType(); 8252 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8253 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8254 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8255 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8256 } 8257 8258 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8259 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8260 /// SDValue. 8261 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8262 SelectionDAG &DAG) const { 8263 const unsigned BytesInVector = 16; 8264 bool IsLE = Subtarget.isLittleEndian(); 8265 SDLoc dl(N); 8266 SDValue V1 = N->getOperand(0); 8267 SDValue V2 = N->getOperand(1); 8268 unsigned ShiftElts = 0, InsertAtByte = 0; 8269 bool Swap = false; 8270 8271 // Shifts required to get the byte we want at element 7. 8272 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8273 0, 15, 14, 13, 12, 11, 10, 9}; 8274 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8275 1, 2, 3, 4, 5, 6, 7, 8}; 8276 8277 ArrayRef<int> Mask = N->getMask(); 8278 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8279 8280 // For each mask element, find out if we're just inserting something 8281 // from V2 into V1 or vice versa. 8282 // Possible permutations inserting an element from V2 into V1: 8283 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8284 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8285 // ... 8286 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8287 // Inserting from V1 into V2 will be similar, except mask range will be 8288 // [16,31]. 8289 8290 bool FoundCandidate = false; 8291 // If both vector operands for the shuffle are the same vector, the mask 8292 // will contain only elements from the first one and the second one will be 8293 // undef. 8294 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8295 // Go through the mask of half-words to find an element that's being moved 8296 // from one vector to the other. 8297 for (unsigned i = 0; i < BytesInVector; ++i) { 8298 unsigned CurrentElement = Mask[i]; 8299 // If 2nd operand is undefined, we should only look for element 7 in the 8300 // Mask. 8301 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8302 continue; 8303 8304 bool OtherElementsInOrder = true; 8305 // Examine the other elements in the Mask to see if they're in original 8306 // order. 8307 for (unsigned j = 0; j < BytesInVector; ++j) { 8308 if (j == i) 8309 continue; 8310 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8311 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8312 // in which we always assume we're always picking from the 1st operand. 8313 int MaskOffset = 8314 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8315 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8316 OtherElementsInOrder = false; 8317 break; 8318 } 8319 } 8320 // If other elements are in original order, we record the number of shifts 8321 // we need to get the element we want into element 7. Also record which byte 8322 // in the vector we should insert into. 8323 if (OtherElementsInOrder) { 8324 // If 2nd operand is undefined, we assume no shifts and no swapping. 8325 if (V2.isUndef()) { 8326 ShiftElts = 0; 8327 Swap = false; 8328 } else { 8329 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8330 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8331 : BigEndianShifts[CurrentElement & 0xF]; 8332 Swap = CurrentElement < BytesInVector; 8333 } 8334 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8335 FoundCandidate = true; 8336 break; 8337 } 8338 } 8339 8340 if (!FoundCandidate) 8341 return SDValue(); 8342 8343 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8344 // optionally with VECSHL if shift is required. 8345 if (Swap) 8346 std::swap(V1, V2); 8347 if (V2.isUndef()) 8348 V2 = V1; 8349 if (ShiftElts) { 8350 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8351 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8352 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8353 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8354 } 8355 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8356 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8357 } 8358 8359 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8360 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8361 /// SDValue. 8362 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8363 SelectionDAG &DAG) const { 8364 const unsigned NumHalfWords = 8; 8365 const unsigned BytesInVector = NumHalfWords * 2; 8366 // Check that the shuffle is on half-words. 8367 if (!isNByteElemShuffleMask(N, 2, 1)) 8368 return SDValue(); 8369 8370 bool IsLE = Subtarget.isLittleEndian(); 8371 SDLoc dl(N); 8372 SDValue V1 = N->getOperand(0); 8373 SDValue V2 = N->getOperand(1); 8374 unsigned ShiftElts = 0, InsertAtByte = 0; 8375 bool Swap = false; 8376 8377 // Shifts required to get the half-word we want at element 3. 8378 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8379 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8380 8381 uint32_t Mask = 0; 8382 uint32_t OriginalOrderLow = 0x1234567; 8383 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8384 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8385 // 32-bit space, only need 4-bit nibbles per element. 8386 for (unsigned i = 0; i < NumHalfWords; ++i) { 8387 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8388 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8389 } 8390 8391 // For each mask element, find out if we're just inserting something 8392 // from V2 into V1 or vice versa. Possible permutations inserting an element 8393 // from V2 into V1: 8394 // X, 1, 2, 3, 4, 5, 6, 7 8395 // 0, X, 2, 3, 4, 5, 6, 7 8396 // 0, 1, X, 3, 4, 5, 6, 7 8397 // 0, 1, 2, X, 4, 5, 6, 7 8398 // 0, 1, 2, 3, X, 5, 6, 7 8399 // 0, 1, 2, 3, 4, X, 6, 7 8400 // 0, 1, 2, 3, 4, 5, X, 7 8401 // 0, 1, 2, 3, 4, 5, 6, X 8402 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8403 8404 bool FoundCandidate = false; 8405 // Go through the mask of half-words to find an element that's being moved 8406 // from one vector to the other. 8407 for (unsigned i = 0; i < NumHalfWords; ++i) { 8408 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8409 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8410 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8411 uint32_t TargetOrder = 0x0; 8412 8413 // If both vector operands for the shuffle are the same vector, the mask 8414 // will contain only elements from the first one and the second one will be 8415 // undef. 8416 if (V2.isUndef()) { 8417 ShiftElts = 0; 8418 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8419 TargetOrder = OriginalOrderLow; 8420 Swap = false; 8421 // Skip if not the correct element or mask of other elements don't equal 8422 // to our expected order. 8423 if (MaskOneElt == VINSERTHSrcElem && 8424 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8425 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8426 FoundCandidate = true; 8427 break; 8428 } 8429 } else { // If both operands are defined. 8430 // Target order is [8,15] if the current mask is between [0,7]. 8431 TargetOrder = 8432 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8433 // Skip if mask of other elements don't equal our expected order. 8434 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8435 // We only need the last 3 bits for the number of shifts. 8436 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8437 : BigEndianShifts[MaskOneElt & 0x7]; 8438 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8439 Swap = MaskOneElt < NumHalfWords; 8440 FoundCandidate = true; 8441 break; 8442 } 8443 } 8444 } 8445 8446 if (!FoundCandidate) 8447 return SDValue(); 8448 8449 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8450 // optionally with VECSHL if shift is required. 8451 if (Swap) 8452 std::swap(V1, V2); 8453 if (V2.isUndef()) 8454 V2 = V1; 8455 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8456 if (ShiftElts) { 8457 // Double ShiftElts because we're left shifting on v16i8 type. 8458 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8459 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8460 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8461 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8462 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8463 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8464 } 8465 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8466 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8467 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8468 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8469 } 8470 8471 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8472 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8473 /// return the code it can be lowered into. Worst case, it can always be 8474 /// lowered into a vperm. 8475 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8476 SelectionDAG &DAG) const { 8477 SDLoc dl(Op); 8478 SDValue V1 = Op.getOperand(0); 8479 SDValue V2 = Op.getOperand(1); 8480 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8481 EVT VT = Op.getValueType(); 8482 bool isLittleEndian = Subtarget.isLittleEndian(); 8483 8484 unsigned ShiftElts, InsertAtByte; 8485 bool Swap = false; 8486 if (Subtarget.hasP9Vector() && 8487 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8488 isLittleEndian)) { 8489 if (Swap) 8490 std::swap(V1, V2); 8491 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8492 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8493 if (ShiftElts) { 8494 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8495 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8496 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8497 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8498 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8499 } 8500 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8501 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8502 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8503 } 8504 8505 if (Subtarget.hasP9Altivec()) { 8506 SDValue NewISDNode; 8507 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8508 return NewISDNode; 8509 8510 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8511 return NewISDNode; 8512 } 8513 8514 if (Subtarget.hasVSX() && 8515 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8516 if (Swap) 8517 std::swap(V1, V2); 8518 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8519 SDValue Conv2 = 8520 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8521 8522 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8523 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8524 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8525 } 8526 8527 if (Subtarget.hasVSX() && 8528 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8529 if (Swap) 8530 std::swap(V1, V2); 8531 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8532 SDValue Conv2 = 8533 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8534 8535 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8536 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8537 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8538 } 8539 8540 if (Subtarget.hasP9Vector()) { 8541 if (PPC::isXXBRHShuffleMask(SVOp)) { 8542 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8543 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8544 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8545 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8546 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8547 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8548 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8549 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8550 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8551 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8552 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8553 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8554 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8555 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8556 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8557 } 8558 } 8559 8560 if (Subtarget.hasVSX()) { 8561 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8562 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8563 8564 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8565 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8566 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8567 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8568 } 8569 8570 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8571 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8572 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8573 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8574 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8575 } 8576 } 8577 8578 if (Subtarget.hasQPX()) { 8579 if (VT.getVectorNumElements() != 4) 8580 return SDValue(); 8581 8582 if (V2.isUndef()) V2 = V1; 8583 8584 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8585 if (AlignIdx != -1) { 8586 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8587 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8588 } else if (SVOp->isSplat()) { 8589 int SplatIdx = SVOp->getSplatIndex(); 8590 if (SplatIdx >= 4) { 8591 std::swap(V1, V2); 8592 SplatIdx -= 4; 8593 } 8594 8595 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8596 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8597 } 8598 8599 // Lower this into a qvgpci/qvfperm pair. 8600 8601 // Compute the qvgpci literal 8602 unsigned idx = 0; 8603 for (unsigned i = 0; i < 4; ++i) { 8604 int m = SVOp->getMaskElt(i); 8605 unsigned mm = m >= 0 ? (unsigned) m : i; 8606 idx |= mm << (3-i)*3; 8607 } 8608 8609 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8610 DAG.getConstant(idx, dl, MVT::i32)); 8611 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8612 } 8613 8614 // Cases that are handled by instructions that take permute immediates 8615 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8616 // selected by the instruction selector. 8617 if (V2.isUndef()) { 8618 if (PPC::isSplatShuffleMask(SVOp, 1) || 8619 PPC::isSplatShuffleMask(SVOp, 2) || 8620 PPC::isSplatShuffleMask(SVOp, 4) || 8621 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8622 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8623 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8624 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8625 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8626 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8627 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8628 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8629 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8630 (Subtarget.hasP8Altivec() && ( 8631 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8632 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8633 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8634 return Op; 8635 } 8636 } 8637 8638 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8639 // and produce a fixed permutation. If any of these match, do not lower to 8640 // VPERM. 8641 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8642 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8643 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8644 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8645 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8646 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8647 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8648 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8649 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8650 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8651 (Subtarget.hasP8Altivec() && ( 8652 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8653 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8654 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8655 return Op; 8656 8657 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8658 // perfect shuffle table to emit an optimal matching sequence. 8659 ArrayRef<int> PermMask = SVOp->getMask(); 8660 8661 unsigned PFIndexes[4]; 8662 bool isFourElementShuffle = true; 8663 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8664 unsigned EltNo = 8; // Start out undef. 8665 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8666 if (PermMask[i*4+j] < 0) 8667 continue; // Undef, ignore it. 8668 8669 unsigned ByteSource = PermMask[i*4+j]; 8670 if ((ByteSource & 3) != j) { 8671 isFourElementShuffle = false; 8672 break; 8673 } 8674 8675 if (EltNo == 8) { 8676 EltNo = ByteSource/4; 8677 } else if (EltNo != ByteSource/4) { 8678 isFourElementShuffle = false; 8679 break; 8680 } 8681 } 8682 PFIndexes[i] = EltNo; 8683 } 8684 8685 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8686 // perfect shuffle vector to determine if it is cost effective to do this as 8687 // discrete instructions, or whether we should use a vperm. 8688 // For now, we skip this for little endian until such time as we have a 8689 // little-endian perfect shuffle table. 8690 if (isFourElementShuffle && !isLittleEndian) { 8691 // Compute the index in the perfect shuffle table. 8692 unsigned PFTableIndex = 8693 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8694 8695 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8696 unsigned Cost = (PFEntry >> 30); 8697 8698 // Determining when to avoid vperm is tricky. Many things affect the cost 8699 // of vperm, particularly how many times the perm mask needs to be computed. 8700 // For example, if the perm mask can be hoisted out of a loop or is already 8701 // used (perhaps because there are multiple permutes with the same shuffle 8702 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8703 // the loop requires an extra register. 8704 // 8705 // As a compromise, we only emit discrete instructions if the shuffle can be 8706 // generated in 3 or fewer operations. When we have loop information 8707 // available, if this block is within a loop, we should avoid using vperm 8708 // for 3-operation perms and use a constant pool load instead. 8709 if (Cost < 3) 8710 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8711 } 8712 8713 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8714 // vector that will get spilled to the constant pool. 8715 if (V2.isUndef()) V2 = V1; 8716 8717 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8718 // that it is in input element units, not in bytes. Convert now. 8719 8720 // For little endian, the order of the input vectors is reversed, and 8721 // the permutation mask is complemented with respect to 31. This is 8722 // necessary to produce proper semantics with the big-endian-biased vperm 8723 // instruction. 8724 EVT EltVT = V1.getValueType().getVectorElementType(); 8725 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8726 8727 SmallVector<SDValue, 16> ResultMask; 8728 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8729 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8730 8731 for (unsigned j = 0; j != BytesPerElement; ++j) 8732 if (isLittleEndian) 8733 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8734 dl, MVT::i32)); 8735 else 8736 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8737 MVT::i32)); 8738 } 8739 8740 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8741 if (isLittleEndian) 8742 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8743 V2, V1, VPermMask); 8744 else 8745 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8746 V1, V2, VPermMask); 8747 } 8748 8749 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 8750 /// vector comparison. If it is, return true and fill in Opc/isDot with 8751 /// information about the intrinsic. 8752 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 8753 bool &isDot, const PPCSubtarget &Subtarget) { 8754 unsigned IntrinsicID = 8755 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 8756 CompareOpc = -1; 8757 isDot = false; 8758 switch (IntrinsicID) { 8759 default: 8760 return false; 8761 // Comparison predicates. 8762 case Intrinsic::ppc_altivec_vcmpbfp_p: 8763 CompareOpc = 966; 8764 isDot = true; 8765 break; 8766 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8767 CompareOpc = 198; 8768 isDot = true; 8769 break; 8770 case Intrinsic::ppc_altivec_vcmpequb_p: 8771 CompareOpc = 6; 8772 isDot = true; 8773 break; 8774 case Intrinsic::ppc_altivec_vcmpequh_p: 8775 CompareOpc = 70; 8776 isDot = true; 8777 break; 8778 case Intrinsic::ppc_altivec_vcmpequw_p: 8779 CompareOpc = 134; 8780 isDot = true; 8781 break; 8782 case Intrinsic::ppc_altivec_vcmpequd_p: 8783 if (Subtarget.hasP8Altivec()) { 8784 CompareOpc = 199; 8785 isDot = true; 8786 } else 8787 return false; 8788 break; 8789 case Intrinsic::ppc_altivec_vcmpneb_p: 8790 case Intrinsic::ppc_altivec_vcmpneh_p: 8791 case Intrinsic::ppc_altivec_vcmpnew_p: 8792 case Intrinsic::ppc_altivec_vcmpnezb_p: 8793 case Intrinsic::ppc_altivec_vcmpnezh_p: 8794 case Intrinsic::ppc_altivec_vcmpnezw_p: 8795 if (Subtarget.hasP9Altivec()) { 8796 switch (IntrinsicID) { 8797 default: 8798 llvm_unreachable("Unknown comparison intrinsic."); 8799 case Intrinsic::ppc_altivec_vcmpneb_p: 8800 CompareOpc = 7; 8801 break; 8802 case Intrinsic::ppc_altivec_vcmpneh_p: 8803 CompareOpc = 71; 8804 break; 8805 case Intrinsic::ppc_altivec_vcmpnew_p: 8806 CompareOpc = 135; 8807 break; 8808 case Intrinsic::ppc_altivec_vcmpnezb_p: 8809 CompareOpc = 263; 8810 break; 8811 case Intrinsic::ppc_altivec_vcmpnezh_p: 8812 CompareOpc = 327; 8813 break; 8814 case Intrinsic::ppc_altivec_vcmpnezw_p: 8815 CompareOpc = 391; 8816 break; 8817 } 8818 isDot = true; 8819 } else 8820 return false; 8821 break; 8822 case Intrinsic::ppc_altivec_vcmpgefp_p: 8823 CompareOpc = 454; 8824 isDot = true; 8825 break; 8826 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8827 CompareOpc = 710; 8828 isDot = true; 8829 break; 8830 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8831 CompareOpc = 774; 8832 isDot = true; 8833 break; 8834 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8835 CompareOpc = 838; 8836 isDot = true; 8837 break; 8838 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8839 CompareOpc = 902; 8840 isDot = true; 8841 break; 8842 case Intrinsic::ppc_altivec_vcmpgtsd_p: 8843 if (Subtarget.hasP8Altivec()) { 8844 CompareOpc = 967; 8845 isDot = true; 8846 } else 8847 return false; 8848 break; 8849 case Intrinsic::ppc_altivec_vcmpgtub_p: 8850 CompareOpc = 518; 8851 isDot = true; 8852 break; 8853 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8854 CompareOpc = 582; 8855 isDot = true; 8856 break; 8857 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8858 CompareOpc = 646; 8859 isDot = true; 8860 break; 8861 case Intrinsic::ppc_altivec_vcmpgtud_p: 8862 if (Subtarget.hasP8Altivec()) { 8863 CompareOpc = 711; 8864 isDot = true; 8865 } else 8866 return false; 8867 break; 8868 8869 // VSX predicate comparisons use the same infrastructure 8870 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8871 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8872 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8873 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8874 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8875 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8876 if (Subtarget.hasVSX()) { 8877 switch (IntrinsicID) { 8878 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8879 CompareOpc = 99; 8880 break; 8881 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8882 CompareOpc = 115; 8883 break; 8884 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8885 CompareOpc = 107; 8886 break; 8887 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8888 CompareOpc = 67; 8889 break; 8890 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8891 CompareOpc = 83; 8892 break; 8893 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8894 CompareOpc = 75; 8895 break; 8896 } 8897 isDot = true; 8898 } else 8899 return false; 8900 break; 8901 8902 // Normal Comparisons. 8903 case Intrinsic::ppc_altivec_vcmpbfp: 8904 CompareOpc = 966; 8905 break; 8906 case Intrinsic::ppc_altivec_vcmpeqfp: 8907 CompareOpc = 198; 8908 break; 8909 case Intrinsic::ppc_altivec_vcmpequb: 8910 CompareOpc = 6; 8911 break; 8912 case Intrinsic::ppc_altivec_vcmpequh: 8913 CompareOpc = 70; 8914 break; 8915 case Intrinsic::ppc_altivec_vcmpequw: 8916 CompareOpc = 134; 8917 break; 8918 case Intrinsic::ppc_altivec_vcmpequd: 8919 if (Subtarget.hasP8Altivec()) 8920 CompareOpc = 199; 8921 else 8922 return false; 8923 break; 8924 case Intrinsic::ppc_altivec_vcmpneb: 8925 case Intrinsic::ppc_altivec_vcmpneh: 8926 case Intrinsic::ppc_altivec_vcmpnew: 8927 case Intrinsic::ppc_altivec_vcmpnezb: 8928 case Intrinsic::ppc_altivec_vcmpnezh: 8929 case Intrinsic::ppc_altivec_vcmpnezw: 8930 if (Subtarget.hasP9Altivec()) 8931 switch (IntrinsicID) { 8932 default: 8933 llvm_unreachable("Unknown comparison intrinsic."); 8934 case Intrinsic::ppc_altivec_vcmpneb: 8935 CompareOpc = 7; 8936 break; 8937 case Intrinsic::ppc_altivec_vcmpneh: 8938 CompareOpc = 71; 8939 break; 8940 case Intrinsic::ppc_altivec_vcmpnew: 8941 CompareOpc = 135; 8942 break; 8943 case Intrinsic::ppc_altivec_vcmpnezb: 8944 CompareOpc = 263; 8945 break; 8946 case Intrinsic::ppc_altivec_vcmpnezh: 8947 CompareOpc = 327; 8948 break; 8949 case Intrinsic::ppc_altivec_vcmpnezw: 8950 CompareOpc = 391; 8951 break; 8952 } 8953 else 8954 return false; 8955 break; 8956 case Intrinsic::ppc_altivec_vcmpgefp: 8957 CompareOpc = 454; 8958 break; 8959 case Intrinsic::ppc_altivec_vcmpgtfp: 8960 CompareOpc = 710; 8961 break; 8962 case Intrinsic::ppc_altivec_vcmpgtsb: 8963 CompareOpc = 774; 8964 break; 8965 case Intrinsic::ppc_altivec_vcmpgtsh: 8966 CompareOpc = 838; 8967 break; 8968 case Intrinsic::ppc_altivec_vcmpgtsw: 8969 CompareOpc = 902; 8970 break; 8971 case Intrinsic::ppc_altivec_vcmpgtsd: 8972 if (Subtarget.hasP8Altivec()) 8973 CompareOpc = 967; 8974 else 8975 return false; 8976 break; 8977 case Intrinsic::ppc_altivec_vcmpgtub: 8978 CompareOpc = 518; 8979 break; 8980 case Intrinsic::ppc_altivec_vcmpgtuh: 8981 CompareOpc = 582; 8982 break; 8983 case Intrinsic::ppc_altivec_vcmpgtuw: 8984 CompareOpc = 646; 8985 break; 8986 case Intrinsic::ppc_altivec_vcmpgtud: 8987 if (Subtarget.hasP8Altivec()) 8988 CompareOpc = 711; 8989 else 8990 return false; 8991 break; 8992 } 8993 return true; 8994 } 8995 8996 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 8997 /// lower, do it, otherwise return null. 8998 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 8999 SelectionDAG &DAG) const { 9000 unsigned IntrinsicID = 9001 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9002 9003 SDLoc dl(Op); 9004 9005 if (IntrinsicID == Intrinsic::thread_pointer) { 9006 // Reads the thread pointer register, used for __builtin_thread_pointer. 9007 if (Subtarget.isPPC64()) 9008 return DAG.getRegister(PPC::X13, MVT::i64); 9009 return DAG.getRegister(PPC::R2, MVT::i32); 9010 } 9011 9012 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9013 // opcode number of the comparison. 9014 int CompareOpc; 9015 bool isDot; 9016 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9017 return SDValue(); // Don't custom lower most intrinsics. 9018 9019 // If this is a non-dot comparison, make the VCMP node and we are done. 9020 if (!isDot) { 9021 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9022 Op.getOperand(1), Op.getOperand(2), 9023 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9024 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9025 } 9026 9027 // Create the PPCISD altivec 'dot' comparison node. 9028 SDValue Ops[] = { 9029 Op.getOperand(2), // LHS 9030 Op.getOperand(3), // RHS 9031 DAG.getConstant(CompareOpc, dl, MVT::i32) 9032 }; 9033 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9034 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9035 9036 // Now that we have the comparison, emit a copy from the CR to a GPR. 9037 // This is flagged to the above dot comparison. 9038 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9039 DAG.getRegister(PPC::CR6, MVT::i32), 9040 CompNode.getValue(1)); 9041 9042 // Unpack the result based on how the target uses it. 9043 unsigned BitNo; // Bit # of CR6. 9044 bool InvertBit; // Invert result? 9045 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9046 default: // Can't happen, don't crash on invalid number though. 9047 case 0: // Return the value of the EQ bit of CR6. 9048 BitNo = 0; InvertBit = false; 9049 break; 9050 case 1: // Return the inverted value of the EQ bit of CR6. 9051 BitNo = 0; InvertBit = true; 9052 break; 9053 case 2: // Return the value of the LT bit of CR6. 9054 BitNo = 2; InvertBit = false; 9055 break; 9056 case 3: // Return the inverted value of the LT bit of CR6. 9057 BitNo = 2; InvertBit = true; 9058 break; 9059 } 9060 9061 // Shift the bit into the low position. 9062 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9063 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9064 // Isolate the bit. 9065 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9066 DAG.getConstant(1, dl, MVT::i32)); 9067 9068 // If we are supposed to, toggle the bit. 9069 if (InvertBit) 9070 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9071 DAG.getConstant(1, dl, MVT::i32)); 9072 return Flags; 9073 } 9074 9075 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9076 SelectionDAG &DAG) const { 9077 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9078 // the beginning of the argument list. 9079 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9080 SDLoc DL(Op); 9081 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9082 case Intrinsic::ppc_cfence: { 9083 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9084 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9085 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9086 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9087 Op.getOperand(ArgStart + 1)), 9088 Op.getOperand(0)), 9089 0); 9090 } 9091 default: 9092 break; 9093 } 9094 return SDValue(); 9095 } 9096 9097 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9098 // Check for a DIV with the same operands as this REM. 9099 for (auto UI : Op.getOperand(1)->uses()) { 9100 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9101 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9102 if (UI->getOperand(0) == Op.getOperand(0) && 9103 UI->getOperand(1) == Op.getOperand(1)) 9104 return SDValue(); 9105 } 9106 return Op; 9107 } 9108 9109 // Lower scalar BSWAP64 to xxbrd. 9110 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9111 SDLoc dl(Op); 9112 // MTVSRDD 9113 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9114 Op.getOperand(0)); 9115 // XXBRD 9116 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9117 // MFVSRD 9118 int VectorIndex = 0; 9119 if (Subtarget.isLittleEndian()) 9120 VectorIndex = 1; 9121 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9122 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9123 return Op; 9124 } 9125 9126 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9127 // compared to a value that is atomically loaded (atomic loads zero-extend). 9128 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9129 SelectionDAG &DAG) const { 9130 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9131 "Expecting an atomic compare-and-swap here."); 9132 SDLoc dl(Op); 9133 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9134 EVT MemVT = AtomicNode->getMemoryVT(); 9135 if (MemVT.getSizeInBits() >= 32) 9136 return Op; 9137 9138 SDValue CmpOp = Op.getOperand(2); 9139 // If this is already correctly zero-extended, leave it alone. 9140 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9141 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9142 return Op; 9143 9144 // Clear the high bits of the compare operand. 9145 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9146 SDValue NewCmpOp = 9147 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9148 DAG.getConstant(MaskVal, dl, MVT::i32)); 9149 9150 // Replace the existing compare operand with the properly zero-extended one. 9151 SmallVector<SDValue, 4> Ops; 9152 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9153 Ops.push_back(AtomicNode->getOperand(i)); 9154 Ops[2] = NewCmpOp; 9155 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9156 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9157 auto NodeTy = 9158 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9159 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9160 } 9161 9162 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9163 SelectionDAG &DAG) const { 9164 SDLoc dl(Op); 9165 // Create a stack slot that is 16-byte aligned. 9166 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9167 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9168 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9169 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9170 9171 // Store the input value into Value#0 of the stack slot. 9172 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9173 MachinePointerInfo()); 9174 // Load it out. 9175 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9176 } 9177 9178 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9179 SelectionDAG &DAG) const { 9180 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9181 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9182 9183 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9184 // We have legal lowering for constant indices but not for variable ones. 9185 if (!C) 9186 return SDValue(); 9187 9188 EVT VT = Op.getValueType(); 9189 SDLoc dl(Op); 9190 SDValue V1 = Op.getOperand(0); 9191 SDValue V2 = Op.getOperand(1); 9192 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9193 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9194 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9195 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9196 unsigned InsertAtElement = C->getZExtValue(); 9197 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9198 if (Subtarget.isLittleEndian()) { 9199 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9200 } 9201 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9202 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9203 } 9204 return Op; 9205 } 9206 9207 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9208 SelectionDAG &DAG) const { 9209 SDLoc dl(Op); 9210 SDNode *N = Op.getNode(); 9211 9212 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9213 "Unknown extract_vector_elt type"); 9214 9215 SDValue Value = N->getOperand(0); 9216 9217 // The first part of this is like the store lowering except that we don't 9218 // need to track the chain. 9219 9220 // The values are now known to be -1 (false) or 1 (true). To convert this 9221 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9222 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9223 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9224 9225 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9226 // understand how to form the extending load. 9227 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9228 9229 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9230 9231 // Now convert to an integer and store. 9232 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9233 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9234 Value); 9235 9236 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9237 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9238 MachinePointerInfo PtrInfo = 9239 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9240 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9241 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9242 9243 SDValue StoreChain = DAG.getEntryNode(); 9244 SDValue Ops[] = {StoreChain, 9245 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9246 Value, FIdx}; 9247 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9248 9249 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9250 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9251 9252 // Extract the value requested. 9253 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9254 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9255 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9256 9257 SDValue IntVal = 9258 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9259 9260 if (!Subtarget.useCRBits()) 9261 return IntVal; 9262 9263 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9264 } 9265 9266 /// Lowering for QPX v4i1 loads 9267 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9268 SelectionDAG &DAG) const { 9269 SDLoc dl(Op); 9270 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9271 SDValue LoadChain = LN->getChain(); 9272 SDValue BasePtr = LN->getBasePtr(); 9273 9274 if (Op.getValueType() == MVT::v4f64 || 9275 Op.getValueType() == MVT::v4f32) { 9276 EVT MemVT = LN->getMemoryVT(); 9277 unsigned Alignment = LN->getAlignment(); 9278 9279 // If this load is properly aligned, then it is legal. 9280 if (Alignment >= MemVT.getStoreSize()) 9281 return Op; 9282 9283 EVT ScalarVT = Op.getValueType().getScalarType(), 9284 ScalarMemVT = MemVT.getScalarType(); 9285 unsigned Stride = ScalarMemVT.getStoreSize(); 9286 9287 SDValue Vals[4], LoadChains[4]; 9288 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9289 SDValue Load; 9290 if (ScalarVT != ScalarMemVT) 9291 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9292 BasePtr, 9293 LN->getPointerInfo().getWithOffset(Idx * Stride), 9294 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9295 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9296 else 9297 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9298 LN->getPointerInfo().getWithOffset(Idx * Stride), 9299 MinAlign(Alignment, Idx * Stride), 9300 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9301 9302 if (Idx == 0 && LN->isIndexed()) { 9303 assert(LN->getAddressingMode() == ISD::PRE_INC && 9304 "Unknown addressing mode on vector load"); 9305 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9306 LN->getAddressingMode()); 9307 } 9308 9309 Vals[Idx] = Load; 9310 LoadChains[Idx] = Load.getValue(1); 9311 9312 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9313 DAG.getConstant(Stride, dl, 9314 BasePtr.getValueType())); 9315 } 9316 9317 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9318 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9319 9320 if (LN->isIndexed()) { 9321 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9322 return DAG.getMergeValues(RetOps, dl); 9323 } 9324 9325 SDValue RetOps[] = { Value, TF }; 9326 return DAG.getMergeValues(RetOps, dl); 9327 } 9328 9329 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9330 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9331 9332 // To lower v4i1 from a byte array, we load the byte elements of the 9333 // vector and then reuse the BUILD_VECTOR logic. 9334 9335 SDValue VectElmts[4], VectElmtChains[4]; 9336 for (unsigned i = 0; i < 4; ++i) { 9337 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9338 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9339 9340 VectElmts[i] = DAG.getExtLoad( 9341 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9342 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9343 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9344 VectElmtChains[i] = VectElmts[i].getValue(1); 9345 } 9346 9347 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9348 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9349 9350 SDValue RVals[] = { Value, LoadChain }; 9351 return DAG.getMergeValues(RVals, dl); 9352 } 9353 9354 /// Lowering for QPX v4i1 stores 9355 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9356 SelectionDAG &DAG) const { 9357 SDLoc dl(Op); 9358 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9359 SDValue StoreChain = SN->getChain(); 9360 SDValue BasePtr = SN->getBasePtr(); 9361 SDValue Value = SN->getValue(); 9362 9363 if (Value.getValueType() == MVT::v4f64 || 9364 Value.getValueType() == MVT::v4f32) { 9365 EVT MemVT = SN->getMemoryVT(); 9366 unsigned Alignment = SN->getAlignment(); 9367 9368 // If this store is properly aligned, then it is legal. 9369 if (Alignment >= MemVT.getStoreSize()) 9370 return Op; 9371 9372 EVT ScalarVT = Value.getValueType().getScalarType(), 9373 ScalarMemVT = MemVT.getScalarType(); 9374 unsigned Stride = ScalarMemVT.getStoreSize(); 9375 9376 SDValue Stores[4]; 9377 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9378 SDValue Ex = DAG.getNode( 9379 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9380 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9381 SDValue Store; 9382 if (ScalarVT != ScalarMemVT) 9383 Store = 9384 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9385 SN->getPointerInfo().getWithOffset(Idx * Stride), 9386 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9387 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9388 else 9389 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9390 SN->getPointerInfo().getWithOffset(Idx * Stride), 9391 MinAlign(Alignment, Idx * Stride), 9392 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9393 9394 if (Idx == 0 && SN->isIndexed()) { 9395 assert(SN->getAddressingMode() == ISD::PRE_INC && 9396 "Unknown addressing mode on vector store"); 9397 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9398 SN->getAddressingMode()); 9399 } 9400 9401 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9402 DAG.getConstant(Stride, dl, 9403 BasePtr.getValueType())); 9404 Stores[Idx] = Store; 9405 } 9406 9407 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9408 9409 if (SN->isIndexed()) { 9410 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9411 return DAG.getMergeValues(RetOps, dl); 9412 } 9413 9414 return TF; 9415 } 9416 9417 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9418 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9419 9420 // The values are now known to be -1 (false) or 1 (true). To convert this 9421 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9422 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9423 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9424 9425 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9426 // understand how to form the extending load. 9427 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9428 9429 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9430 9431 // Now convert to an integer and store. 9432 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9433 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9434 Value); 9435 9436 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9437 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9438 MachinePointerInfo PtrInfo = 9439 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9440 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9441 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9442 9443 SDValue Ops[] = {StoreChain, 9444 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9445 Value, FIdx}; 9446 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9447 9448 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9449 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9450 9451 // Move data into the byte array. 9452 SDValue Loads[4], LoadChains[4]; 9453 for (unsigned i = 0; i < 4; ++i) { 9454 unsigned Offset = 4*i; 9455 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9456 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9457 9458 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9459 PtrInfo.getWithOffset(Offset)); 9460 LoadChains[i] = Loads[i].getValue(1); 9461 } 9462 9463 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9464 9465 SDValue Stores[4]; 9466 for (unsigned i = 0; i < 4; ++i) { 9467 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9468 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9469 9470 Stores[i] = DAG.getTruncStore( 9471 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9472 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9473 SN->getAAInfo()); 9474 } 9475 9476 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9477 9478 return StoreChain; 9479 } 9480 9481 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9482 SDLoc dl(Op); 9483 if (Op.getValueType() == MVT::v4i32) { 9484 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9485 9486 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9487 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9488 9489 SDValue RHSSwap = // = vrlw RHS, 16 9490 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9491 9492 // Shrinkify inputs to v8i16. 9493 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9494 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9495 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9496 9497 // Low parts multiplied together, generating 32-bit results (we ignore the 9498 // top parts). 9499 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9500 LHS, RHS, DAG, dl, MVT::v4i32); 9501 9502 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9503 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9504 // Shift the high parts up 16 bits. 9505 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9506 Neg16, DAG, dl); 9507 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9508 } else if (Op.getValueType() == MVT::v8i16) { 9509 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9510 9511 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9512 9513 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9514 LHS, RHS, Zero, DAG, dl); 9515 } else if (Op.getValueType() == MVT::v16i8) { 9516 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9517 bool isLittleEndian = Subtarget.isLittleEndian(); 9518 9519 // Multiply the even 8-bit parts, producing 16-bit sums. 9520 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9521 LHS, RHS, DAG, dl, MVT::v8i16); 9522 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9523 9524 // Multiply the odd 8-bit parts, producing 16-bit sums. 9525 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9526 LHS, RHS, DAG, dl, MVT::v8i16); 9527 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9528 9529 // Merge the results together. Because vmuleub and vmuloub are 9530 // instructions with a big-endian bias, we must reverse the 9531 // element numbering and reverse the meaning of "odd" and "even" 9532 // when generating little endian code. 9533 int Ops[16]; 9534 for (unsigned i = 0; i != 8; ++i) { 9535 if (isLittleEndian) { 9536 Ops[i*2 ] = 2*i; 9537 Ops[i*2+1] = 2*i+16; 9538 } else { 9539 Ops[i*2 ] = 2*i+1; 9540 Ops[i*2+1] = 2*i+1+16; 9541 } 9542 } 9543 if (isLittleEndian) 9544 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9545 else 9546 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9547 } else { 9548 llvm_unreachable("Unknown mul to lower!"); 9549 } 9550 } 9551 9552 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 9553 9554 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 9555 9556 EVT VT = Op.getValueType(); 9557 assert(VT.isVector() && 9558 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 9559 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 9560 VT == MVT::v16i8) && 9561 "Unexpected vector element type!"); 9562 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 9563 "Current subtarget doesn't support smax v2i64!"); 9564 9565 // For vector abs, it can be lowered to: 9566 // abs x 9567 // ==> 9568 // y = -x 9569 // smax(x, y) 9570 9571 SDLoc dl(Op); 9572 SDValue X = Op.getOperand(0); 9573 SDValue Zero = DAG.getConstant(0, dl, VT); 9574 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 9575 9576 // SMAX patch https://reviews.llvm.org/D47332 9577 // hasn't landed yet, so use intrinsic first here. 9578 // TODO: Should use SMAX directly once SMAX patch landed 9579 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 9580 if (VT == MVT::v2i64) 9581 BifID = Intrinsic::ppc_altivec_vmaxsd; 9582 else if (VT == MVT::v8i16) 9583 BifID = Intrinsic::ppc_altivec_vmaxsh; 9584 else if (VT == MVT::v16i8) 9585 BifID = Intrinsic::ppc_altivec_vmaxsb; 9586 9587 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 9588 } 9589 9590 /// LowerOperation - Provide custom lowering hooks for some operations. 9591 /// 9592 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9593 switch (Op.getOpcode()) { 9594 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9595 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9596 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9597 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9598 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9599 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9600 case ISD::SETCC: return LowerSETCC(Op, DAG); 9601 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9602 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9603 9604 // Variable argument lowering. 9605 case ISD::VASTART: return LowerVASTART(Op, DAG); 9606 case ISD::VAARG: return LowerVAARG(Op, DAG); 9607 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9608 9609 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 9610 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9611 case ISD::GET_DYNAMIC_AREA_OFFSET: 9612 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9613 9614 // Exception handling lowering. 9615 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 9616 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9617 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9618 9619 case ISD::LOAD: return LowerLOAD(Op, DAG); 9620 case ISD::STORE: return LowerSTORE(Op, DAG); 9621 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9622 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9623 case ISD::FP_TO_UINT: 9624 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 9625 case ISD::UINT_TO_FP: 9626 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9627 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9628 9629 // Lower 64-bit shifts. 9630 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9631 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9632 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9633 9634 // Vector-related lowering. 9635 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9636 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9637 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9638 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9639 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9640 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9641 case ISD::MUL: return LowerMUL(Op, DAG); 9642 case ISD::ABS: return LowerABS(Op, DAG); 9643 9644 // For counter-based loop handling. 9645 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9646 9647 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 9648 9649 // Frame & Return address. 9650 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9651 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9652 9653 case ISD::INTRINSIC_VOID: 9654 return LowerINTRINSIC_VOID(Op, DAG); 9655 case ISD::SREM: 9656 case ISD::UREM: 9657 return LowerREM(Op, DAG); 9658 case ISD::BSWAP: 9659 return LowerBSWAP(Op, DAG); 9660 case ISD::ATOMIC_CMP_SWAP: 9661 return LowerATOMIC_CMP_SWAP(Op, DAG); 9662 } 9663 } 9664 9665 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9666 SmallVectorImpl<SDValue>&Results, 9667 SelectionDAG &DAG) const { 9668 SDLoc dl(N); 9669 switch (N->getOpcode()) { 9670 default: 9671 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9672 case ISD::READCYCLECOUNTER: { 9673 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9674 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9675 9676 Results.push_back(RTB); 9677 Results.push_back(RTB.getValue(1)); 9678 Results.push_back(RTB.getValue(2)); 9679 break; 9680 } 9681 case ISD::INTRINSIC_W_CHAIN: { 9682 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9683 Intrinsic::ppc_is_decremented_ctr_nonzero) 9684 break; 9685 9686 assert(N->getValueType(0) == MVT::i1 && 9687 "Unexpected result type for CTR decrement intrinsic"); 9688 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9689 N->getValueType(0)); 9690 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9691 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9692 N->getOperand(1)); 9693 9694 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 9695 Results.push_back(NewInt.getValue(1)); 9696 break; 9697 } 9698 case ISD::VAARG: { 9699 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 9700 return; 9701 9702 EVT VT = N->getValueType(0); 9703 9704 if (VT == MVT::i64) { 9705 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 9706 9707 Results.push_back(NewNode); 9708 Results.push_back(NewNode.getValue(1)); 9709 } 9710 return; 9711 } 9712 case ISD::FP_TO_SINT: 9713 case ISD::FP_TO_UINT: 9714 // LowerFP_TO_INT() can only handle f32 and f64. 9715 if (N->getOperand(0).getValueType() == MVT::ppcf128) 9716 return; 9717 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 9718 return; 9719 case ISD::BITCAST: 9720 // Don't handle bitcast here. 9721 return; 9722 } 9723 } 9724 9725 //===----------------------------------------------------------------------===// 9726 // Other Lowering Code 9727 //===----------------------------------------------------------------------===// 9728 9729 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 9730 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9731 Function *Func = Intrinsic::getDeclaration(M, Id); 9732 return Builder.CreateCall(Func, {}); 9733 } 9734 9735 // The mappings for emitLeading/TrailingFence is taken from 9736 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 9737 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 9738 Instruction *Inst, 9739 AtomicOrdering Ord) const { 9740 if (Ord == AtomicOrdering::SequentiallyConsistent) 9741 return callIntrinsic(Builder, Intrinsic::ppc_sync); 9742 if (isReleaseOrStronger(Ord)) 9743 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9744 return nullptr; 9745 } 9746 9747 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 9748 Instruction *Inst, 9749 AtomicOrdering Ord) const { 9750 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 9751 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 9752 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 9753 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 9754 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 9755 return Builder.CreateCall( 9756 Intrinsic::getDeclaration( 9757 Builder.GetInsertBlock()->getParent()->getParent(), 9758 Intrinsic::ppc_cfence, {Inst->getType()}), 9759 {Inst}); 9760 // FIXME: Can use isync for rmw operation. 9761 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9762 } 9763 return nullptr; 9764 } 9765 9766 MachineBasicBlock * 9767 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 9768 unsigned AtomicSize, 9769 unsigned BinOpcode, 9770 unsigned CmpOpcode, 9771 unsigned CmpPred) const { 9772 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9773 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9774 9775 auto LoadMnemonic = PPC::LDARX; 9776 auto StoreMnemonic = PPC::STDCX; 9777 switch (AtomicSize) { 9778 default: 9779 llvm_unreachable("Unexpected size of atomic entity"); 9780 case 1: 9781 LoadMnemonic = PPC::LBARX; 9782 StoreMnemonic = PPC::STBCX; 9783 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9784 break; 9785 case 2: 9786 LoadMnemonic = PPC::LHARX; 9787 StoreMnemonic = PPC::STHCX; 9788 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9789 break; 9790 case 4: 9791 LoadMnemonic = PPC::LWARX; 9792 StoreMnemonic = PPC::STWCX; 9793 break; 9794 case 8: 9795 LoadMnemonic = PPC::LDARX; 9796 StoreMnemonic = PPC::STDCX; 9797 break; 9798 } 9799 9800 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9801 MachineFunction *F = BB->getParent(); 9802 MachineFunction::iterator It = ++BB->getIterator(); 9803 9804 unsigned dest = MI.getOperand(0).getReg(); 9805 unsigned ptrA = MI.getOperand(1).getReg(); 9806 unsigned ptrB = MI.getOperand(2).getReg(); 9807 unsigned incr = MI.getOperand(3).getReg(); 9808 DebugLoc dl = MI.getDebugLoc(); 9809 9810 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9811 MachineBasicBlock *loop2MBB = 9812 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9813 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9814 F->insert(It, loopMBB); 9815 if (CmpOpcode) 9816 F->insert(It, loop2MBB); 9817 F->insert(It, exitMBB); 9818 exitMBB->splice(exitMBB->begin(), BB, 9819 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9820 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9821 9822 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9823 unsigned TmpReg = (!BinOpcode) ? incr : 9824 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 9825 : &PPC::GPRCRegClass); 9826 9827 // thisMBB: 9828 // ... 9829 // fallthrough --> loopMBB 9830 BB->addSuccessor(loopMBB); 9831 9832 // loopMBB: 9833 // l[wd]arx dest, ptr 9834 // add r0, dest, incr 9835 // st[wd]cx. r0, ptr 9836 // bne- loopMBB 9837 // fallthrough --> exitMBB 9838 9839 // For max/min... 9840 // loopMBB: 9841 // l[wd]arx dest, ptr 9842 // cmpl?[wd] incr, dest 9843 // bgt exitMBB 9844 // loop2MBB: 9845 // st[wd]cx. dest, ptr 9846 // bne- loopMBB 9847 // fallthrough --> exitMBB 9848 9849 BB = loopMBB; 9850 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9851 .addReg(ptrA).addReg(ptrB); 9852 if (BinOpcode) 9853 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 9854 if (CmpOpcode) { 9855 // Signed comparisons of byte or halfword values must be sign-extended. 9856 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 9857 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9858 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 9859 ExtReg).addReg(dest); 9860 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9861 .addReg(incr).addReg(ExtReg); 9862 } else 9863 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9864 .addReg(incr).addReg(dest); 9865 9866 BuildMI(BB, dl, TII->get(PPC::BCC)) 9867 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9868 BB->addSuccessor(loop2MBB); 9869 BB->addSuccessor(exitMBB); 9870 BB = loop2MBB; 9871 } 9872 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9873 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 9874 BuildMI(BB, dl, TII->get(PPC::BCC)) 9875 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9876 BB->addSuccessor(loopMBB); 9877 BB->addSuccessor(exitMBB); 9878 9879 // exitMBB: 9880 // ... 9881 BB = exitMBB; 9882 return BB; 9883 } 9884 9885 MachineBasicBlock * 9886 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI, 9887 MachineBasicBlock *BB, 9888 bool is8bit, // operation 9889 unsigned BinOpcode, 9890 unsigned CmpOpcode, 9891 unsigned CmpPred) const { 9892 // If we support part-word atomic mnemonics, just use them 9893 if (Subtarget.hasPartwordAtomics()) 9894 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, 9895 CmpOpcode, CmpPred); 9896 9897 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9898 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9899 // In 64 bit mode we have to use 64 bits for addresses, even though the 9900 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 9901 // registers without caring whether they're 32 or 64, but here we're 9902 // doing actual arithmetic on the addresses. 9903 bool is64bit = Subtarget.isPPC64(); 9904 bool isLittleEndian = Subtarget.isLittleEndian(); 9905 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9906 9907 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9908 MachineFunction *F = BB->getParent(); 9909 MachineFunction::iterator It = ++BB->getIterator(); 9910 9911 unsigned dest = MI.getOperand(0).getReg(); 9912 unsigned ptrA = MI.getOperand(1).getReg(); 9913 unsigned ptrB = MI.getOperand(2).getReg(); 9914 unsigned incr = MI.getOperand(3).getReg(); 9915 DebugLoc dl = MI.getDebugLoc(); 9916 9917 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9918 MachineBasicBlock *loop2MBB = 9919 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9920 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9921 F->insert(It, loopMBB); 9922 if (CmpOpcode) 9923 F->insert(It, loop2MBB); 9924 F->insert(It, exitMBB); 9925 exitMBB->splice(exitMBB->begin(), BB, 9926 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9927 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9928 9929 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9930 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 9931 : &PPC::GPRCRegClass; 9932 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9933 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 9934 unsigned ShiftReg = 9935 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 9936 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 9937 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 9938 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 9939 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 9940 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 9941 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 9942 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 9943 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 9944 unsigned Ptr1Reg; 9945 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 9946 9947 // thisMBB: 9948 // ... 9949 // fallthrough --> loopMBB 9950 BB->addSuccessor(loopMBB); 9951 9952 // The 4-byte load must be aligned, while a char or short may be 9953 // anywhere in the word. Hence all this nasty bookkeeping code. 9954 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9955 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9956 // xori shift, shift1, 24 [16] 9957 // rlwinm ptr, ptr1, 0, 0, 29 9958 // slw incr2, incr, shift 9959 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9960 // slw mask, mask2, shift 9961 // loopMBB: 9962 // lwarx tmpDest, ptr 9963 // add tmp, tmpDest, incr2 9964 // andc tmp2, tmpDest, mask 9965 // and tmp3, tmp, mask 9966 // or tmp4, tmp3, tmp2 9967 // stwcx. tmp4, ptr 9968 // bne- loopMBB 9969 // fallthrough --> exitMBB 9970 // srw dest, tmpDest, shift 9971 if (ptrA != ZeroReg) { 9972 Ptr1Reg = RegInfo.createVirtualRegister(RC); 9973 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 9974 .addReg(ptrA).addReg(ptrB); 9975 } else { 9976 Ptr1Reg = ptrB; 9977 } 9978 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 9979 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 9980 if (!isLittleEndian) 9981 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 9982 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 9983 if (is64bit) 9984 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 9985 .addReg(Ptr1Reg).addImm(0).addImm(61); 9986 else 9987 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 9988 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 9989 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 9990 .addReg(incr).addReg(ShiftReg); 9991 if (is8bit) 9992 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 9993 else { 9994 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 9995 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 9996 } 9997 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 9998 .addReg(Mask2Reg).addReg(ShiftReg); 9999 10000 BB = loopMBB; 10001 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10002 .addReg(ZeroReg).addReg(PtrReg); 10003 if (BinOpcode) 10004 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10005 .addReg(Incr2Reg).addReg(TmpDestReg); 10006 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 10007 .addReg(TmpDestReg).addReg(MaskReg); 10008 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 10009 .addReg(TmpReg).addReg(MaskReg); 10010 if (CmpOpcode) { 10011 // For unsigned comparisons, we can directly compare the shifted values. 10012 // For signed comparisons we shift and sign extend. 10013 unsigned SReg = RegInfo.createVirtualRegister(RC); 10014 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg) 10015 .addReg(TmpDestReg).addReg(MaskReg); 10016 unsigned ValueReg = SReg; 10017 unsigned CmpReg = Incr2Reg; 10018 if (CmpOpcode == PPC::CMPW) { 10019 ValueReg = RegInfo.createVirtualRegister(RC); 10020 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10021 .addReg(SReg).addReg(ShiftReg); 10022 unsigned ValueSReg = RegInfo.createVirtualRegister(RC); 10023 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10024 .addReg(ValueReg); 10025 ValueReg = ValueSReg; 10026 CmpReg = incr; 10027 } 10028 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10029 .addReg(CmpReg).addReg(ValueReg); 10030 BuildMI(BB, dl, TII->get(PPC::BCC)) 10031 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10032 BB->addSuccessor(loop2MBB); 10033 BB->addSuccessor(exitMBB); 10034 BB = loop2MBB; 10035 } 10036 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 10037 .addReg(Tmp3Reg).addReg(Tmp2Reg); 10038 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10039 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 10040 BuildMI(BB, dl, TII->get(PPC::BCC)) 10041 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10042 BB->addSuccessor(loopMBB); 10043 BB->addSuccessor(exitMBB); 10044 10045 // exitMBB: 10046 // ... 10047 BB = exitMBB; 10048 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 10049 .addReg(ShiftReg); 10050 return BB; 10051 } 10052 10053 llvm::MachineBasicBlock * 10054 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10055 MachineBasicBlock *MBB) const { 10056 DebugLoc DL = MI.getDebugLoc(); 10057 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10058 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10059 10060 MachineFunction *MF = MBB->getParent(); 10061 MachineRegisterInfo &MRI = MF->getRegInfo(); 10062 10063 const BasicBlock *BB = MBB->getBasicBlock(); 10064 MachineFunction::iterator I = ++MBB->getIterator(); 10065 10066 unsigned DstReg = MI.getOperand(0).getReg(); 10067 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10068 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10069 unsigned mainDstReg = MRI.createVirtualRegister(RC); 10070 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 10071 10072 MVT PVT = getPointerTy(MF->getDataLayout()); 10073 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10074 "Invalid Pointer Size!"); 10075 // For v = setjmp(buf), we generate 10076 // 10077 // thisMBB: 10078 // SjLjSetup mainMBB 10079 // bl mainMBB 10080 // v_restore = 1 10081 // b sinkMBB 10082 // 10083 // mainMBB: 10084 // buf[LabelOffset] = LR 10085 // v_main = 0 10086 // 10087 // sinkMBB: 10088 // v = phi(main, restore) 10089 // 10090 10091 MachineBasicBlock *thisMBB = MBB; 10092 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10093 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10094 MF->insert(I, mainMBB); 10095 MF->insert(I, sinkMBB); 10096 10097 MachineInstrBuilder MIB; 10098 10099 // Transfer the remainder of BB and its successor edges to sinkMBB. 10100 sinkMBB->splice(sinkMBB->begin(), MBB, 10101 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10102 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10103 10104 // Note that the structure of the jmp_buf used here is not compatible 10105 // with that used by libc, and is not designed to be. Specifically, it 10106 // stores only those 'reserved' registers that LLVM does not otherwise 10107 // understand how to spill. Also, by convention, by the time this 10108 // intrinsic is called, Clang has already stored the frame address in the 10109 // first slot of the buffer and stack address in the third. Following the 10110 // X86 target code, we'll store the jump address in the second slot. We also 10111 // need to save the TOC pointer (R2) to handle jumps between shared 10112 // libraries, and that will be stored in the fourth slot. The thread 10113 // identifier (R13) is not affected. 10114 10115 // thisMBB: 10116 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10117 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10118 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10119 10120 // Prepare IP either in reg. 10121 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10122 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 10123 unsigned BufReg = MI.getOperand(1).getReg(); 10124 10125 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 10126 setUsesTOCBasePtr(*MBB->getParent()); 10127 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10128 .addReg(PPC::X2) 10129 .addImm(TOCOffset) 10130 .addReg(BufReg) 10131 .cloneMemRefs(MI); 10132 } 10133 10134 // Naked functions never have a base pointer, and so we use r1. For all 10135 // other functions, this decision must be delayed until during PEI. 10136 unsigned BaseReg; 10137 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10138 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10139 else 10140 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10141 10142 MIB = BuildMI(*thisMBB, MI, DL, 10143 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10144 .addReg(BaseReg) 10145 .addImm(BPOffset) 10146 .addReg(BufReg) 10147 .cloneMemRefs(MI); 10148 10149 // Setup 10150 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10151 MIB.addRegMask(TRI->getNoPreservedMask()); 10152 10153 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10154 10155 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10156 .addMBB(mainMBB); 10157 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10158 10159 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10160 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10161 10162 // mainMBB: 10163 // mainDstReg = 0 10164 MIB = 10165 BuildMI(mainMBB, DL, 10166 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10167 10168 // Store IP 10169 if (Subtarget.isPPC64()) { 10170 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10171 .addReg(LabelReg) 10172 .addImm(LabelOffset) 10173 .addReg(BufReg); 10174 } else { 10175 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10176 .addReg(LabelReg) 10177 .addImm(LabelOffset) 10178 .addReg(BufReg); 10179 } 10180 MIB.cloneMemRefs(MI); 10181 10182 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10183 mainMBB->addSuccessor(sinkMBB); 10184 10185 // sinkMBB: 10186 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10187 TII->get(PPC::PHI), DstReg) 10188 .addReg(mainDstReg).addMBB(mainMBB) 10189 .addReg(restoreDstReg).addMBB(thisMBB); 10190 10191 MI.eraseFromParent(); 10192 return sinkMBB; 10193 } 10194 10195 MachineBasicBlock * 10196 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10197 MachineBasicBlock *MBB) const { 10198 DebugLoc DL = MI.getDebugLoc(); 10199 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10200 10201 MachineFunction *MF = MBB->getParent(); 10202 MachineRegisterInfo &MRI = MF->getRegInfo(); 10203 10204 MVT PVT = getPointerTy(MF->getDataLayout()); 10205 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10206 "Invalid Pointer Size!"); 10207 10208 const TargetRegisterClass *RC = 10209 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10210 unsigned Tmp = MRI.createVirtualRegister(RC); 10211 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10212 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10213 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10214 unsigned BP = 10215 (PVT == MVT::i64) 10216 ? PPC::X30 10217 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10218 : PPC::R30); 10219 10220 MachineInstrBuilder MIB; 10221 10222 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10223 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10224 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10225 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10226 10227 unsigned BufReg = MI.getOperand(0).getReg(); 10228 10229 // Reload FP (the jumped-to function may not have had a 10230 // frame pointer, and if so, then its r31 will be restored 10231 // as necessary). 10232 if (PVT == MVT::i64) { 10233 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10234 .addImm(0) 10235 .addReg(BufReg); 10236 } else { 10237 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10238 .addImm(0) 10239 .addReg(BufReg); 10240 } 10241 MIB.cloneMemRefs(MI); 10242 10243 // Reload IP 10244 if (PVT == MVT::i64) { 10245 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10246 .addImm(LabelOffset) 10247 .addReg(BufReg); 10248 } else { 10249 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10250 .addImm(LabelOffset) 10251 .addReg(BufReg); 10252 } 10253 MIB.cloneMemRefs(MI); 10254 10255 // Reload SP 10256 if (PVT == MVT::i64) { 10257 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10258 .addImm(SPOffset) 10259 .addReg(BufReg); 10260 } else { 10261 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10262 .addImm(SPOffset) 10263 .addReg(BufReg); 10264 } 10265 MIB.cloneMemRefs(MI); 10266 10267 // Reload BP 10268 if (PVT == MVT::i64) { 10269 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10270 .addImm(BPOffset) 10271 .addReg(BufReg); 10272 } else { 10273 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10274 .addImm(BPOffset) 10275 .addReg(BufReg); 10276 } 10277 MIB.cloneMemRefs(MI); 10278 10279 // Reload TOC 10280 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10281 setUsesTOCBasePtr(*MBB->getParent()); 10282 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10283 .addImm(TOCOffset) 10284 .addReg(BufReg) 10285 .cloneMemRefs(MI); 10286 } 10287 10288 // Jump 10289 BuildMI(*MBB, MI, DL, 10290 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10291 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10292 10293 MI.eraseFromParent(); 10294 return MBB; 10295 } 10296 10297 MachineBasicBlock * 10298 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10299 MachineBasicBlock *BB) const { 10300 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10301 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10302 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10303 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10304 // Call lowering should have added an r2 operand to indicate a dependence 10305 // on the TOC base pointer value. It can't however, because there is no 10306 // way to mark the dependence as implicit there, and so the stackmap code 10307 // will confuse it with a regular operand. Instead, add the dependence 10308 // here. 10309 setUsesTOCBasePtr(*BB->getParent()); 10310 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10311 } 10312 10313 return emitPatchPoint(MI, BB); 10314 } 10315 10316 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10317 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10318 return emitEHSjLjSetJmp(MI, BB); 10319 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10320 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10321 return emitEHSjLjLongJmp(MI, BB); 10322 } 10323 10324 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10325 10326 // To "insert" these instructions we actually have to insert their 10327 // control-flow patterns. 10328 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10329 MachineFunction::iterator It = ++BB->getIterator(); 10330 10331 MachineFunction *F = BB->getParent(); 10332 10333 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10334 MI.getOpcode() == PPC::SELECT_CC_I8 || 10335 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) { 10336 SmallVector<MachineOperand, 2> Cond; 10337 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10338 MI.getOpcode() == PPC::SELECT_CC_I8) 10339 Cond.push_back(MI.getOperand(4)); 10340 else 10341 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10342 Cond.push_back(MI.getOperand(1)); 10343 10344 DebugLoc dl = MI.getDebugLoc(); 10345 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10346 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10347 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10348 MI.getOpcode() == PPC::SELECT_CC_I8 || 10349 MI.getOpcode() == PPC::SELECT_CC_F4 || 10350 MI.getOpcode() == PPC::SELECT_CC_F8 || 10351 MI.getOpcode() == PPC::SELECT_CC_F16 || 10352 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10353 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10354 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10355 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10356 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10357 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10358 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10359 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 10360 MI.getOpcode() == PPC::SELECT_CC_SPE || 10361 MI.getOpcode() == PPC::SELECT_I4 || 10362 MI.getOpcode() == PPC::SELECT_I8 || 10363 MI.getOpcode() == PPC::SELECT_F4 || 10364 MI.getOpcode() == PPC::SELECT_F8 || 10365 MI.getOpcode() == PPC::SELECT_F16 || 10366 MI.getOpcode() == PPC::SELECT_QFRC || 10367 MI.getOpcode() == PPC::SELECT_QSRC || 10368 MI.getOpcode() == PPC::SELECT_QBRC || 10369 MI.getOpcode() == PPC::SELECT_SPE || 10370 MI.getOpcode() == PPC::SELECT_SPE4 || 10371 MI.getOpcode() == PPC::SELECT_VRRC || 10372 MI.getOpcode() == PPC::SELECT_VSFRC || 10373 MI.getOpcode() == PPC::SELECT_VSSRC || 10374 MI.getOpcode() == PPC::SELECT_VSRC) { 10375 // The incoming instruction knows the destination vreg to set, the 10376 // condition code register to branch on, the true/false values to 10377 // select between, and a branch opcode to use. 10378 10379 // thisMBB: 10380 // ... 10381 // TrueVal = ... 10382 // cmpTY ccX, r1, r2 10383 // bCC copy1MBB 10384 // fallthrough --> copy0MBB 10385 MachineBasicBlock *thisMBB = BB; 10386 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10387 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10388 DebugLoc dl = MI.getDebugLoc(); 10389 F->insert(It, copy0MBB); 10390 F->insert(It, sinkMBB); 10391 10392 // Transfer the remainder of BB and its successor edges to sinkMBB. 10393 sinkMBB->splice(sinkMBB->begin(), BB, 10394 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10395 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10396 10397 // Next, add the true and fallthrough blocks as its successors. 10398 BB->addSuccessor(copy0MBB); 10399 BB->addSuccessor(sinkMBB); 10400 10401 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10402 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10403 MI.getOpcode() == PPC::SELECT_F16 || 10404 MI.getOpcode() == PPC::SELECT_SPE4 || 10405 MI.getOpcode() == PPC::SELECT_SPE || 10406 MI.getOpcode() == PPC::SELECT_QFRC || 10407 MI.getOpcode() == PPC::SELECT_QSRC || 10408 MI.getOpcode() == PPC::SELECT_QBRC || 10409 MI.getOpcode() == PPC::SELECT_VRRC || 10410 MI.getOpcode() == PPC::SELECT_VSFRC || 10411 MI.getOpcode() == PPC::SELECT_VSSRC || 10412 MI.getOpcode() == PPC::SELECT_VSRC) { 10413 BuildMI(BB, dl, TII->get(PPC::BC)) 10414 .addReg(MI.getOperand(1).getReg()) 10415 .addMBB(sinkMBB); 10416 } else { 10417 unsigned SelectPred = MI.getOperand(4).getImm(); 10418 BuildMI(BB, dl, TII->get(PPC::BCC)) 10419 .addImm(SelectPred) 10420 .addReg(MI.getOperand(1).getReg()) 10421 .addMBB(sinkMBB); 10422 } 10423 10424 // copy0MBB: 10425 // %FalseValue = ... 10426 // # fallthrough to sinkMBB 10427 BB = copy0MBB; 10428 10429 // Update machine-CFG edges 10430 BB->addSuccessor(sinkMBB); 10431 10432 // sinkMBB: 10433 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10434 // ... 10435 BB = sinkMBB; 10436 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10437 .addReg(MI.getOperand(3).getReg()) 10438 .addMBB(copy0MBB) 10439 .addReg(MI.getOperand(2).getReg()) 10440 .addMBB(thisMBB); 10441 } else if (MI.getOpcode() == PPC::ReadTB) { 10442 // To read the 64-bit time-base register on a 32-bit target, we read the 10443 // two halves. Should the counter have wrapped while it was being read, we 10444 // need to try again. 10445 // ... 10446 // readLoop: 10447 // mfspr Rx,TBU # load from TBU 10448 // mfspr Ry,TB # load from TB 10449 // mfspr Rz,TBU # load from TBU 10450 // cmpw crX,Rx,Rz # check if 'old'='new' 10451 // bne readLoop # branch if they're not equal 10452 // ... 10453 10454 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10455 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10456 DebugLoc dl = MI.getDebugLoc(); 10457 F->insert(It, readMBB); 10458 F->insert(It, sinkMBB); 10459 10460 // Transfer the remainder of BB and its successor edges to sinkMBB. 10461 sinkMBB->splice(sinkMBB->begin(), BB, 10462 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10463 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10464 10465 BB->addSuccessor(readMBB); 10466 BB = readMBB; 10467 10468 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10469 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10470 unsigned LoReg = MI.getOperand(0).getReg(); 10471 unsigned HiReg = MI.getOperand(1).getReg(); 10472 10473 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10474 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10475 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10476 10477 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10478 10479 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10480 .addReg(HiReg).addReg(ReadAgainReg); 10481 BuildMI(BB, dl, TII->get(PPC::BCC)) 10482 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB); 10483 10484 BB->addSuccessor(readMBB); 10485 BB->addSuccessor(sinkMBB); 10486 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10487 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10488 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10489 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10490 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10491 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10492 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10493 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10494 10495 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10496 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10497 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10498 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10499 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10500 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10501 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10502 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10503 10504 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10505 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10506 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10507 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10508 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10509 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10510 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10511 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10512 10513 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10514 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10515 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10516 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10517 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10518 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10519 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10520 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10521 10522 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10523 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10524 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10525 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10526 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10527 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10528 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10529 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10530 10531 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10532 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10533 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10534 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10535 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10536 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10537 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10538 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10539 10540 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10541 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10542 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10543 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10544 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10545 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10546 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10547 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10548 10549 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10550 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10551 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10552 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10553 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10554 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10555 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10556 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10557 10558 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10559 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10560 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10561 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10562 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10563 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10564 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10565 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10566 10567 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10568 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10569 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10570 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10571 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10572 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10573 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10574 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10575 10576 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10577 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10578 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10579 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10580 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10581 BB = EmitAtomicBinary(MI, BB, 4, 0); 10582 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10583 BB = EmitAtomicBinary(MI, BB, 8, 0); 10584 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10585 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10586 (Subtarget.hasPartwordAtomics() && 10587 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10588 (Subtarget.hasPartwordAtomics() && 10589 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10590 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10591 10592 auto LoadMnemonic = PPC::LDARX; 10593 auto StoreMnemonic = PPC::STDCX; 10594 switch (MI.getOpcode()) { 10595 default: 10596 llvm_unreachable("Compare and swap of unknown size"); 10597 case PPC::ATOMIC_CMP_SWAP_I8: 10598 LoadMnemonic = PPC::LBARX; 10599 StoreMnemonic = PPC::STBCX; 10600 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10601 break; 10602 case PPC::ATOMIC_CMP_SWAP_I16: 10603 LoadMnemonic = PPC::LHARX; 10604 StoreMnemonic = PPC::STHCX; 10605 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10606 break; 10607 case PPC::ATOMIC_CMP_SWAP_I32: 10608 LoadMnemonic = PPC::LWARX; 10609 StoreMnemonic = PPC::STWCX; 10610 break; 10611 case PPC::ATOMIC_CMP_SWAP_I64: 10612 LoadMnemonic = PPC::LDARX; 10613 StoreMnemonic = PPC::STDCX; 10614 break; 10615 } 10616 unsigned dest = MI.getOperand(0).getReg(); 10617 unsigned ptrA = MI.getOperand(1).getReg(); 10618 unsigned ptrB = MI.getOperand(2).getReg(); 10619 unsigned oldval = MI.getOperand(3).getReg(); 10620 unsigned newval = MI.getOperand(4).getReg(); 10621 DebugLoc dl = MI.getDebugLoc(); 10622 10623 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10624 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10625 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10626 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10627 F->insert(It, loop1MBB); 10628 F->insert(It, loop2MBB); 10629 F->insert(It, midMBB); 10630 F->insert(It, exitMBB); 10631 exitMBB->splice(exitMBB->begin(), BB, 10632 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10633 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10634 10635 // thisMBB: 10636 // ... 10637 // fallthrough --> loopMBB 10638 BB->addSuccessor(loop1MBB); 10639 10640 // loop1MBB: 10641 // l[bhwd]arx dest, ptr 10642 // cmp[wd] dest, oldval 10643 // bne- midMBB 10644 // loop2MBB: 10645 // st[bhwd]cx. newval, ptr 10646 // bne- loopMBB 10647 // b exitBB 10648 // midMBB: 10649 // st[bhwd]cx. dest, ptr 10650 // exitBB: 10651 BB = loop1MBB; 10652 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10653 .addReg(ptrA).addReg(ptrB); 10654 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10655 .addReg(oldval).addReg(dest); 10656 BuildMI(BB, dl, TII->get(PPC::BCC)) 10657 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10658 BB->addSuccessor(loop2MBB); 10659 BB->addSuccessor(midMBB); 10660 10661 BB = loop2MBB; 10662 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10663 .addReg(newval).addReg(ptrA).addReg(ptrB); 10664 BuildMI(BB, dl, TII->get(PPC::BCC)) 10665 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10666 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10667 BB->addSuccessor(loop1MBB); 10668 BB->addSuccessor(exitMBB); 10669 10670 BB = midMBB; 10671 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10672 .addReg(dest).addReg(ptrA).addReg(ptrB); 10673 BB->addSuccessor(exitMBB); 10674 10675 // exitMBB: 10676 // ... 10677 BB = exitMBB; 10678 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 10679 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 10680 // We must use 64-bit registers for addresses when targeting 64-bit, 10681 // since we're actually doing arithmetic on them. Other registers 10682 // can be 32-bit. 10683 bool is64bit = Subtarget.isPPC64(); 10684 bool isLittleEndian = Subtarget.isLittleEndian(); 10685 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 10686 10687 unsigned dest = MI.getOperand(0).getReg(); 10688 unsigned ptrA = MI.getOperand(1).getReg(); 10689 unsigned ptrB = MI.getOperand(2).getReg(); 10690 unsigned oldval = MI.getOperand(3).getReg(); 10691 unsigned newval = MI.getOperand(4).getReg(); 10692 DebugLoc dl = MI.getDebugLoc(); 10693 10694 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10695 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10696 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10697 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10698 F->insert(It, loop1MBB); 10699 F->insert(It, loop2MBB); 10700 F->insert(It, midMBB); 10701 F->insert(It, exitMBB); 10702 exitMBB->splice(exitMBB->begin(), BB, 10703 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10704 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10705 10706 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10707 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 10708 : &PPC::GPRCRegClass; 10709 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10710 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 10711 unsigned ShiftReg = 10712 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 10713 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 10714 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 10715 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 10716 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 10717 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 10718 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 10719 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 10720 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 10721 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 10722 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 10723 unsigned Ptr1Reg; 10724 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 10725 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10726 // thisMBB: 10727 // ... 10728 // fallthrough --> loopMBB 10729 BB->addSuccessor(loop1MBB); 10730 10731 // The 4-byte load must be aligned, while a char or short may be 10732 // anywhere in the word. Hence all this nasty bookkeeping code. 10733 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10734 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10735 // xori shift, shift1, 24 [16] 10736 // rlwinm ptr, ptr1, 0, 0, 29 10737 // slw newval2, newval, shift 10738 // slw oldval2, oldval,shift 10739 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10740 // slw mask, mask2, shift 10741 // and newval3, newval2, mask 10742 // and oldval3, oldval2, mask 10743 // loop1MBB: 10744 // lwarx tmpDest, ptr 10745 // and tmp, tmpDest, mask 10746 // cmpw tmp, oldval3 10747 // bne- midMBB 10748 // loop2MBB: 10749 // andc tmp2, tmpDest, mask 10750 // or tmp4, tmp2, newval3 10751 // stwcx. tmp4, ptr 10752 // bne- loop1MBB 10753 // b exitBB 10754 // midMBB: 10755 // stwcx. tmpDest, ptr 10756 // exitBB: 10757 // srw dest, tmpDest, shift 10758 if (ptrA != ZeroReg) { 10759 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10760 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10761 .addReg(ptrA).addReg(ptrB); 10762 } else { 10763 Ptr1Reg = ptrB; 10764 } 10765 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 10766 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 10767 if (!isLittleEndian) 10768 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 10769 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 10770 if (is64bit) 10771 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10772 .addReg(Ptr1Reg).addImm(0).addImm(61); 10773 else 10774 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10775 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 10776 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 10777 .addReg(newval).addReg(ShiftReg); 10778 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 10779 .addReg(oldval).addReg(ShiftReg); 10780 if (is8bit) 10781 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10782 else { 10783 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10784 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10785 .addReg(Mask3Reg).addImm(65535); 10786 } 10787 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10788 .addReg(Mask2Reg).addReg(ShiftReg); 10789 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 10790 .addReg(NewVal2Reg).addReg(MaskReg); 10791 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 10792 .addReg(OldVal2Reg).addReg(MaskReg); 10793 10794 BB = loop1MBB; 10795 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10796 .addReg(ZeroReg).addReg(PtrReg); 10797 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 10798 .addReg(TmpDestReg).addReg(MaskReg); 10799 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 10800 .addReg(TmpReg).addReg(OldVal3Reg); 10801 BuildMI(BB, dl, TII->get(PPC::BCC)) 10802 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10803 BB->addSuccessor(loop2MBB); 10804 BB->addSuccessor(midMBB); 10805 10806 BB = loop2MBB; 10807 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 10808 .addReg(TmpDestReg).addReg(MaskReg); 10809 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 10810 .addReg(Tmp2Reg).addReg(NewVal3Reg); 10811 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 10812 .addReg(ZeroReg).addReg(PtrReg); 10813 BuildMI(BB, dl, TII->get(PPC::BCC)) 10814 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10815 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10816 BB->addSuccessor(loop1MBB); 10817 BB->addSuccessor(exitMBB); 10818 10819 BB = midMBB; 10820 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 10821 .addReg(ZeroReg).addReg(PtrReg); 10822 BB->addSuccessor(exitMBB); 10823 10824 // exitMBB: 10825 // ... 10826 BB = exitMBB; 10827 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 10828 .addReg(ShiftReg); 10829 } else if (MI.getOpcode() == PPC::FADDrtz) { 10830 // This pseudo performs an FADD with rounding mode temporarily forced 10831 // to round-to-zero. We emit this via custom inserter since the FPSCR 10832 // is not modeled at the SelectionDAG level. 10833 unsigned Dest = MI.getOperand(0).getReg(); 10834 unsigned Src1 = MI.getOperand(1).getReg(); 10835 unsigned Src2 = MI.getOperand(2).getReg(); 10836 DebugLoc dl = MI.getDebugLoc(); 10837 10838 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10839 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 10840 10841 // Save FPSCR value. 10842 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 10843 10844 // Set rounding mode to round-to-zero. 10845 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 10846 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 10847 10848 // Perform addition. 10849 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 10850 10851 // Restore FPSCR value. 10852 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 10853 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10854 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 10855 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10856 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 10857 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10858 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 10859 ? PPC::ANDIo8 10860 : PPC::ANDIo; 10861 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10862 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 10863 10864 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10865 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? 10866 &PPC::GPRCRegClass : 10867 &PPC::G8RCRegClass); 10868 10869 DebugLoc dl = MI.getDebugLoc(); 10870 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 10871 .addReg(MI.getOperand(1).getReg()) 10872 .addImm(1); 10873 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 10874 MI.getOperand(0).getReg()) 10875 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 10876 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 10877 DebugLoc Dl = MI.getDebugLoc(); 10878 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10879 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10880 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 10881 return BB; 10882 } else { 10883 llvm_unreachable("Unexpected instr type to insert"); 10884 } 10885 10886 MI.eraseFromParent(); // The pseudo instruction is gone now. 10887 return BB; 10888 } 10889 10890 //===----------------------------------------------------------------------===// 10891 // Target Optimization Hooks 10892 //===----------------------------------------------------------------------===// 10893 10894 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 10895 // For the estimates, convergence is quadratic, so we essentially double the 10896 // number of digits correct after every iteration. For both FRE and FRSQRTE, 10897 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 10898 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 10899 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 10900 if (VT.getScalarType() == MVT::f64) 10901 RefinementSteps++; 10902 return RefinementSteps; 10903 } 10904 10905 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 10906 int Enabled, int &RefinementSteps, 10907 bool &UseOneConstNR, 10908 bool Reciprocal) const { 10909 EVT VT = Operand.getValueType(); 10910 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 10911 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 10912 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10913 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10914 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10915 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10916 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10917 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10918 10919 UseOneConstNR = true; 10920 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 10921 } 10922 return SDValue(); 10923 } 10924 10925 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 10926 int Enabled, 10927 int &RefinementSteps) const { 10928 EVT VT = Operand.getValueType(); 10929 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 10930 (VT == MVT::f64 && Subtarget.hasFRE()) || 10931 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10932 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10933 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10934 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10935 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10936 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10937 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 10938 } 10939 return SDValue(); 10940 } 10941 10942 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 10943 // Note: This functionality is used only when unsafe-fp-math is enabled, and 10944 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 10945 // enabled for division), this functionality is redundant with the default 10946 // combiner logic (once the division -> reciprocal/multiply transformation 10947 // has taken place). As a result, this matters more for older cores than for 10948 // newer ones. 10949 10950 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10951 // reciprocal if there are two or more FDIVs (for embedded cores with only 10952 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 10953 switch (Subtarget.getDarwinDirective()) { 10954 default: 10955 return 3; 10956 case PPC::DIR_440: 10957 case PPC::DIR_A2: 10958 case PPC::DIR_E500: 10959 case PPC::DIR_E500mc: 10960 case PPC::DIR_E5500: 10961 return 2; 10962 } 10963 } 10964 10965 // isConsecutiveLSLoc needs to work even if all adds have not yet been 10966 // collapsed, and so we need to look through chains of them. 10967 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 10968 int64_t& Offset, SelectionDAG &DAG) { 10969 if (DAG.isBaseWithConstantOffset(Loc)) { 10970 Base = Loc.getOperand(0); 10971 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 10972 10973 // The base might itself be a base plus an offset, and if so, accumulate 10974 // that as well. 10975 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 10976 } 10977 } 10978 10979 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 10980 unsigned Bytes, int Dist, 10981 SelectionDAG &DAG) { 10982 if (VT.getSizeInBits() / 8 != Bytes) 10983 return false; 10984 10985 SDValue BaseLoc = Base->getBasePtr(); 10986 if (Loc.getOpcode() == ISD::FrameIndex) { 10987 if (BaseLoc.getOpcode() != ISD::FrameIndex) 10988 return false; 10989 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10990 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 10991 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 10992 int FS = MFI.getObjectSize(FI); 10993 int BFS = MFI.getObjectSize(BFI); 10994 if (FS != BFS || FS != (int)Bytes) return false; 10995 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 10996 } 10997 10998 SDValue Base1 = Loc, Base2 = BaseLoc; 10999 int64_t Offset1 = 0, Offset2 = 0; 11000 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 11001 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 11002 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 11003 return true; 11004 11005 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11006 const GlobalValue *GV1 = nullptr; 11007 const GlobalValue *GV2 = nullptr; 11008 Offset1 = 0; 11009 Offset2 = 0; 11010 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 11011 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 11012 if (isGA1 && isGA2 && GV1 == GV2) 11013 return Offset1 == (Offset2 + Dist*Bytes); 11014 return false; 11015 } 11016 11017 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11018 // not enforce equality of the chain operands. 11019 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11020 unsigned Bytes, int Dist, 11021 SelectionDAG &DAG) { 11022 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11023 EVT VT = LS->getMemoryVT(); 11024 SDValue Loc = LS->getBasePtr(); 11025 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11026 } 11027 11028 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11029 EVT VT; 11030 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11031 default: return false; 11032 case Intrinsic::ppc_qpx_qvlfd: 11033 case Intrinsic::ppc_qpx_qvlfda: 11034 VT = MVT::v4f64; 11035 break; 11036 case Intrinsic::ppc_qpx_qvlfs: 11037 case Intrinsic::ppc_qpx_qvlfsa: 11038 VT = MVT::v4f32; 11039 break; 11040 case Intrinsic::ppc_qpx_qvlfcd: 11041 case Intrinsic::ppc_qpx_qvlfcda: 11042 VT = MVT::v2f64; 11043 break; 11044 case Intrinsic::ppc_qpx_qvlfcs: 11045 case Intrinsic::ppc_qpx_qvlfcsa: 11046 VT = MVT::v2f32; 11047 break; 11048 case Intrinsic::ppc_qpx_qvlfiwa: 11049 case Intrinsic::ppc_qpx_qvlfiwz: 11050 case Intrinsic::ppc_altivec_lvx: 11051 case Intrinsic::ppc_altivec_lvxl: 11052 case Intrinsic::ppc_vsx_lxvw4x: 11053 case Intrinsic::ppc_vsx_lxvw4x_be: 11054 VT = MVT::v4i32; 11055 break; 11056 case Intrinsic::ppc_vsx_lxvd2x: 11057 case Intrinsic::ppc_vsx_lxvd2x_be: 11058 VT = MVT::v2f64; 11059 break; 11060 case Intrinsic::ppc_altivec_lvebx: 11061 VT = MVT::i8; 11062 break; 11063 case Intrinsic::ppc_altivec_lvehx: 11064 VT = MVT::i16; 11065 break; 11066 case Intrinsic::ppc_altivec_lvewx: 11067 VT = MVT::i32; 11068 break; 11069 } 11070 11071 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 11072 } 11073 11074 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 11075 EVT VT; 11076 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11077 default: return false; 11078 case Intrinsic::ppc_qpx_qvstfd: 11079 case Intrinsic::ppc_qpx_qvstfda: 11080 VT = MVT::v4f64; 11081 break; 11082 case Intrinsic::ppc_qpx_qvstfs: 11083 case Intrinsic::ppc_qpx_qvstfsa: 11084 VT = MVT::v4f32; 11085 break; 11086 case Intrinsic::ppc_qpx_qvstfcd: 11087 case Intrinsic::ppc_qpx_qvstfcda: 11088 VT = MVT::v2f64; 11089 break; 11090 case Intrinsic::ppc_qpx_qvstfcs: 11091 case Intrinsic::ppc_qpx_qvstfcsa: 11092 VT = MVT::v2f32; 11093 break; 11094 case Intrinsic::ppc_qpx_qvstfiw: 11095 case Intrinsic::ppc_qpx_qvstfiwa: 11096 case Intrinsic::ppc_altivec_stvx: 11097 case Intrinsic::ppc_altivec_stvxl: 11098 case Intrinsic::ppc_vsx_stxvw4x: 11099 VT = MVT::v4i32; 11100 break; 11101 case Intrinsic::ppc_vsx_stxvd2x: 11102 VT = MVT::v2f64; 11103 break; 11104 case Intrinsic::ppc_vsx_stxvw4x_be: 11105 VT = MVT::v4i32; 11106 break; 11107 case Intrinsic::ppc_vsx_stxvd2x_be: 11108 VT = MVT::v2f64; 11109 break; 11110 case Intrinsic::ppc_altivec_stvebx: 11111 VT = MVT::i8; 11112 break; 11113 case Intrinsic::ppc_altivec_stvehx: 11114 VT = MVT::i16; 11115 break; 11116 case Intrinsic::ppc_altivec_stvewx: 11117 VT = MVT::i32; 11118 break; 11119 } 11120 11121 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 11122 } 11123 11124 return false; 11125 } 11126 11127 // Return true is there is a nearyby consecutive load to the one provided 11128 // (regardless of alignment). We search up and down the chain, looking though 11129 // token factors and other loads (but nothing else). As a result, a true result 11130 // indicates that it is safe to create a new consecutive load adjacent to the 11131 // load provided. 11132 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 11133 SDValue Chain = LD->getChain(); 11134 EVT VT = LD->getMemoryVT(); 11135 11136 SmallSet<SDNode *, 16> LoadRoots; 11137 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 11138 SmallSet<SDNode *, 16> Visited; 11139 11140 // First, search up the chain, branching to follow all token-factor operands. 11141 // If we find a consecutive load, then we're done, otherwise, record all 11142 // nodes just above the top-level loads and token factors. 11143 while (!Queue.empty()) { 11144 SDNode *ChainNext = Queue.pop_back_val(); 11145 if (!Visited.insert(ChainNext).second) 11146 continue; 11147 11148 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 11149 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11150 return true; 11151 11152 if (!Visited.count(ChainLD->getChain().getNode())) 11153 Queue.push_back(ChainLD->getChain().getNode()); 11154 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 11155 for (const SDUse &O : ChainNext->ops()) 11156 if (!Visited.count(O.getNode())) 11157 Queue.push_back(O.getNode()); 11158 } else 11159 LoadRoots.insert(ChainNext); 11160 } 11161 11162 // Second, search down the chain, starting from the top-level nodes recorded 11163 // in the first phase. These top-level nodes are the nodes just above all 11164 // loads and token factors. Starting with their uses, recursively look though 11165 // all loads (just the chain uses) and token factors to find a consecutive 11166 // load. 11167 Visited.clear(); 11168 Queue.clear(); 11169 11170 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 11171 IE = LoadRoots.end(); I != IE; ++I) { 11172 Queue.push_back(*I); 11173 11174 while (!Queue.empty()) { 11175 SDNode *LoadRoot = Queue.pop_back_val(); 11176 if (!Visited.insert(LoadRoot).second) 11177 continue; 11178 11179 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 11180 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11181 return true; 11182 11183 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 11184 UE = LoadRoot->use_end(); UI != UE; ++UI) 11185 if (((isa<MemSDNode>(*UI) && 11186 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 11187 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 11188 Queue.push_back(*UI); 11189 } 11190 } 11191 11192 return false; 11193 } 11194 11195 /// This function is called when we have proved that a SETCC node can be replaced 11196 /// by subtraction (and other supporting instructions) so that the result of 11197 /// comparison is kept in a GPR instead of CR. This function is purely for 11198 /// codegen purposes and has some flags to guide the codegen process. 11199 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 11200 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 11201 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11202 11203 // Zero extend the operands to the largest legal integer. Originally, they 11204 // must be of a strictly smaller size. 11205 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 11206 DAG.getConstant(Size, DL, MVT::i32)); 11207 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 11208 DAG.getConstant(Size, DL, MVT::i32)); 11209 11210 // Swap if needed. Depends on the condition code. 11211 if (Swap) 11212 std::swap(Op0, Op1); 11213 11214 // Subtract extended integers. 11215 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 11216 11217 // Move the sign bit to the least significant position and zero out the rest. 11218 // Now the least significant bit carries the result of original comparison. 11219 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 11220 DAG.getConstant(Size - 1, DL, MVT::i32)); 11221 auto Final = Shifted; 11222 11223 // Complement the result if needed. Based on the condition code. 11224 if (Complement) 11225 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 11226 DAG.getConstant(1, DL, MVT::i64)); 11227 11228 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11229 } 11230 11231 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11232 DAGCombinerInfo &DCI) const { 11233 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11234 11235 SelectionDAG &DAG = DCI.DAG; 11236 SDLoc DL(N); 11237 11238 // Size of integers being compared has a critical role in the following 11239 // analysis, so we prefer to do this when all types are legal. 11240 if (!DCI.isAfterLegalizeDAG()) 11241 return SDValue(); 11242 11243 // If all users of SETCC extend its value to a legal integer type 11244 // then we replace SETCC with a subtraction 11245 for (SDNode::use_iterator UI = N->use_begin(), 11246 UE = N->use_end(); UI != UE; ++UI) { 11247 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11248 return SDValue(); 11249 } 11250 11251 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11252 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11253 11254 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11255 11256 if (OpSize < Size) { 11257 switch (CC) { 11258 default: break; 11259 case ISD::SETULT: 11260 return generateEquivalentSub(N, Size, false, false, DL, DAG); 11261 case ISD::SETULE: 11262 return generateEquivalentSub(N, Size, true, true, DL, DAG); 11263 case ISD::SETUGT: 11264 return generateEquivalentSub(N, Size, false, true, DL, DAG); 11265 case ISD::SETUGE: 11266 return generateEquivalentSub(N, Size, true, false, DL, DAG); 11267 } 11268 } 11269 11270 return SDValue(); 11271 } 11272 11273 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 11274 DAGCombinerInfo &DCI) const { 11275 SelectionDAG &DAG = DCI.DAG; 11276 SDLoc dl(N); 11277 11278 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11279 // If we're tracking CR bits, we need to be careful that we don't have: 11280 // trunc(binary-ops(zext(x), zext(y))) 11281 // or 11282 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11283 // such that we're unnecessarily moving things into GPRs when it would be 11284 // better to keep them in CR bits. 11285 11286 // Note that trunc here can be an actual i1 trunc, or can be the effective 11287 // truncation that comes from a setcc or select_cc. 11288 if (N->getOpcode() == ISD::TRUNCATE && 11289 N->getValueType(0) != MVT::i1) 11290 return SDValue(); 11291 11292 if (N->getOperand(0).getValueType() != MVT::i32 && 11293 N->getOperand(0).getValueType() != MVT::i64) 11294 return SDValue(); 11295 11296 if (N->getOpcode() == ISD::SETCC || 11297 N->getOpcode() == ISD::SELECT_CC) { 11298 // If we're looking at a comparison, then we need to make sure that the 11299 // high bits (all except for the first) don't matter the result. 11300 ISD::CondCode CC = 11301 cast<CondCodeSDNode>(N->getOperand( 11302 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11303 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11304 11305 if (ISD::isSignedIntSetCC(CC)) { 11306 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11307 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11308 return SDValue(); 11309 } else if (ISD::isUnsignedIntSetCC(CC)) { 11310 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11311 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11312 !DAG.MaskedValueIsZero(N->getOperand(1), 11313 APInt::getHighBitsSet(OpBits, OpBits-1))) 11314 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11315 : SDValue()); 11316 } else { 11317 // This is neither a signed nor an unsigned comparison, just make sure 11318 // that the high bits are equal. 11319 KnownBits Op1Known, Op2Known; 11320 DAG.computeKnownBits(N->getOperand(0), Op1Known); 11321 DAG.computeKnownBits(N->getOperand(1), Op2Known); 11322 11323 // We don't really care about what is known about the first bit (if 11324 // anything), so clear it in all masks prior to comparing them. 11325 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11326 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11327 11328 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11329 return SDValue(); 11330 } 11331 } 11332 11333 // We now know that the higher-order bits are irrelevant, we just need to 11334 // make sure that all of the intermediate operations are bit operations, and 11335 // all inputs are extensions. 11336 if (N->getOperand(0).getOpcode() != ISD::AND && 11337 N->getOperand(0).getOpcode() != ISD::OR && 11338 N->getOperand(0).getOpcode() != ISD::XOR && 11339 N->getOperand(0).getOpcode() != ISD::SELECT && 11340 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11341 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11342 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11343 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11344 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11345 return SDValue(); 11346 11347 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11348 N->getOperand(1).getOpcode() != ISD::AND && 11349 N->getOperand(1).getOpcode() != ISD::OR && 11350 N->getOperand(1).getOpcode() != ISD::XOR && 11351 N->getOperand(1).getOpcode() != ISD::SELECT && 11352 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11353 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11354 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11355 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11356 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11357 return SDValue(); 11358 11359 SmallVector<SDValue, 4> Inputs; 11360 SmallVector<SDValue, 8> BinOps, PromOps; 11361 SmallPtrSet<SDNode *, 16> Visited; 11362 11363 for (unsigned i = 0; i < 2; ++i) { 11364 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11365 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11366 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11367 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11368 isa<ConstantSDNode>(N->getOperand(i))) 11369 Inputs.push_back(N->getOperand(i)); 11370 else 11371 BinOps.push_back(N->getOperand(i)); 11372 11373 if (N->getOpcode() == ISD::TRUNCATE) 11374 break; 11375 } 11376 11377 // Visit all inputs, collect all binary operations (and, or, xor and 11378 // select) that are all fed by extensions. 11379 while (!BinOps.empty()) { 11380 SDValue BinOp = BinOps.back(); 11381 BinOps.pop_back(); 11382 11383 if (!Visited.insert(BinOp.getNode()).second) 11384 continue; 11385 11386 PromOps.push_back(BinOp); 11387 11388 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11389 // The condition of the select is not promoted. 11390 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11391 continue; 11392 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11393 continue; 11394 11395 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11396 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11397 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11398 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11399 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11400 Inputs.push_back(BinOp.getOperand(i)); 11401 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11402 BinOp.getOperand(i).getOpcode() == ISD::OR || 11403 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11404 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11405 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11406 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11407 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11408 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11409 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11410 BinOps.push_back(BinOp.getOperand(i)); 11411 } else { 11412 // We have an input that is not an extension or another binary 11413 // operation; we'll abort this transformation. 11414 return SDValue(); 11415 } 11416 } 11417 } 11418 11419 // Make sure that this is a self-contained cluster of operations (which 11420 // is not quite the same thing as saying that everything has only one 11421 // use). 11422 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11423 if (isa<ConstantSDNode>(Inputs[i])) 11424 continue; 11425 11426 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11427 UE = Inputs[i].getNode()->use_end(); 11428 UI != UE; ++UI) { 11429 SDNode *User = *UI; 11430 if (User != N && !Visited.count(User)) 11431 return SDValue(); 11432 11433 // Make sure that we're not going to promote the non-output-value 11434 // operand(s) or SELECT or SELECT_CC. 11435 // FIXME: Although we could sometimes handle this, and it does occur in 11436 // practice that one of the condition inputs to the select is also one of 11437 // the outputs, we currently can't deal with this. 11438 if (User->getOpcode() == ISD::SELECT) { 11439 if (User->getOperand(0) == Inputs[i]) 11440 return SDValue(); 11441 } else if (User->getOpcode() == ISD::SELECT_CC) { 11442 if (User->getOperand(0) == Inputs[i] || 11443 User->getOperand(1) == Inputs[i]) 11444 return SDValue(); 11445 } 11446 } 11447 } 11448 11449 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11450 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11451 UE = PromOps[i].getNode()->use_end(); 11452 UI != UE; ++UI) { 11453 SDNode *User = *UI; 11454 if (User != N && !Visited.count(User)) 11455 return SDValue(); 11456 11457 // Make sure that we're not going to promote the non-output-value 11458 // operand(s) or SELECT or SELECT_CC. 11459 // FIXME: Although we could sometimes handle this, and it does occur in 11460 // practice that one of the condition inputs to the select is also one of 11461 // the outputs, we currently can't deal with this. 11462 if (User->getOpcode() == ISD::SELECT) { 11463 if (User->getOperand(0) == PromOps[i]) 11464 return SDValue(); 11465 } else if (User->getOpcode() == ISD::SELECT_CC) { 11466 if (User->getOperand(0) == PromOps[i] || 11467 User->getOperand(1) == PromOps[i]) 11468 return SDValue(); 11469 } 11470 } 11471 } 11472 11473 // Replace all inputs with the extension operand. 11474 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11475 // Constants may have users outside the cluster of to-be-promoted nodes, 11476 // and so we need to replace those as we do the promotions. 11477 if (isa<ConstantSDNode>(Inputs[i])) 11478 continue; 11479 else 11480 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 11481 } 11482 11483 std::list<HandleSDNode> PromOpHandles; 11484 for (auto &PromOp : PromOps) 11485 PromOpHandles.emplace_back(PromOp); 11486 11487 // Replace all operations (these are all the same, but have a different 11488 // (i1) return type). DAG.getNode will validate that the types of 11489 // a binary operator match, so go through the list in reverse so that 11490 // we've likely promoted both operands first. Any intermediate truncations or 11491 // extensions disappear. 11492 while (!PromOpHandles.empty()) { 11493 SDValue PromOp = PromOpHandles.back().getValue(); 11494 PromOpHandles.pop_back(); 11495 11496 if (PromOp.getOpcode() == ISD::TRUNCATE || 11497 PromOp.getOpcode() == ISD::SIGN_EXTEND || 11498 PromOp.getOpcode() == ISD::ZERO_EXTEND || 11499 PromOp.getOpcode() == ISD::ANY_EXTEND) { 11500 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 11501 PromOp.getOperand(0).getValueType() != MVT::i1) { 11502 // The operand is not yet ready (see comment below). 11503 PromOpHandles.emplace_front(PromOp); 11504 continue; 11505 } 11506 11507 SDValue RepValue = PromOp.getOperand(0); 11508 if (isa<ConstantSDNode>(RepValue)) 11509 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 11510 11511 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 11512 continue; 11513 } 11514 11515 unsigned C; 11516 switch (PromOp.getOpcode()) { 11517 default: C = 0; break; 11518 case ISD::SELECT: C = 1; break; 11519 case ISD::SELECT_CC: C = 2; break; 11520 } 11521 11522 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11523 PromOp.getOperand(C).getValueType() != MVT::i1) || 11524 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11525 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 11526 // The to-be-promoted operands of this node have not yet been 11527 // promoted (this should be rare because we're going through the 11528 // list backward, but if one of the operands has several users in 11529 // this cluster of to-be-promoted nodes, it is possible). 11530 PromOpHandles.emplace_front(PromOp); 11531 continue; 11532 } 11533 11534 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11535 PromOp.getNode()->op_end()); 11536 11537 // If there are any constant inputs, make sure they're replaced now. 11538 for (unsigned i = 0; i < 2; ++i) 11539 if (isa<ConstantSDNode>(Ops[C+i])) 11540 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 11541 11542 DAG.ReplaceAllUsesOfValueWith(PromOp, 11543 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 11544 } 11545 11546 // Now we're left with the initial truncation itself. 11547 if (N->getOpcode() == ISD::TRUNCATE) 11548 return N->getOperand(0); 11549 11550 // Otherwise, this is a comparison. The operands to be compared have just 11551 // changed type (to i1), but everything else is the same. 11552 return SDValue(N, 0); 11553 } 11554 11555 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 11556 DAGCombinerInfo &DCI) const { 11557 SelectionDAG &DAG = DCI.DAG; 11558 SDLoc dl(N); 11559 11560 // If we're tracking CR bits, we need to be careful that we don't have: 11561 // zext(binary-ops(trunc(x), trunc(y))) 11562 // or 11563 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 11564 // such that we're unnecessarily moving things into CR bits that can more 11565 // efficiently stay in GPRs. Note that if we're not certain that the high 11566 // bits are set as required by the final extension, we still may need to do 11567 // some masking to get the proper behavior. 11568 11569 // This same functionality is important on PPC64 when dealing with 11570 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 11571 // the return values of functions. Because it is so similar, it is handled 11572 // here as well. 11573 11574 if (N->getValueType(0) != MVT::i32 && 11575 N->getValueType(0) != MVT::i64) 11576 return SDValue(); 11577 11578 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 11579 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 11580 return SDValue(); 11581 11582 if (N->getOperand(0).getOpcode() != ISD::AND && 11583 N->getOperand(0).getOpcode() != ISD::OR && 11584 N->getOperand(0).getOpcode() != ISD::XOR && 11585 N->getOperand(0).getOpcode() != ISD::SELECT && 11586 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 11587 return SDValue(); 11588 11589 SmallVector<SDValue, 4> Inputs; 11590 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 11591 SmallPtrSet<SDNode *, 16> Visited; 11592 11593 // Visit all inputs, collect all binary operations (and, or, xor and 11594 // select) that are all fed by truncations. 11595 while (!BinOps.empty()) { 11596 SDValue BinOp = BinOps.back(); 11597 BinOps.pop_back(); 11598 11599 if (!Visited.insert(BinOp.getNode()).second) 11600 continue; 11601 11602 PromOps.push_back(BinOp); 11603 11604 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11605 // The condition of the select is not promoted. 11606 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11607 continue; 11608 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11609 continue; 11610 11611 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11612 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11613 Inputs.push_back(BinOp.getOperand(i)); 11614 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11615 BinOp.getOperand(i).getOpcode() == ISD::OR || 11616 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11617 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11618 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 11619 BinOps.push_back(BinOp.getOperand(i)); 11620 } else { 11621 // We have an input that is not a truncation or another binary 11622 // operation; we'll abort this transformation. 11623 return SDValue(); 11624 } 11625 } 11626 } 11627 11628 // The operands of a select that must be truncated when the select is 11629 // promoted because the operand is actually part of the to-be-promoted set. 11630 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 11631 11632 // Make sure that this is a self-contained cluster of operations (which 11633 // is not quite the same thing as saying that everything has only one 11634 // use). 11635 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11636 if (isa<ConstantSDNode>(Inputs[i])) 11637 continue; 11638 11639 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11640 UE = Inputs[i].getNode()->use_end(); 11641 UI != UE; ++UI) { 11642 SDNode *User = *UI; 11643 if (User != N && !Visited.count(User)) 11644 return SDValue(); 11645 11646 // If we're going to promote the non-output-value operand(s) or SELECT or 11647 // SELECT_CC, record them for truncation. 11648 if (User->getOpcode() == ISD::SELECT) { 11649 if (User->getOperand(0) == Inputs[i]) 11650 SelectTruncOp[0].insert(std::make_pair(User, 11651 User->getOperand(0).getValueType())); 11652 } else if (User->getOpcode() == ISD::SELECT_CC) { 11653 if (User->getOperand(0) == Inputs[i]) 11654 SelectTruncOp[0].insert(std::make_pair(User, 11655 User->getOperand(0).getValueType())); 11656 if (User->getOperand(1) == Inputs[i]) 11657 SelectTruncOp[1].insert(std::make_pair(User, 11658 User->getOperand(1).getValueType())); 11659 } 11660 } 11661 } 11662 11663 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11664 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11665 UE = PromOps[i].getNode()->use_end(); 11666 UI != UE; ++UI) { 11667 SDNode *User = *UI; 11668 if (User != N && !Visited.count(User)) 11669 return SDValue(); 11670 11671 // If we're going to promote the non-output-value operand(s) or SELECT or 11672 // SELECT_CC, record them for truncation. 11673 if (User->getOpcode() == ISD::SELECT) { 11674 if (User->getOperand(0) == PromOps[i]) 11675 SelectTruncOp[0].insert(std::make_pair(User, 11676 User->getOperand(0).getValueType())); 11677 } else if (User->getOpcode() == ISD::SELECT_CC) { 11678 if (User->getOperand(0) == PromOps[i]) 11679 SelectTruncOp[0].insert(std::make_pair(User, 11680 User->getOperand(0).getValueType())); 11681 if (User->getOperand(1) == PromOps[i]) 11682 SelectTruncOp[1].insert(std::make_pair(User, 11683 User->getOperand(1).getValueType())); 11684 } 11685 } 11686 } 11687 11688 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 11689 bool ReallyNeedsExt = false; 11690 if (N->getOpcode() != ISD::ANY_EXTEND) { 11691 // If all of the inputs are not already sign/zero extended, then 11692 // we'll still need to do that at the end. 11693 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11694 if (isa<ConstantSDNode>(Inputs[i])) 11695 continue; 11696 11697 unsigned OpBits = 11698 Inputs[i].getOperand(0).getValueSizeInBits(); 11699 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 11700 11701 if ((N->getOpcode() == ISD::ZERO_EXTEND && 11702 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 11703 APInt::getHighBitsSet(OpBits, 11704 OpBits-PromBits))) || 11705 (N->getOpcode() == ISD::SIGN_EXTEND && 11706 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 11707 (OpBits-(PromBits-1)))) { 11708 ReallyNeedsExt = true; 11709 break; 11710 } 11711 } 11712 } 11713 11714 // Replace all inputs, either with the truncation operand, or a 11715 // truncation or extension to the final output type. 11716 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11717 // Constant inputs need to be replaced with the to-be-promoted nodes that 11718 // use them because they might have users outside of the cluster of 11719 // promoted nodes. 11720 if (isa<ConstantSDNode>(Inputs[i])) 11721 continue; 11722 11723 SDValue InSrc = Inputs[i].getOperand(0); 11724 if (Inputs[i].getValueType() == N->getValueType(0)) 11725 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 11726 else if (N->getOpcode() == ISD::SIGN_EXTEND) 11727 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11728 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 11729 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11730 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11731 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 11732 else 11733 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11734 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 11735 } 11736 11737 std::list<HandleSDNode> PromOpHandles; 11738 for (auto &PromOp : PromOps) 11739 PromOpHandles.emplace_back(PromOp); 11740 11741 // Replace all operations (these are all the same, but have a different 11742 // (promoted) return type). DAG.getNode will validate that the types of 11743 // a binary operator match, so go through the list in reverse so that 11744 // we've likely promoted both operands first. 11745 while (!PromOpHandles.empty()) { 11746 SDValue PromOp = PromOpHandles.back().getValue(); 11747 PromOpHandles.pop_back(); 11748 11749 unsigned C; 11750 switch (PromOp.getOpcode()) { 11751 default: C = 0; break; 11752 case ISD::SELECT: C = 1; break; 11753 case ISD::SELECT_CC: C = 2; break; 11754 } 11755 11756 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11757 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 11758 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11759 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 11760 // The to-be-promoted operands of this node have not yet been 11761 // promoted (this should be rare because we're going through the 11762 // list backward, but if one of the operands has several users in 11763 // this cluster of to-be-promoted nodes, it is possible). 11764 PromOpHandles.emplace_front(PromOp); 11765 continue; 11766 } 11767 11768 // For SELECT and SELECT_CC nodes, we do a similar check for any 11769 // to-be-promoted comparison inputs. 11770 if (PromOp.getOpcode() == ISD::SELECT || 11771 PromOp.getOpcode() == ISD::SELECT_CC) { 11772 if ((SelectTruncOp[0].count(PromOp.getNode()) && 11773 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 11774 (SelectTruncOp[1].count(PromOp.getNode()) && 11775 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 11776 PromOpHandles.emplace_front(PromOp); 11777 continue; 11778 } 11779 } 11780 11781 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11782 PromOp.getNode()->op_end()); 11783 11784 // If this node has constant inputs, then they'll need to be promoted here. 11785 for (unsigned i = 0; i < 2; ++i) { 11786 if (!isa<ConstantSDNode>(Ops[C+i])) 11787 continue; 11788 if (Ops[C+i].getValueType() == N->getValueType(0)) 11789 continue; 11790 11791 if (N->getOpcode() == ISD::SIGN_EXTEND) 11792 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11793 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11794 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11795 else 11796 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11797 } 11798 11799 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 11800 // truncate them again to the original value type. 11801 if (PromOp.getOpcode() == ISD::SELECT || 11802 PromOp.getOpcode() == ISD::SELECT_CC) { 11803 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 11804 if (SI0 != SelectTruncOp[0].end()) 11805 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 11806 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 11807 if (SI1 != SelectTruncOp[1].end()) 11808 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 11809 } 11810 11811 DAG.ReplaceAllUsesOfValueWith(PromOp, 11812 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 11813 } 11814 11815 // Now we're left with the initial extension itself. 11816 if (!ReallyNeedsExt) 11817 return N->getOperand(0); 11818 11819 // To zero extend, just mask off everything except for the first bit (in the 11820 // i1 case). 11821 if (N->getOpcode() == ISD::ZERO_EXTEND) 11822 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 11823 DAG.getConstant(APInt::getLowBitsSet( 11824 N->getValueSizeInBits(0), PromBits), 11825 dl, N->getValueType(0))); 11826 11827 assert(N->getOpcode() == ISD::SIGN_EXTEND && 11828 "Invalid extension type"); 11829 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 11830 SDValue ShiftCst = 11831 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 11832 return DAG.getNode( 11833 ISD::SRA, dl, N->getValueType(0), 11834 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 11835 ShiftCst); 11836 } 11837 11838 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 11839 DAGCombinerInfo &DCI) const { 11840 assert(N->getOpcode() == ISD::SETCC && 11841 "Should be called with a SETCC node"); 11842 11843 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11844 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 11845 SDValue LHS = N->getOperand(0); 11846 SDValue RHS = N->getOperand(1); 11847 11848 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 11849 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 11850 LHS.hasOneUse()) 11851 std::swap(LHS, RHS); 11852 11853 // x == 0-y --> x+y == 0 11854 // x != 0-y --> x+y != 0 11855 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 11856 RHS.hasOneUse()) { 11857 SDLoc DL(N); 11858 SelectionDAG &DAG = DCI.DAG; 11859 EVT VT = N->getValueType(0); 11860 EVT OpVT = LHS.getValueType(); 11861 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 11862 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 11863 } 11864 } 11865 11866 return DAGCombineTruncBoolExt(N, DCI); 11867 } 11868 11869 // Is this an extending load from an f32 to an f64? 11870 static bool isFPExtLoad(SDValue Op) { 11871 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 11872 return LD->getExtensionType() == ISD::EXTLOAD && 11873 Op.getValueType() == MVT::f64; 11874 return false; 11875 } 11876 11877 /// Reduces the number of fp-to-int conversion when building a vector. 11878 /// 11879 /// If this vector is built out of floating to integer conversions, 11880 /// transform it to a vector built out of floating point values followed by a 11881 /// single floating to integer conversion of the vector. 11882 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 11883 /// becomes (fptosi (build_vector ($A, $B, ...))) 11884 SDValue PPCTargetLowering:: 11885 combineElementTruncationToVectorTruncation(SDNode *N, 11886 DAGCombinerInfo &DCI) const { 11887 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11888 "Should be called with a BUILD_VECTOR node"); 11889 11890 SelectionDAG &DAG = DCI.DAG; 11891 SDLoc dl(N); 11892 11893 SDValue FirstInput = N->getOperand(0); 11894 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 11895 "The input operand must be an fp-to-int conversion."); 11896 11897 // This combine happens after legalization so the fp_to_[su]i nodes are 11898 // already converted to PPCSISD nodes. 11899 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 11900 if (FirstConversion == PPCISD::FCTIDZ || 11901 FirstConversion == PPCISD::FCTIDUZ || 11902 FirstConversion == PPCISD::FCTIWZ || 11903 FirstConversion == PPCISD::FCTIWUZ) { 11904 bool IsSplat = true; 11905 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 11906 FirstConversion == PPCISD::FCTIWUZ; 11907 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 11908 SmallVector<SDValue, 4> Ops; 11909 EVT TargetVT = N->getValueType(0); 11910 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11911 SDValue NextOp = N->getOperand(i); 11912 if (NextOp.getOpcode() != PPCISD::MFVSR) 11913 return SDValue(); 11914 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 11915 if (NextConversion != FirstConversion) 11916 return SDValue(); 11917 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 11918 // This is not valid if the input was originally double precision. It is 11919 // also not profitable to do unless this is an extending load in which 11920 // case doing this combine will allow us to combine consecutive loads. 11921 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 11922 return SDValue(); 11923 if (N->getOperand(i) != FirstInput) 11924 IsSplat = false; 11925 } 11926 11927 // If this is a splat, we leave it as-is since there will be only a single 11928 // fp-to-int conversion followed by a splat of the integer. This is better 11929 // for 32-bit and smaller ints and neutral for 64-bit ints. 11930 if (IsSplat) 11931 return SDValue(); 11932 11933 // Now that we know we have the right type of node, get its operands 11934 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11935 SDValue In = N->getOperand(i).getOperand(0); 11936 if (Is32Bit) { 11937 // For 32-bit values, we need to add an FP_ROUND node (if we made it 11938 // here, we know that all inputs are extending loads so this is safe). 11939 if (In.isUndef()) 11940 Ops.push_back(DAG.getUNDEF(SrcVT)); 11941 else { 11942 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 11943 MVT::f32, In.getOperand(0), 11944 DAG.getIntPtrConstant(1, dl)); 11945 Ops.push_back(Trunc); 11946 } 11947 } else 11948 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 11949 } 11950 11951 unsigned Opcode; 11952 if (FirstConversion == PPCISD::FCTIDZ || 11953 FirstConversion == PPCISD::FCTIWZ) 11954 Opcode = ISD::FP_TO_SINT; 11955 else 11956 Opcode = ISD::FP_TO_UINT; 11957 11958 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 11959 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 11960 return DAG.getNode(Opcode, dl, TargetVT, BV); 11961 } 11962 return SDValue(); 11963 } 11964 11965 /// Reduce the number of loads when building a vector. 11966 /// 11967 /// Building a vector out of multiple loads can be converted to a load 11968 /// of the vector type if the loads are consecutive. If the loads are 11969 /// consecutive but in descending order, a shuffle is added at the end 11970 /// to reorder the vector. 11971 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 11972 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11973 "Should be called with a BUILD_VECTOR node"); 11974 11975 SDLoc dl(N); 11976 bool InputsAreConsecutiveLoads = true; 11977 bool InputsAreReverseConsecutive = true; 11978 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8; 11979 SDValue FirstInput = N->getOperand(0); 11980 bool IsRoundOfExtLoad = false; 11981 11982 if (FirstInput.getOpcode() == ISD::FP_ROUND && 11983 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 11984 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 11985 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 11986 } 11987 // Not a build vector of (possibly fp_rounded) loads. 11988 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 11989 N->getNumOperands() == 1) 11990 return SDValue(); 11991 11992 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 11993 // If any inputs are fp_round(extload), they all must be. 11994 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 11995 return SDValue(); 11996 11997 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 11998 N->getOperand(i); 11999 if (NextInput.getOpcode() != ISD::LOAD) 12000 return SDValue(); 12001 12002 SDValue PreviousInput = 12003 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 12004 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 12005 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 12006 12007 // If any inputs are fp_round(extload), they all must be. 12008 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 12009 return SDValue(); 12010 12011 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 12012 InputsAreConsecutiveLoads = false; 12013 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 12014 InputsAreReverseConsecutive = false; 12015 12016 // Exit early if the loads are neither consecutive nor reverse consecutive. 12017 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12018 return SDValue(); 12019 } 12020 12021 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12022 "The loads cannot be both consecutive and reverse consecutive."); 12023 12024 SDValue FirstLoadOp = 12025 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12026 SDValue LastLoadOp = 12027 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12028 N->getOperand(N->getNumOperands()-1); 12029 12030 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12031 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12032 if (InputsAreConsecutiveLoads) { 12033 assert(LD1 && "Input needs to be a LoadSDNode."); 12034 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12035 LD1->getBasePtr(), LD1->getPointerInfo(), 12036 LD1->getAlignment()); 12037 } 12038 if (InputsAreReverseConsecutive) { 12039 assert(LDL && "Input needs to be a LoadSDNode."); 12040 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12041 LDL->getBasePtr(), LDL->getPointerInfo(), 12042 LDL->getAlignment()); 12043 SmallVector<int, 16> Ops; 12044 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12045 Ops.push_back(i); 12046 12047 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12048 DAG.getUNDEF(N->getValueType(0)), Ops); 12049 } 12050 return SDValue(); 12051 } 12052 12053 // This function adds the required vector_shuffle needed to get 12054 // the elements of the vector extract in the correct position 12055 // as specified by the CorrectElems encoding. 12056 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12057 SDValue Input, uint64_t Elems, 12058 uint64_t CorrectElems) { 12059 SDLoc dl(N); 12060 12061 unsigned NumElems = Input.getValueType().getVectorNumElements(); 12062 SmallVector<int, 16> ShuffleMask(NumElems, -1); 12063 12064 // Knowing the element indices being extracted from the original 12065 // vector and the order in which they're being inserted, just put 12066 // them at element indices required for the instruction. 12067 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12068 if (DAG.getDataLayout().isLittleEndian()) 12069 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 12070 else 12071 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 12072 CorrectElems = CorrectElems >> 8; 12073 Elems = Elems >> 8; 12074 } 12075 12076 SDValue Shuffle = 12077 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 12078 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 12079 12080 EVT Ty = N->getValueType(0); 12081 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 12082 return BV; 12083 } 12084 12085 // Look for build vector patterns where input operands come from sign 12086 // extended vector_extract elements of specific indices. If the correct indices 12087 // aren't used, add a vector shuffle to fix up the indices and create a new 12088 // PPCISD:SExtVElems node which selects the vector sign extend instructions 12089 // during instruction selection. 12090 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 12091 // This array encodes the indices that the vector sign extend instructions 12092 // extract from when extending from one type to another for both BE and LE. 12093 // The right nibble of each byte corresponds to the LE incides. 12094 // and the left nibble of each byte corresponds to the BE incides. 12095 // For example: 0x3074B8FC byte->word 12096 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 12097 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 12098 // For example: 0x000070F8 byte->double word 12099 // For LE: the allowed indices are: 0x0,0x8 12100 // For BE: the allowed indices are: 0x7,0xF 12101 uint64_t TargetElems[] = { 12102 0x3074B8FC, // b->w 12103 0x000070F8, // b->d 12104 0x10325476, // h->w 12105 0x00003074, // h->d 12106 0x00001032, // w->d 12107 }; 12108 12109 uint64_t Elems = 0; 12110 int Index; 12111 SDValue Input; 12112 12113 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 12114 if (!Op) 12115 return false; 12116 if (Op.getOpcode() != ISD::SIGN_EXTEND && 12117 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 12118 return false; 12119 12120 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 12121 // of the right width. 12122 SDValue Extract = Op.getOperand(0); 12123 if (Extract.getOpcode() == ISD::ANY_EXTEND) 12124 Extract = Extract.getOperand(0); 12125 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12126 return false; 12127 12128 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 12129 if (!ExtOp) 12130 return false; 12131 12132 Index = ExtOp->getZExtValue(); 12133 if (Input && Input != Extract.getOperand(0)) 12134 return false; 12135 12136 if (!Input) 12137 Input = Extract.getOperand(0); 12138 12139 Elems = Elems << 8; 12140 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 12141 Elems |= Index; 12142 12143 return true; 12144 }; 12145 12146 // If the build vector operands aren't sign extended vector extracts, 12147 // of the same input vector, then return. 12148 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12149 if (!isSExtOfVecExtract(N->getOperand(i))) { 12150 return SDValue(); 12151 } 12152 } 12153 12154 // If the vector extract indicies are not correct, add the appropriate 12155 // vector_shuffle. 12156 int TgtElemArrayIdx; 12157 int InputSize = Input.getValueType().getScalarSizeInBits(); 12158 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 12159 if (InputSize + OutputSize == 40) 12160 TgtElemArrayIdx = 0; 12161 else if (InputSize + OutputSize == 72) 12162 TgtElemArrayIdx = 1; 12163 else if (InputSize + OutputSize == 48) 12164 TgtElemArrayIdx = 2; 12165 else if (InputSize + OutputSize == 80) 12166 TgtElemArrayIdx = 3; 12167 else if (InputSize + OutputSize == 96) 12168 TgtElemArrayIdx = 4; 12169 else 12170 return SDValue(); 12171 12172 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 12173 CorrectElems = DAG.getDataLayout().isLittleEndian() 12174 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 12175 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 12176 if (Elems != CorrectElems) { 12177 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 12178 } 12179 12180 // Regular lowering will catch cases where a shuffle is not needed. 12181 return SDValue(); 12182 } 12183 12184 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 12185 DAGCombinerInfo &DCI) const { 12186 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12187 "Should be called with a BUILD_VECTOR node"); 12188 12189 SelectionDAG &DAG = DCI.DAG; 12190 SDLoc dl(N); 12191 12192 if (!Subtarget.hasVSX()) 12193 return SDValue(); 12194 12195 // The target independent DAG combiner will leave a build_vector of 12196 // float-to-int conversions intact. We can generate MUCH better code for 12197 // a float-to-int conversion of a vector of floats. 12198 SDValue FirstInput = N->getOperand(0); 12199 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 12200 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 12201 if (Reduced) 12202 return Reduced; 12203 } 12204 12205 // If we're building a vector out of consecutive loads, just load that 12206 // vector type. 12207 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 12208 if (Reduced) 12209 return Reduced; 12210 12211 // If we're building a vector out of extended elements from another vector 12212 // we have P9 vector integer extend instructions. The code assumes legal 12213 // input types (i.e. it can't handle things like v4i16) so do not run before 12214 // legalization. 12215 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 12216 Reduced = combineBVOfVecSExt(N, DAG); 12217 if (Reduced) 12218 return Reduced; 12219 } 12220 12221 12222 if (N->getValueType(0) != MVT::v2f64) 12223 return SDValue(); 12224 12225 // Looking for: 12226 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 12227 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 12228 FirstInput.getOpcode() != ISD::UINT_TO_FP) 12229 return SDValue(); 12230 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 12231 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 12232 return SDValue(); 12233 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 12234 return SDValue(); 12235 12236 SDValue Ext1 = FirstInput.getOperand(0); 12237 SDValue Ext2 = N->getOperand(1).getOperand(0); 12238 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12239 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12240 return SDValue(); 12241 12242 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 12243 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 12244 if (!Ext1Op || !Ext2Op) 12245 return SDValue(); 12246 if (Ext1.getValueType() != MVT::i32 || 12247 Ext2.getValueType() != MVT::i32) 12248 if (Ext1.getOperand(0) != Ext2.getOperand(0)) 12249 return SDValue(); 12250 12251 int FirstElem = Ext1Op->getZExtValue(); 12252 int SecondElem = Ext2Op->getZExtValue(); 12253 int SubvecIdx; 12254 if (FirstElem == 0 && SecondElem == 1) 12255 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 12256 else if (FirstElem == 2 && SecondElem == 3) 12257 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 12258 else 12259 return SDValue(); 12260 12261 SDValue SrcVec = Ext1.getOperand(0); 12262 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 12263 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 12264 return DAG.getNode(NodeType, dl, MVT::v2f64, 12265 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 12266 } 12267 12268 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 12269 DAGCombinerInfo &DCI) const { 12270 assert((N->getOpcode() == ISD::SINT_TO_FP || 12271 N->getOpcode() == ISD::UINT_TO_FP) && 12272 "Need an int -> FP conversion node here"); 12273 12274 if (useSoftFloat() || !Subtarget.has64BitSupport()) 12275 return SDValue(); 12276 12277 SelectionDAG &DAG = DCI.DAG; 12278 SDLoc dl(N); 12279 SDValue Op(N, 0); 12280 12281 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 12282 // from the hardware. 12283 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 12284 return SDValue(); 12285 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 12286 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 12287 return SDValue(); 12288 12289 SDValue FirstOperand(Op.getOperand(0)); 12290 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 12291 (FirstOperand.getValueType() == MVT::i8 || 12292 FirstOperand.getValueType() == MVT::i16); 12293 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 12294 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 12295 bool DstDouble = Op.getValueType() == MVT::f64; 12296 unsigned ConvOp = Signed ? 12297 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 12298 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 12299 SDValue WidthConst = 12300 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 12301 dl, false); 12302 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 12303 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 12304 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 12305 DAG.getVTList(MVT::f64, MVT::Other), 12306 Ops, MVT::i8, LDN->getMemOperand()); 12307 12308 // For signed conversion, we need to sign-extend the value in the VSR 12309 if (Signed) { 12310 SDValue ExtOps[] = { Ld, WidthConst }; 12311 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 12312 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 12313 } else 12314 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 12315 } 12316 12317 12318 // For i32 intermediate values, unfortunately, the conversion functions 12319 // leave the upper 32 bits of the value are undefined. Within the set of 12320 // scalar instructions, we have no method for zero- or sign-extending the 12321 // value. Thus, we cannot handle i32 intermediate values here. 12322 if (Op.getOperand(0).getValueType() == MVT::i32) 12323 return SDValue(); 12324 12325 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 12326 "UINT_TO_FP is supported only with FPCVT"); 12327 12328 // If we have FCFIDS, then use it when converting to single-precision. 12329 // Otherwise, convert to double-precision and then round. 12330 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12331 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12332 : PPCISD::FCFIDS) 12333 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12334 : PPCISD::FCFID); 12335 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12336 ? MVT::f32 12337 : MVT::f64; 12338 12339 // If we're converting from a float, to an int, and back to a float again, 12340 // then we don't need the store/load pair at all. 12341 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12342 Subtarget.hasFPCVT()) || 12343 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12344 SDValue Src = Op.getOperand(0).getOperand(0); 12345 if (Src.getValueType() == MVT::f32) { 12346 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12347 DCI.AddToWorklist(Src.getNode()); 12348 } else if (Src.getValueType() != MVT::f64) { 12349 // Make sure that we don't pick up a ppc_fp128 source value. 12350 return SDValue(); 12351 } 12352 12353 unsigned FCTOp = 12354 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12355 PPCISD::FCTIDUZ; 12356 12357 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12358 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12359 12360 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12361 FP = DAG.getNode(ISD::FP_ROUND, dl, 12362 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12363 DCI.AddToWorklist(FP.getNode()); 12364 } 12365 12366 return FP; 12367 } 12368 12369 return SDValue(); 12370 } 12371 12372 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12373 // builtins) into loads with swaps. 12374 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12375 DAGCombinerInfo &DCI) const { 12376 SelectionDAG &DAG = DCI.DAG; 12377 SDLoc dl(N); 12378 SDValue Chain; 12379 SDValue Base; 12380 MachineMemOperand *MMO; 12381 12382 switch (N->getOpcode()) { 12383 default: 12384 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12385 case ISD::LOAD: { 12386 LoadSDNode *LD = cast<LoadSDNode>(N); 12387 Chain = LD->getChain(); 12388 Base = LD->getBasePtr(); 12389 MMO = LD->getMemOperand(); 12390 // If the MMO suggests this isn't a load of a full vector, leave 12391 // things alone. For a built-in, we have to make the change for 12392 // correctness, so if there is a size problem that will be a bug. 12393 if (MMO->getSize() < 16) 12394 return SDValue(); 12395 break; 12396 } 12397 case ISD::INTRINSIC_W_CHAIN: { 12398 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12399 Chain = Intrin->getChain(); 12400 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12401 // us what we want. Get operand 2 instead. 12402 Base = Intrin->getOperand(2); 12403 MMO = Intrin->getMemOperand(); 12404 break; 12405 } 12406 } 12407 12408 MVT VecTy = N->getValueType(0).getSimpleVT(); 12409 12410 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12411 // aligned and the type is a vector with elements up to 4 bytes 12412 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12413 && VecTy.getScalarSizeInBits() <= 32 ) { 12414 return SDValue(); 12415 } 12416 12417 SDValue LoadOps[] = { Chain, Base }; 12418 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12419 DAG.getVTList(MVT::v2f64, MVT::Other), 12420 LoadOps, MVT::v2f64, MMO); 12421 12422 DCI.AddToWorklist(Load.getNode()); 12423 Chain = Load.getValue(1); 12424 SDValue Swap = DAG.getNode( 12425 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12426 DCI.AddToWorklist(Swap.getNode()); 12427 12428 // Add a bitcast if the resulting load type doesn't match v2f64. 12429 if (VecTy != MVT::v2f64) { 12430 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12431 DCI.AddToWorklist(N.getNode()); 12432 // Package {bitcast value, swap's chain} to match Load's shape. 12433 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12434 N, Swap.getValue(1)); 12435 } 12436 12437 return Swap; 12438 } 12439 12440 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12441 // builtins) into stores with swaps. 12442 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12443 DAGCombinerInfo &DCI) const { 12444 SelectionDAG &DAG = DCI.DAG; 12445 SDLoc dl(N); 12446 SDValue Chain; 12447 SDValue Base; 12448 unsigned SrcOpnd; 12449 MachineMemOperand *MMO; 12450 12451 switch (N->getOpcode()) { 12452 default: 12453 llvm_unreachable("Unexpected opcode for little endian VSX store"); 12454 case ISD::STORE: { 12455 StoreSDNode *ST = cast<StoreSDNode>(N); 12456 Chain = ST->getChain(); 12457 Base = ST->getBasePtr(); 12458 MMO = ST->getMemOperand(); 12459 SrcOpnd = 1; 12460 // If the MMO suggests this isn't a store of a full vector, leave 12461 // things alone. For a built-in, we have to make the change for 12462 // correctness, so if there is a size problem that will be a bug. 12463 if (MMO->getSize() < 16) 12464 return SDValue(); 12465 break; 12466 } 12467 case ISD::INTRINSIC_VOID: { 12468 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12469 Chain = Intrin->getChain(); 12470 // Intrin->getBasePtr() oddly does not get what we want. 12471 Base = Intrin->getOperand(3); 12472 MMO = Intrin->getMemOperand(); 12473 SrcOpnd = 2; 12474 break; 12475 } 12476 } 12477 12478 SDValue Src = N->getOperand(SrcOpnd); 12479 MVT VecTy = Src.getValueType().getSimpleVT(); 12480 12481 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 12482 // aligned and the type is a vector with elements up to 4 bytes 12483 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12484 && VecTy.getScalarSizeInBits() <= 32 ) { 12485 return SDValue(); 12486 } 12487 12488 // All stores are done as v2f64 and possible bit cast. 12489 if (VecTy != MVT::v2f64) { 12490 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 12491 DCI.AddToWorklist(Src.getNode()); 12492 } 12493 12494 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 12495 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 12496 DCI.AddToWorklist(Swap.getNode()); 12497 Chain = Swap.getValue(1); 12498 SDValue StoreOps[] = { Chain, Swap, Base }; 12499 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 12500 DAG.getVTList(MVT::Other), 12501 StoreOps, VecTy, MMO); 12502 DCI.AddToWorklist(Store.getNode()); 12503 return Store; 12504 } 12505 12506 // Handle DAG combine for STORE (FP_TO_INT F). 12507 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 12508 DAGCombinerInfo &DCI) const { 12509 12510 SelectionDAG &DAG = DCI.DAG; 12511 SDLoc dl(N); 12512 unsigned Opcode = N->getOperand(1).getOpcode(); 12513 12514 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 12515 && "Not a FP_TO_INT Instruction!"); 12516 12517 SDValue Val = N->getOperand(1).getOperand(0); 12518 EVT Op1VT = N->getOperand(1).getValueType(); 12519 EVT ResVT = Val.getValueType(); 12520 12521 // Floating point types smaller than 32 bits are not legal on Power. 12522 if (ResVT.getScalarSizeInBits() < 32) 12523 return SDValue(); 12524 12525 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 12526 bool ValidTypeForStoreFltAsInt = 12527 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 12528 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 12529 12530 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 12531 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 12532 return SDValue(); 12533 12534 // Extend f32 values to f64 12535 if (ResVT.getScalarSizeInBits() == 32) { 12536 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 12537 DCI.AddToWorklist(Val.getNode()); 12538 } 12539 12540 // Set signed or unsigned conversion opcode. 12541 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 12542 PPCISD::FP_TO_SINT_IN_VSR : 12543 PPCISD::FP_TO_UINT_IN_VSR; 12544 12545 Val = DAG.getNode(ConvOpcode, 12546 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 12547 DCI.AddToWorklist(Val.getNode()); 12548 12549 // Set number of bytes being converted. 12550 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 12551 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 12552 DAG.getIntPtrConstant(ByteSize, dl, false), 12553 DAG.getValueType(Op1VT) }; 12554 12555 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 12556 DAG.getVTList(MVT::Other), Ops, 12557 cast<StoreSDNode>(N)->getMemoryVT(), 12558 cast<StoreSDNode>(N)->getMemOperand()); 12559 12560 DCI.AddToWorklist(Val.getNode()); 12561 return Val; 12562 } 12563 12564 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 12565 DAGCombinerInfo &DCI) const { 12566 SelectionDAG &DAG = DCI.DAG; 12567 SDLoc dl(N); 12568 switch (N->getOpcode()) { 12569 default: break; 12570 case ISD::ADD: 12571 return combineADD(N, DCI); 12572 case ISD::SHL: 12573 return combineSHL(N, DCI); 12574 case ISD::SRA: 12575 return combineSRA(N, DCI); 12576 case ISD::SRL: 12577 return combineSRL(N, DCI); 12578 case PPCISD::SHL: 12579 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 12580 return N->getOperand(0); 12581 break; 12582 case PPCISD::SRL: 12583 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 12584 return N->getOperand(0); 12585 break; 12586 case PPCISD::SRA: 12587 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 12588 if (C->isNullValue() || // 0 >>s V -> 0. 12589 C->isAllOnesValue()) // -1 >>s V -> -1. 12590 return N->getOperand(0); 12591 } 12592 break; 12593 case ISD::SIGN_EXTEND: 12594 case ISD::ZERO_EXTEND: 12595 case ISD::ANY_EXTEND: 12596 return DAGCombineExtBoolTrunc(N, DCI); 12597 case ISD::TRUNCATE: 12598 return combineTRUNCATE(N, DCI); 12599 case ISD::SETCC: 12600 if (SDValue CSCC = combineSetCC(N, DCI)) 12601 return CSCC; 12602 LLVM_FALLTHROUGH; 12603 case ISD::SELECT_CC: 12604 return DAGCombineTruncBoolExt(N, DCI); 12605 case ISD::SINT_TO_FP: 12606 case ISD::UINT_TO_FP: 12607 return combineFPToIntToFP(N, DCI); 12608 case ISD::STORE: { 12609 12610 EVT Op1VT = N->getOperand(1).getValueType(); 12611 unsigned Opcode = N->getOperand(1).getOpcode(); 12612 12613 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 12614 SDValue Val= combineStoreFPToInt(N, DCI); 12615 if (Val) 12616 return Val; 12617 } 12618 12619 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 12620 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 12621 N->getOperand(1).getNode()->hasOneUse() && 12622 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 12623 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 12624 12625 // STBRX can only handle simple types and it makes no sense to store less 12626 // two bytes in byte-reversed order. 12627 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 12628 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 12629 break; 12630 12631 SDValue BSwapOp = N->getOperand(1).getOperand(0); 12632 // Do an any-extend to 32-bits if this is a half-word input. 12633 if (BSwapOp.getValueType() == MVT::i16) 12634 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 12635 12636 // If the type of BSWAP operand is wider than stored memory width 12637 // it need to be shifted to the right side before STBRX. 12638 if (Op1VT.bitsGT(mVT)) { 12639 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 12640 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 12641 DAG.getConstant(Shift, dl, MVT::i32)); 12642 // Need to truncate if this is a bswap of i64 stored as i32/i16. 12643 if (Op1VT == MVT::i64) 12644 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 12645 } 12646 12647 SDValue Ops[] = { 12648 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 12649 }; 12650 return 12651 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 12652 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 12653 cast<StoreSDNode>(N)->getMemOperand()); 12654 } 12655 12656 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 12657 // So it can increase the chance of CSE constant construction. 12658 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 12659 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 12660 // Need to sign-extended to 64-bits to handle negative values. 12661 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 12662 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 12663 MemVT.getSizeInBits()); 12664 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 12665 12666 // DAG.getTruncStore() can't be used here because it doesn't accept 12667 // the general (base + offset) addressing mode. 12668 // So we use UpdateNodeOperands and setTruncatingStore instead. 12669 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 12670 N->getOperand(3)); 12671 cast<StoreSDNode>(N)->setTruncatingStore(true); 12672 return SDValue(N, 0); 12673 } 12674 12675 // For little endian, VSX stores require generating xxswapd/lxvd2x. 12676 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12677 if (Op1VT.isSimple()) { 12678 MVT StoreVT = Op1VT.getSimpleVT(); 12679 if (Subtarget.needsSwapsForVSXMemOps() && 12680 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 12681 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 12682 return expandVSXStoreForLE(N, DCI); 12683 } 12684 break; 12685 } 12686 case ISD::LOAD: { 12687 LoadSDNode *LD = cast<LoadSDNode>(N); 12688 EVT VT = LD->getValueType(0); 12689 12690 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12691 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12692 if (VT.isSimple()) { 12693 MVT LoadVT = VT.getSimpleVT(); 12694 if (Subtarget.needsSwapsForVSXMemOps() && 12695 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 12696 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 12697 return expandVSXLoadForLE(N, DCI); 12698 } 12699 12700 // We sometimes end up with a 64-bit integer load, from which we extract 12701 // two single-precision floating-point numbers. This happens with 12702 // std::complex<float>, and other similar structures, because of the way we 12703 // canonicalize structure copies. However, if we lack direct moves, 12704 // then the final bitcasts from the extracted integer values to the 12705 // floating-point numbers turn into store/load pairs. Even with direct moves, 12706 // just loading the two floating-point numbers is likely better. 12707 auto ReplaceTwoFloatLoad = [&]() { 12708 if (VT != MVT::i64) 12709 return false; 12710 12711 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 12712 LD->isVolatile()) 12713 return false; 12714 12715 // We're looking for a sequence like this: 12716 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 12717 // t16: i64 = srl t13, Constant:i32<32> 12718 // t17: i32 = truncate t16 12719 // t18: f32 = bitcast t17 12720 // t19: i32 = truncate t13 12721 // t20: f32 = bitcast t19 12722 12723 if (!LD->hasNUsesOfValue(2, 0)) 12724 return false; 12725 12726 auto UI = LD->use_begin(); 12727 while (UI.getUse().getResNo() != 0) ++UI; 12728 SDNode *Trunc = *UI++; 12729 while (UI.getUse().getResNo() != 0) ++UI; 12730 SDNode *RightShift = *UI; 12731 if (Trunc->getOpcode() != ISD::TRUNCATE) 12732 std::swap(Trunc, RightShift); 12733 12734 if (Trunc->getOpcode() != ISD::TRUNCATE || 12735 Trunc->getValueType(0) != MVT::i32 || 12736 !Trunc->hasOneUse()) 12737 return false; 12738 if (RightShift->getOpcode() != ISD::SRL || 12739 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 12740 RightShift->getConstantOperandVal(1) != 32 || 12741 !RightShift->hasOneUse()) 12742 return false; 12743 12744 SDNode *Trunc2 = *RightShift->use_begin(); 12745 if (Trunc2->getOpcode() != ISD::TRUNCATE || 12746 Trunc2->getValueType(0) != MVT::i32 || 12747 !Trunc2->hasOneUse()) 12748 return false; 12749 12750 SDNode *Bitcast = *Trunc->use_begin(); 12751 SDNode *Bitcast2 = *Trunc2->use_begin(); 12752 12753 if (Bitcast->getOpcode() != ISD::BITCAST || 12754 Bitcast->getValueType(0) != MVT::f32) 12755 return false; 12756 if (Bitcast2->getOpcode() != ISD::BITCAST || 12757 Bitcast2->getValueType(0) != MVT::f32) 12758 return false; 12759 12760 if (Subtarget.isLittleEndian()) 12761 std::swap(Bitcast, Bitcast2); 12762 12763 // Bitcast has the second float (in memory-layout order) and Bitcast2 12764 // has the first one. 12765 12766 SDValue BasePtr = LD->getBasePtr(); 12767 if (LD->isIndexed()) { 12768 assert(LD->getAddressingMode() == ISD::PRE_INC && 12769 "Non-pre-inc AM on PPC?"); 12770 BasePtr = 12771 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 12772 LD->getOffset()); 12773 } 12774 12775 auto MMOFlags = 12776 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 12777 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 12778 LD->getPointerInfo(), LD->getAlignment(), 12779 MMOFlags, LD->getAAInfo()); 12780 SDValue AddPtr = 12781 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 12782 BasePtr, DAG.getIntPtrConstant(4, dl)); 12783 SDValue FloatLoad2 = DAG.getLoad( 12784 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 12785 LD->getPointerInfo().getWithOffset(4), 12786 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 12787 12788 if (LD->isIndexed()) { 12789 // Note that DAGCombine should re-form any pre-increment load(s) from 12790 // what is produced here if that makes sense. 12791 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 12792 } 12793 12794 DCI.CombineTo(Bitcast2, FloatLoad); 12795 DCI.CombineTo(Bitcast, FloatLoad2); 12796 12797 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 12798 SDValue(FloatLoad2.getNode(), 1)); 12799 return true; 12800 }; 12801 12802 if (ReplaceTwoFloatLoad()) 12803 return SDValue(N, 0); 12804 12805 EVT MemVT = LD->getMemoryVT(); 12806 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 12807 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 12808 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 12809 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 12810 if (LD->isUnindexed() && VT.isVector() && 12811 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 12812 // P8 and later hardware should just use LOAD. 12813 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 12814 VT == MVT::v4i32 || VT == MVT::v4f32)) || 12815 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 12816 LD->getAlignment() >= ScalarABIAlignment)) && 12817 LD->getAlignment() < ABIAlignment) { 12818 // This is a type-legal unaligned Altivec or QPX load. 12819 SDValue Chain = LD->getChain(); 12820 SDValue Ptr = LD->getBasePtr(); 12821 bool isLittleEndian = Subtarget.isLittleEndian(); 12822 12823 // This implements the loading of unaligned vectors as described in 12824 // the venerable Apple Velocity Engine overview. Specifically: 12825 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 12826 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 12827 // 12828 // The general idea is to expand a sequence of one or more unaligned 12829 // loads into an alignment-based permutation-control instruction (lvsl 12830 // or lvsr), a series of regular vector loads (which always truncate 12831 // their input address to an aligned address), and a series of 12832 // permutations. The results of these permutations are the requested 12833 // loaded values. The trick is that the last "extra" load is not taken 12834 // from the address you might suspect (sizeof(vector) bytes after the 12835 // last requested load), but rather sizeof(vector) - 1 bytes after the 12836 // last requested vector. The point of this is to avoid a page fault if 12837 // the base address happened to be aligned. This works because if the 12838 // base address is aligned, then adding less than a full vector length 12839 // will cause the last vector in the sequence to be (re)loaded. 12840 // Otherwise, the next vector will be fetched as you might suspect was 12841 // necessary. 12842 12843 // We might be able to reuse the permutation generation from 12844 // a different base address offset from this one by an aligned amount. 12845 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 12846 // optimization later. 12847 Intrinsic::ID Intr, IntrLD, IntrPerm; 12848 MVT PermCntlTy, PermTy, LDTy; 12849 if (Subtarget.hasAltivec()) { 12850 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 12851 Intrinsic::ppc_altivec_lvsl; 12852 IntrLD = Intrinsic::ppc_altivec_lvx; 12853 IntrPerm = Intrinsic::ppc_altivec_vperm; 12854 PermCntlTy = MVT::v16i8; 12855 PermTy = MVT::v4i32; 12856 LDTy = MVT::v4i32; 12857 } else { 12858 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 12859 Intrinsic::ppc_qpx_qvlpcls; 12860 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 12861 Intrinsic::ppc_qpx_qvlfs; 12862 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 12863 PermCntlTy = MVT::v4f64; 12864 PermTy = MVT::v4f64; 12865 LDTy = MemVT.getSimpleVT(); 12866 } 12867 12868 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 12869 12870 // Create the new MMO for the new base load. It is like the original MMO, 12871 // but represents an area in memory almost twice the vector size centered 12872 // on the original address. If the address is unaligned, we might start 12873 // reading up to (sizeof(vector)-1) bytes below the address of the 12874 // original unaligned load. 12875 MachineFunction &MF = DAG.getMachineFunction(); 12876 MachineMemOperand *BaseMMO = 12877 MF.getMachineMemOperand(LD->getMemOperand(), 12878 -(long)MemVT.getStoreSize()+1, 12879 2*MemVT.getStoreSize()-1); 12880 12881 // Create the new base load. 12882 SDValue LDXIntID = 12883 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 12884 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 12885 SDValue BaseLoad = 12886 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12887 DAG.getVTList(PermTy, MVT::Other), 12888 BaseLoadOps, LDTy, BaseMMO); 12889 12890 // Note that the value of IncOffset (which is provided to the next 12891 // load's pointer info offset value, and thus used to calculate the 12892 // alignment), and the value of IncValue (which is actually used to 12893 // increment the pointer value) are different! This is because we 12894 // require the next load to appear to be aligned, even though it 12895 // is actually offset from the base pointer by a lesser amount. 12896 int IncOffset = VT.getSizeInBits() / 8; 12897 int IncValue = IncOffset; 12898 12899 // Walk (both up and down) the chain looking for another load at the real 12900 // (aligned) offset (the alignment of the other load does not matter in 12901 // this case). If found, then do not use the offset reduction trick, as 12902 // that will prevent the loads from being later combined (as they would 12903 // otherwise be duplicates). 12904 if (!findConsecutiveLoad(LD, DAG)) 12905 --IncValue; 12906 12907 SDValue Increment = 12908 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 12909 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 12910 12911 MachineMemOperand *ExtraMMO = 12912 MF.getMachineMemOperand(LD->getMemOperand(), 12913 1, 2*MemVT.getStoreSize()-1); 12914 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 12915 SDValue ExtraLoad = 12916 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12917 DAG.getVTList(PermTy, MVT::Other), 12918 ExtraLoadOps, LDTy, ExtraMMO); 12919 12920 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 12921 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 12922 12923 // Because vperm has a big-endian bias, we must reverse the order 12924 // of the input vectors and complement the permute control vector 12925 // when generating little endian code. We have already handled the 12926 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 12927 // and ExtraLoad here. 12928 SDValue Perm; 12929 if (isLittleEndian) 12930 Perm = BuildIntrinsicOp(IntrPerm, 12931 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 12932 else 12933 Perm = BuildIntrinsicOp(IntrPerm, 12934 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 12935 12936 if (VT != PermTy) 12937 Perm = Subtarget.hasAltivec() ? 12938 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 12939 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 12940 DAG.getTargetConstant(1, dl, MVT::i64)); 12941 // second argument is 1 because this rounding 12942 // is always exact. 12943 12944 // The output of the permutation is our loaded result, the TokenFactor is 12945 // our new chain. 12946 DCI.CombineTo(N, Perm, TF); 12947 return SDValue(N, 0); 12948 } 12949 } 12950 break; 12951 case ISD::INTRINSIC_WO_CHAIN: { 12952 bool isLittleEndian = Subtarget.isLittleEndian(); 12953 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12954 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 12955 : Intrinsic::ppc_altivec_lvsl); 12956 if ((IID == Intr || 12957 IID == Intrinsic::ppc_qpx_qvlpcld || 12958 IID == Intrinsic::ppc_qpx_qvlpcls) && 12959 N->getOperand(1)->getOpcode() == ISD::ADD) { 12960 SDValue Add = N->getOperand(1); 12961 12962 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 12963 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 12964 12965 if (DAG.MaskedValueIsZero(Add->getOperand(1), 12966 APInt::getAllOnesValue(Bits /* alignment */) 12967 .zext(Add.getScalarValueSizeInBits()))) { 12968 SDNode *BasePtr = Add->getOperand(0).getNode(); 12969 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12970 UE = BasePtr->use_end(); 12971 UI != UE; ++UI) { 12972 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12973 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 12974 // We've found another LVSL/LVSR, and this address is an aligned 12975 // multiple of that one. The results will be the same, so use the 12976 // one we've just found instead. 12977 12978 return SDValue(*UI, 0); 12979 } 12980 } 12981 } 12982 12983 if (isa<ConstantSDNode>(Add->getOperand(1))) { 12984 SDNode *BasePtr = Add->getOperand(0).getNode(); 12985 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12986 UE = BasePtr->use_end(); UI != UE; ++UI) { 12987 if (UI->getOpcode() == ISD::ADD && 12988 isa<ConstantSDNode>(UI->getOperand(1)) && 12989 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 12990 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 12991 (1ULL << Bits) == 0) { 12992 SDNode *OtherAdd = *UI; 12993 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 12994 VE = OtherAdd->use_end(); VI != VE; ++VI) { 12995 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12996 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 12997 return SDValue(*VI, 0); 12998 } 12999 } 13000 } 13001 } 13002 } 13003 } 13004 13005 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 13006 // Expose the vabsduw/h/b opportunity for down stream 13007 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 13008 (IID == Intrinsic::ppc_altivec_vmaxsw || 13009 IID == Intrinsic::ppc_altivec_vmaxsh || 13010 IID == Intrinsic::ppc_altivec_vmaxsb)) { 13011 SDValue V1 = N->getOperand(1); 13012 SDValue V2 = N->getOperand(2); 13013 if ((V1.getSimpleValueType() == MVT::v4i32 || 13014 V1.getSimpleValueType() == MVT::v8i16 || 13015 V1.getSimpleValueType() == MVT::v16i8) && 13016 V1.getSimpleValueType() == V2.getSimpleValueType()) { 13017 // (0-a, a) 13018 if (V1.getOpcode() == ISD::SUB && 13019 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 13020 V1.getOperand(1) == V2) { 13021 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 13022 } 13023 // (a, 0-a) 13024 if (V2.getOpcode() == ISD::SUB && 13025 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 13026 V2.getOperand(1) == V1) { 13027 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13028 } 13029 // (x-y, y-x) 13030 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 13031 V1.getOperand(0) == V2.getOperand(1) && 13032 V1.getOperand(1) == V2.getOperand(0)) { 13033 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13034 } 13035 } 13036 } 13037 } 13038 13039 break; 13040 case ISD::INTRINSIC_W_CHAIN: 13041 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13042 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13043 if (Subtarget.needsSwapsForVSXMemOps()) { 13044 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13045 default: 13046 break; 13047 case Intrinsic::ppc_vsx_lxvw4x: 13048 case Intrinsic::ppc_vsx_lxvd2x: 13049 return expandVSXLoadForLE(N, DCI); 13050 } 13051 } 13052 break; 13053 case ISD::INTRINSIC_VOID: 13054 // For little endian, VSX stores require generating xxswapd/stxvd2x. 13055 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13056 if (Subtarget.needsSwapsForVSXMemOps()) { 13057 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13058 default: 13059 break; 13060 case Intrinsic::ppc_vsx_stxvw4x: 13061 case Intrinsic::ppc_vsx_stxvd2x: 13062 return expandVSXStoreForLE(N, DCI); 13063 } 13064 } 13065 break; 13066 case ISD::BSWAP: 13067 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 13068 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 13069 N->getOperand(0).hasOneUse() && 13070 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 13071 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 13072 N->getValueType(0) == MVT::i64))) { 13073 SDValue Load = N->getOperand(0); 13074 LoadSDNode *LD = cast<LoadSDNode>(Load); 13075 // Create the byte-swapping load. 13076 SDValue Ops[] = { 13077 LD->getChain(), // Chain 13078 LD->getBasePtr(), // Ptr 13079 DAG.getValueType(N->getValueType(0)) // VT 13080 }; 13081 SDValue BSLoad = 13082 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 13083 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 13084 MVT::i64 : MVT::i32, MVT::Other), 13085 Ops, LD->getMemoryVT(), LD->getMemOperand()); 13086 13087 // If this is an i16 load, insert the truncate. 13088 SDValue ResVal = BSLoad; 13089 if (N->getValueType(0) == MVT::i16) 13090 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 13091 13092 // First, combine the bswap away. This makes the value produced by the 13093 // load dead. 13094 DCI.CombineTo(N, ResVal); 13095 13096 // Next, combine the load away, we give it a bogus result value but a real 13097 // chain result. The result value is dead because the bswap is dead. 13098 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 13099 13100 // Return N so it doesn't get rechecked! 13101 return SDValue(N, 0); 13102 } 13103 break; 13104 case PPCISD::VCMP: 13105 // If a VCMPo node already exists with exactly the same operands as this 13106 // node, use its result instead of this node (VCMPo computes both a CR6 and 13107 // a normal output). 13108 // 13109 if (!N->getOperand(0).hasOneUse() && 13110 !N->getOperand(1).hasOneUse() && 13111 !N->getOperand(2).hasOneUse()) { 13112 13113 // Scan all of the users of the LHS, looking for VCMPo's that match. 13114 SDNode *VCMPoNode = nullptr; 13115 13116 SDNode *LHSN = N->getOperand(0).getNode(); 13117 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 13118 UI != E; ++UI) 13119 if (UI->getOpcode() == PPCISD::VCMPo && 13120 UI->getOperand(1) == N->getOperand(1) && 13121 UI->getOperand(2) == N->getOperand(2) && 13122 UI->getOperand(0) == N->getOperand(0)) { 13123 VCMPoNode = *UI; 13124 break; 13125 } 13126 13127 // If there is no VCMPo node, or if the flag value has a single use, don't 13128 // transform this. 13129 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 13130 break; 13131 13132 // Look at the (necessarily single) use of the flag value. If it has a 13133 // chain, this transformation is more complex. Note that multiple things 13134 // could use the value result, which we should ignore. 13135 SDNode *FlagUser = nullptr; 13136 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 13137 FlagUser == nullptr; ++UI) { 13138 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 13139 SDNode *User = *UI; 13140 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 13141 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 13142 FlagUser = User; 13143 break; 13144 } 13145 } 13146 } 13147 13148 // If the user is a MFOCRF instruction, we know this is safe. 13149 // Otherwise we give up for right now. 13150 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 13151 return SDValue(VCMPoNode, 0); 13152 } 13153 break; 13154 case ISD::BRCOND: { 13155 SDValue Cond = N->getOperand(1); 13156 SDValue Target = N->getOperand(2); 13157 13158 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13159 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 13160 Intrinsic::ppc_is_decremented_ctr_nonzero) { 13161 13162 // We now need to make the intrinsic dead (it cannot be instruction 13163 // selected). 13164 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 13165 assert(Cond.getNode()->hasOneUse() && 13166 "Counter decrement has more than one use"); 13167 13168 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 13169 N->getOperand(0), Target); 13170 } 13171 } 13172 break; 13173 case ISD::BR_CC: { 13174 // If this is a branch on an altivec predicate comparison, lower this so 13175 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 13176 // lowering is done pre-legalize, because the legalizer lowers the predicate 13177 // compare down to code that is difficult to reassemble. 13178 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13179 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 13180 13181 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 13182 // value. If so, pass-through the AND to get to the intrinsic. 13183 if (LHS.getOpcode() == ISD::AND && 13184 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 13185 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 13186 Intrinsic::ppc_is_decremented_ctr_nonzero && 13187 isa<ConstantSDNode>(LHS.getOperand(1)) && 13188 !isNullConstant(LHS.getOperand(1))) 13189 LHS = LHS.getOperand(0); 13190 13191 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13192 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 13193 Intrinsic::ppc_is_decremented_ctr_nonzero && 13194 isa<ConstantSDNode>(RHS)) { 13195 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 13196 "Counter decrement comparison is not EQ or NE"); 13197 13198 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13199 bool isBDNZ = (CC == ISD::SETEQ && Val) || 13200 (CC == ISD::SETNE && !Val); 13201 13202 // We now need to make the intrinsic dead (it cannot be instruction 13203 // selected). 13204 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 13205 assert(LHS.getNode()->hasOneUse() && 13206 "Counter decrement has more than one use"); 13207 13208 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 13209 N->getOperand(0), N->getOperand(4)); 13210 } 13211 13212 int CompareOpc; 13213 bool isDot; 13214 13215 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13216 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 13217 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 13218 assert(isDot && "Can't compare against a vector result!"); 13219 13220 // If this is a comparison against something other than 0/1, then we know 13221 // that the condition is never/always true. 13222 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13223 if (Val != 0 && Val != 1) { 13224 if (CC == ISD::SETEQ) // Cond never true, remove branch. 13225 return N->getOperand(0); 13226 // Always !=, turn it into an unconditional branch. 13227 return DAG.getNode(ISD::BR, dl, MVT::Other, 13228 N->getOperand(0), N->getOperand(4)); 13229 } 13230 13231 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 13232 13233 // Create the PPCISD altivec 'dot' comparison node. 13234 SDValue Ops[] = { 13235 LHS.getOperand(2), // LHS of compare 13236 LHS.getOperand(3), // RHS of compare 13237 DAG.getConstant(CompareOpc, dl, MVT::i32) 13238 }; 13239 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 13240 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 13241 13242 // Unpack the result based on how the target uses it. 13243 PPC::Predicate CompOpc; 13244 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 13245 default: // Can't happen, don't crash on invalid number though. 13246 case 0: // Branch on the value of the EQ bit of CR6. 13247 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 13248 break; 13249 case 1: // Branch on the inverted value of the EQ bit of CR6. 13250 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 13251 break; 13252 case 2: // Branch on the value of the LT bit of CR6. 13253 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 13254 break; 13255 case 3: // Branch on the inverted value of the LT bit of CR6. 13256 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 13257 break; 13258 } 13259 13260 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 13261 DAG.getConstant(CompOpc, dl, MVT::i32), 13262 DAG.getRegister(PPC::CR6, MVT::i32), 13263 N->getOperand(4), CompNode.getValue(1)); 13264 } 13265 break; 13266 } 13267 case ISD::BUILD_VECTOR: 13268 return DAGCombineBuildVector(N, DCI); 13269 case ISD::ABS: 13270 return combineABS(N, DCI); 13271 case ISD::VSELECT: 13272 return combineVSelect(N, DCI); 13273 } 13274 13275 return SDValue(); 13276 } 13277 13278 SDValue 13279 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 13280 SelectionDAG &DAG, 13281 SmallVectorImpl<SDNode *> &Created) const { 13282 // fold (sdiv X, pow2) 13283 EVT VT = N->getValueType(0); 13284 if (VT == MVT::i64 && !Subtarget.isPPC64()) 13285 return SDValue(); 13286 if ((VT != MVT::i32 && VT != MVT::i64) || 13287 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 13288 return SDValue(); 13289 13290 SDLoc DL(N); 13291 SDValue N0 = N->getOperand(0); 13292 13293 bool IsNegPow2 = (-Divisor).isPowerOf2(); 13294 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 13295 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 13296 13297 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 13298 Created.push_back(Op.getNode()); 13299 13300 if (IsNegPow2) { 13301 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 13302 Created.push_back(Op.getNode()); 13303 } 13304 13305 return Op; 13306 } 13307 13308 //===----------------------------------------------------------------------===// 13309 // Inline Assembly Support 13310 //===----------------------------------------------------------------------===// 13311 13312 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13313 KnownBits &Known, 13314 const APInt &DemandedElts, 13315 const SelectionDAG &DAG, 13316 unsigned Depth) const { 13317 Known.resetAll(); 13318 switch (Op.getOpcode()) { 13319 default: break; 13320 case PPCISD::LBRX: { 13321 // lhbrx is known to have the top bits cleared out. 13322 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 13323 Known.Zero = 0xFFFF0000; 13324 break; 13325 } 13326 case ISD::INTRINSIC_WO_CHAIN: { 13327 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 13328 default: break; 13329 case Intrinsic::ppc_altivec_vcmpbfp_p: 13330 case Intrinsic::ppc_altivec_vcmpeqfp_p: 13331 case Intrinsic::ppc_altivec_vcmpequb_p: 13332 case Intrinsic::ppc_altivec_vcmpequh_p: 13333 case Intrinsic::ppc_altivec_vcmpequw_p: 13334 case Intrinsic::ppc_altivec_vcmpequd_p: 13335 case Intrinsic::ppc_altivec_vcmpgefp_p: 13336 case Intrinsic::ppc_altivec_vcmpgtfp_p: 13337 case Intrinsic::ppc_altivec_vcmpgtsb_p: 13338 case Intrinsic::ppc_altivec_vcmpgtsh_p: 13339 case Intrinsic::ppc_altivec_vcmpgtsw_p: 13340 case Intrinsic::ppc_altivec_vcmpgtsd_p: 13341 case Intrinsic::ppc_altivec_vcmpgtub_p: 13342 case Intrinsic::ppc_altivec_vcmpgtuh_p: 13343 case Intrinsic::ppc_altivec_vcmpgtuw_p: 13344 case Intrinsic::ppc_altivec_vcmpgtud_p: 13345 Known.Zero = ~1U; // All bits but the low one are known to be zero. 13346 break; 13347 } 13348 } 13349 } 13350 } 13351 13352 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 13353 switch (Subtarget.getDarwinDirective()) { 13354 default: break; 13355 case PPC::DIR_970: 13356 case PPC::DIR_PWR4: 13357 case PPC::DIR_PWR5: 13358 case PPC::DIR_PWR5X: 13359 case PPC::DIR_PWR6: 13360 case PPC::DIR_PWR6X: 13361 case PPC::DIR_PWR7: 13362 case PPC::DIR_PWR8: 13363 case PPC::DIR_PWR9: { 13364 if (!ML) 13365 break; 13366 13367 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 13368 13369 // For small loops (between 5 and 8 instructions), align to a 32-byte 13370 // boundary so that the entire loop fits in one instruction-cache line. 13371 uint64_t LoopSize = 0; 13372 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 13373 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 13374 LoopSize += TII->getInstSizeInBytes(*J); 13375 if (LoopSize > 32) 13376 break; 13377 } 13378 13379 if (LoopSize > 16 && LoopSize <= 32) 13380 return 5; 13381 13382 break; 13383 } 13384 } 13385 13386 return TargetLowering::getPrefLoopAlignment(ML); 13387 } 13388 13389 /// getConstraintType - Given a constraint, return the type of 13390 /// constraint it is for this target. 13391 PPCTargetLowering::ConstraintType 13392 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 13393 if (Constraint.size() == 1) { 13394 switch (Constraint[0]) { 13395 default: break; 13396 case 'b': 13397 case 'r': 13398 case 'f': 13399 case 'd': 13400 case 'v': 13401 case 'y': 13402 return C_RegisterClass; 13403 case 'Z': 13404 // FIXME: While Z does indicate a memory constraint, it specifically 13405 // indicates an r+r address (used in conjunction with the 'y' modifier 13406 // in the replacement string). Currently, we're forcing the base 13407 // register to be r0 in the asm printer (which is interpreted as zero) 13408 // and forming the complete address in the second register. This is 13409 // suboptimal. 13410 return C_Memory; 13411 } 13412 } else if (Constraint == "wc") { // individual CR bits. 13413 return C_RegisterClass; 13414 } else if (Constraint == "wa" || Constraint == "wd" || 13415 Constraint == "wf" || Constraint == "ws" || 13416 Constraint == "wi") { 13417 return C_RegisterClass; // VSX registers. 13418 } 13419 return TargetLowering::getConstraintType(Constraint); 13420 } 13421 13422 /// Examine constraint type and operand type and determine a weight value. 13423 /// This object must already have been set up with the operand type 13424 /// and the current alternative constraint selected. 13425 TargetLowering::ConstraintWeight 13426 PPCTargetLowering::getSingleConstraintMatchWeight( 13427 AsmOperandInfo &info, const char *constraint) const { 13428 ConstraintWeight weight = CW_Invalid; 13429 Value *CallOperandVal = info.CallOperandVal; 13430 // If we don't have a value, we can't do a match, 13431 // but allow it at the lowest weight. 13432 if (!CallOperandVal) 13433 return CW_Default; 13434 Type *type = CallOperandVal->getType(); 13435 13436 // Look at the constraint type. 13437 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 13438 return CW_Register; // an individual CR bit. 13439 else if ((StringRef(constraint) == "wa" || 13440 StringRef(constraint) == "wd" || 13441 StringRef(constraint) == "wf") && 13442 type->isVectorTy()) 13443 return CW_Register; 13444 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 13445 return CW_Register; 13446 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 13447 return CW_Register; // just hold 64-bit integers data. 13448 13449 switch (*constraint) { 13450 default: 13451 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13452 break; 13453 case 'b': 13454 if (type->isIntegerTy()) 13455 weight = CW_Register; 13456 break; 13457 case 'f': 13458 if (type->isFloatTy()) 13459 weight = CW_Register; 13460 break; 13461 case 'd': 13462 if (type->isDoubleTy()) 13463 weight = CW_Register; 13464 break; 13465 case 'v': 13466 if (type->isVectorTy()) 13467 weight = CW_Register; 13468 break; 13469 case 'y': 13470 weight = CW_Register; 13471 break; 13472 case 'Z': 13473 weight = CW_Memory; 13474 break; 13475 } 13476 return weight; 13477 } 13478 13479 std::pair<unsigned, const TargetRegisterClass *> 13480 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 13481 StringRef Constraint, 13482 MVT VT) const { 13483 if (Constraint.size() == 1) { 13484 // GCC RS6000 Constraint Letters 13485 switch (Constraint[0]) { 13486 case 'b': // R1-R31 13487 if (VT == MVT::i64 && Subtarget.isPPC64()) 13488 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 13489 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 13490 case 'r': // R0-R31 13491 if (VT == MVT::i64 && Subtarget.isPPC64()) 13492 return std::make_pair(0U, &PPC::G8RCRegClass); 13493 return std::make_pair(0U, &PPC::GPRCRegClass); 13494 // 'd' and 'f' constraints are both defined to be "the floating point 13495 // registers", where one is for 32-bit and the other for 64-bit. We don't 13496 // really care overly much here so just give them all the same reg classes. 13497 case 'd': 13498 case 'f': 13499 if (Subtarget.hasSPE()) { 13500 if (VT == MVT::f32 || VT == MVT::i32) 13501 return std::make_pair(0U, &PPC::SPE4RCRegClass); 13502 if (VT == MVT::f64 || VT == MVT::i64) 13503 return std::make_pair(0U, &PPC::SPERCRegClass); 13504 } else { 13505 if (VT == MVT::f32 || VT == MVT::i32) 13506 return std::make_pair(0U, &PPC::F4RCRegClass); 13507 if (VT == MVT::f64 || VT == MVT::i64) 13508 return std::make_pair(0U, &PPC::F8RCRegClass); 13509 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13510 return std::make_pair(0U, &PPC::QFRCRegClass); 13511 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13512 return std::make_pair(0U, &PPC::QSRCRegClass); 13513 } 13514 break; 13515 case 'v': 13516 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13517 return std::make_pair(0U, &PPC::QFRCRegClass); 13518 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13519 return std::make_pair(0U, &PPC::QSRCRegClass); 13520 if (Subtarget.hasAltivec()) 13521 return std::make_pair(0U, &PPC::VRRCRegClass); 13522 break; 13523 case 'y': // crrc 13524 return std::make_pair(0U, &PPC::CRRCRegClass); 13525 } 13526 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 13527 // An individual CR bit. 13528 return std::make_pair(0U, &PPC::CRBITRCRegClass); 13529 } else if ((Constraint == "wa" || Constraint == "wd" || 13530 Constraint == "wf" || Constraint == "wi") && 13531 Subtarget.hasVSX()) { 13532 return std::make_pair(0U, &PPC::VSRCRegClass); 13533 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 13534 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 13535 return std::make_pair(0U, &PPC::VSSRCRegClass); 13536 else 13537 return std::make_pair(0U, &PPC::VSFRCRegClass); 13538 } 13539 13540 std::pair<unsigned, const TargetRegisterClass *> R = 13541 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13542 13543 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 13544 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 13545 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 13546 // register. 13547 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 13548 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 13549 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 13550 PPC::GPRCRegClass.contains(R.first)) 13551 return std::make_pair(TRI->getMatchingSuperReg(R.first, 13552 PPC::sub_32, &PPC::G8RCRegClass), 13553 &PPC::G8RCRegClass); 13554 13555 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 13556 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 13557 R.first = PPC::CR0; 13558 R.second = &PPC::CRRCRegClass; 13559 } 13560 13561 return R; 13562 } 13563 13564 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13565 /// vector. If it is invalid, don't add anything to Ops. 13566 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13567 std::string &Constraint, 13568 std::vector<SDValue>&Ops, 13569 SelectionDAG &DAG) const { 13570 SDValue Result; 13571 13572 // Only support length 1 constraints. 13573 if (Constraint.length() > 1) return; 13574 13575 char Letter = Constraint[0]; 13576 switch (Letter) { 13577 default: break; 13578 case 'I': 13579 case 'J': 13580 case 'K': 13581 case 'L': 13582 case 'M': 13583 case 'N': 13584 case 'O': 13585 case 'P': { 13586 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 13587 if (!CST) return; // Must be an immediate to match. 13588 SDLoc dl(Op); 13589 int64_t Value = CST->getSExtValue(); 13590 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 13591 // numbers are printed as such. 13592 switch (Letter) { 13593 default: llvm_unreachable("Unknown constraint letter!"); 13594 case 'I': // "I" is a signed 16-bit constant. 13595 if (isInt<16>(Value)) 13596 Result = DAG.getTargetConstant(Value, dl, TCVT); 13597 break; 13598 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 13599 if (isShiftedUInt<16, 16>(Value)) 13600 Result = DAG.getTargetConstant(Value, dl, TCVT); 13601 break; 13602 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 13603 if (isShiftedInt<16, 16>(Value)) 13604 Result = DAG.getTargetConstant(Value, dl, TCVT); 13605 break; 13606 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 13607 if (isUInt<16>(Value)) 13608 Result = DAG.getTargetConstant(Value, dl, TCVT); 13609 break; 13610 case 'M': // "M" is a constant that is greater than 31. 13611 if (Value > 31) 13612 Result = DAG.getTargetConstant(Value, dl, TCVT); 13613 break; 13614 case 'N': // "N" is a positive constant that is an exact power of two. 13615 if (Value > 0 && isPowerOf2_64(Value)) 13616 Result = DAG.getTargetConstant(Value, dl, TCVT); 13617 break; 13618 case 'O': // "O" is the constant zero. 13619 if (Value == 0) 13620 Result = DAG.getTargetConstant(Value, dl, TCVT); 13621 break; 13622 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 13623 if (isInt<16>(-Value)) 13624 Result = DAG.getTargetConstant(Value, dl, TCVT); 13625 break; 13626 } 13627 break; 13628 } 13629 } 13630 13631 if (Result.getNode()) { 13632 Ops.push_back(Result); 13633 return; 13634 } 13635 13636 // Handle standard constraint letters. 13637 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13638 } 13639 13640 // isLegalAddressingMode - Return true if the addressing mode represented 13641 // by AM is legal for this target, for a load/store of the specified type. 13642 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13643 const AddrMode &AM, Type *Ty, 13644 unsigned AS, Instruction *I) const { 13645 // PPC does not allow r+i addressing modes for vectors! 13646 if (Ty->isVectorTy() && AM.BaseOffs != 0) 13647 return false; 13648 13649 // PPC allows a sign-extended 16-bit immediate field. 13650 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 13651 return false; 13652 13653 // No global is ever allowed as a base. 13654 if (AM.BaseGV) 13655 return false; 13656 13657 // PPC only support r+r, 13658 switch (AM.Scale) { 13659 case 0: // "r+i" or just "i", depending on HasBaseReg. 13660 break; 13661 case 1: 13662 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 13663 return false; 13664 // Otherwise we have r+r or r+i. 13665 break; 13666 case 2: 13667 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 13668 return false; 13669 // Allow 2*r as r+r. 13670 break; 13671 default: 13672 // No other scales are supported. 13673 return false; 13674 } 13675 13676 return true; 13677 } 13678 13679 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 13680 SelectionDAG &DAG) const { 13681 MachineFunction &MF = DAG.getMachineFunction(); 13682 MachineFrameInfo &MFI = MF.getFrameInfo(); 13683 MFI.setReturnAddressIsTaken(true); 13684 13685 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 13686 return SDValue(); 13687 13688 SDLoc dl(Op); 13689 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13690 13691 // Make sure the function does not optimize away the store of the RA to 13692 // the stack. 13693 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 13694 FuncInfo->setLRStoreRequired(); 13695 bool isPPC64 = Subtarget.isPPC64(); 13696 auto PtrVT = getPointerTy(MF.getDataLayout()); 13697 13698 if (Depth > 0) { 13699 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 13700 SDValue Offset = 13701 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 13702 isPPC64 ? MVT::i64 : MVT::i32); 13703 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 13704 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 13705 MachinePointerInfo()); 13706 } 13707 13708 // Just load the return address off the stack. 13709 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 13710 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 13711 MachinePointerInfo()); 13712 } 13713 13714 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 13715 SelectionDAG &DAG) const { 13716 SDLoc dl(Op); 13717 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13718 13719 MachineFunction &MF = DAG.getMachineFunction(); 13720 MachineFrameInfo &MFI = MF.getFrameInfo(); 13721 MFI.setFrameAddressIsTaken(true); 13722 13723 EVT PtrVT = getPointerTy(MF.getDataLayout()); 13724 bool isPPC64 = PtrVT == MVT::i64; 13725 13726 // Naked functions never have a frame pointer, and so we use r1. For all 13727 // other functions, this decision must be delayed until during PEI. 13728 unsigned FrameReg; 13729 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 13730 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 13731 else 13732 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 13733 13734 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 13735 PtrVT); 13736 while (Depth--) 13737 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 13738 FrameAddr, MachinePointerInfo()); 13739 return FrameAddr; 13740 } 13741 13742 // FIXME? Maybe this could be a TableGen attribute on some registers and 13743 // this table could be generated automatically from RegInfo. 13744 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 13745 SelectionDAG &DAG) const { 13746 bool isPPC64 = Subtarget.isPPC64(); 13747 bool isDarwinABI = Subtarget.isDarwinABI(); 13748 13749 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 13750 (!isPPC64 && VT != MVT::i32)) 13751 report_fatal_error("Invalid register global variable type"); 13752 13753 bool is64Bit = isPPC64 && VT == MVT::i64; 13754 unsigned Reg = StringSwitch<unsigned>(RegName) 13755 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 13756 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 13757 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 13758 (is64Bit ? PPC::X13 : PPC::R13)) 13759 .Default(0); 13760 13761 if (Reg) 13762 return Reg; 13763 report_fatal_error("Invalid register name global variable"); 13764 } 13765 13766 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 13767 // 32-bit SVR4 ABI access everything as got-indirect. 13768 if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 13769 return true; 13770 13771 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 13772 // If it is small or large code model, module locals are accessed 13773 // indirectly by loading their address from .toc/.got. The difference 13774 // is that for large code model we have ADDISTocHa + LDtocL and for 13775 // small code model we simply have LDtoc. 13776 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 13777 return true; 13778 13779 // JumpTable and BlockAddress are accessed as got-indirect. 13780 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 13781 return true; 13782 13783 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) { 13784 const GlobalValue *GV = G->getGlobal(); 13785 unsigned char GVFlags = Subtarget.classifyGlobalReference(GV); 13786 // The NLP flag indicates that a global access has to use an 13787 // extra indirection. 13788 if (GVFlags & PPCII::MO_NLP_FLAG) 13789 return true; 13790 } 13791 13792 return false; 13793 } 13794 13795 bool 13796 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13797 // The PowerPC target isn't yet aware of offsets. 13798 return false; 13799 } 13800 13801 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13802 const CallInst &I, 13803 MachineFunction &MF, 13804 unsigned Intrinsic) const { 13805 switch (Intrinsic) { 13806 case Intrinsic::ppc_qpx_qvlfd: 13807 case Intrinsic::ppc_qpx_qvlfs: 13808 case Intrinsic::ppc_qpx_qvlfcd: 13809 case Intrinsic::ppc_qpx_qvlfcs: 13810 case Intrinsic::ppc_qpx_qvlfiwa: 13811 case Intrinsic::ppc_qpx_qvlfiwz: 13812 case Intrinsic::ppc_altivec_lvx: 13813 case Intrinsic::ppc_altivec_lvxl: 13814 case Intrinsic::ppc_altivec_lvebx: 13815 case Intrinsic::ppc_altivec_lvehx: 13816 case Intrinsic::ppc_altivec_lvewx: 13817 case Intrinsic::ppc_vsx_lxvd2x: 13818 case Intrinsic::ppc_vsx_lxvw4x: { 13819 EVT VT; 13820 switch (Intrinsic) { 13821 case Intrinsic::ppc_altivec_lvebx: 13822 VT = MVT::i8; 13823 break; 13824 case Intrinsic::ppc_altivec_lvehx: 13825 VT = MVT::i16; 13826 break; 13827 case Intrinsic::ppc_altivec_lvewx: 13828 VT = MVT::i32; 13829 break; 13830 case Intrinsic::ppc_vsx_lxvd2x: 13831 VT = MVT::v2f64; 13832 break; 13833 case Intrinsic::ppc_qpx_qvlfd: 13834 VT = MVT::v4f64; 13835 break; 13836 case Intrinsic::ppc_qpx_qvlfs: 13837 VT = MVT::v4f32; 13838 break; 13839 case Intrinsic::ppc_qpx_qvlfcd: 13840 VT = MVT::v2f64; 13841 break; 13842 case Intrinsic::ppc_qpx_qvlfcs: 13843 VT = MVT::v2f32; 13844 break; 13845 default: 13846 VT = MVT::v4i32; 13847 break; 13848 } 13849 13850 Info.opc = ISD::INTRINSIC_W_CHAIN; 13851 Info.memVT = VT; 13852 Info.ptrVal = I.getArgOperand(0); 13853 Info.offset = -VT.getStoreSize()+1; 13854 Info.size = 2*VT.getStoreSize()-1; 13855 Info.align = 1; 13856 Info.flags = MachineMemOperand::MOLoad; 13857 return true; 13858 } 13859 case Intrinsic::ppc_qpx_qvlfda: 13860 case Intrinsic::ppc_qpx_qvlfsa: 13861 case Intrinsic::ppc_qpx_qvlfcda: 13862 case Intrinsic::ppc_qpx_qvlfcsa: 13863 case Intrinsic::ppc_qpx_qvlfiwaa: 13864 case Intrinsic::ppc_qpx_qvlfiwza: { 13865 EVT VT; 13866 switch (Intrinsic) { 13867 case Intrinsic::ppc_qpx_qvlfda: 13868 VT = MVT::v4f64; 13869 break; 13870 case Intrinsic::ppc_qpx_qvlfsa: 13871 VT = MVT::v4f32; 13872 break; 13873 case Intrinsic::ppc_qpx_qvlfcda: 13874 VT = MVT::v2f64; 13875 break; 13876 case Intrinsic::ppc_qpx_qvlfcsa: 13877 VT = MVT::v2f32; 13878 break; 13879 default: 13880 VT = MVT::v4i32; 13881 break; 13882 } 13883 13884 Info.opc = ISD::INTRINSIC_W_CHAIN; 13885 Info.memVT = VT; 13886 Info.ptrVal = I.getArgOperand(0); 13887 Info.offset = 0; 13888 Info.size = VT.getStoreSize(); 13889 Info.align = 1; 13890 Info.flags = MachineMemOperand::MOLoad; 13891 return true; 13892 } 13893 case Intrinsic::ppc_qpx_qvstfd: 13894 case Intrinsic::ppc_qpx_qvstfs: 13895 case Intrinsic::ppc_qpx_qvstfcd: 13896 case Intrinsic::ppc_qpx_qvstfcs: 13897 case Intrinsic::ppc_qpx_qvstfiw: 13898 case Intrinsic::ppc_altivec_stvx: 13899 case Intrinsic::ppc_altivec_stvxl: 13900 case Intrinsic::ppc_altivec_stvebx: 13901 case Intrinsic::ppc_altivec_stvehx: 13902 case Intrinsic::ppc_altivec_stvewx: 13903 case Intrinsic::ppc_vsx_stxvd2x: 13904 case Intrinsic::ppc_vsx_stxvw4x: { 13905 EVT VT; 13906 switch (Intrinsic) { 13907 case Intrinsic::ppc_altivec_stvebx: 13908 VT = MVT::i8; 13909 break; 13910 case Intrinsic::ppc_altivec_stvehx: 13911 VT = MVT::i16; 13912 break; 13913 case Intrinsic::ppc_altivec_stvewx: 13914 VT = MVT::i32; 13915 break; 13916 case Intrinsic::ppc_vsx_stxvd2x: 13917 VT = MVT::v2f64; 13918 break; 13919 case Intrinsic::ppc_qpx_qvstfd: 13920 VT = MVT::v4f64; 13921 break; 13922 case Intrinsic::ppc_qpx_qvstfs: 13923 VT = MVT::v4f32; 13924 break; 13925 case Intrinsic::ppc_qpx_qvstfcd: 13926 VT = MVT::v2f64; 13927 break; 13928 case Intrinsic::ppc_qpx_qvstfcs: 13929 VT = MVT::v2f32; 13930 break; 13931 default: 13932 VT = MVT::v4i32; 13933 break; 13934 } 13935 13936 Info.opc = ISD::INTRINSIC_VOID; 13937 Info.memVT = VT; 13938 Info.ptrVal = I.getArgOperand(1); 13939 Info.offset = -VT.getStoreSize()+1; 13940 Info.size = 2*VT.getStoreSize()-1; 13941 Info.align = 1; 13942 Info.flags = MachineMemOperand::MOStore; 13943 return true; 13944 } 13945 case Intrinsic::ppc_qpx_qvstfda: 13946 case Intrinsic::ppc_qpx_qvstfsa: 13947 case Intrinsic::ppc_qpx_qvstfcda: 13948 case Intrinsic::ppc_qpx_qvstfcsa: 13949 case Intrinsic::ppc_qpx_qvstfiwa: { 13950 EVT VT; 13951 switch (Intrinsic) { 13952 case Intrinsic::ppc_qpx_qvstfda: 13953 VT = MVT::v4f64; 13954 break; 13955 case Intrinsic::ppc_qpx_qvstfsa: 13956 VT = MVT::v4f32; 13957 break; 13958 case Intrinsic::ppc_qpx_qvstfcda: 13959 VT = MVT::v2f64; 13960 break; 13961 case Intrinsic::ppc_qpx_qvstfcsa: 13962 VT = MVT::v2f32; 13963 break; 13964 default: 13965 VT = MVT::v4i32; 13966 break; 13967 } 13968 13969 Info.opc = ISD::INTRINSIC_VOID; 13970 Info.memVT = VT; 13971 Info.ptrVal = I.getArgOperand(1); 13972 Info.offset = 0; 13973 Info.size = VT.getStoreSize(); 13974 Info.align = 1; 13975 Info.flags = MachineMemOperand::MOStore; 13976 return true; 13977 } 13978 default: 13979 break; 13980 } 13981 13982 return false; 13983 } 13984 13985 /// getOptimalMemOpType - Returns the target specific optimal type for load 13986 /// and store operations as a result of memset, memcpy, and memmove 13987 /// lowering. If DstAlign is zero that means it's safe to destination 13988 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 13989 /// means there isn't a need to check it against alignment requirement, 13990 /// probably because the source does not need to be loaded. If 'IsMemset' is 13991 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 13992 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 13993 /// source is constant so it does not need to be loaded. 13994 /// It returns EVT::Other if the type should be determined using generic 13995 /// target-independent logic. 13996 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 13997 unsigned DstAlign, unsigned SrcAlign, 13998 bool IsMemset, bool ZeroMemset, 13999 bool MemcpyStrSrc, 14000 MachineFunction &MF) const { 14001 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 14002 const Function &F = MF.getFunction(); 14003 // When expanding a memset, require at least two QPX instructions to cover 14004 // the cost of loading the value to be stored from the constant pool. 14005 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 14006 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 14007 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 14008 return MVT::v4f64; 14009 } 14010 14011 // We should use Altivec/VSX loads and stores when available. For unaligned 14012 // addresses, unaligned VSX loads are only fast starting with the P8. 14013 if (Subtarget.hasAltivec() && Size >= 16 && 14014 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 14015 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 14016 return MVT::v4i32; 14017 } 14018 14019 if (Subtarget.isPPC64()) { 14020 return MVT::i64; 14021 } 14022 14023 return MVT::i32; 14024 } 14025 14026 /// Returns true if it is beneficial to convert a load of a constant 14027 /// to just the constant itself. 14028 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14029 Type *Ty) const { 14030 assert(Ty->isIntegerTy()); 14031 14032 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 14033 return !(BitSize == 0 || BitSize > 64); 14034 } 14035 14036 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 14037 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14038 return false; 14039 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 14040 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 14041 return NumBits1 == 64 && NumBits2 == 32; 14042 } 14043 14044 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 14045 if (!VT1.isInteger() || !VT2.isInteger()) 14046 return false; 14047 unsigned NumBits1 = VT1.getSizeInBits(); 14048 unsigned NumBits2 = VT2.getSizeInBits(); 14049 return NumBits1 == 64 && NumBits2 == 32; 14050 } 14051 14052 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14053 // Generally speaking, zexts are not free, but they are free when they can be 14054 // folded with other operations. 14055 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 14056 EVT MemVT = LD->getMemoryVT(); 14057 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 14058 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 14059 (LD->getExtensionType() == ISD::NON_EXTLOAD || 14060 LD->getExtensionType() == ISD::ZEXTLOAD)) 14061 return true; 14062 } 14063 14064 // FIXME: Add other cases... 14065 // - 32-bit shifts with a zext to i64 14066 // - zext after ctlz, bswap, etc. 14067 // - zext after and by a constant mask 14068 14069 return TargetLowering::isZExtFree(Val, VT2); 14070 } 14071 14072 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 14073 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 14074 "invalid fpext types"); 14075 // Extending to float128 is not free. 14076 if (DestVT == MVT::f128) 14077 return false; 14078 return true; 14079 } 14080 14081 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14082 return isInt<16>(Imm) || isUInt<16>(Imm); 14083 } 14084 14085 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14086 return isInt<16>(Imm) || isUInt<16>(Imm); 14087 } 14088 14089 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 14090 unsigned, 14091 unsigned, 14092 bool *Fast) const { 14093 if (DisablePPCUnaligned) 14094 return false; 14095 14096 // PowerPC supports unaligned memory access for simple non-vector types. 14097 // Although accessing unaligned addresses is not as efficient as accessing 14098 // aligned addresses, it is generally more efficient than manual expansion, 14099 // and generally only traps for software emulation when crossing page 14100 // boundaries. 14101 14102 if (!VT.isSimple()) 14103 return false; 14104 14105 if (VT.getSimpleVT().isVector()) { 14106 if (Subtarget.hasVSX()) { 14107 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 14108 VT != MVT::v4f32 && VT != MVT::v4i32) 14109 return false; 14110 } else { 14111 return false; 14112 } 14113 } 14114 14115 if (VT == MVT::ppcf128) 14116 return false; 14117 14118 if (Fast) 14119 *Fast = true; 14120 14121 return true; 14122 } 14123 14124 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 14125 VT = VT.getScalarType(); 14126 14127 if (!VT.isSimple()) 14128 return false; 14129 14130 switch (VT.getSimpleVT().SimpleTy) { 14131 case MVT::f32: 14132 case MVT::f64: 14133 return true; 14134 case MVT::f128: 14135 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 14136 default: 14137 break; 14138 } 14139 14140 return false; 14141 } 14142 14143 const MCPhysReg * 14144 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 14145 // LR is a callee-save register, but we must treat it as clobbered by any call 14146 // site. Hence we include LR in the scratch registers, which are in turn added 14147 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 14148 // to CTR, which is used by any indirect call. 14149 static const MCPhysReg ScratchRegs[] = { 14150 PPC::X12, PPC::LR8, PPC::CTR8, 0 14151 }; 14152 14153 return ScratchRegs; 14154 } 14155 14156 unsigned PPCTargetLowering::getExceptionPointerRegister( 14157 const Constant *PersonalityFn) const { 14158 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 14159 } 14160 14161 unsigned PPCTargetLowering::getExceptionSelectorRegister( 14162 const Constant *PersonalityFn) const { 14163 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 14164 } 14165 14166 bool 14167 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 14168 EVT VT , unsigned DefinedValues) const { 14169 if (VT == MVT::v2i64) 14170 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 14171 14172 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 14173 return true; 14174 14175 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 14176 } 14177 14178 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 14179 if (DisableILPPref || Subtarget.enableMachineScheduler()) 14180 return TargetLowering::getSchedulingPreference(N); 14181 14182 return Sched::ILP; 14183 } 14184 14185 // Create a fast isel object. 14186 FastISel * 14187 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 14188 const TargetLibraryInfo *LibInfo) const { 14189 return PPC::createFastISel(FuncInfo, LibInfo); 14190 } 14191 14192 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14193 if (Subtarget.isDarwinABI()) return; 14194 if (!Subtarget.isPPC64()) return; 14195 14196 // Update IsSplitCSR in PPCFunctionInfo 14197 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 14198 PFI->setIsSplitCSR(true); 14199 } 14200 14201 void PPCTargetLowering::insertCopiesSplitCSR( 14202 MachineBasicBlock *Entry, 14203 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14204 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 14205 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14206 if (!IStart) 14207 return; 14208 14209 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 14210 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14211 MachineBasicBlock::iterator MBBI = Entry->begin(); 14212 for (const MCPhysReg *I = IStart; *I; ++I) { 14213 const TargetRegisterClass *RC = nullptr; 14214 if (PPC::G8RCRegClass.contains(*I)) 14215 RC = &PPC::G8RCRegClass; 14216 else if (PPC::F8RCRegClass.contains(*I)) 14217 RC = &PPC::F8RCRegClass; 14218 else if (PPC::CRRCRegClass.contains(*I)) 14219 RC = &PPC::CRRCRegClass; 14220 else if (PPC::VRRCRegClass.contains(*I)) 14221 RC = &PPC::VRRCRegClass; 14222 else 14223 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14224 14225 unsigned NewVR = MRI->createVirtualRegister(RC); 14226 // Create copy from CSR to a virtual register. 14227 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14228 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14229 // nounwind. If we want to generalize this later, we may need to emit 14230 // CFI pseudo-instructions. 14231 assert(Entry->getParent()->getFunction().hasFnAttribute( 14232 Attribute::NoUnwind) && 14233 "Function should be nounwind in insertCopiesSplitCSR!"); 14234 Entry->addLiveIn(*I); 14235 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14236 .addReg(*I); 14237 14238 // Insert the copy-back instructions right before the terminator 14239 for (auto *Exit : Exits) 14240 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14241 TII->get(TargetOpcode::COPY), *I) 14242 .addReg(NewVR); 14243 } 14244 } 14245 14246 // Override to enable LOAD_STACK_GUARD lowering on Linux. 14247 bool PPCTargetLowering::useLoadStackGuardNode() const { 14248 if (!Subtarget.isTargetLinux()) 14249 return TargetLowering::useLoadStackGuardNode(); 14250 return true; 14251 } 14252 14253 // Override to disable global variable loading on Linux. 14254 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 14255 if (!Subtarget.isTargetLinux()) 14256 return TargetLowering::insertSSPDeclarations(M); 14257 } 14258 14259 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 14260 if (!VT.isSimple() || !Subtarget.hasVSX()) 14261 return false; 14262 14263 switch(VT.getSimpleVT().SimpleTy) { 14264 default: 14265 // For FP types that are currently not supported by PPC backend, return 14266 // false. Examples: f16, f80. 14267 return false; 14268 case MVT::f32: 14269 case MVT::f64: 14270 case MVT::ppcf128: 14271 return Imm.isPosZero(); 14272 } 14273 } 14274 14275 // For vector shift operation op, fold 14276 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 14277 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 14278 SelectionDAG &DAG) { 14279 SDValue N0 = N->getOperand(0); 14280 SDValue N1 = N->getOperand(1); 14281 EVT VT = N0.getValueType(); 14282 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 14283 unsigned Opcode = N->getOpcode(); 14284 unsigned TargetOpcode; 14285 14286 switch (Opcode) { 14287 default: 14288 llvm_unreachable("Unexpected shift operation"); 14289 case ISD::SHL: 14290 TargetOpcode = PPCISD::SHL; 14291 break; 14292 case ISD::SRL: 14293 TargetOpcode = PPCISD::SRL; 14294 break; 14295 case ISD::SRA: 14296 TargetOpcode = PPCISD::SRA; 14297 break; 14298 } 14299 14300 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 14301 N1->getOpcode() == ISD::AND) 14302 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 14303 if (Mask->getZExtValue() == OpSizeInBits - 1) 14304 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 14305 14306 return SDValue(); 14307 } 14308 14309 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 14310 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14311 return Value; 14312 14313 SDValue N0 = N->getOperand(0); 14314 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14315 if (!Subtarget.isISA3_0() || 14316 N0.getOpcode() != ISD::SIGN_EXTEND || 14317 N0.getOperand(0).getValueType() != MVT::i32 || 14318 CN1 == nullptr || N->getValueType(0) != MVT::i64) 14319 return SDValue(); 14320 14321 // We can't save an operation here if the value is already extended, and 14322 // the existing shift is easier to combine. 14323 SDValue ExtsSrc = N0.getOperand(0); 14324 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 14325 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 14326 return SDValue(); 14327 14328 SDLoc DL(N0); 14329 SDValue ShiftBy = SDValue(CN1, 0); 14330 // We want the shift amount to be i32 on the extswli, but the shift could 14331 // have an i64. 14332 if (ShiftBy.getValueType() == MVT::i64) 14333 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 14334 14335 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 14336 ShiftBy); 14337 } 14338 14339 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 14340 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14341 return Value; 14342 14343 return SDValue(); 14344 } 14345 14346 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 14347 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14348 return Value; 14349 14350 return SDValue(); 14351 } 14352 14353 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 14354 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 14355 // When C is zero, the equation (addi Z, -C) can be simplified to Z 14356 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 14357 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 14358 const PPCSubtarget &Subtarget) { 14359 if (!Subtarget.isPPC64()) 14360 return SDValue(); 14361 14362 SDValue LHS = N->getOperand(0); 14363 SDValue RHS = N->getOperand(1); 14364 14365 auto isZextOfCompareWithConstant = [](SDValue Op) { 14366 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 14367 Op.getValueType() != MVT::i64) 14368 return false; 14369 14370 SDValue Cmp = Op.getOperand(0); 14371 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 14372 Cmp.getOperand(0).getValueType() != MVT::i64) 14373 return false; 14374 14375 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 14376 int64_t NegConstant = 0 - Constant->getSExtValue(); 14377 // Due to the limitations of the addi instruction, 14378 // -C is required to be [-32768, 32767]. 14379 return isInt<16>(NegConstant); 14380 } 14381 14382 return false; 14383 }; 14384 14385 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 14386 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 14387 14388 // If there is a pattern, canonicalize a zext operand to the RHS. 14389 if (LHSHasPattern && !RHSHasPattern) 14390 std::swap(LHS, RHS); 14391 else if (!LHSHasPattern && !RHSHasPattern) 14392 return SDValue(); 14393 14394 SDLoc DL(N); 14395 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i64); 14396 SDValue Cmp = RHS.getOperand(0); 14397 SDValue Z = Cmp.getOperand(0); 14398 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 14399 14400 assert(Constant && "Constant Should not be a null pointer."); 14401 int64_t NegConstant = 0 - Constant->getSExtValue(); 14402 14403 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 14404 default: break; 14405 case ISD::SETNE: { 14406 // when C == 0 14407 // --> addze X, (addic Z, -1).carry 14408 // / 14409 // add X, (zext(setne Z, C))-- 14410 // \ when -32768 <= -C <= 32767 && C != 0 14411 // --> addze X, (addic (addi Z, -C), -1).carry 14412 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14413 DAG.getConstant(NegConstant, DL, MVT::i64)); 14414 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14415 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14416 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 14417 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14418 SDValue(Addc.getNode(), 1)); 14419 } 14420 case ISD::SETEQ: { 14421 // when C == 0 14422 // --> addze X, (subfic Z, 0).carry 14423 // / 14424 // add X, (zext(sete Z, C))-- 14425 // \ when -32768 <= -C <= 32767 && C != 0 14426 // --> addze X, (subfic (addi Z, -C), 0).carry 14427 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14428 DAG.getConstant(NegConstant, DL, MVT::i64)); 14429 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14430 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14431 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 14432 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14433 SDValue(Subc.getNode(), 1)); 14434 } 14435 } 14436 14437 return SDValue(); 14438 } 14439 14440 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 14441 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 14442 return Value; 14443 14444 return SDValue(); 14445 } 14446 14447 // Detect TRUNCATE operations on bitcasts of float128 values. 14448 // What we are looking for here is the situtation where we extract a subset 14449 // of bits from a 128 bit float. 14450 // This can be of two forms: 14451 // 1) BITCAST of f128 feeding TRUNCATE 14452 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 14453 // The reason this is required is because we do not have a legal i128 type 14454 // and so we want to prevent having to store the f128 and then reload part 14455 // of it. 14456 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 14457 DAGCombinerInfo &DCI) const { 14458 // If we are using CRBits then try that first. 14459 if (Subtarget.useCRBits()) { 14460 // Check if CRBits did anything and return that if it did. 14461 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 14462 return CRTruncValue; 14463 } 14464 14465 SDLoc dl(N); 14466 SDValue Op0 = N->getOperand(0); 14467 14468 // Looking for a truncate of i128 to i64. 14469 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 14470 return SDValue(); 14471 14472 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 14473 14474 // SRL feeding TRUNCATE. 14475 if (Op0.getOpcode() == ISD::SRL) { 14476 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 14477 // The right shift has to be by 64 bits. 14478 if (!ConstNode || ConstNode->getZExtValue() != 64) 14479 return SDValue(); 14480 14481 // Switch the element number to extract. 14482 EltToExtract = EltToExtract ? 0 : 1; 14483 // Update Op0 past the SRL. 14484 Op0 = Op0.getOperand(0); 14485 } 14486 14487 // BITCAST feeding a TRUNCATE possibly via SRL. 14488 if (Op0.getOpcode() == ISD::BITCAST && 14489 Op0.getValueType() == MVT::i128 && 14490 Op0.getOperand(0).getValueType() == MVT::f128) { 14491 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 14492 return DCI.DAG.getNode( 14493 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 14494 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 14495 } 14496 return SDValue(); 14497 } 14498 14499 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 14500 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 14501 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 14502 return false; 14503 14504 // If not a tail call then no need to proceed. 14505 if (!CI->isTailCall()) 14506 return false; 14507 14508 // If tail calls are disabled for the caller then we are done. 14509 const Function *Caller = CI->getParent()->getParent(); 14510 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 14511 if (Attr.getValueAsString() == "true") 14512 return false; 14513 14514 // If sibling calls have been disabled and tail-calls aren't guaranteed 14515 // there is no reason to duplicate. 14516 auto &TM = getTargetMachine(); 14517 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 14518 return false; 14519 14520 // Can't tail call a function called indirectly, or if it has variadic args. 14521 const Function *Callee = CI->getCalledFunction(); 14522 if (!Callee || Callee->isVarArg()) 14523 return false; 14524 14525 // Make sure the callee and caller calling conventions are eligible for tco. 14526 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 14527 CI->getCallingConv())) 14528 return false; 14529 14530 // If the function is local then we have a good chance at tail-calling it 14531 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 14532 } 14533 14534 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 14535 if (!Subtarget.hasVSX()) 14536 return false; 14537 if (Subtarget.hasP9Vector() && VT == MVT::f128) 14538 return true; 14539 return VT == MVT::f32 || VT == MVT::f64 || 14540 VT == MVT::v4f32 || VT == MVT::v2f64; 14541 } 14542 14543 bool PPCTargetLowering:: 14544 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 14545 const Value *Mask = AndI.getOperand(1); 14546 // If the mask is suitable for andi. or andis. we should sink the and. 14547 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 14548 // Can't handle constants wider than 64-bits. 14549 if (CI->getBitWidth() > 64) 14550 return false; 14551 int64_t ConstVal = CI->getZExtValue(); 14552 return isUInt<16>(ConstVal) || 14553 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 14554 } 14555 14556 // For non-constant masks, we can always use the record-form and. 14557 return true; 14558 } 14559 14560 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 14561 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 14562 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 14563 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 14564 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 14565 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 14566 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 14567 assert(Subtarget.hasP9Altivec() && 14568 "Only combine this when P9 altivec supported!"); 14569 EVT VT = N->getValueType(0); 14570 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 14571 return SDValue(); 14572 14573 SelectionDAG &DAG = DCI.DAG; 14574 SDLoc dl(N); 14575 if (N->getOperand(0).getOpcode() == ISD::SUB) { 14576 // Even for signed integers, if it's known to be positive (as signed 14577 // integer) due to zero-extended inputs. 14578 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 14579 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 14580 if ((SubOpcd0 == ISD::ZERO_EXTEND || 14581 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 14582 (SubOpcd1 == ISD::ZERO_EXTEND || 14583 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 14584 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 14585 N->getOperand(0)->getOperand(0), 14586 N->getOperand(0)->getOperand(1), 14587 DAG.getTargetConstant(0, dl, MVT::i32)); 14588 } 14589 14590 // For type v4i32, it can be optimized with xvnegsp + vabsduw 14591 if (N->getOperand(0).getValueType() == MVT::v4i32 && 14592 N->getOperand(0).hasOneUse()) { 14593 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 14594 N->getOperand(0)->getOperand(0), 14595 N->getOperand(0)->getOperand(1), 14596 DAG.getTargetConstant(1, dl, MVT::i32)); 14597 } 14598 } 14599 14600 return SDValue(); 14601 } 14602 14603 // For type v4i32/v8ii16/v16i8, transform 14604 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 14605 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 14606 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 14607 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 14608 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 14609 DAGCombinerInfo &DCI) const { 14610 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 14611 assert(Subtarget.hasP9Altivec() && 14612 "Only combine this when P9 altivec supported!"); 14613 14614 SelectionDAG &DAG = DCI.DAG; 14615 SDLoc dl(N); 14616 SDValue Cond = N->getOperand(0); 14617 SDValue TrueOpnd = N->getOperand(1); 14618 SDValue FalseOpnd = N->getOperand(2); 14619 EVT VT = N->getOperand(1).getValueType(); 14620 14621 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 14622 FalseOpnd.getOpcode() != ISD::SUB) 14623 return SDValue(); 14624 14625 // ABSD only available for type v4i32/v8i16/v16i8 14626 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 14627 return SDValue(); 14628 14629 // At least to save one more dependent computation 14630 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 14631 return SDValue(); 14632 14633 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 14634 14635 // Can only handle unsigned comparison here 14636 switch (CC) { 14637 default: 14638 return SDValue(); 14639 case ISD::SETUGT: 14640 case ISD::SETUGE: 14641 break; 14642 case ISD::SETULT: 14643 case ISD::SETULE: 14644 std::swap(TrueOpnd, FalseOpnd); 14645 break; 14646 } 14647 14648 SDValue CmpOpnd1 = Cond.getOperand(0); 14649 SDValue CmpOpnd2 = Cond.getOperand(1); 14650 14651 // SETCC CmpOpnd1 CmpOpnd2 cond 14652 // TrueOpnd = CmpOpnd1 - CmpOpnd2 14653 // FalseOpnd = CmpOpnd2 - CmpOpnd1 14654 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 14655 TrueOpnd.getOperand(1) == CmpOpnd2 && 14656 FalseOpnd.getOperand(0) == CmpOpnd2 && 14657 FalseOpnd.getOperand(1) == CmpOpnd1) { 14658 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 14659 CmpOpnd1, CmpOpnd2, 14660 DAG.getTargetConstant(0, dl, MVT::i32)); 14661 } 14662 14663 return SDValue(); 14664 } 14665