1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PPCISelLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCISelLowering.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCCState.h" 17 #include "PPCCallingConv.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCMachineFunctionInfo.h" 21 #include "PPCPerfectShuffle.h" 22 #include "PPCRegisterInfo.h" 23 #include "PPCSubtarget.h" 24 #include "PPCTargetMachine.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/CodeGen/CallingConvLower.h" 38 #include "llvm/CodeGen/ISDOpcodes.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.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/MCContext.h" 74 #include "llvm/MC/MCExpr.h" 75 #include "llvm/MC/MCRegisterInfo.h" 76 #include "llvm/MC/MCSymbolXCOFF.h" 77 #include "llvm/Support/AtomicOrdering.h" 78 #include "llvm/Support/BranchProbability.h" 79 #include "llvm/Support/Casting.h" 80 #include "llvm/Support/CodeGen.h" 81 #include "llvm/Support/CommandLine.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/Debug.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/KnownBits.h" 87 #include "llvm/Support/MachineValueType.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include "llvm/Target/TargetMachine.h" 91 #include "llvm/Target/TargetOptions.h" 92 #include <algorithm> 93 #include <cassert> 94 #include <cstdint> 95 #include <iterator> 96 #include <list> 97 #include <utility> 98 #include <vector> 99 100 using namespace llvm; 101 102 #define DEBUG_TYPE "ppc-lowering" 103 104 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 105 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 106 107 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 108 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 109 110 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 111 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 112 113 static cl::opt<bool> DisableSCO("disable-ppc-sco", 114 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 115 116 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 117 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 118 119 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 120 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 121 122 STATISTIC(NumTailCalls, "Number of tail calls"); 123 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 124 125 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 126 127 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 128 129 // FIXME: Remove this once the bug has been fixed! 130 extern cl::opt<bool> ANDIGlueBug; 131 132 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 133 const PPCSubtarget &STI) 134 : TargetLowering(TM), Subtarget(STI) { 135 // Use _setjmp/_longjmp instead of setjmp/longjmp. 136 setUseUnderscoreSetJmp(true); 137 setUseUnderscoreLongJmp(true); 138 139 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 140 // arguments are at least 4/8 bytes aligned. 141 bool isPPC64 = Subtarget.isPPC64(); 142 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 143 144 // Set up the register classes. 145 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 146 if (!useSoftFloat()) { 147 if (hasSPE()) { 148 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 149 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 150 } else { 151 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 152 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 153 } 154 } 155 156 // Match BITREVERSE to customized fast code sequence in the td file. 157 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 158 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 159 160 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 161 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 162 163 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 164 for (MVT VT : MVT::integer_valuetypes()) { 165 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 167 } 168 169 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 170 171 // PowerPC has pre-inc load and store's. 172 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 173 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 174 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 175 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 176 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 177 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 178 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 179 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 180 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 181 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 182 if (!Subtarget.hasSPE()) { 183 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 184 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 185 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 186 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 187 } 188 189 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 190 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 191 for (MVT VT : ScalarIntVTs) { 192 setOperationAction(ISD::ADDC, VT, Legal); 193 setOperationAction(ISD::ADDE, VT, Legal); 194 setOperationAction(ISD::SUBC, VT, Legal); 195 setOperationAction(ISD::SUBE, VT, Legal); 196 } 197 198 if (Subtarget.useCRBits()) { 199 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 200 201 if (isPPC64 || Subtarget.hasFPCVT()) { 202 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 203 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 204 isPPC64 ? MVT::i64 : MVT::i32); 205 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 206 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 207 isPPC64 ? MVT::i64 : MVT::i32); 208 } else { 209 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 210 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 211 } 212 213 // PowerPC does not support direct load/store of condition registers. 214 setOperationAction(ISD::LOAD, MVT::i1, Custom); 215 setOperationAction(ISD::STORE, MVT::i1, Custom); 216 217 // FIXME: Remove this once the ANDI glue bug is fixed: 218 if (ANDIGlueBug) 219 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 220 221 for (MVT VT : MVT::integer_valuetypes()) { 222 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 223 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 224 setTruncStoreAction(VT, MVT::i1, Expand); 225 } 226 227 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 228 } 229 230 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 231 // PPC (the libcall is not available). 232 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 233 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 234 235 // We do not currently implement these libm ops for PowerPC. 236 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 237 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 238 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 239 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 240 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 241 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 242 243 // PowerPC has no SREM/UREM instructions unless we are on P9 244 // On P9 we may use a hardware instruction to compute the remainder. 245 // The instructions are not legalized directly because in the cases where the 246 // result of both the remainder and the division is required it is more 247 // efficient to compute the remainder from the result of the division rather 248 // than use the remainder instruction. 249 if (Subtarget.isISA3_0()) { 250 setOperationAction(ISD::SREM, MVT::i32, Custom); 251 setOperationAction(ISD::UREM, MVT::i32, Custom); 252 setOperationAction(ISD::SREM, MVT::i64, Custom); 253 setOperationAction(ISD::UREM, MVT::i64, Custom); 254 } else { 255 setOperationAction(ISD::SREM, MVT::i32, Expand); 256 setOperationAction(ISD::UREM, MVT::i32, Expand); 257 setOperationAction(ISD::SREM, MVT::i64, Expand); 258 setOperationAction(ISD::UREM, MVT::i64, Expand); 259 } 260 261 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 262 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 263 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 264 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 265 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 266 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 267 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 268 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 269 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 270 271 // We don't support sin/cos/sqrt/fmod/pow 272 setOperationAction(ISD::FSIN , MVT::f64, Expand); 273 setOperationAction(ISD::FCOS , MVT::f64, Expand); 274 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 275 setOperationAction(ISD::FREM , MVT::f64, Expand); 276 setOperationAction(ISD::FPOW , MVT::f64, Expand); 277 setOperationAction(ISD::FSIN , MVT::f32, Expand); 278 setOperationAction(ISD::FCOS , MVT::f32, Expand); 279 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 280 setOperationAction(ISD::FREM , MVT::f32, Expand); 281 setOperationAction(ISD::FPOW , MVT::f32, Expand); 282 if (Subtarget.hasSPE()) { 283 setOperationAction(ISD::FMA , MVT::f64, Expand); 284 setOperationAction(ISD::FMA , MVT::f32, Expand); 285 } else { 286 setOperationAction(ISD::FMA , MVT::f64, Legal); 287 setOperationAction(ISD::FMA , MVT::f32, Legal); 288 } 289 290 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 291 292 // If we're enabling GP optimizations, use hardware square root 293 if (!Subtarget.hasFSQRT() && 294 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 295 Subtarget.hasFRE())) 296 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 297 298 if (!Subtarget.hasFSQRT() && 299 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 300 Subtarget.hasFRES())) 301 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 302 303 if (Subtarget.hasFCPSGN()) { 304 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 305 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 306 } else { 307 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 308 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 309 } 310 311 if (Subtarget.hasFPRND()) { 312 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 313 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 314 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 315 setOperationAction(ISD::FROUND, MVT::f64, Legal); 316 317 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 318 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 319 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 320 setOperationAction(ISD::FROUND, MVT::f32, Legal); 321 } 322 323 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 324 // to speed up scalar BSWAP64. 325 // CTPOP or CTTZ were introduced in P8/P9 respectively 326 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 327 if (Subtarget.hasP9Vector()) 328 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 329 else 330 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 331 if (Subtarget.isISA3_0()) { 332 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 333 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 334 } else { 335 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 336 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 337 } 338 339 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 340 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 341 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 342 } else { 343 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 344 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 345 } 346 347 // PowerPC does not have ROTR 348 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 349 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 350 351 if (!Subtarget.useCRBits()) { 352 // PowerPC does not have Select 353 setOperationAction(ISD::SELECT, MVT::i32, Expand); 354 setOperationAction(ISD::SELECT, MVT::i64, Expand); 355 setOperationAction(ISD::SELECT, MVT::f32, Expand); 356 setOperationAction(ISD::SELECT, MVT::f64, Expand); 357 } 358 359 // PowerPC wants to turn select_cc of FP into fsel when possible. 360 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 361 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 362 363 // PowerPC wants to optimize integer setcc a bit 364 if (!Subtarget.useCRBits()) 365 setOperationAction(ISD::SETCC, MVT::i32, Custom); 366 367 // PowerPC does not have BRCOND which requires SetCC 368 if (!Subtarget.useCRBits()) 369 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 370 371 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 372 373 if (Subtarget.hasSPE()) { 374 // SPE has built-in conversions 375 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 376 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 377 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 378 } else { 379 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 380 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 381 382 // PowerPC does not have [U|S]INT_TO_FP 383 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 384 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 385 } 386 387 if (Subtarget.hasDirectMove() && isPPC64) { 388 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 389 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 390 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 391 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 392 } else { 393 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 394 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 395 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 396 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 397 } 398 399 // We cannot sextinreg(i1). Expand to shifts. 400 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 401 402 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 403 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 404 // support continuation, user-level threading, and etc.. As a result, no 405 // other SjLj exception interfaces are implemented and please don't build 406 // your own exception handling based on them. 407 // LLVM/Clang supports zero-cost DWARF exception handling. 408 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 409 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 410 411 // We want to legalize GlobalAddress and ConstantPool nodes into the 412 // appropriate instructions to materialize the address. 413 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 414 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 415 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 416 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 417 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 418 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 419 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 420 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 421 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 422 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 423 424 // TRAP is legal. 425 setOperationAction(ISD::TRAP, MVT::Other, Legal); 426 427 // TRAMPOLINE is custom lowered. 428 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 429 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 430 431 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 432 setOperationAction(ISD::VASTART , MVT::Other, Custom); 433 434 if (Subtarget.is64BitELFABI()) { 435 // VAARG always uses double-word chunks, so promote anything smaller. 436 setOperationAction(ISD::VAARG, MVT::i1, Promote); 437 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 438 setOperationAction(ISD::VAARG, MVT::i8, Promote); 439 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 440 setOperationAction(ISD::VAARG, MVT::i16, Promote); 441 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 442 setOperationAction(ISD::VAARG, MVT::i32, Promote); 443 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 444 setOperationAction(ISD::VAARG, MVT::Other, Expand); 445 } else if (Subtarget.is32BitELFABI()) { 446 // VAARG is custom lowered with the 32-bit SVR4 ABI. 447 setOperationAction(ISD::VAARG, MVT::Other, Custom); 448 setOperationAction(ISD::VAARG, MVT::i64, Custom); 449 } else 450 setOperationAction(ISD::VAARG, MVT::Other, Expand); 451 452 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 453 if (Subtarget.is32BitELFABI()) 454 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 455 else 456 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 457 458 // Use the default implementation. 459 setOperationAction(ISD::VAEND , MVT::Other, Expand); 460 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 461 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 462 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 463 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 464 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 465 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 466 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 467 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 468 469 // We want to custom lower some of our intrinsics. 470 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 471 472 // To handle counter-based loop conditions. 473 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 474 475 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 476 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 477 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 478 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 479 480 // Comparisons that require checking two conditions. 481 if (Subtarget.hasSPE()) { 482 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 483 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 484 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 485 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 486 } 487 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 488 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 489 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 490 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 491 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 492 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 493 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 494 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 495 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 496 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 497 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 498 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 499 500 if (Subtarget.has64BitSupport()) { 501 // They also have instructions for converting between i64 and fp. 502 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 503 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 504 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 505 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 506 // This is just the low 32 bits of a (signed) fp->i64 conversion. 507 // We cannot do this with Promote because i64 is not a legal type. 508 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 509 510 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 511 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 512 } else { 513 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 514 if (Subtarget.hasSPE()) 515 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 516 else 517 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 518 } 519 520 // With the instructions enabled under FPCVT, we can do everything. 521 if (Subtarget.hasFPCVT()) { 522 if (Subtarget.has64BitSupport()) { 523 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 524 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 525 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 526 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 527 } 528 529 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 530 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 531 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 532 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 533 } 534 535 if (Subtarget.use64BitRegs()) { 536 // 64-bit PowerPC implementations can support i64 types directly 537 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 538 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 539 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 540 // 64-bit PowerPC wants to expand i128 shifts itself. 541 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 542 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 543 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 544 } else { 545 // 32-bit PowerPC wants to expand i64 shifts itself. 546 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 547 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 548 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 549 } 550 551 if (Subtarget.hasVSX()) { 552 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 553 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 554 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 555 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 556 } 557 558 if (Subtarget.hasAltivec()) { 559 // First set operation action for all vector types to expand. Then we 560 // will selectively turn on ones that can be effectively codegen'd. 561 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 562 // add/sub are legal for all supported vector VT's. 563 setOperationAction(ISD::ADD, VT, Legal); 564 setOperationAction(ISD::SUB, VT, Legal); 565 566 // For v2i64, these are only valid with P8Vector. This is corrected after 567 // the loop. 568 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 569 setOperationAction(ISD::SMAX, VT, Legal); 570 setOperationAction(ISD::SMIN, VT, Legal); 571 setOperationAction(ISD::UMAX, VT, Legal); 572 setOperationAction(ISD::UMIN, VT, Legal); 573 } 574 else { 575 setOperationAction(ISD::SMAX, VT, Expand); 576 setOperationAction(ISD::SMIN, VT, Expand); 577 setOperationAction(ISD::UMAX, VT, Expand); 578 setOperationAction(ISD::UMIN, VT, Expand); 579 } 580 581 if (Subtarget.hasVSX()) { 582 setOperationAction(ISD::FMAXNUM, VT, Legal); 583 setOperationAction(ISD::FMINNUM, VT, Legal); 584 } 585 586 // Vector instructions introduced in P8 587 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 588 setOperationAction(ISD::CTPOP, VT, Legal); 589 setOperationAction(ISD::CTLZ, VT, Legal); 590 } 591 else { 592 setOperationAction(ISD::CTPOP, VT, Expand); 593 setOperationAction(ISD::CTLZ, VT, Expand); 594 } 595 596 // Vector instructions introduced in P9 597 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 598 setOperationAction(ISD::CTTZ, VT, Legal); 599 else 600 setOperationAction(ISD::CTTZ, VT, Expand); 601 602 // We promote all shuffles to v16i8. 603 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 604 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 605 606 // We promote all non-typed operations to v4i32. 607 setOperationAction(ISD::AND , VT, Promote); 608 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 609 setOperationAction(ISD::OR , VT, Promote); 610 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 611 setOperationAction(ISD::XOR , VT, Promote); 612 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 613 setOperationAction(ISD::LOAD , VT, Promote); 614 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 615 setOperationAction(ISD::SELECT, VT, Promote); 616 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 617 setOperationAction(ISD::VSELECT, VT, Legal); 618 setOperationAction(ISD::SELECT_CC, VT, Promote); 619 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 620 setOperationAction(ISD::STORE, VT, Promote); 621 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 622 623 // No other operations are legal. 624 setOperationAction(ISD::MUL , VT, Expand); 625 setOperationAction(ISD::SDIV, VT, Expand); 626 setOperationAction(ISD::SREM, VT, Expand); 627 setOperationAction(ISD::UDIV, VT, Expand); 628 setOperationAction(ISD::UREM, VT, Expand); 629 setOperationAction(ISD::FDIV, VT, Expand); 630 setOperationAction(ISD::FREM, VT, Expand); 631 setOperationAction(ISD::FNEG, VT, Expand); 632 setOperationAction(ISD::FSQRT, VT, Expand); 633 setOperationAction(ISD::FLOG, VT, Expand); 634 setOperationAction(ISD::FLOG10, VT, Expand); 635 setOperationAction(ISD::FLOG2, VT, Expand); 636 setOperationAction(ISD::FEXP, VT, Expand); 637 setOperationAction(ISD::FEXP2, VT, Expand); 638 setOperationAction(ISD::FSIN, VT, Expand); 639 setOperationAction(ISD::FCOS, VT, Expand); 640 setOperationAction(ISD::FABS, VT, Expand); 641 setOperationAction(ISD::FFLOOR, VT, Expand); 642 setOperationAction(ISD::FCEIL, VT, Expand); 643 setOperationAction(ISD::FTRUNC, VT, Expand); 644 setOperationAction(ISD::FRINT, VT, Expand); 645 setOperationAction(ISD::FNEARBYINT, VT, Expand); 646 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 647 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 648 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 649 setOperationAction(ISD::MULHU, VT, Expand); 650 setOperationAction(ISD::MULHS, VT, Expand); 651 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 652 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 653 setOperationAction(ISD::UDIVREM, VT, Expand); 654 setOperationAction(ISD::SDIVREM, VT, Expand); 655 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 656 setOperationAction(ISD::FPOW, VT, Expand); 657 setOperationAction(ISD::BSWAP, VT, Expand); 658 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 659 setOperationAction(ISD::ROTL, VT, Expand); 660 setOperationAction(ISD::ROTR, VT, Expand); 661 662 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 663 setTruncStoreAction(VT, InnerVT, Expand); 664 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 665 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 666 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 667 } 668 } 669 if (!Subtarget.hasP8Vector()) { 670 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 671 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 672 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 673 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 674 } 675 676 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 677 setOperationAction(ISD::ABS, VT, Custom); 678 679 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 680 // with merges, splats, etc. 681 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 682 683 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 684 // are cheap, so handle them before they get expanded to scalar. 685 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 686 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 687 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 688 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 689 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 690 691 setOperationAction(ISD::AND , MVT::v4i32, Legal); 692 setOperationAction(ISD::OR , MVT::v4i32, Legal); 693 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 694 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 695 setOperationAction(ISD::SELECT, MVT::v4i32, 696 Subtarget.useCRBits() ? Legal : Expand); 697 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 698 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 699 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 700 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 701 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 702 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 703 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 704 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 705 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 706 707 // Without hasP8Altivec set, v2i64 SMAX isn't available. 708 // But ABS custom lowering requires SMAX support. 709 if (!Subtarget.hasP8Altivec()) 710 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 711 712 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 713 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 714 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 715 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 716 717 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 718 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 719 720 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 721 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 722 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 723 } 724 725 if (Subtarget.hasP8Altivec()) 726 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 727 else 728 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 729 730 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 731 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 732 733 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 734 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 735 736 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 737 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 738 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 739 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 740 741 // Altivec does not contain unordered floating-point compare instructions 742 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 743 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 744 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 745 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 746 747 if (Subtarget.hasVSX()) { 748 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 749 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 750 if (Subtarget.hasP8Vector()) { 751 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 752 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 753 } 754 if (Subtarget.hasDirectMove() && isPPC64) { 755 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 756 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 757 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 758 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 759 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 760 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 761 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 762 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 763 } 764 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 765 766 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 767 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 768 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 769 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 770 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 771 772 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 773 774 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 775 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 776 777 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 778 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 779 780 // Share the Altivec comparison restrictions. 781 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 782 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 783 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 784 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 785 786 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 787 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 788 789 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 790 791 if (Subtarget.hasP8Vector()) 792 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 793 794 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 795 796 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 797 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 798 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 799 800 if (Subtarget.hasP8Altivec()) { 801 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 802 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 803 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 804 805 // 128 bit shifts can be accomplished via 3 instructions for SHL and 806 // SRL, but not for SRA because of the instructions available: 807 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 808 // doing 809 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 810 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 811 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 812 813 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 814 } 815 else { 816 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 817 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 818 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 819 820 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 821 822 // VSX v2i64 only supports non-arithmetic operations. 823 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 824 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 825 } 826 827 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 828 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 829 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 830 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 831 832 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 833 834 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 835 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 836 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 837 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 838 839 // Custom handling for partial vectors of integers converted to 840 // floating point. We already have optimal handling for v2i32 through 841 // the DAG combine, so those aren't necessary. 842 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 843 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 844 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 845 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 846 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 847 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 848 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 849 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 850 851 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 852 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 853 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 854 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 855 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 856 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 857 858 if (Subtarget.hasDirectMove()) 859 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 860 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 861 862 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 863 } 864 865 if (Subtarget.hasP8Altivec()) { 866 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 867 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 868 } 869 870 if (Subtarget.hasP9Vector()) { 871 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 872 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 873 874 // 128 bit shifts can be accomplished via 3 instructions for SHL and 875 // SRL, but not for SRA because of the instructions available: 876 // VS{RL} and VS{RL}O. 877 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 878 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 879 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 880 881 if (EnableQuadPrecision) { 882 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 883 setOperationAction(ISD::FADD, MVT::f128, Legal); 884 setOperationAction(ISD::FSUB, MVT::f128, Legal); 885 setOperationAction(ISD::FDIV, MVT::f128, Legal); 886 setOperationAction(ISD::FMUL, MVT::f128, Legal); 887 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 888 // No extending loads to f128 on PPC. 889 for (MVT FPT : MVT::fp_valuetypes()) 890 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 891 setOperationAction(ISD::FMA, MVT::f128, Legal); 892 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 893 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 894 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 895 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 896 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 897 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 898 899 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 900 setOperationAction(ISD::FRINT, MVT::f128, Legal); 901 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 902 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 903 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 904 setOperationAction(ISD::FROUND, MVT::f128, Legal); 905 906 setOperationAction(ISD::SELECT, MVT::f128, Expand); 907 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 908 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 909 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 910 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 911 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 912 // No implementation for these ops for PowerPC. 913 setOperationAction(ISD::FSIN , MVT::f128, Expand); 914 setOperationAction(ISD::FCOS , MVT::f128, Expand); 915 setOperationAction(ISD::FPOW, MVT::f128, Expand); 916 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 917 setOperationAction(ISD::FREM, MVT::f128, Expand); 918 } 919 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 920 921 } 922 923 if (Subtarget.hasP9Altivec()) { 924 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 925 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 926 } 927 } 928 929 if (Subtarget.hasQPX()) { 930 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 931 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 932 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 933 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 934 935 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 936 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 937 938 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 939 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 940 941 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 942 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 943 944 if (!Subtarget.useCRBits()) 945 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 946 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 947 948 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 949 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 950 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 951 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 952 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 953 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 954 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 955 956 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 957 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 958 959 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 960 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 961 962 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 963 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 964 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 965 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 966 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 967 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 968 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 969 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 970 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 971 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 972 973 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 974 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 975 976 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 977 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 978 979 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 980 981 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 982 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 983 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 984 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 985 986 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 987 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 988 989 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 990 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 991 992 if (!Subtarget.useCRBits()) 993 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 994 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 995 996 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 997 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 998 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 999 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1000 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1001 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1002 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1003 1004 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1005 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1006 1007 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1008 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1009 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1010 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1011 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1012 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1013 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1014 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1015 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1016 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1017 1018 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1019 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1020 1021 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1022 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1023 1024 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1025 1026 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1027 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1028 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1029 1030 if (!Subtarget.useCRBits()) 1031 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1032 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1033 1034 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1035 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1036 1037 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1038 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1039 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1040 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1041 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1042 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1043 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1044 1045 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1046 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1047 1048 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1049 1050 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1051 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1052 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1053 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1054 1055 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1056 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1057 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1058 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1059 1060 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1061 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1062 1063 // These need to set FE_INEXACT, and so cannot be vectorized here. 1064 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1065 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1066 1067 if (TM.Options.UnsafeFPMath) { 1068 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1069 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1070 1071 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1072 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1073 } else { 1074 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1075 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1076 1077 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1078 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1079 } 1080 } 1081 1082 if (Subtarget.has64BitSupport()) 1083 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1084 1085 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1086 1087 if (!isPPC64) { 1088 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1089 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1090 } 1091 1092 setBooleanContents(ZeroOrOneBooleanContent); 1093 1094 if (Subtarget.hasAltivec()) { 1095 // Altivec instructions set fields to all zeros or all ones. 1096 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1097 } 1098 1099 if (!isPPC64) { 1100 // These libcalls are not available in 32-bit. 1101 setLibcallName(RTLIB::SHL_I128, nullptr); 1102 setLibcallName(RTLIB::SRL_I128, nullptr); 1103 setLibcallName(RTLIB::SRA_I128, nullptr); 1104 } 1105 1106 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1107 1108 // We have target-specific dag combine patterns for the following nodes: 1109 setTargetDAGCombine(ISD::ADD); 1110 setTargetDAGCombine(ISD::SHL); 1111 setTargetDAGCombine(ISD::SRA); 1112 setTargetDAGCombine(ISD::SRL); 1113 setTargetDAGCombine(ISD::MUL); 1114 setTargetDAGCombine(ISD::SINT_TO_FP); 1115 setTargetDAGCombine(ISD::BUILD_VECTOR); 1116 if (Subtarget.hasFPCVT()) 1117 setTargetDAGCombine(ISD::UINT_TO_FP); 1118 setTargetDAGCombine(ISD::LOAD); 1119 setTargetDAGCombine(ISD::STORE); 1120 setTargetDAGCombine(ISD::BR_CC); 1121 if (Subtarget.useCRBits()) 1122 setTargetDAGCombine(ISD::BRCOND); 1123 setTargetDAGCombine(ISD::BSWAP); 1124 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1125 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1126 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1127 1128 setTargetDAGCombine(ISD::SIGN_EXTEND); 1129 setTargetDAGCombine(ISD::ZERO_EXTEND); 1130 setTargetDAGCombine(ISD::ANY_EXTEND); 1131 1132 setTargetDAGCombine(ISD::TRUNCATE); 1133 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1134 1135 1136 if (Subtarget.useCRBits()) { 1137 setTargetDAGCombine(ISD::TRUNCATE); 1138 setTargetDAGCombine(ISD::SETCC); 1139 setTargetDAGCombine(ISD::SELECT_CC); 1140 } 1141 1142 // Use reciprocal estimates. 1143 if (TM.Options.UnsafeFPMath) { 1144 setTargetDAGCombine(ISD::FDIV); 1145 setTargetDAGCombine(ISD::FSQRT); 1146 } 1147 1148 if (Subtarget.hasP9Altivec()) { 1149 setTargetDAGCombine(ISD::ABS); 1150 setTargetDAGCombine(ISD::VSELECT); 1151 } 1152 1153 // Darwin long double math library functions have $LDBL128 appended. 1154 if (Subtarget.isDarwin()) { 1155 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1156 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1157 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1158 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1159 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1160 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1161 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1162 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1163 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1164 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1165 } 1166 1167 if (EnableQuadPrecision) { 1168 setLibcallName(RTLIB::LOG_F128, "logf128"); 1169 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1170 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1171 setLibcallName(RTLIB::EXP_F128, "expf128"); 1172 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1173 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1174 setLibcallName(RTLIB::COS_F128, "cosf128"); 1175 setLibcallName(RTLIB::POW_F128, "powf128"); 1176 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1177 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1178 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1179 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1180 } 1181 1182 // With 32 condition bits, we don't need to sink (and duplicate) compares 1183 // aggressively in CodeGenPrep. 1184 if (Subtarget.useCRBits()) { 1185 setHasMultipleConditionRegisters(); 1186 setJumpIsExpensive(); 1187 } 1188 1189 setMinFunctionAlignment(Align(4)); 1190 if (Subtarget.isDarwin()) 1191 setPrefFunctionAlignment(Align(16)); 1192 1193 switch (Subtarget.getDarwinDirective()) { 1194 default: break; 1195 case PPC::DIR_970: 1196 case PPC::DIR_A2: 1197 case PPC::DIR_E500: 1198 case PPC::DIR_E500mc: 1199 case PPC::DIR_E5500: 1200 case PPC::DIR_PWR4: 1201 case PPC::DIR_PWR5: 1202 case PPC::DIR_PWR5X: 1203 case PPC::DIR_PWR6: 1204 case PPC::DIR_PWR6X: 1205 case PPC::DIR_PWR7: 1206 case PPC::DIR_PWR8: 1207 case PPC::DIR_PWR9: 1208 setPrefLoopAlignment(Align(16)); 1209 setPrefFunctionAlignment(Align(16)); 1210 break; 1211 } 1212 1213 if (Subtarget.enableMachineScheduler()) 1214 setSchedulingPreference(Sched::Source); 1215 else 1216 setSchedulingPreference(Sched::Hybrid); 1217 1218 computeRegisterProperties(STI.getRegisterInfo()); 1219 1220 // The Freescale cores do better with aggressive inlining of memcpy and 1221 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1222 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1223 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1224 MaxStoresPerMemset = 32; 1225 MaxStoresPerMemsetOptSize = 16; 1226 MaxStoresPerMemcpy = 32; 1227 MaxStoresPerMemcpyOptSize = 8; 1228 MaxStoresPerMemmove = 32; 1229 MaxStoresPerMemmoveOptSize = 8; 1230 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1231 // The A2 also benefits from (very) aggressive inlining of memcpy and 1232 // friends. The overhead of a the function call, even when warm, can be 1233 // over one hundred cycles. 1234 MaxStoresPerMemset = 128; 1235 MaxStoresPerMemcpy = 128; 1236 MaxStoresPerMemmove = 128; 1237 MaxLoadsPerMemcmp = 128; 1238 } else { 1239 MaxLoadsPerMemcmp = 8; 1240 MaxLoadsPerMemcmpOptSize = 4; 1241 } 1242 } 1243 1244 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1245 /// the desired ByVal argument alignment. 1246 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1247 unsigned MaxMaxAlign) { 1248 if (MaxAlign == MaxMaxAlign) 1249 return; 1250 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1251 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1252 MaxAlign = 32; 1253 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1254 MaxAlign = 16; 1255 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1256 unsigned EltAlign = 0; 1257 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1258 if (EltAlign > MaxAlign) 1259 MaxAlign = EltAlign; 1260 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1261 for (auto *EltTy : STy->elements()) { 1262 unsigned EltAlign = 0; 1263 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1264 if (EltAlign > MaxAlign) 1265 MaxAlign = EltAlign; 1266 if (MaxAlign == MaxMaxAlign) 1267 break; 1268 } 1269 } 1270 } 1271 1272 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1273 /// function arguments in the caller parameter area. 1274 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1275 const DataLayout &DL) const { 1276 // Darwin passes everything on 4 byte boundary. 1277 if (Subtarget.isDarwin()) 1278 return 4; 1279 1280 // 16byte and wider vectors are passed on 16byte boundary. 1281 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1282 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1283 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1284 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1285 return Align; 1286 } 1287 1288 bool PPCTargetLowering::useSoftFloat() const { 1289 return Subtarget.useSoftFloat(); 1290 } 1291 1292 bool PPCTargetLowering::hasSPE() const { 1293 return Subtarget.hasSPE(); 1294 } 1295 1296 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1297 return VT.isScalarInteger(); 1298 } 1299 1300 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1301 switch ((PPCISD::NodeType)Opcode) { 1302 case PPCISD::FIRST_NUMBER: break; 1303 case PPCISD::FSEL: return "PPCISD::FSEL"; 1304 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1305 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1306 case PPCISD::FCFID: return "PPCISD::FCFID"; 1307 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1308 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1309 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1310 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1311 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1312 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1313 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1314 case PPCISD::FP_TO_UINT_IN_VSR: 1315 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1316 case PPCISD::FP_TO_SINT_IN_VSR: 1317 return "PPCISD::FP_TO_SINT_IN_VSR"; 1318 case PPCISD::FRE: return "PPCISD::FRE"; 1319 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1320 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1321 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1322 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1323 case PPCISD::VPERM: return "PPCISD::VPERM"; 1324 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1325 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1326 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1327 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1328 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1329 case PPCISD::CMPB: return "PPCISD::CMPB"; 1330 case PPCISD::Hi: return "PPCISD::Hi"; 1331 case PPCISD::Lo: return "PPCISD::Lo"; 1332 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1333 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1334 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1335 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1336 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1337 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1338 case PPCISD::SRL: return "PPCISD::SRL"; 1339 case PPCISD::SRA: return "PPCISD::SRA"; 1340 case PPCISD::SHL: return "PPCISD::SHL"; 1341 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1342 case PPCISD::CALL: return "PPCISD::CALL"; 1343 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1344 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1345 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1346 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1347 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1348 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1349 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1350 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1351 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1352 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1353 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1354 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1355 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1356 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1357 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1358 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1359 case PPCISD::VCMP: return "PPCISD::VCMP"; 1360 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1361 case PPCISD::LBRX: return "PPCISD::LBRX"; 1362 case PPCISD::STBRX: return "PPCISD::STBRX"; 1363 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1364 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1365 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1366 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1367 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1368 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1369 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1370 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1371 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1372 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1373 case PPCISD::ST_VSR_SCAL_INT: 1374 return "PPCISD::ST_VSR_SCAL_INT"; 1375 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1376 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1377 case PPCISD::BDZ: return "PPCISD::BDZ"; 1378 case PPCISD::MFFS: return "PPCISD::MFFS"; 1379 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1380 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1381 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1382 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1383 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1384 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1385 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1386 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1387 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1388 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1389 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1390 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1391 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1392 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1393 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1394 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1395 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1396 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1397 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1398 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1399 case PPCISD::SC: return "PPCISD::SC"; 1400 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1401 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1402 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1403 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1404 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1405 case PPCISD::VABSD: return "PPCISD::VABSD"; 1406 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1407 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1408 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1409 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1410 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1411 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1412 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1413 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1414 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1415 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1416 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1417 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1418 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1419 } 1420 return nullptr; 1421 } 1422 1423 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1424 EVT VT) const { 1425 if (!VT.isVector()) 1426 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1427 1428 if (Subtarget.hasQPX()) 1429 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1430 1431 return VT.changeVectorElementTypeToInteger(); 1432 } 1433 1434 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1435 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1436 return true; 1437 } 1438 1439 //===----------------------------------------------------------------------===// 1440 // Node matching predicates, for use by the tblgen matching code. 1441 //===----------------------------------------------------------------------===// 1442 1443 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1444 static bool isFloatingPointZero(SDValue Op) { 1445 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1446 return CFP->getValueAPF().isZero(); 1447 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1448 // Maybe this has already been legalized into the constant pool? 1449 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1450 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1451 return CFP->getValueAPF().isZero(); 1452 } 1453 return false; 1454 } 1455 1456 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1457 /// true if Op is undef or if it matches the specified value. 1458 static bool isConstantOrUndef(int Op, int Val) { 1459 return Op < 0 || Op == Val; 1460 } 1461 1462 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1463 /// VPKUHUM instruction. 1464 /// The ShuffleKind distinguishes between big-endian operations with 1465 /// two different inputs (0), either-endian operations with two identical 1466 /// inputs (1), and little-endian operations with two different inputs (2). 1467 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1468 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1469 SelectionDAG &DAG) { 1470 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1471 if (ShuffleKind == 0) { 1472 if (IsLE) 1473 return false; 1474 for (unsigned i = 0; i != 16; ++i) 1475 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1476 return false; 1477 } else if (ShuffleKind == 2) { 1478 if (!IsLE) 1479 return false; 1480 for (unsigned i = 0; i != 16; ++i) 1481 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1482 return false; 1483 } else if (ShuffleKind == 1) { 1484 unsigned j = IsLE ? 0 : 1; 1485 for (unsigned i = 0; i != 8; ++i) 1486 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1487 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1488 return false; 1489 } 1490 return true; 1491 } 1492 1493 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1494 /// VPKUWUM instruction. 1495 /// The ShuffleKind distinguishes between big-endian operations with 1496 /// two different inputs (0), either-endian operations with two identical 1497 /// inputs (1), and little-endian operations with two different inputs (2). 1498 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1499 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1500 SelectionDAG &DAG) { 1501 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1502 if (ShuffleKind == 0) { 1503 if (IsLE) 1504 return false; 1505 for (unsigned i = 0; i != 16; i += 2) 1506 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1507 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1508 return false; 1509 } else if (ShuffleKind == 2) { 1510 if (!IsLE) 1511 return false; 1512 for (unsigned i = 0; i != 16; i += 2) 1513 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1514 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1515 return false; 1516 } else if (ShuffleKind == 1) { 1517 unsigned j = IsLE ? 0 : 2; 1518 for (unsigned i = 0; i != 8; i += 2) 1519 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1520 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1521 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1522 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1523 return false; 1524 } 1525 return true; 1526 } 1527 1528 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1529 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1530 /// current subtarget. 1531 /// 1532 /// The ShuffleKind distinguishes between big-endian operations with 1533 /// two different inputs (0), either-endian operations with two identical 1534 /// inputs (1), and little-endian operations with two different inputs (2). 1535 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1536 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1537 SelectionDAG &DAG) { 1538 const PPCSubtarget& Subtarget = 1539 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1540 if (!Subtarget.hasP8Vector()) 1541 return false; 1542 1543 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1544 if (ShuffleKind == 0) { 1545 if (IsLE) 1546 return false; 1547 for (unsigned i = 0; i != 16; i += 4) 1548 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1549 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1550 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1551 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1552 return false; 1553 } else if (ShuffleKind == 2) { 1554 if (!IsLE) 1555 return false; 1556 for (unsigned i = 0; i != 16; i += 4) 1557 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1558 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1559 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1560 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1561 return false; 1562 } else if (ShuffleKind == 1) { 1563 unsigned j = IsLE ? 0 : 4; 1564 for (unsigned i = 0; i != 8; i += 4) 1565 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1566 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1567 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1568 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1569 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1570 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1571 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1572 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1573 return false; 1574 } 1575 return true; 1576 } 1577 1578 /// isVMerge - Common function, used to match vmrg* shuffles. 1579 /// 1580 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1581 unsigned LHSStart, unsigned RHSStart) { 1582 if (N->getValueType(0) != MVT::v16i8) 1583 return false; 1584 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1585 "Unsupported merge size!"); 1586 1587 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1588 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1589 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1590 LHSStart+j+i*UnitSize) || 1591 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1592 RHSStart+j+i*UnitSize)) 1593 return false; 1594 } 1595 return true; 1596 } 1597 1598 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1599 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1600 /// The ShuffleKind distinguishes between big-endian merges with two 1601 /// different inputs (0), either-endian merges with two identical inputs (1), 1602 /// and little-endian merges with two different inputs (2). For the latter, 1603 /// the input operands are swapped (see PPCInstrAltivec.td). 1604 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1605 unsigned ShuffleKind, SelectionDAG &DAG) { 1606 if (DAG.getDataLayout().isLittleEndian()) { 1607 if (ShuffleKind == 1) // unary 1608 return isVMerge(N, UnitSize, 0, 0); 1609 else if (ShuffleKind == 2) // swapped 1610 return isVMerge(N, UnitSize, 0, 16); 1611 else 1612 return false; 1613 } else { 1614 if (ShuffleKind == 1) // unary 1615 return isVMerge(N, UnitSize, 8, 8); 1616 else if (ShuffleKind == 0) // normal 1617 return isVMerge(N, UnitSize, 8, 24); 1618 else 1619 return false; 1620 } 1621 } 1622 1623 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1624 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1625 /// The ShuffleKind distinguishes between big-endian merges with two 1626 /// different inputs (0), either-endian merges with two identical inputs (1), 1627 /// and little-endian merges with two different inputs (2). For the latter, 1628 /// the input operands are swapped (see PPCInstrAltivec.td). 1629 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1630 unsigned ShuffleKind, SelectionDAG &DAG) { 1631 if (DAG.getDataLayout().isLittleEndian()) { 1632 if (ShuffleKind == 1) // unary 1633 return isVMerge(N, UnitSize, 8, 8); 1634 else if (ShuffleKind == 2) // swapped 1635 return isVMerge(N, UnitSize, 8, 24); 1636 else 1637 return false; 1638 } else { 1639 if (ShuffleKind == 1) // unary 1640 return isVMerge(N, UnitSize, 0, 0); 1641 else if (ShuffleKind == 0) // normal 1642 return isVMerge(N, UnitSize, 0, 16); 1643 else 1644 return false; 1645 } 1646 } 1647 1648 /** 1649 * Common function used to match vmrgew and vmrgow shuffles 1650 * 1651 * The indexOffset determines whether to look for even or odd words in 1652 * the shuffle mask. This is based on the of the endianness of the target 1653 * machine. 1654 * - Little Endian: 1655 * - Use offset of 0 to check for odd elements 1656 * - Use offset of 4 to check for even elements 1657 * - Big Endian: 1658 * - Use offset of 0 to check for even elements 1659 * - Use offset of 4 to check for odd elements 1660 * A detailed description of the vector element ordering for little endian and 1661 * big endian can be found at 1662 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1663 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1664 * compiler differences mean to you 1665 * 1666 * The mask to the shuffle vector instruction specifies the indices of the 1667 * elements from the two input vectors to place in the result. The elements are 1668 * numbered in array-access order, starting with the first vector. These vectors 1669 * are always of type v16i8, thus each vector will contain 16 elements of size 1670 * 8. More info on the shuffle vector can be found in the 1671 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1672 * Language Reference. 1673 * 1674 * The RHSStartValue indicates whether the same input vectors are used (unary) 1675 * or two different input vectors are used, based on the following: 1676 * - If the instruction uses the same vector for both inputs, the range of the 1677 * indices will be 0 to 15. In this case, the RHSStart value passed should 1678 * be 0. 1679 * - If the instruction has two different vectors then the range of the 1680 * indices will be 0 to 31. In this case, the RHSStart value passed should 1681 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1682 * to 31 specify elements in the second vector). 1683 * 1684 * \param[in] N The shuffle vector SD Node to analyze 1685 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1686 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1687 * vector to the shuffle_vector instruction 1688 * \return true iff this shuffle vector represents an even or odd word merge 1689 */ 1690 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1691 unsigned RHSStartValue) { 1692 if (N->getValueType(0) != MVT::v16i8) 1693 return false; 1694 1695 for (unsigned i = 0; i < 2; ++i) 1696 for (unsigned j = 0; j < 4; ++j) 1697 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1698 i*RHSStartValue+j+IndexOffset) || 1699 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1700 i*RHSStartValue+j+IndexOffset+8)) 1701 return false; 1702 return true; 1703 } 1704 1705 /** 1706 * Determine if the specified shuffle mask is suitable for the vmrgew or 1707 * vmrgow instructions. 1708 * 1709 * \param[in] N The shuffle vector SD Node to analyze 1710 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1711 * \param[in] ShuffleKind Identify the type of merge: 1712 * - 0 = big-endian merge with two different inputs; 1713 * - 1 = either-endian merge with two identical inputs; 1714 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1715 * little-endian merges). 1716 * \param[in] DAG The current SelectionDAG 1717 * \return true iff this shuffle mask 1718 */ 1719 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1720 unsigned ShuffleKind, SelectionDAG &DAG) { 1721 if (DAG.getDataLayout().isLittleEndian()) { 1722 unsigned indexOffset = CheckEven ? 4 : 0; 1723 if (ShuffleKind == 1) // Unary 1724 return isVMerge(N, indexOffset, 0); 1725 else if (ShuffleKind == 2) // swapped 1726 return isVMerge(N, indexOffset, 16); 1727 else 1728 return false; 1729 } 1730 else { 1731 unsigned indexOffset = CheckEven ? 0 : 4; 1732 if (ShuffleKind == 1) // Unary 1733 return isVMerge(N, indexOffset, 0); 1734 else if (ShuffleKind == 0) // Normal 1735 return isVMerge(N, indexOffset, 16); 1736 else 1737 return false; 1738 } 1739 return false; 1740 } 1741 1742 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1743 /// amount, otherwise return -1. 1744 /// The ShuffleKind distinguishes between big-endian operations with two 1745 /// different inputs (0), either-endian operations with two identical inputs 1746 /// (1), and little-endian operations with two different inputs (2). For the 1747 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1748 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1749 SelectionDAG &DAG) { 1750 if (N->getValueType(0) != MVT::v16i8) 1751 return -1; 1752 1753 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1754 1755 // Find the first non-undef value in the shuffle mask. 1756 unsigned i; 1757 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1758 /*search*/; 1759 1760 if (i == 16) return -1; // all undef. 1761 1762 // Otherwise, check to see if the rest of the elements are consecutively 1763 // numbered from this value. 1764 unsigned ShiftAmt = SVOp->getMaskElt(i); 1765 if (ShiftAmt < i) return -1; 1766 1767 ShiftAmt -= i; 1768 bool isLE = DAG.getDataLayout().isLittleEndian(); 1769 1770 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1771 // Check the rest of the elements to see if they are consecutive. 1772 for (++i; i != 16; ++i) 1773 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1774 return -1; 1775 } else if (ShuffleKind == 1) { 1776 // Check the rest of the elements to see if they are consecutive. 1777 for (++i; i != 16; ++i) 1778 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1779 return -1; 1780 } else 1781 return -1; 1782 1783 if (isLE) 1784 ShiftAmt = 16 - ShiftAmt; 1785 1786 return ShiftAmt; 1787 } 1788 1789 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1790 /// specifies a splat of a single element that is suitable for input to 1791 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1792 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1793 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1794 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1795 1796 // The consecutive indices need to specify an element, not part of two 1797 // different elements. So abandon ship early if this isn't the case. 1798 if (N->getMaskElt(0) % EltSize != 0) 1799 return false; 1800 1801 // This is a splat operation if each element of the permute is the same, and 1802 // if the value doesn't reference the second vector. 1803 unsigned ElementBase = N->getMaskElt(0); 1804 1805 // FIXME: Handle UNDEF elements too! 1806 if (ElementBase >= 16) 1807 return false; 1808 1809 // Check that the indices are consecutive, in the case of a multi-byte element 1810 // splatted with a v16i8 mask. 1811 for (unsigned i = 1; i != EltSize; ++i) 1812 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1813 return false; 1814 1815 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1816 if (N->getMaskElt(i) < 0) continue; 1817 for (unsigned j = 0; j != EltSize; ++j) 1818 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1819 return false; 1820 } 1821 return true; 1822 } 1823 1824 /// Check that the mask is shuffling N byte elements. Within each N byte 1825 /// element of the mask, the indices could be either in increasing or 1826 /// decreasing order as long as they are consecutive. 1827 /// \param[in] N the shuffle vector SD Node to analyze 1828 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1829 /// Word/DoubleWord/QuadWord). 1830 /// \param[in] StepLen the delta indices number among the N byte element, if 1831 /// the mask is in increasing/decreasing order then it is 1/-1. 1832 /// \return true iff the mask is shuffling N byte elements. 1833 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1834 int StepLen) { 1835 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1836 "Unexpected element width."); 1837 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1838 1839 unsigned NumOfElem = 16 / Width; 1840 unsigned MaskVal[16]; // Width is never greater than 16 1841 for (unsigned i = 0; i < NumOfElem; ++i) { 1842 MaskVal[0] = N->getMaskElt(i * Width); 1843 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1844 return false; 1845 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1846 return false; 1847 } 1848 1849 for (unsigned int j = 1; j < Width; ++j) { 1850 MaskVal[j] = N->getMaskElt(i * Width + j); 1851 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1852 return false; 1853 } 1854 } 1855 } 1856 1857 return true; 1858 } 1859 1860 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1861 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1862 if (!isNByteElemShuffleMask(N, 4, 1)) 1863 return false; 1864 1865 // Now we look at mask elements 0,4,8,12 1866 unsigned M0 = N->getMaskElt(0) / 4; 1867 unsigned M1 = N->getMaskElt(4) / 4; 1868 unsigned M2 = N->getMaskElt(8) / 4; 1869 unsigned M3 = N->getMaskElt(12) / 4; 1870 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1871 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1872 1873 // Below, let H and L be arbitrary elements of the shuffle mask 1874 // where H is in the range [4,7] and L is in the range [0,3]. 1875 // H, 1, 2, 3 or L, 5, 6, 7 1876 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1877 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1878 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1879 InsertAtByte = IsLE ? 12 : 0; 1880 Swap = M0 < 4; 1881 return true; 1882 } 1883 // 0, H, 2, 3 or 4, L, 6, 7 1884 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1885 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1886 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1887 InsertAtByte = IsLE ? 8 : 4; 1888 Swap = M1 < 4; 1889 return true; 1890 } 1891 // 0, 1, H, 3 or 4, 5, L, 7 1892 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1893 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1894 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1895 InsertAtByte = IsLE ? 4 : 8; 1896 Swap = M2 < 4; 1897 return true; 1898 } 1899 // 0, 1, 2, H or 4, 5, 6, L 1900 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1901 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1902 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1903 InsertAtByte = IsLE ? 0 : 12; 1904 Swap = M3 < 4; 1905 return true; 1906 } 1907 1908 // If both vector operands for the shuffle are the same vector, the mask will 1909 // contain only elements from the first one and the second one will be undef. 1910 if (N->getOperand(1).isUndef()) { 1911 ShiftElts = 0; 1912 Swap = true; 1913 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1914 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1915 InsertAtByte = IsLE ? 12 : 0; 1916 return true; 1917 } 1918 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1919 InsertAtByte = IsLE ? 8 : 4; 1920 return true; 1921 } 1922 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1923 InsertAtByte = IsLE ? 4 : 8; 1924 return true; 1925 } 1926 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1927 InsertAtByte = IsLE ? 0 : 12; 1928 return true; 1929 } 1930 } 1931 1932 return false; 1933 } 1934 1935 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1936 bool &Swap, bool IsLE) { 1937 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1938 // Ensure each byte index of the word is consecutive. 1939 if (!isNByteElemShuffleMask(N, 4, 1)) 1940 return false; 1941 1942 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1943 unsigned M0 = N->getMaskElt(0) / 4; 1944 unsigned M1 = N->getMaskElt(4) / 4; 1945 unsigned M2 = N->getMaskElt(8) / 4; 1946 unsigned M3 = N->getMaskElt(12) / 4; 1947 1948 // If both vector operands for the shuffle are the same vector, the mask will 1949 // contain only elements from the first one and the second one will be undef. 1950 if (N->getOperand(1).isUndef()) { 1951 assert(M0 < 4 && "Indexing into an undef vector?"); 1952 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1953 return false; 1954 1955 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1956 Swap = false; 1957 return true; 1958 } 1959 1960 // Ensure each word index of the ShuffleVector Mask is consecutive. 1961 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1962 return false; 1963 1964 if (IsLE) { 1965 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1966 // Input vectors don't need to be swapped if the leading element 1967 // of the result is one of the 3 left elements of the second vector 1968 // (or if there is no shift to be done at all). 1969 Swap = false; 1970 ShiftElts = (8 - M0) % 8; 1971 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1972 // Input vectors need to be swapped if the leading element 1973 // of the result is one of the 3 left elements of the first vector 1974 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1975 Swap = true; 1976 ShiftElts = (4 - M0) % 4; 1977 } 1978 1979 return true; 1980 } else { // BE 1981 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1982 // Input vectors don't need to be swapped if the leading element 1983 // of the result is one of the 4 elements of the first vector. 1984 Swap = false; 1985 ShiftElts = M0; 1986 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1987 // Input vectors need to be swapped if the leading element 1988 // of the result is one of the 4 elements of the right vector. 1989 Swap = true; 1990 ShiftElts = M0 - 4; 1991 } 1992 1993 return true; 1994 } 1995 } 1996 1997 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1998 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1999 2000 if (!isNByteElemShuffleMask(N, Width, -1)) 2001 return false; 2002 2003 for (int i = 0; i < 16; i += Width) 2004 if (N->getMaskElt(i) != i + Width - 1) 2005 return false; 2006 2007 return true; 2008 } 2009 2010 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2011 return isXXBRShuffleMaskHelper(N, 2); 2012 } 2013 2014 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2015 return isXXBRShuffleMaskHelper(N, 4); 2016 } 2017 2018 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2019 return isXXBRShuffleMaskHelper(N, 8); 2020 } 2021 2022 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2023 return isXXBRShuffleMaskHelper(N, 16); 2024 } 2025 2026 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2027 /// if the inputs to the instruction should be swapped and set \p DM to the 2028 /// value for the immediate. 2029 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2030 /// AND element 0 of the result comes from the first input (LE) or second input 2031 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2032 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2033 /// mask. 2034 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2035 bool &Swap, bool IsLE) { 2036 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2037 2038 // Ensure each byte index of the double word is consecutive. 2039 if (!isNByteElemShuffleMask(N, 8, 1)) 2040 return false; 2041 2042 unsigned M0 = N->getMaskElt(0) / 8; 2043 unsigned M1 = N->getMaskElt(8) / 8; 2044 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2045 2046 // If both vector operands for the shuffle are the same vector, the mask will 2047 // contain only elements from the first one and the second one will be undef. 2048 if (N->getOperand(1).isUndef()) { 2049 if ((M0 | M1) < 2) { 2050 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2051 Swap = false; 2052 return true; 2053 } else 2054 return false; 2055 } 2056 2057 if (IsLE) { 2058 if (M0 > 1 && M1 < 2) { 2059 Swap = false; 2060 } else if (M0 < 2 && M1 > 1) { 2061 M0 = (M0 + 2) % 4; 2062 M1 = (M1 + 2) % 4; 2063 Swap = true; 2064 } else 2065 return false; 2066 2067 // Note: if control flow comes here that means Swap is already set above 2068 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2069 return true; 2070 } else { // BE 2071 if (M0 < 2 && M1 > 1) { 2072 Swap = false; 2073 } else if (M0 > 1 && M1 < 2) { 2074 M0 = (M0 + 2) % 4; 2075 M1 = (M1 + 2) % 4; 2076 Swap = true; 2077 } else 2078 return false; 2079 2080 // Note: if control flow comes here that means Swap is already set above 2081 DM = (M0 << 1) + (M1 & 1); 2082 return true; 2083 } 2084 } 2085 2086 2087 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2088 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2089 /// elements are counted from the left of the vector register). 2090 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2091 SelectionDAG &DAG) { 2092 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2093 assert(isSplatShuffleMask(SVOp, EltSize)); 2094 if (DAG.getDataLayout().isLittleEndian()) 2095 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2096 else 2097 return SVOp->getMaskElt(0) / EltSize; 2098 } 2099 2100 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2101 /// by using a vspltis[bhw] instruction of the specified element size, return 2102 /// the constant being splatted. The ByteSize field indicates the number of 2103 /// bytes of each element [124] -> [bhw]. 2104 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2105 SDValue OpVal(nullptr, 0); 2106 2107 // If ByteSize of the splat is bigger than the element size of the 2108 // build_vector, then we have a case where we are checking for a splat where 2109 // multiple elements of the buildvector are folded together into a single 2110 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2111 unsigned EltSize = 16/N->getNumOperands(); 2112 if (EltSize < ByteSize) { 2113 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2114 SDValue UniquedVals[4]; 2115 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2116 2117 // See if all of the elements in the buildvector agree across. 2118 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2119 if (N->getOperand(i).isUndef()) continue; 2120 // If the element isn't a constant, bail fully out. 2121 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2122 2123 if (!UniquedVals[i&(Multiple-1)].getNode()) 2124 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2125 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2126 return SDValue(); // no match. 2127 } 2128 2129 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2130 // either constant or undef values that are identical for each chunk. See 2131 // if these chunks can form into a larger vspltis*. 2132 2133 // Check to see if all of the leading entries are either 0 or -1. If 2134 // neither, then this won't fit into the immediate field. 2135 bool LeadingZero = true; 2136 bool LeadingOnes = true; 2137 for (unsigned i = 0; i != Multiple-1; ++i) { 2138 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2139 2140 LeadingZero &= isNullConstant(UniquedVals[i]); 2141 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2142 } 2143 // Finally, check the least significant entry. 2144 if (LeadingZero) { 2145 if (!UniquedVals[Multiple-1].getNode()) 2146 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2147 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2148 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2149 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2150 } 2151 if (LeadingOnes) { 2152 if (!UniquedVals[Multiple-1].getNode()) 2153 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2154 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2155 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2156 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2157 } 2158 2159 return SDValue(); 2160 } 2161 2162 // Check to see if this buildvec has a single non-undef value in its elements. 2163 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2164 if (N->getOperand(i).isUndef()) continue; 2165 if (!OpVal.getNode()) 2166 OpVal = N->getOperand(i); 2167 else if (OpVal != N->getOperand(i)) 2168 return SDValue(); 2169 } 2170 2171 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2172 2173 unsigned ValSizeInBytes = EltSize; 2174 uint64_t Value = 0; 2175 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2176 Value = CN->getZExtValue(); 2177 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2178 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2179 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2180 } 2181 2182 // If the splat value is larger than the element value, then we can never do 2183 // this splat. The only case that we could fit the replicated bits into our 2184 // immediate field for would be zero, and we prefer to use vxor for it. 2185 if (ValSizeInBytes < ByteSize) return SDValue(); 2186 2187 // If the element value is larger than the splat value, check if it consists 2188 // of a repeated bit pattern of size ByteSize. 2189 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2190 return SDValue(); 2191 2192 // Properly sign extend the value. 2193 int MaskVal = SignExtend32(Value, ByteSize * 8); 2194 2195 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2196 if (MaskVal == 0) return SDValue(); 2197 2198 // Finally, if this value fits in a 5 bit sext field, return it 2199 if (SignExtend32<5>(MaskVal) == MaskVal) 2200 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2201 return SDValue(); 2202 } 2203 2204 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2205 /// amount, otherwise return -1. 2206 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2207 EVT VT = N->getValueType(0); 2208 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2209 return -1; 2210 2211 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2212 2213 // Find the first non-undef value in the shuffle mask. 2214 unsigned i; 2215 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2216 /*search*/; 2217 2218 if (i == 4) return -1; // all undef. 2219 2220 // Otherwise, check to see if the rest of the elements are consecutively 2221 // numbered from this value. 2222 unsigned ShiftAmt = SVOp->getMaskElt(i); 2223 if (ShiftAmt < i) return -1; 2224 ShiftAmt -= i; 2225 2226 // Check the rest of the elements to see if they are consecutive. 2227 for (++i; i != 4; ++i) 2228 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2229 return -1; 2230 2231 return ShiftAmt; 2232 } 2233 2234 //===----------------------------------------------------------------------===// 2235 // Addressing Mode Selection 2236 //===----------------------------------------------------------------------===// 2237 2238 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2239 /// or 64-bit immediate, and if the value can be accurately represented as a 2240 /// sign extension from a 16-bit value. If so, this returns true and the 2241 /// immediate. 2242 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2243 if (!isa<ConstantSDNode>(N)) 2244 return false; 2245 2246 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2247 if (N->getValueType(0) == MVT::i32) 2248 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2249 else 2250 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2251 } 2252 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2253 return isIntS16Immediate(Op.getNode(), Imm); 2254 } 2255 2256 2257 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2258 /// be represented as an indexed [r+r] operation. 2259 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2260 SDValue &Index, 2261 SelectionDAG &DAG) const { 2262 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2263 UI != E; ++UI) { 2264 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2265 if (Memop->getMemoryVT() == MVT::f64) { 2266 Base = N.getOperand(0); 2267 Index = N.getOperand(1); 2268 return true; 2269 } 2270 } 2271 } 2272 return false; 2273 } 2274 2275 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2276 /// can be represented as an indexed [r+r] operation. Returns false if it 2277 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2278 /// non-zero and N can be represented by a base register plus a signed 16-bit 2279 /// displacement, make a more precise judgement by checking (displacement % \p 2280 /// EncodingAlignment). 2281 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2282 SDValue &Index, SelectionDAG &DAG, 2283 unsigned EncodingAlignment) const { 2284 int16_t imm = 0; 2285 if (N.getOpcode() == ISD::ADD) { 2286 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2287 // SPE load/store can only handle 8-bit offsets. 2288 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2289 return true; 2290 if (isIntS16Immediate(N.getOperand(1), imm) && 2291 (!EncodingAlignment || !(imm % EncodingAlignment))) 2292 return false; // r+i 2293 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2294 return false; // r+i 2295 2296 Base = N.getOperand(0); 2297 Index = N.getOperand(1); 2298 return true; 2299 } else if (N.getOpcode() == ISD::OR) { 2300 if (isIntS16Immediate(N.getOperand(1), imm) && 2301 (!EncodingAlignment || !(imm % EncodingAlignment))) 2302 return false; // r+i can fold it if we can. 2303 2304 // If this is an or of disjoint bitfields, we can codegen this as an add 2305 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2306 // disjoint. 2307 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2308 2309 if (LHSKnown.Zero.getBoolValue()) { 2310 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2311 // If all of the bits are known zero on the LHS or RHS, the add won't 2312 // carry. 2313 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2314 Base = N.getOperand(0); 2315 Index = N.getOperand(1); 2316 return true; 2317 } 2318 } 2319 } 2320 2321 return false; 2322 } 2323 2324 // If we happen to be doing an i64 load or store into a stack slot that has 2325 // less than a 4-byte alignment, then the frame-index elimination may need to 2326 // use an indexed load or store instruction (because the offset may not be a 2327 // multiple of 4). The extra register needed to hold the offset comes from the 2328 // register scavenger, and it is possible that the scavenger will need to use 2329 // an emergency spill slot. As a result, we need to make sure that a spill slot 2330 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2331 // stack slot. 2332 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2333 // FIXME: This does not handle the LWA case. 2334 if (VT != MVT::i64) 2335 return; 2336 2337 // NOTE: We'll exclude negative FIs here, which come from argument 2338 // lowering, because there are no known test cases triggering this problem 2339 // using packed structures (or similar). We can remove this exclusion if 2340 // we find such a test case. The reason why this is so test-case driven is 2341 // because this entire 'fixup' is only to prevent crashes (from the 2342 // register scavenger) on not-really-valid inputs. For example, if we have: 2343 // %a = alloca i1 2344 // %b = bitcast i1* %a to i64* 2345 // store i64* a, i64 b 2346 // then the store should really be marked as 'align 1', but is not. If it 2347 // were marked as 'align 1' then the indexed form would have been 2348 // instruction-selected initially, and the problem this 'fixup' is preventing 2349 // won't happen regardless. 2350 if (FrameIdx < 0) 2351 return; 2352 2353 MachineFunction &MF = DAG.getMachineFunction(); 2354 MachineFrameInfo &MFI = MF.getFrameInfo(); 2355 2356 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2357 if (Align >= 4) 2358 return; 2359 2360 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2361 FuncInfo->setHasNonRISpills(); 2362 } 2363 2364 /// Returns true if the address N can be represented by a base register plus 2365 /// a signed 16-bit displacement [r+imm], and if it is not better 2366 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2367 /// displacements that are multiples of that value. 2368 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2369 SDValue &Base, 2370 SelectionDAG &DAG, 2371 unsigned EncodingAlignment) const { 2372 // FIXME dl should come from parent load or store, not from address 2373 SDLoc dl(N); 2374 // If this can be more profitably realized as r+r, fail. 2375 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2376 return false; 2377 2378 if (N.getOpcode() == ISD::ADD) { 2379 int16_t imm = 0; 2380 if (isIntS16Immediate(N.getOperand(1), imm) && 2381 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2382 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2383 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2384 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2385 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2386 } else { 2387 Base = N.getOperand(0); 2388 } 2389 return true; // [r+i] 2390 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2391 // Match LOAD (ADD (X, Lo(G))). 2392 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2393 && "Cannot handle constant offsets yet!"); 2394 Disp = N.getOperand(1).getOperand(0); // The global address. 2395 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2396 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2397 Disp.getOpcode() == ISD::TargetConstantPool || 2398 Disp.getOpcode() == ISD::TargetJumpTable); 2399 Base = N.getOperand(0); 2400 return true; // [&g+r] 2401 } 2402 } else if (N.getOpcode() == ISD::OR) { 2403 int16_t imm = 0; 2404 if (isIntS16Immediate(N.getOperand(1), imm) && 2405 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2406 // If this is an or of disjoint bitfields, we can codegen this as an add 2407 // (for better address arithmetic) if the LHS and RHS of the OR are 2408 // provably disjoint. 2409 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2410 2411 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2412 // If all of the bits are known zero on the LHS or RHS, the add won't 2413 // carry. 2414 if (FrameIndexSDNode *FI = 2415 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2416 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2417 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2418 } else { 2419 Base = N.getOperand(0); 2420 } 2421 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2422 return true; 2423 } 2424 } 2425 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2426 // Loading from a constant address. 2427 2428 // If this address fits entirely in a 16-bit sext immediate field, codegen 2429 // this as "d, 0" 2430 int16_t Imm; 2431 if (isIntS16Immediate(CN, Imm) && 2432 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2433 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2434 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2435 CN->getValueType(0)); 2436 return true; 2437 } 2438 2439 // Handle 32-bit sext immediates with LIS + addr mode. 2440 if ((CN->getValueType(0) == MVT::i32 || 2441 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2442 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2443 int Addr = (int)CN->getZExtValue(); 2444 2445 // Otherwise, break this down into an LIS + disp. 2446 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2447 2448 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2449 MVT::i32); 2450 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2451 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2452 return true; 2453 } 2454 } 2455 2456 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2457 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2458 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2459 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2460 } else 2461 Base = N; 2462 return true; // [r+0] 2463 } 2464 2465 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2466 /// represented as an indexed [r+r] operation. 2467 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2468 SDValue &Index, 2469 SelectionDAG &DAG) const { 2470 // Check to see if we can easily represent this as an [r+r] address. This 2471 // will fail if it thinks that the address is more profitably represented as 2472 // reg+imm, e.g. where imm = 0. 2473 if (SelectAddressRegReg(N, Base, Index, DAG)) 2474 return true; 2475 2476 // If the address is the result of an add, we will utilize the fact that the 2477 // address calculation includes an implicit add. However, we can reduce 2478 // register pressure if we do not materialize a constant just for use as the 2479 // index register. We only get rid of the add if it is not an add of a 2480 // value and a 16-bit signed constant and both have a single use. 2481 int16_t imm = 0; 2482 if (N.getOpcode() == ISD::ADD && 2483 (!isIntS16Immediate(N.getOperand(1), imm) || 2484 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2485 Base = N.getOperand(0); 2486 Index = N.getOperand(1); 2487 return true; 2488 } 2489 2490 // Otherwise, do it the hard way, using R0 as the base register. 2491 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2492 N.getValueType()); 2493 Index = N; 2494 return true; 2495 } 2496 2497 /// Returns true if we should use a direct load into vector instruction 2498 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2499 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2500 2501 // If there are any other uses other than scalar to vector, then we should 2502 // keep it as a scalar load -> direct move pattern to prevent multiple 2503 // loads. 2504 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2505 if (!LD) 2506 return false; 2507 2508 EVT MemVT = LD->getMemoryVT(); 2509 if (!MemVT.isSimple()) 2510 return false; 2511 switch(MemVT.getSimpleVT().SimpleTy) { 2512 case MVT::i64: 2513 break; 2514 case MVT::i32: 2515 if (!ST.hasP8Vector()) 2516 return false; 2517 break; 2518 case MVT::i16: 2519 case MVT::i8: 2520 if (!ST.hasP9Vector()) 2521 return false; 2522 break; 2523 default: 2524 return false; 2525 } 2526 2527 SDValue LoadedVal(N, 0); 2528 if (!LoadedVal.hasOneUse()) 2529 return false; 2530 2531 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2532 UI != UE; ++UI) 2533 if (UI.getUse().get().getResNo() == 0 && 2534 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2535 return false; 2536 2537 return true; 2538 } 2539 2540 /// getPreIndexedAddressParts - returns true by value, base pointer and 2541 /// offset pointer and addressing mode by reference if the node's address 2542 /// can be legally represented as pre-indexed load / store address. 2543 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2544 SDValue &Offset, 2545 ISD::MemIndexedMode &AM, 2546 SelectionDAG &DAG) const { 2547 if (DisablePPCPreinc) return false; 2548 2549 bool isLoad = true; 2550 SDValue Ptr; 2551 EVT VT; 2552 unsigned Alignment; 2553 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2554 Ptr = LD->getBasePtr(); 2555 VT = LD->getMemoryVT(); 2556 Alignment = LD->getAlignment(); 2557 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2558 Ptr = ST->getBasePtr(); 2559 VT = ST->getMemoryVT(); 2560 Alignment = ST->getAlignment(); 2561 isLoad = false; 2562 } else 2563 return false; 2564 2565 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2566 // instructions because we can fold these into a more efficient instruction 2567 // instead, (such as LXSD). 2568 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2569 return false; 2570 } 2571 2572 // PowerPC doesn't have preinc load/store instructions for vectors (except 2573 // for QPX, which does have preinc r+r forms). 2574 if (VT.isVector()) { 2575 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2576 return false; 2577 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2578 AM = ISD::PRE_INC; 2579 return true; 2580 } 2581 } 2582 2583 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2584 // Common code will reject creating a pre-inc form if the base pointer 2585 // is a frame index, or if N is a store and the base pointer is either 2586 // the same as or a predecessor of the value being stored. Check for 2587 // those situations here, and try with swapped Base/Offset instead. 2588 bool Swap = false; 2589 2590 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2591 Swap = true; 2592 else if (!isLoad) { 2593 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2594 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2595 Swap = true; 2596 } 2597 2598 if (Swap) 2599 std::swap(Base, Offset); 2600 2601 AM = ISD::PRE_INC; 2602 return true; 2603 } 2604 2605 // LDU/STU can only handle immediates that are a multiple of 4. 2606 if (VT != MVT::i64) { 2607 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2608 return false; 2609 } else { 2610 // LDU/STU need an address with at least 4-byte alignment. 2611 if (Alignment < 4) 2612 return false; 2613 2614 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2615 return false; 2616 } 2617 2618 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2619 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2620 // sext i32 to i64 when addr mode is r+i. 2621 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2622 LD->getExtensionType() == ISD::SEXTLOAD && 2623 isa<ConstantSDNode>(Offset)) 2624 return false; 2625 } 2626 2627 AM = ISD::PRE_INC; 2628 return true; 2629 } 2630 2631 //===----------------------------------------------------------------------===// 2632 // LowerOperation implementation 2633 //===----------------------------------------------------------------------===// 2634 2635 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2636 /// and LoOpFlags to the target MO flags. 2637 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2638 unsigned &HiOpFlags, unsigned &LoOpFlags, 2639 const GlobalValue *GV = nullptr) { 2640 HiOpFlags = PPCII::MO_HA; 2641 LoOpFlags = PPCII::MO_LO; 2642 2643 // Don't use the pic base if not in PIC relocation model. 2644 if (IsPIC) { 2645 HiOpFlags |= PPCII::MO_PIC_FLAG; 2646 LoOpFlags |= PPCII::MO_PIC_FLAG; 2647 } 2648 2649 // If this is a reference to a global value that requires a non-lazy-ptr, make 2650 // sure that instruction lowering adds it. 2651 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2652 HiOpFlags |= PPCII::MO_NLP_FLAG; 2653 LoOpFlags |= PPCII::MO_NLP_FLAG; 2654 2655 if (GV->hasHiddenVisibility()) { 2656 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2657 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2658 } 2659 } 2660 } 2661 2662 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2663 SelectionDAG &DAG) { 2664 SDLoc DL(HiPart); 2665 EVT PtrVT = HiPart.getValueType(); 2666 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2667 2668 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2669 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2670 2671 // With PIC, the first instruction is actually "GR+hi(&G)". 2672 if (isPIC) 2673 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2674 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2675 2676 // Generate non-pic code that has direct accesses to the constant pool. 2677 // The address of the global is just (hi(&g)+lo(&g)). 2678 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2679 } 2680 2681 static void setUsesTOCBasePtr(MachineFunction &MF) { 2682 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2683 FuncInfo->setUsesTOCBasePtr(); 2684 } 2685 2686 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2687 setUsesTOCBasePtr(DAG.getMachineFunction()); 2688 } 2689 2690 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2691 SDValue GA) const { 2692 const bool Is64Bit = Subtarget.isPPC64(); 2693 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2694 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2695 : Subtarget.isAIXABI() 2696 ? DAG.getRegister(PPC::R2, VT) 2697 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2698 SDValue Ops[] = { GA, Reg }; 2699 return DAG.getMemIntrinsicNode( 2700 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2701 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2702 MachineMemOperand::MOLoad); 2703 } 2704 2705 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2706 SelectionDAG &DAG) const { 2707 EVT PtrVT = Op.getValueType(); 2708 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2709 const Constant *C = CP->getConstVal(); 2710 2711 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2712 // The actual address of the GlobalValue is stored in the TOC. 2713 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2714 setUsesTOCBasePtr(DAG); 2715 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2716 return getTOCEntry(DAG, SDLoc(CP), GA); 2717 } 2718 2719 unsigned MOHiFlag, MOLoFlag; 2720 bool IsPIC = isPositionIndependent(); 2721 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2722 2723 if (IsPIC && Subtarget.isSVR4ABI()) { 2724 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2725 PPCII::MO_PIC_FLAG); 2726 return getTOCEntry(DAG, SDLoc(CP), GA); 2727 } 2728 2729 SDValue CPIHi = 2730 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2731 SDValue CPILo = 2732 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2733 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2734 } 2735 2736 // For 64-bit PowerPC, prefer the more compact relative encodings. 2737 // This trades 32 bits per jump table entry for one or two instructions 2738 // on the jump site. 2739 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2740 if (isJumpTableRelative()) 2741 return MachineJumpTableInfo::EK_LabelDifference32; 2742 2743 return TargetLowering::getJumpTableEncoding(); 2744 } 2745 2746 bool PPCTargetLowering::isJumpTableRelative() const { 2747 if (Subtarget.isPPC64()) 2748 return true; 2749 return TargetLowering::isJumpTableRelative(); 2750 } 2751 2752 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2753 SelectionDAG &DAG) const { 2754 if (!Subtarget.isPPC64()) 2755 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2756 2757 switch (getTargetMachine().getCodeModel()) { 2758 case CodeModel::Small: 2759 case CodeModel::Medium: 2760 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2761 default: 2762 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2763 getPointerTy(DAG.getDataLayout())); 2764 } 2765 } 2766 2767 const MCExpr * 2768 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2769 unsigned JTI, 2770 MCContext &Ctx) const { 2771 if (!Subtarget.isPPC64()) 2772 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2773 2774 switch (getTargetMachine().getCodeModel()) { 2775 case CodeModel::Small: 2776 case CodeModel::Medium: 2777 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2778 default: 2779 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2780 } 2781 } 2782 2783 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2784 EVT PtrVT = Op.getValueType(); 2785 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2786 2787 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2788 // The actual address of the GlobalValue is stored in the TOC. 2789 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2790 setUsesTOCBasePtr(DAG); 2791 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2792 return getTOCEntry(DAG, SDLoc(JT), GA); 2793 } 2794 2795 unsigned MOHiFlag, MOLoFlag; 2796 bool IsPIC = isPositionIndependent(); 2797 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2798 2799 if (IsPIC && Subtarget.isSVR4ABI()) { 2800 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2801 PPCII::MO_PIC_FLAG); 2802 return getTOCEntry(DAG, SDLoc(GA), GA); 2803 } 2804 2805 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2806 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2807 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2808 } 2809 2810 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2811 SelectionDAG &DAG) const { 2812 EVT PtrVT = Op.getValueType(); 2813 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2814 const BlockAddress *BA = BASDN->getBlockAddress(); 2815 2816 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2817 // The actual BlockAddress is stored in the TOC. 2818 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2819 setUsesTOCBasePtr(DAG); 2820 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2821 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2822 } 2823 2824 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2825 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2826 return getTOCEntry( 2827 DAG, SDLoc(BASDN), 2828 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2829 2830 unsigned MOHiFlag, MOLoFlag; 2831 bool IsPIC = isPositionIndependent(); 2832 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2833 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2834 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2835 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2836 } 2837 2838 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2839 SelectionDAG &DAG) const { 2840 // FIXME: TLS addresses currently use medium model code sequences, 2841 // which is the most useful form. Eventually support for small and 2842 // large models could be added if users need it, at the cost of 2843 // additional complexity. 2844 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2845 if (DAG.getTarget().useEmulatedTLS()) 2846 return LowerToTLSEmulatedModel(GA, DAG); 2847 2848 SDLoc dl(GA); 2849 const GlobalValue *GV = GA->getGlobal(); 2850 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2851 bool is64bit = Subtarget.isPPC64(); 2852 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2853 PICLevel::Level picLevel = M->getPICLevel(); 2854 2855 const TargetMachine &TM = getTargetMachine(); 2856 TLSModel::Model Model = TM.getTLSModel(GV); 2857 2858 if (Model == TLSModel::LocalExec) { 2859 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2860 PPCII::MO_TPREL_HA); 2861 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2862 PPCII::MO_TPREL_LO); 2863 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2864 : DAG.getRegister(PPC::R2, MVT::i32); 2865 2866 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2867 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2868 } 2869 2870 if (Model == TLSModel::InitialExec) { 2871 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2872 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2873 PPCII::MO_TLS); 2874 SDValue GOTPtr; 2875 if (is64bit) { 2876 setUsesTOCBasePtr(DAG); 2877 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2878 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2879 PtrVT, GOTReg, TGA); 2880 } else { 2881 if (!TM.isPositionIndependent()) 2882 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2883 else if (picLevel == PICLevel::SmallPIC) 2884 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2885 else 2886 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2887 } 2888 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2889 PtrVT, TGA, GOTPtr); 2890 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2891 } 2892 2893 if (Model == TLSModel::GeneralDynamic) { 2894 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2895 SDValue GOTPtr; 2896 if (is64bit) { 2897 setUsesTOCBasePtr(DAG); 2898 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2899 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2900 GOTReg, TGA); 2901 } else { 2902 if (picLevel == PICLevel::SmallPIC) 2903 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2904 else 2905 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2906 } 2907 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2908 GOTPtr, TGA, TGA); 2909 } 2910 2911 if (Model == TLSModel::LocalDynamic) { 2912 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2913 SDValue GOTPtr; 2914 if (is64bit) { 2915 setUsesTOCBasePtr(DAG); 2916 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2917 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2918 GOTReg, TGA); 2919 } else { 2920 if (picLevel == PICLevel::SmallPIC) 2921 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2922 else 2923 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2924 } 2925 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2926 PtrVT, GOTPtr, TGA, TGA); 2927 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2928 PtrVT, TLSAddr, TGA); 2929 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2930 } 2931 2932 llvm_unreachable("Unknown TLS model!"); 2933 } 2934 2935 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2936 SelectionDAG &DAG) const { 2937 EVT PtrVT = Op.getValueType(); 2938 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2939 SDLoc DL(GSDN); 2940 const GlobalValue *GV = GSDN->getGlobal(); 2941 2942 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 2943 // The actual address of the GlobalValue is stored in the TOC. 2944 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2945 setUsesTOCBasePtr(DAG); 2946 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2947 return getTOCEntry(DAG, DL, GA); 2948 } 2949 2950 unsigned MOHiFlag, MOLoFlag; 2951 bool IsPIC = isPositionIndependent(); 2952 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2953 2954 if (IsPIC && Subtarget.isSVR4ABI()) { 2955 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2956 GSDN->getOffset(), 2957 PPCII::MO_PIC_FLAG); 2958 return getTOCEntry(DAG, DL, GA); 2959 } 2960 2961 SDValue GAHi = 2962 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2963 SDValue GALo = 2964 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2965 2966 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2967 2968 // If the global reference is actually to a non-lazy-pointer, we have to do an 2969 // extra load to get the address of the global. 2970 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2971 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2972 return Ptr; 2973 } 2974 2975 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2976 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2977 SDLoc dl(Op); 2978 2979 if (Op.getValueType() == MVT::v2i64) { 2980 // When the operands themselves are v2i64 values, we need to do something 2981 // special because VSX has no underlying comparison operations for these. 2982 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2983 // Equality can be handled by casting to the legal type for Altivec 2984 // comparisons, everything else needs to be expanded. 2985 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2986 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2987 DAG.getSetCC(dl, MVT::v4i32, 2988 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2989 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2990 CC)); 2991 } 2992 2993 return SDValue(); 2994 } 2995 2996 // We handle most of these in the usual way. 2997 return Op; 2998 } 2999 3000 // If we're comparing for equality to zero, expose the fact that this is 3001 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3002 // fold the new nodes. 3003 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3004 return V; 3005 3006 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3007 // Leave comparisons against 0 and -1 alone for now, since they're usually 3008 // optimized. FIXME: revisit this when we can custom lower all setcc 3009 // optimizations. 3010 if (C->isAllOnesValue() || C->isNullValue()) 3011 return SDValue(); 3012 } 3013 3014 // If we have an integer seteq/setne, turn it into a compare against zero 3015 // by xor'ing the rhs with the lhs, which is faster than setting a 3016 // condition register, reading it back out, and masking the correct bit. The 3017 // normal approach here uses sub to do this instead of xor. Using xor exposes 3018 // the result to other bit-twiddling opportunities. 3019 EVT LHSVT = Op.getOperand(0).getValueType(); 3020 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3021 EVT VT = Op.getValueType(); 3022 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3023 Op.getOperand(1)); 3024 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3025 } 3026 return SDValue(); 3027 } 3028 3029 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3030 SDNode *Node = Op.getNode(); 3031 EVT VT = Node->getValueType(0); 3032 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3033 SDValue InChain = Node->getOperand(0); 3034 SDValue VAListPtr = Node->getOperand(1); 3035 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3036 SDLoc dl(Node); 3037 3038 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3039 3040 // gpr_index 3041 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3042 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3043 InChain = GprIndex.getValue(1); 3044 3045 if (VT == MVT::i64) { 3046 // Check if GprIndex is even 3047 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3048 DAG.getConstant(1, dl, MVT::i32)); 3049 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3050 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3051 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3052 DAG.getConstant(1, dl, MVT::i32)); 3053 // Align GprIndex to be even if it isn't 3054 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3055 GprIndex); 3056 } 3057 3058 // fpr index is 1 byte after gpr 3059 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3060 DAG.getConstant(1, dl, MVT::i32)); 3061 3062 // fpr 3063 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3064 FprPtr, MachinePointerInfo(SV), MVT::i8); 3065 InChain = FprIndex.getValue(1); 3066 3067 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3068 DAG.getConstant(8, dl, MVT::i32)); 3069 3070 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3071 DAG.getConstant(4, dl, MVT::i32)); 3072 3073 // areas 3074 SDValue OverflowArea = 3075 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3076 InChain = OverflowArea.getValue(1); 3077 3078 SDValue RegSaveArea = 3079 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3080 InChain = RegSaveArea.getValue(1); 3081 3082 // select overflow_area if index > 8 3083 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3084 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3085 3086 // adjustment constant gpr_index * 4/8 3087 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3088 VT.isInteger() ? GprIndex : FprIndex, 3089 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3090 MVT::i32)); 3091 3092 // OurReg = RegSaveArea + RegConstant 3093 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3094 RegConstant); 3095 3096 // Floating types are 32 bytes into RegSaveArea 3097 if (VT.isFloatingPoint()) 3098 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3099 DAG.getConstant(32, dl, MVT::i32)); 3100 3101 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3102 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3103 VT.isInteger() ? GprIndex : FprIndex, 3104 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3105 MVT::i32)); 3106 3107 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3108 VT.isInteger() ? VAListPtr : FprPtr, 3109 MachinePointerInfo(SV), MVT::i8); 3110 3111 // determine if we should load from reg_save_area or overflow_area 3112 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3113 3114 // increase overflow_area by 4/8 if gpr/fpr > 8 3115 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3116 DAG.getConstant(VT.isInteger() ? 4 : 8, 3117 dl, MVT::i32)); 3118 3119 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3120 OverflowAreaPlusN); 3121 3122 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3123 MachinePointerInfo(), MVT::i32); 3124 3125 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3126 } 3127 3128 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3129 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3130 3131 // We have to copy the entire va_list struct: 3132 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3133 return DAG.getMemcpy(Op.getOperand(0), Op, 3134 Op.getOperand(1), Op.getOperand(2), 3135 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3136 false, MachinePointerInfo(), MachinePointerInfo()); 3137 } 3138 3139 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3140 SelectionDAG &DAG) const { 3141 return Op.getOperand(0); 3142 } 3143 3144 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3145 SelectionDAG &DAG) const { 3146 SDValue Chain = Op.getOperand(0); 3147 SDValue Trmp = Op.getOperand(1); // trampoline 3148 SDValue FPtr = Op.getOperand(2); // nested function 3149 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3150 SDLoc dl(Op); 3151 3152 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3153 bool isPPC64 = (PtrVT == MVT::i64); 3154 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3155 3156 TargetLowering::ArgListTy Args; 3157 TargetLowering::ArgListEntry Entry; 3158 3159 Entry.Ty = IntPtrTy; 3160 Entry.Node = Trmp; Args.push_back(Entry); 3161 3162 // TrampSize == (isPPC64 ? 48 : 40); 3163 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3164 isPPC64 ? MVT::i64 : MVT::i32); 3165 Args.push_back(Entry); 3166 3167 Entry.Node = FPtr; Args.push_back(Entry); 3168 Entry.Node = Nest; Args.push_back(Entry); 3169 3170 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3171 TargetLowering::CallLoweringInfo CLI(DAG); 3172 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3173 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3174 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3175 3176 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3177 return CallResult.second; 3178 } 3179 3180 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3181 MachineFunction &MF = DAG.getMachineFunction(); 3182 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3183 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3184 3185 SDLoc dl(Op); 3186 3187 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3188 // vastart just stores the address of the VarArgsFrameIndex slot into the 3189 // memory location argument. 3190 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3191 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3192 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3193 MachinePointerInfo(SV)); 3194 } 3195 3196 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3197 // We suppose the given va_list is already allocated. 3198 // 3199 // typedef struct { 3200 // char gpr; /* index into the array of 8 GPRs 3201 // * stored in the register save area 3202 // * gpr=0 corresponds to r3, 3203 // * gpr=1 to r4, etc. 3204 // */ 3205 // char fpr; /* index into the array of 8 FPRs 3206 // * stored in the register save area 3207 // * fpr=0 corresponds to f1, 3208 // * fpr=1 to f2, etc. 3209 // */ 3210 // char *overflow_arg_area; 3211 // /* location on stack that holds 3212 // * the next overflow argument 3213 // */ 3214 // char *reg_save_area; 3215 // /* where r3:r10 and f1:f8 (if saved) 3216 // * are stored 3217 // */ 3218 // } va_list[1]; 3219 3220 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3221 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3222 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3223 PtrVT); 3224 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3225 PtrVT); 3226 3227 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3228 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3229 3230 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3231 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3232 3233 uint64_t FPROffset = 1; 3234 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3235 3236 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3237 3238 // Store first byte : number of int regs 3239 SDValue firstStore = 3240 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3241 MachinePointerInfo(SV), MVT::i8); 3242 uint64_t nextOffset = FPROffset; 3243 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3244 ConstFPROffset); 3245 3246 // Store second byte : number of float regs 3247 SDValue secondStore = 3248 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3249 MachinePointerInfo(SV, nextOffset), MVT::i8); 3250 nextOffset += StackOffset; 3251 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3252 3253 // Store second word : arguments given on stack 3254 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3255 MachinePointerInfo(SV, nextOffset)); 3256 nextOffset += FrameOffset; 3257 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3258 3259 // Store third word : arguments given in registers 3260 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3261 MachinePointerInfo(SV, nextOffset)); 3262 } 3263 3264 /// FPR - The set of FP registers that should be allocated for arguments 3265 /// on Darwin and AIX. 3266 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3267 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3268 PPC::F11, PPC::F12, PPC::F13}; 3269 3270 /// QFPR - The set of QPX registers that should be allocated for arguments. 3271 static const MCPhysReg QFPR[] = { 3272 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3273 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3274 3275 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3276 /// the stack. 3277 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3278 unsigned PtrByteSize) { 3279 unsigned ArgSize = ArgVT.getStoreSize(); 3280 if (Flags.isByVal()) 3281 ArgSize = Flags.getByValSize(); 3282 3283 // Round up to multiples of the pointer size, except for array members, 3284 // which are always packed. 3285 if (!Flags.isInConsecutiveRegs()) 3286 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3287 3288 return ArgSize; 3289 } 3290 3291 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3292 /// on the stack. 3293 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3294 ISD::ArgFlagsTy Flags, 3295 unsigned PtrByteSize) { 3296 unsigned Align = PtrByteSize; 3297 3298 // Altivec parameters are padded to a 16 byte boundary. 3299 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3300 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3301 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3302 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3303 Align = 16; 3304 // QPX vector types stored in double-precision are padded to a 32 byte 3305 // boundary. 3306 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3307 Align = 32; 3308 3309 // ByVal parameters are aligned as requested. 3310 if (Flags.isByVal()) { 3311 unsigned BVAlign = Flags.getByValAlign(); 3312 if (BVAlign > PtrByteSize) { 3313 if (BVAlign % PtrByteSize != 0) 3314 llvm_unreachable( 3315 "ByVal alignment is not a multiple of the pointer size"); 3316 3317 Align = BVAlign; 3318 } 3319 } 3320 3321 // Array members are always packed to their original alignment. 3322 if (Flags.isInConsecutiveRegs()) { 3323 // If the array member was split into multiple registers, the first 3324 // needs to be aligned to the size of the full type. (Except for 3325 // ppcf128, which is only aligned as its f64 components.) 3326 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3327 Align = OrigVT.getStoreSize(); 3328 else 3329 Align = ArgVT.getStoreSize(); 3330 } 3331 3332 return Align; 3333 } 3334 3335 /// CalculateStackSlotUsed - Return whether this argument will use its 3336 /// stack slot (instead of being passed in registers). ArgOffset, 3337 /// AvailableFPRs, and AvailableVRs must hold the current argument 3338 /// position, and will be updated to account for this argument. 3339 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3340 ISD::ArgFlagsTy Flags, 3341 unsigned PtrByteSize, 3342 unsigned LinkageSize, 3343 unsigned ParamAreaSize, 3344 unsigned &ArgOffset, 3345 unsigned &AvailableFPRs, 3346 unsigned &AvailableVRs, bool HasQPX) { 3347 bool UseMemory = false; 3348 3349 // Respect alignment of argument on the stack. 3350 unsigned Align = 3351 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3352 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3353 // If there's no space left in the argument save area, we must 3354 // use memory (this check also catches zero-sized arguments). 3355 if (ArgOffset >= LinkageSize + ParamAreaSize) 3356 UseMemory = true; 3357 3358 // Allocate argument on the stack. 3359 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3360 if (Flags.isInConsecutiveRegsLast()) 3361 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3362 // If we overran the argument save area, we must use memory 3363 // (this check catches arguments passed partially in memory) 3364 if (ArgOffset > LinkageSize + ParamAreaSize) 3365 UseMemory = true; 3366 3367 // However, if the argument is actually passed in an FPR or a VR, 3368 // we don't use memory after all. 3369 if (!Flags.isByVal()) { 3370 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3371 // QPX registers overlap with the scalar FP registers. 3372 (HasQPX && (ArgVT == MVT::v4f32 || 3373 ArgVT == MVT::v4f64 || 3374 ArgVT == MVT::v4i1))) 3375 if (AvailableFPRs > 0) { 3376 --AvailableFPRs; 3377 return false; 3378 } 3379 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3380 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3381 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3382 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3383 if (AvailableVRs > 0) { 3384 --AvailableVRs; 3385 return false; 3386 } 3387 } 3388 3389 return UseMemory; 3390 } 3391 3392 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3393 /// ensure minimum alignment required for target. 3394 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3395 unsigned NumBytes) { 3396 unsigned TargetAlign = Lowering->getStackAlignment(); 3397 unsigned AlignMask = TargetAlign - 1; 3398 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3399 return NumBytes; 3400 } 3401 3402 SDValue PPCTargetLowering::LowerFormalArguments( 3403 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3404 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3405 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3406 if (Subtarget.is64BitELFABI()) 3407 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3408 InVals); 3409 else if (Subtarget.is32BitELFABI()) 3410 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3411 InVals); 3412 3413 // FIXME: We are using this for both AIX and Darwin. We should add appropriate 3414 // AIX testing, and rename it appropriately. 3415 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3416 InVals); 3417 } 3418 3419 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3420 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3421 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3422 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3423 3424 // 32-bit SVR4 ABI Stack Frame Layout: 3425 // +-----------------------------------+ 3426 // +--> | Back chain | 3427 // | +-----------------------------------+ 3428 // | | Floating-point register save area | 3429 // | +-----------------------------------+ 3430 // | | General register save area | 3431 // | +-----------------------------------+ 3432 // | | CR save word | 3433 // | +-----------------------------------+ 3434 // | | VRSAVE save word | 3435 // | +-----------------------------------+ 3436 // | | Alignment padding | 3437 // | +-----------------------------------+ 3438 // | | Vector register save area | 3439 // | +-----------------------------------+ 3440 // | | Local variable space | 3441 // | +-----------------------------------+ 3442 // | | Parameter list area | 3443 // | +-----------------------------------+ 3444 // | | LR save word | 3445 // | +-----------------------------------+ 3446 // SP--> +--- | Back chain | 3447 // +-----------------------------------+ 3448 // 3449 // Specifications: 3450 // System V Application Binary Interface PowerPC Processor Supplement 3451 // AltiVec Technology Programming Interface Manual 3452 3453 MachineFunction &MF = DAG.getMachineFunction(); 3454 MachineFrameInfo &MFI = MF.getFrameInfo(); 3455 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3456 3457 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3458 // Potential tail calls could cause overwriting of argument stack slots. 3459 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3460 (CallConv == CallingConv::Fast)); 3461 unsigned PtrByteSize = 4; 3462 3463 // Assign locations to all of the incoming arguments. 3464 SmallVector<CCValAssign, 16> ArgLocs; 3465 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3466 *DAG.getContext()); 3467 3468 // Reserve space for the linkage area on the stack. 3469 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3470 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3471 if (useSoftFloat()) 3472 CCInfo.PreAnalyzeFormalArguments(Ins); 3473 3474 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3475 CCInfo.clearWasPPCF128(); 3476 3477 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3478 CCValAssign &VA = ArgLocs[i]; 3479 3480 // Arguments stored in registers. 3481 if (VA.isRegLoc()) { 3482 const TargetRegisterClass *RC; 3483 EVT ValVT = VA.getValVT(); 3484 3485 switch (ValVT.getSimpleVT().SimpleTy) { 3486 default: 3487 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3488 case MVT::i1: 3489 case MVT::i32: 3490 RC = &PPC::GPRCRegClass; 3491 break; 3492 case MVT::f32: 3493 if (Subtarget.hasP8Vector()) 3494 RC = &PPC::VSSRCRegClass; 3495 else if (Subtarget.hasSPE()) 3496 RC = &PPC::GPRCRegClass; 3497 else 3498 RC = &PPC::F4RCRegClass; 3499 break; 3500 case MVT::f64: 3501 if (Subtarget.hasVSX()) 3502 RC = &PPC::VSFRCRegClass; 3503 else if (Subtarget.hasSPE()) 3504 // SPE passes doubles in GPR pairs. 3505 RC = &PPC::GPRCRegClass; 3506 else 3507 RC = &PPC::F8RCRegClass; 3508 break; 3509 case MVT::v16i8: 3510 case MVT::v8i16: 3511 case MVT::v4i32: 3512 RC = &PPC::VRRCRegClass; 3513 break; 3514 case MVT::v4f32: 3515 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3516 break; 3517 case MVT::v2f64: 3518 case MVT::v2i64: 3519 RC = &PPC::VRRCRegClass; 3520 break; 3521 case MVT::v4f64: 3522 RC = &PPC::QFRCRegClass; 3523 break; 3524 case MVT::v4i1: 3525 RC = &PPC::QBRCRegClass; 3526 break; 3527 } 3528 3529 SDValue ArgValue; 3530 // Transform the arguments stored in physical registers into 3531 // virtual ones. 3532 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3533 assert(i + 1 < e && "No second half of double precision argument"); 3534 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3535 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3536 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3537 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3538 if (!Subtarget.isLittleEndian()) 3539 std::swap (ArgValueLo, ArgValueHi); 3540 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3541 ArgValueHi); 3542 } else { 3543 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3544 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3545 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3546 if (ValVT == MVT::i1) 3547 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3548 } 3549 3550 InVals.push_back(ArgValue); 3551 } else { 3552 // Argument stored in memory. 3553 assert(VA.isMemLoc()); 3554 3555 // Get the extended size of the argument type in stack 3556 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3557 // Get the actual size of the argument type 3558 unsigned ObjSize = VA.getValVT().getStoreSize(); 3559 unsigned ArgOffset = VA.getLocMemOffset(); 3560 // Stack objects in PPC32 are right justified. 3561 ArgOffset += ArgSize - ObjSize; 3562 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3563 3564 // Create load nodes to retrieve arguments from the stack. 3565 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3566 InVals.push_back( 3567 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3568 } 3569 } 3570 3571 // Assign locations to all of the incoming aggregate by value arguments. 3572 // Aggregates passed by value are stored in the local variable space of the 3573 // caller's stack frame, right above the parameter list area. 3574 SmallVector<CCValAssign, 16> ByValArgLocs; 3575 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3576 ByValArgLocs, *DAG.getContext()); 3577 3578 // Reserve stack space for the allocations in CCInfo. 3579 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3580 3581 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3582 3583 // Area that is at least reserved in the caller of this function. 3584 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3585 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3586 3587 // Set the size that is at least reserved in caller of this function. Tail 3588 // call optimized function's reserved stack space needs to be aligned so that 3589 // taking the difference between two stack areas will result in an aligned 3590 // stack. 3591 MinReservedArea = 3592 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3593 FuncInfo->setMinReservedArea(MinReservedArea); 3594 3595 SmallVector<SDValue, 8> MemOps; 3596 3597 // If the function takes variable number of arguments, make a frame index for 3598 // the start of the first vararg value... for expansion of llvm.va_start. 3599 if (isVarArg) { 3600 static const MCPhysReg GPArgRegs[] = { 3601 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3602 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3603 }; 3604 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3605 3606 static const MCPhysReg FPArgRegs[] = { 3607 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3608 PPC::F8 3609 }; 3610 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3611 3612 if (useSoftFloat() || hasSPE()) 3613 NumFPArgRegs = 0; 3614 3615 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3616 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3617 3618 // Make room for NumGPArgRegs and NumFPArgRegs. 3619 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3620 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3621 3622 FuncInfo->setVarArgsStackOffset( 3623 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3624 CCInfo.getNextStackOffset(), true)); 3625 3626 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3627 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3628 3629 // The fixed integer arguments of a variadic function are stored to the 3630 // VarArgsFrameIndex on the stack so that they may be loaded by 3631 // dereferencing the result of va_next. 3632 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3633 // Get an existing live-in vreg, or add a new one. 3634 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3635 if (!VReg) 3636 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3637 3638 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3639 SDValue Store = 3640 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3641 MemOps.push_back(Store); 3642 // Increment the address by four for the next argument to store 3643 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3644 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3645 } 3646 3647 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3648 // is set. 3649 // The double arguments are stored to the VarArgsFrameIndex 3650 // on the stack. 3651 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3652 // Get an existing live-in vreg, or add a new one. 3653 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3654 if (!VReg) 3655 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3656 3657 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3658 SDValue Store = 3659 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3660 MemOps.push_back(Store); 3661 // Increment the address by eight for the next argument to store 3662 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3663 PtrVT); 3664 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3665 } 3666 } 3667 3668 if (!MemOps.empty()) 3669 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3670 3671 return Chain; 3672 } 3673 3674 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3675 // value to MVT::i64 and then truncate to the correct register size. 3676 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3677 EVT ObjectVT, SelectionDAG &DAG, 3678 SDValue ArgVal, 3679 const SDLoc &dl) const { 3680 if (Flags.isSExt()) 3681 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3682 DAG.getValueType(ObjectVT)); 3683 else if (Flags.isZExt()) 3684 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3685 DAG.getValueType(ObjectVT)); 3686 3687 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3688 } 3689 3690 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3691 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3692 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3693 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3694 // TODO: add description of PPC stack frame format, or at least some docs. 3695 // 3696 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3697 bool isLittleEndian = Subtarget.isLittleEndian(); 3698 MachineFunction &MF = DAG.getMachineFunction(); 3699 MachineFrameInfo &MFI = MF.getFrameInfo(); 3700 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3701 3702 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3703 "fastcc not supported on varargs functions"); 3704 3705 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3706 // Potential tail calls could cause overwriting of argument stack slots. 3707 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3708 (CallConv == CallingConv::Fast)); 3709 unsigned PtrByteSize = 8; 3710 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3711 3712 static const MCPhysReg GPR[] = { 3713 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3714 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3715 }; 3716 static const MCPhysReg VR[] = { 3717 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3718 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3719 }; 3720 3721 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3722 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3723 const unsigned Num_VR_Regs = array_lengthof(VR); 3724 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3725 3726 // Do a first pass over the arguments to determine whether the ABI 3727 // guarantees that our caller has allocated the parameter save area 3728 // on its stack frame. In the ELFv1 ABI, this is always the case; 3729 // in the ELFv2 ABI, it is true if this is a vararg function or if 3730 // any parameter is located in a stack slot. 3731 3732 bool HasParameterArea = !isELFv2ABI || isVarArg; 3733 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3734 unsigned NumBytes = LinkageSize; 3735 unsigned AvailableFPRs = Num_FPR_Regs; 3736 unsigned AvailableVRs = Num_VR_Regs; 3737 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3738 if (Ins[i].Flags.isNest()) 3739 continue; 3740 3741 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3742 PtrByteSize, LinkageSize, ParamAreaSize, 3743 NumBytes, AvailableFPRs, AvailableVRs, 3744 Subtarget.hasQPX())) 3745 HasParameterArea = true; 3746 } 3747 3748 // Add DAG nodes to load the arguments or copy them out of registers. On 3749 // entry to a function on PPC, the arguments start after the linkage area, 3750 // although the first ones are often in registers. 3751 3752 unsigned ArgOffset = LinkageSize; 3753 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3754 unsigned &QFPR_idx = FPR_idx; 3755 SmallVector<SDValue, 8> MemOps; 3756 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3757 unsigned CurArgIdx = 0; 3758 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3759 SDValue ArgVal; 3760 bool needsLoad = false; 3761 EVT ObjectVT = Ins[ArgNo].VT; 3762 EVT OrigVT = Ins[ArgNo].ArgVT; 3763 unsigned ObjSize = ObjectVT.getStoreSize(); 3764 unsigned ArgSize = ObjSize; 3765 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3766 if (Ins[ArgNo].isOrigArg()) { 3767 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3768 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3769 } 3770 // We re-align the argument offset for each argument, except when using the 3771 // fast calling convention, when we need to make sure we do that only when 3772 // we'll actually use a stack slot. 3773 unsigned CurArgOffset, Align; 3774 auto ComputeArgOffset = [&]() { 3775 /* Respect alignment of argument on the stack. */ 3776 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3777 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3778 CurArgOffset = ArgOffset; 3779 }; 3780 3781 if (CallConv != CallingConv::Fast) { 3782 ComputeArgOffset(); 3783 3784 /* Compute GPR index associated with argument offset. */ 3785 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3786 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3787 } 3788 3789 // FIXME the codegen can be much improved in some cases. 3790 // We do not have to keep everything in memory. 3791 if (Flags.isByVal()) { 3792 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3793 3794 if (CallConv == CallingConv::Fast) 3795 ComputeArgOffset(); 3796 3797 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3798 ObjSize = Flags.getByValSize(); 3799 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3800 // Empty aggregate parameters do not take up registers. Examples: 3801 // struct { } a; 3802 // union { } b; 3803 // int c[0]; 3804 // etc. However, we have to provide a place-holder in InVals, so 3805 // pretend we have an 8-byte item at the current address for that 3806 // purpose. 3807 if (!ObjSize) { 3808 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3809 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3810 InVals.push_back(FIN); 3811 continue; 3812 } 3813 3814 // Create a stack object covering all stack doublewords occupied 3815 // by the argument. If the argument is (fully or partially) on 3816 // the stack, or if the argument is fully in registers but the 3817 // caller has allocated the parameter save anyway, we can refer 3818 // directly to the caller's stack frame. Otherwise, create a 3819 // local copy in our own frame. 3820 int FI; 3821 if (HasParameterArea || 3822 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3823 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3824 else 3825 FI = MFI.CreateStackObject(ArgSize, Align, false); 3826 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3827 3828 // Handle aggregates smaller than 8 bytes. 3829 if (ObjSize < PtrByteSize) { 3830 // The value of the object is its address, which differs from the 3831 // address of the enclosing doubleword on big-endian systems. 3832 SDValue Arg = FIN; 3833 if (!isLittleEndian) { 3834 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3835 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3836 } 3837 InVals.push_back(Arg); 3838 3839 if (GPR_idx != Num_GPR_Regs) { 3840 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3841 FuncInfo->addLiveInAttr(VReg, Flags); 3842 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3843 SDValue Store; 3844 3845 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3846 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3847 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3848 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3849 MachinePointerInfo(&*FuncArg), ObjType); 3850 } else { 3851 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3852 // store the whole register as-is to the parameter save area 3853 // slot. 3854 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3855 MachinePointerInfo(&*FuncArg)); 3856 } 3857 3858 MemOps.push_back(Store); 3859 } 3860 // Whether we copied from a register or not, advance the offset 3861 // into the parameter save area by a full doubleword. 3862 ArgOffset += PtrByteSize; 3863 continue; 3864 } 3865 3866 // The value of the object is its address, which is the address of 3867 // its first stack doubleword. 3868 InVals.push_back(FIN); 3869 3870 // Store whatever pieces of the object are in registers to memory. 3871 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3872 if (GPR_idx == Num_GPR_Regs) 3873 break; 3874 3875 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3876 FuncInfo->addLiveInAttr(VReg, Flags); 3877 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3878 SDValue Addr = FIN; 3879 if (j) { 3880 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3881 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3882 } 3883 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3884 MachinePointerInfo(&*FuncArg, j)); 3885 MemOps.push_back(Store); 3886 ++GPR_idx; 3887 } 3888 ArgOffset += ArgSize; 3889 continue; 3890 } 3891 3892 switch (ObjectVT.getSimpleVT().SimpleTy) { 3893 default: llvm_unreachable("Unhandled argument type!"); 3894 case MVT::i1: 3895 case MVT::i32: 3896 case MVT::i64: 3897 if (Flags.isNest()) { 3898 // The 'nest' parameter, if any, is passed in R11. 3899 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3900 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3901 3902 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3903 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3904 3905 break; 3906 } 3907 3908 // These can be scalar arguments or elements of an integer array type 3909 // passed directly. Clang may use those instead of "byval" aggregate 3910 // types to avoid forcing arguments to memory unnecessarily. 3911 if (GPR_idx != Num_GPR_Regs) { 3912 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3913 FuncInfo->addLiveInAttr(VReg, Flags); 3914 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3915 3916 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3917 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3918 // value to MVT::i64 and then truncate to the correct register size. 3919 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3920 } else { 3921 if (CallConv == CallingConv::Fast) 3922 ComputeArgOffset(); 3923 3924 needsLoad = true; 3925 ArgSize = PtrByteSize; 3926 } 3927 if (CallConv != CallingConv::Fast || needsLoad) 3928 ArgOffset += 8; 3929 break; 3930 3931 case MVT::f32: 3932 case MVT::f64: 3933 // These can be scalar arguments or elements of a float array type 3934 // passed directly. The latter are used to implement ELFv2 homogenous 3935 // float aggregates. 3936 if (FPR_idx != Num_FPR_Regs) { 3937 unsigned VReg; 3938 3939 if (ObjectVT == MVT::f32) 3940 VReg = MF.addLiveIn(FPR[FPR_idx], 3941 Subtarget.hasP8Vector() 3942 ? &PPC::VSSRCRegClass 3943 : &PPC::F4RCRegClass); 3944 else 3945 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3946 ? &PPC::VSFRCRegClass 3947 : &PPC::F8RCRegClass); 3948 3949 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3950 ++FPR_idx; 3951 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3952 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3953 // once we support fp <-> gpr moves. 3954 3955 // This can only ever happen in the presence of f32 array types, 3956 // since otherwise we never run out of FPRs before running out 3957 // of GPRs. 3958 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3959 FuncInfo->addLiveInAttr(VReg, Flags); 3960 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3961 3962 if (ObjectVT == MVT::f32) { 3963 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3964 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3965 DAG.getConstant(32, dl, MVT::i32)); 3966 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3967 } 3968 3969 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3970 } else { 3971 if (CallConv == CallingConv::Fast) 3972 ComputeArgOffset(); 3973 3974 needsLoad = true; 3975 } 3976 3977 // When passing an array of floats, the array occupies consecutive 3978 // space in the argument area; only round up to the next doubleword 3979 // at the end of the array. Otherwise, each float takes 8 bytes. 3980 if (CallConv != CallingConv::Fast || needsLoad) { 3981 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3982 ArgOffset += ArgSize; 3983 if (Flags.isInConsecutiveRegsLast()) 3984 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3985 } 3986 break; 3987 case MVT::v4f32: 3988 case MVT::v4i32: 3989 case MVT::v8i16: 3990 case MVT::v16i8: 3991 case MVT::v2f64: 3992 case MVT::v2i64: 3993 case MVT::v1i128: 3994 case MVT::f128: 3995 if (!Subtarget.hasQPX()) { 3996 // These can be scalar arguments or elements of a vector array type 3997 // passed directly. The latter are used to implement ELFv2 homogenous 3998 // vector aggregates. 3999 if (VR_idx != Num_VR_Regs) { 4000 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4001 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4002 ++VR_idx; 4003 } else { 4004 if (CallConv == CallingConv::Fast) 4005 ComputeArgOffset(); 4006 needsLoad = true; 4007 } 4008 if (CallConv != CallingConv::Fast || needsLoad) 4009 ArgOffset += 16; 4010 break; 4011 } // not QPX 4012 4013 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4014 "Invalid QPX parameter type"); 4015 LLVM_FALLTHROUGH; 4016 4017 case MVT::v4f64: 4018 case MVT::v4i1: 4019 // QPX vectors are treated like their scalar floating-point subregisters 4020 // (except that they're larger). 4021 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4022 if (QFPR_idx != Num_QFPR_Regs) { 4023 const TargetRegisterClass *RC; 4024 switch (ObjectVT.getSimpleVT().SimpleTy) { 4025 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4026 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4027 default: RC = &PPC::QBRCRegClass; break; 4028 } 4029 4030 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4031 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4032 ++QFPR_idx; 4033 } else { 4034 if (CallConv == CallingConv::Fast) 4035 ComputeArgOffset(); 4036 needsLoad = true; 4037 } 4038 if (CallConv != CallingConv::Fast || needsLoad) 4039 ArgOffset += Sz; 4040 break; 4041 } 4042 4043 // We need to load the argument to a virtual register if we determined 4044 // above that we ran out of physical registers of the appropriate type. 4045 if (needsLoad) { 4046 if (ObjSize < ArgSize && !isLittleEndian) 4047 CurArgOffset += ArgSize - ObjSize; 4048 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4049 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4050 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4051 } 4052 4053 InVals.push_back(ArgVal); 4054 } 4055 4056 // Area that is at least reserved in the caller of this function. 4057 unsigned MinReservedArea; 4058 if (HasParameterArea) 4059 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4060 else 4061 MinReservedArea = LinkageSize; 4062 4063 // Set the size that is at least reserved in caller of this function. Tail 4064 // call optimized functions' reserved stack space needs to be aligned so that 4065 // taking the difference between two stack areas will result in an aligned 4066 // stack. 4067 MinReservedArea = 4068 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4069 FuncInfo->setMinReservedArea(MinReservedArea); 4070 4071 // If the function takes variable number of arguments, make a frame index for 4072 // the start of the first vararg value... for expansion of llvm.va_start. 4073 if (isVarArg) { 4074 int Depth = ArgOffset; 4075 4076 FuncInfo->setVarArgsFrameIndex( 4077 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4078 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4079 4080 // If this function is vararg, store any remaining integer argument regs 4081 // to their spots on the stack so that they may be loaded by dereferencing 4082 // the result of va_next. 4083 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4084 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4085 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4086 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4087 SDValue Store = 4088 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4089 MemOps.push_back(Store); 4090 // Increment the address by four for the next argument to store 4091 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4092 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4093 } 4094 } 4095 4096 if (!MemOps.empty()) 4097 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4098 4099 return Chain; 4100 } 4101 4102 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4103 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4104 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4105 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4106 // TODO: add description of PPC stack frame format, or at least some docs. 4107 // 4108 MachineFunction &MF = DAG.getMachineFunction(); 4109 MachineFrameInfo &MFI = MF.getFrameInfo(); 4110 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4111 4112 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4113 bool isPPC64 = PtrVT == MVT::i64; 4114 // Potential tail calls could cause overwriting of argument stack slots. 4115 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4116 (CallConv == CallingConv::Fast)); 4117 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4118 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4119 unsigned ArgOffset = LinkageSize; 4120 // Area that is at least reserved in caller of this function. 4121 unsigned MinReservedArea = ArgOffset; 4122 4123 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4124 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4125 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4126 }; 4127 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4128 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4129 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4130 }; 4131 static const MCPhysReg VR[] = { 4132 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4133 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4134 }; 4135 4136 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4137 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4138 const unsigned Num_VR_Regs = array_lengthof( VR); 4139 4140 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4141 4142 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4143 4144 // In 32-bit non-varargs functions, the stack space for vectors is after the 4145 // stack space for non-vectors. We do not use this space unless we have 4146 // too many vectors to fit in registers, something that only occurs in 4147 // constructed examples:), but we have to walk the arglist to figure 4148 // that out...for the pathological case, compute VecArgOffset as the 4149 // start of the vector parameter area. Computing VecArgOffset is the 4150 // entire point of the following loop. 4151 unsigned VecArgOffset = ArgOffset; 4152 if (!isVarArg && !isPPC64) { 4153 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4154 ++ArgNo) { 4155 EVT ObjectVT = Ins[ArgNo].VT; 4156 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4157 4158 if (Flags.isByVal()) { 4159 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4160 unsigned ObjSize = Flags.getByValSize(); 4161 unsigned ArgSize = 4162 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4163 VecArgOffset += ArgSize; 4164 continue; 4165 } 4166 4167 switch(ObjectVT.getSimpleVT().SimpleTy) { 4168 default: llvm_unreachable("Unhandled argument type!"); 4169 case MVT::i1: 4170 case MVT::i32: 4171 case MVT::f32: 4172 VecArgOffset += 4; 4173 break; 4174 case MVT::i64: // PPC64 4175 case MVT::f64: 4176 // FIXME: We are guaranteed to be !isPPC64 at this point. 4177 // Does MVT::i64 apply? 4178 VecArgOffset += 8; 4179 break; 4180 case MVT::v4f32: 4181 case MVT::v4i32: 4182 case MVT::v8i16: 4183 case MVT::v16i8: 4184 // Nothing to do, we're only looking at Nonvector args here. 4185 break; 4186 } 4187 } 4188 } 4189 // We've found where the vector parameter area in memory is. Skip the 4190 // first 12 parameters; these don't use that memory. 4191 VecArgOffset = ((VecArgOffset+15)/16)*16; 4192 VecArgOffset += 12*16; 4193 4194 // Add DAG nodes to load the arguments or copy them out of registers. On 4195 // entry to a function on PPC, the arguments start after the linkage area, 4196 // although the first ones are often in registers. 4197 4198 SmallVector<SDValue, 8> MemOps; 4199 unsigned nAltivecParamsAtEnd = 0; 4200 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4201 unsigned CurArgIdx = 0; 4202 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4203 SDValue ArgVal; 4204 bool needsLoad = false; 4205 EVT ObjectVT = Ins[ArgNo].VT; 4206 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4207 unsigned ArgSize = ObjSize; 4208 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4209 if (Ins[ArgNo].isOrigArg()) { 4210 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4211 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4212 } 4213 unsigned CurArgOffset = ArgOffset; 4214 4215 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4216 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4217 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4218 if (isVarArg || isPPC64) { 4219 MinReservedArea = ((MinReservedArea+15)/16)*16; 4220 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4221 Flags, 4222 PtrByteSize); 4223 } else nAltivecParamsAtEnd++; 4224 } else 4225 // Calculate min reserved area. 4226 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4227 Flags, 4228 PtrByteSize); 4229 4230 // FIXME the codegen can be much improved in some cases. 4231 // We do not have to keep everything in memory. 4232 if (Flags.isByVal()) { 4233 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4234 4235 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4236 ObjSize = Flags.getByValSize(); 4237 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4238 // Objects of size 1 and 2 are right justified, everything else is 4239 // left justified. This means the memory address is adjusted forwards. 4240 if (ObjSize==1 || ObjSize==2) { 4241 CurArgOffset = CurArgOffset + (4 - ObjSize); 4242 } 4243 // The value of the object is its address. 4244 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4245 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4246 InVals.push_back(FIN); 4247 if (ObjSize==1 || ObjSize==2) { 4248 if (GPR_idx != Num_GPR_Regs) { 4249 unsigned VReg; 4250 if (isPPC64) 4251 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4252 else 4253 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4254 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4255 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4256 SDValue Store = 4257 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4258 MachinePointerInfo(&*FuncArg), ObjType); 4259 MemOps.push_back(Store); 4260 ++GPR_idx; 4261 } 4262 4263 ArgOffset += PtrByteSize; 4264 4265 continue; 4266 } 4267 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4268 // Store whatever pieces of the object are in registers 4269 // to memory. ArgOffset will be the address of the beginning 4270 // of the object. 4271 if (GPR_idx != Num_GPR_Regs) { 4272 unsigned VReg; 4273 if (isPPC64) 4274 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4275 else 4276 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4277 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4278 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4279 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4280 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4281 MachinePointerInfo(&*FuncArg, j)); 4282 MemOps.push_back(Store); 4283 ++GPR_idx; 4284 ArgOffset += PtrByteSize; 4285 } else { 4286 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4287 break; 4288 } 4289 } 4290 continue; 4291 } 4292 4293 switch (ObjectVT.getSimpleVT().SimpleTy) { 4294 default: llvm_unreachable("Unhandled argument type!"); 4295 case MVT::i1: 4296 case MVT::i32: 4297 if (!isPPC64) { 4298 if (GPR_idx != Num_GPR_Regs) { 4299 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4300 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4301 4302 if (ObjectVT == MVT::i1) 4303 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4304 4305 ++GPR_idx; 4306 } else { 4307 needsLoad = true; 4308 ArgSize = PtrByteSize; 4309 } 4310 // All int arguments reserve stack space in the Darwin ABI. 4311 ArgOffset += PtrByteSize; 4312 break; 4313 } 4314 LLVM_FALLTHROUGH; 4315 case MVT::i64: // PPC64 4316 if (GPR_idx != Num_GPR_Regs) { 4317 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4318 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4319 4320 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4321 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4322 // value to MVT::i64 and then truncate to the correct register size. 4323 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4324 4325 ++GPR_idx; 4326 } else { 4327 needsLoad = true; 4328 ArgSize = PtrByteSize; 4329 } 4330 // All int arguments reserve stack space in the Darwin ABI. 4331 ArgOffset += 8; 4332 break; 4333 4334 case MVT::f32: 4335 case MVT::f64: 4336 // Every 4 bytes of argument space consumes one of the GPRs available for 4337 // argument passing. 4338 if (GPR_idx != Num_GPR_Regs) { 4339 ++GPR_idx; 4340 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4341 ++GPR_idx; 4342 } 4343 if (FPR_idx != Num_FPR_Regs) { 4344 unsigned VReg; 4345 4346 if (ObjectVT == MVT::f32) 4347 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4348 else 4349 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4350 4351 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4352 ++FPR_idx; 4353 } else { 4354 needsLoad = true; 4355 } 4356 4357 // All FP arguments reserve stack space in the Darwin ABI. 4358 ArgOffset += isPPC64 ? 8 : ObjSize; 4359 break; 4360 case MVT::v4f32: 4361 case MVT::v4i32: 4362 case MVT::v8i16: 4363 case MVT::v16i8: 4364 // Note that vector arguments in registers don't reserve stack space, 4365 // except in varargs functions. 4366 if (VR_idx != Num_VR_Regs) { 4367 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4368 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4369 if (isVarArg) { 4370 while ((ArgOffset % 16) != 0) { 4371 ArgOffset += PtrByteSize; 4372 if (GPR_idx != Num_GPR_Regs) 4373 GPR_idx++; 4374 } 4375 ArgOffset += 16; 4376 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4377 } 4378 ++VR_idx; 4379 } else { 4380 if (!isVarArg && !isPPC64) { 4381 // Vectors go after all the nonvectors. 4382 CurArgOffset = VecArgOffset; 4383 VecArgOffset += 16; 4384 } else { 4385 // Vectors are aligned. 4386 ArgOffset = ((ArgOffset+15)/16)*16; 4387 CurArgOffset = ArgOffset; 4388 ArgOffset += 16; 4389 } 4390 needsLoad = true; 4391 } 4392 break; 4393 } 4394 4395 // We need to load the argument to a virtual register if we determined above 4396 // that we ran out of physical registers of the appropriate type. 4397 if (needsLoad) { 4398 int FI = MFI.CreateFixedObject(ObjSize, 4399 CurArgOffset + (ArgSize - ObjSize), 4400 isImmutable); 4401 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4402 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4403 } 4404 4405 InVals.push_back(ArgVal); 4406 } 4407 4408 // Allow for Altivec parameters at the end, if needed. 4409 if (nAltivecParamsAtEnd) { 4410 MinReservedArea = ((MinReservedArea+15)/16)*16; 4411 MinReservedArea += 16*nAltivecParamsAtEnd; 4412 } 4413 4414 // Area that is at least reserved in the caller of this function. 4415 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4416 4417 // Set the size that is at least reserved in caller of this function. Tail 4418 // call optimized functions' reserved stack space needs to be aligned so that 4419 // taking the difference between two stack areas will result in an aligned 4420 // stack. 4421 MinReservedArea = 4422 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4423 FuncInfo->setMinReservedArea(MinReservedArea); 4424 4425 // If the function takes variable number of arguments, make a frame index for 4426 // the start of the first vararg value... for expansion of llvm.va_start. 4427 if (isVarArg) { 4428 int Depth = ArgOffset; 4429 4430 FuncInfo->setVarArgsFrameIndex( 4431 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4432 Depth, true)); 4433 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4434 4435 // If this function is vararg, store any remaining integer argument regs 4436 // to their spots on the stack so that they may be loaded by dereferencing 4437 // the result of va_next. 4438 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4439 unsigned VReg; 4440 4441 if (isPPC64) 4442 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4443 else 4444 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4445 4446 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4447 SDValue Store = 4448 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4449 MemOps.push_back(Store); 4450 // Increment the address by four for the next argument to store 4451 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4452 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4453 } 4454 } 4455 4456 if (!MemOps.empty()) 4457 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4458 4459 return Chain; 4460 } 4461 4462 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4463 /// adjusted to accommodate the arguments for the tailcall. 4464 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4465 unsigned ParamSize) { 4466 4467 if (!isTailCall) return 0; 4468 4469 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4470 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4471 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4472 // Remember only if the new adjustment is bigger. 4473 if (SPDiff < FI->getTailCallSPDelta()) 4474 FI->setTailCallSPDelta(SPDiff); 4475 4476 return SPDiff; 4477 } 4478 4479 static bool isFunctionGlobalAddress(SDValue Callee); 4480 4481 static bool 4482 callsShareTOCBase(const Function *Caller, SDValue Callee, 4483 const TargetMachine &TM) { 4484 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4485 // don't have enough information to determine if the caller and calle share 4486 // the same TOC base, so we have to pessimistically assume they don't for 4487 // correctness. 4488 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4489 if (!G) 4490 return false; 4491 4492 const GlobalValue *GV = G->getGlobal(); 4493 // The medium and large code models are expected to provide a sufficiently 4494 // large TOC to provide all data addressing needs of a module with a 4495 // single TOC. Since each module will be addressed with a single TOC then we 4496 // only need to check that caller and callee don't cross dso boundaries. 4497 if (CodeModel::Medium == TM.getCodeModel() || 4498 CodeModel::Large == TM.getCodeModel()) 4499 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4500 4501 // Otherwise we need to ensure callee and caller are in the same section, 4502 // since the linker may allocate multiple TOCs, and we don't know which 4503 // sections will belong to the same TOC base. 4504 4505 if (!GV->isStrongDefinitionForLinker()) 4506 return false; 4507 4508 // Any explicitly-specified sections and section prefixes must also match. 4509 // Also, if we're using -ffunction-sections, then each function is always in 4510 // a different section (the same is true for COMDAT functions). 4511 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4512 GV->getSection() != Caller->getSection()) 4513 return false; 4514 if (const auto *F = dyn_cast<Function>(GV)) { 4515 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4516 return false; 4517 } 4518 4519 // If the callee might be interposed, then we can't assume the ultimate call 4520 // target will be in the same section. Even in cases where we can assume that 4521 // interposition won't happen, in any case where the linker might insert a 4522 // stub to allow for interposition, we must generate code as though 4523 // interposition might occur. To understand why this matters, consider a 4524 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4525 // in the same section, but a is in a different module (i.e. has a different 4526 // TOC base pointer). If the linker allows for interposition between b and c, 4527 // then it will generate a stub for the call edge between b and c which will 4528 // save the TOC pointer into the designated stack slot allocated by b. If we 4529 // return true here, and therefore allow a tail call between b and c, that 4530 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4531 // pointer into the stack slot allocated by a (where the a -> b stub saved 4532 // a's TOC base pointer). If we're not considering a tail call, but rather, 4533 // whether a nop is needed after the call instruction in b, because the linker 4534 // will insert a stub, it might complain about a missing nop if we omit it 4535 // (although many don't complain in this case). 4536 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4537 return false; 4538 4539 return true; 4540 } 4541 4542 static bool 4543 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4544 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4545 assert(Subtarget.is64BitELFABI()); 4546 4547 const unsigned PtrByteSize = 8; 4548 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4549 4550 static const MCPhysReg GPR[] = { 4551 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4552 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4553 }; 4554 static const MCPhysReg VR[] = { 4555 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4556 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4557 }; 4558 4559 const unsigned NumGPRs = array_lengthof(GPR); 4560 const unsigned NumFPRs = 13; 4561 const unsigned NumVRs = array_lengthof(VR); 4562 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4563 4564 unsigned NumBytes = LinkageSize; 4565 unsigned AvailableFPRs = NumFPRs; 4566 unsigned AvailableVRs = NumVRs; 4567 4568 for (const ISD::OutputArg& Param : Outs) { 4569 if (Param.Flags.isNest()) continue; 4570 4571 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4572 PtrByteSize, LinkageSize, ParamAreaSize, 4573 NumBytes, AvailableFPRs, AvailableVRs, 4574 Subtarget.hasQPX())) 4575 return true; 4576 } 4577 return false; 4578 } 4579 4580 static bool 4581 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4582 if (CS.arg_size() != CallerFn->arg_size()) 4583 return false; 4584 4585 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4586 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4587 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4588 4589 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4590 const Value* CalleeArg = *CalleeArgIter; 4591 const Value* CallerArg = &(*CallerArgIter); 4592 if (CalleeArg == CallerArg) 4593 continue; 4594 4595 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4596 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4597 // } 4598 // 1st argument of callee is undef and has the same type as caller. 4599 if (CalleeArg->getType() == CallerArg->getType() && 4600 isa<UndefValue>(CalleeArg)) 4601 continue; 4602 4603 return false; 4604 } 4605 4606 return true; 4607 } 4608 4609 // Returns true if TCO is possible between the callers and callees 4610 // calling conventions. 4611 static bool 4612 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4613 CallingConv::ID CalleeCC) { 4614 // Tail calls are possible with fastcc and ccc. 4615 auto isTailCallableCC = [] (CallingConv::ID CC){ 4616 return CC == CallingConv::C || CC == CallingConv::Fast; 4617 }; 4618 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4619 return false; 4620 4621 // We can safely tail call both fastcc and ccc callees from a c calling 4622 // convention caller. If the caller is fastcc, we may have less stack space 4623 // than a non-fastcc caller with the same signature so disable tail-calls in 4624 // that case. 4625 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4626 } 4627 4628 bool 4629 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4630 SDValue Callee, 4631 CallingConv::ID CalleeCC, 4632 ImmutableCallSite CS, 4633 bool isVarArg, 4634 const SmallVectorImpl<ISD::OutputArg> &Outs, 4635 const SmallVectorImpl<ISD::InputArg> &Ins, 4636 SelectionDAG& DAG) const { 4637 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4638 4639 if (DisableSCO && !TailCallOpt) return false; 4640 4641 // Variadic argument functions are not supported. 4642 if (isVarArg) return false; 4643 4644 auto &Caller = DAG.getMachineFunction().getFunction(); 4645 // Check that the calling conventions are compatible for tco. 4646 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4647 return false; 4648 4649 // Caller contains any byval parameter is not supported. 4650 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4651 return false; 4652 4653 // Callee contains any byval parameter is not supported, too. 4654 // Note: This is a quick work around, because in some cases, e.g. 4655 // caller's stack size > callee's stack size, we are still able to apply 4656 // sibling call optimization. For example, gcc is able to do SCO for caller1 4657 // in the following example, but not for caller2. 4658 // struct test { 4659 // long int a; 4660 // char ary[56]; 4661 // } gTest; 4662 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4663 // b->a = v.a; 4664 // return 0; 4665 // } 4666 // void caller1(struct test a, struct test c, struct test *b) { 4667 // callee(gTest, b); } 4668 // void caller2(struct test *b) { callee(gTest, b); } 4669 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4670 return false; 4671 4672 // If callee and caller use different calling conventions, we cannot pass 4673 // parameters on stack since offsets for the parameter area may be different. 4674 if (Caller.getCallingConv() != CalleeCC && 4675 needStackSlotPassParameters(Subtarget, Outs)) 4676 return false; 4677 4678 // No TCO/SCO on indirect call because Caller have to restore its TOC 4679 if (!isFunctionGlobalAddress(Callee) && 4680 !isa<ExternalSymbolSDNode>(Callee)) 4681 return false; 4682 4683 // If the caller and callee potentially have different TOC bases then we 4684 // cannot tail call since we need to restore the TOC pointer after the call. 4685 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4686 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4687 return false; 4688 4689 // TCO allows altering callee ABI, so we don't have to check further. 4690 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4691 return true; 4692 4693 if (DisableSCO) return false; 4694 4695 // If callee use the same argument list that caller is using, then we can 4696 // apply SCO on this case. If it is not, then we need to check if callee needs 4697 // stack for passing arguments. 4698 if (!hasSameArgumentList(&Caller, CS) && 4699 needStackSlotPassParameters(Subtarget, Outs)) { 4700 return false; 4701 } 4702 4703 return true; 4704 } 4705 4706 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4707 /// for tail call optimization. Targets which want to do tail call 4708 /// optimization should implement this function. 4709 bool 4710 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4711 CallingConv::ID CalleeCC, 4712 bool isVarArg, 4713 const SmallVectorImpl<ISD::InputArg> &Ins, 4714 SelectionDAG& DAG) const { 4715 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4716 return false; 4717 4718 // Variable argument functions are not supported. 4719 if (isVarArg) 4720 return false; 4721 4722 MachineFunction &MF = DAG.getMachineFunction(); 4723 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4724 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4725 // Functions containing by val parameters are not supported. 4726 for (unsigned i = 0; i != Ins.size(); i++) { 4727 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4728 if (Flags.isByVal()) return false; 4729 } 4730 4731 // Non-PIC/GOT tail calls are supported. 4732 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4733 return true; 4734 4735 // At the moment we can only do local tail calls (in same module, hidden 4736 // or protected) if we are generating PIC. 4737 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4738 return G->getGlobal()->hasHiddenVisibility() 4739 || G->getGlobal()->hasProtectedVisibility(); 4740 } 4741 4742 return false; 4743 } 4744 4745 /// isCallCompatibleAddress - Return the immediate to use if the specified 4746 /// 32-bit value is representable in the immediate field of a BxA instruction. 4747 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4748 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4749 if (!C) return nullptr; 4750 4751 int Addr = C->getZExtValue(); 4752 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4753 SignExtend32<26>(Addr) != Addr) 4754 return nullptr; // Top 6 bits have to be sext of immediate. 4755 4756 return DAG 4757 .getConstant( 4758 (int)C->getZExtValue() >> 2, SDLoc(Op), 4759 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4760 .getNode(); 4761 } 4762 4763 namespace { 4764 4765 struct TailCallArgumentInfo { 4766 SDValue Arg; 4767 SDValue FrameIdxOp; 4768 int FrameIdx = 0; 4769 4770 TailCallArgumentInfo() = default; 4771 }; 4772 4773 } // end anonymous namespace 4774 4775 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4776 static void StoreTailCallArgumentsToStackSlot( 4777 SelectionDAG &DAG, SDValue Chain, 4778 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4779 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4780 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4781 SDValue Arg = TailCallArgs[i].Arg; 4782 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4783 int FI = TailCallArgs[i].FrameIdx; 4784 // Store relative to framepointer. 4785 MemOpChains.push_back(DAG.getStore( 4786 Chain, dl, Arg, FIN, 4787 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4788 } 4789 } 4790 4791 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4792 /// the appropriate stack slot for the tail call optimized function call. 4793 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4794 SDValue OldRetAddr, SDValue OldFP, 4795 int SPDiff, const SDLoc &dl) { 4796 if (SPDiff) { 4797 // Calculate the new stack slot for the return address. 4798 MachineFunction &MF = DAG.getMachineFunction(); 4799 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4800 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4801 bool isPPC64 = Subtarget.isPPC64(); 4802 int SlotSize = isPPC64 ? 8 : 4; 4803 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4804 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4805 NewRetAddrLoc, true); 4806 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4807 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4808 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4809 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4810 4811 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4812 // slot as the FP is never overwritten. 4813 if (Subtarget.isDarwinABI()) { 4814 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4815 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4816 true); 4817 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4818 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4819 MachinePointerInfo::getFixedStack( 4820 DAG.getMachineFunction(), NewFPIdx)); 4821 } 4822 } 4823 return Chain; 4824 } 4825 4826 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4827 /// the position of the argument. 4828 static void 4829 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4830 SDValue Arg, int SPDiff, unsigned ArgOffset, 4831 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4832 int Offset = ArgOffset + SPDiff; 4833 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4834 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4835 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4836 SDValue FIN = DAG.getFrameIndex(FI, VT); 4837 TailCallArgumentInfo Info; 4838 Info.Arg = Arg; 4839 Info.FrameIdxOp = FIN; 4840 Info.FrameIdx = FI; 4841 TailCallArguments.push_back(Info); 4842 } 4843 4844 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4845 /// stack slot. Returns the chain as result and the loaded frame pointers in 4846 /// LROpOut/FPOpout. Used when tail calling. 4847 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4848 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4849 SDValue &FPOpOut, const SDLoc &dl) const { 4850 if (SPDiff) { 4851 // Load the LR and FP stack slot for later adjusting. 4852 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4853 LROpOut = getReturnAddrFrameIndex(DAG); 4854 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4855 Chain = SDValue(LROpOut.getNode(), 1); 4856 4857 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4858 // slot as the FP is never overwritten. 4859 if (Subtarget.isDarwinABI()) { 4860 FPOpOut = getFramePointerFrameIndex(DAG); 4861 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4862 Chain = SDValue(FPOpOut.getNode(), 1); 4863 } 4864 } 4865 return Chain; 4866 } 4867 4868 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4869 /// by "Src" to address "Dst" of size "Size". Alignment information is 4870 /// specified by the specific parameter attribute. The copy will be passed as 4871 /// a byval function parameter. 4872 /// Sometimes what we are copying is the end of a larger object, the part that 4873 /// does not fit in registers. 4874 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4875 SDValue Chain, ISD::ArgFlagsTy Flags, 4876 SelectionDAG &DAG, const SDLoc &dl) { 4877 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4878 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4879 false, false, false, MachinePointerInfo(), 4880 MachinePointerInfo()); 4881 } 4882 4883 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4884 /// tail calls. 4885 static void LowerMemOpCallTo( 4886 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4887 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4888 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4889 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4890 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4891 if (!isTailCall) { 4892 if (isVector) { 4893 SDValue StackPtr; 4894 if (isPPC64) 4895 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4896 else 4897 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4898 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4899 DAG.getConstant(ArgOffset, dl, PtrVT)); 4900 } 4901 MemOpChains.push_back( 4902 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4903 // Calculate and remember argument location. 4904 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4905 TailCallArguments); 4906 } 4907 4908 static void 4909 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4910 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4911 SDValue FPOp, 4912 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4913 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4914 // might overwrite each other in case of tail call optimization. 4915 SmallVector<SDValue, 8> MemOpChains2; 4916 // Do not flag preceding copytoreg stuff together with the following stuff. 4917 InFlag = SDValue(); 4918 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4919 MemOpChains2, dl); 4920 if (!MemOpChains2.empty()) 4921 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4922 4923 // Store the return address to the appropriate stack slot. 4924 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4925 4926 // Emit callseq_end just before tailcall node. 4927 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4928 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4929 InFlag = Chain.getValue(1); 4930 } 4931 4932 // Is this global address that of a function that can be called by name? (as 4933 // opposed to something that must hold a descriptor for an indirect call). 4934 static bool isFunctionGlobalAddress(SDValue Callee) { 4935 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4936 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4937 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4938 return false; 4939 4940 return G->getGlobal()->getValueType()->isFunctionTy(); 4941 } 4942 4943 return false; 4944 } 4945 4946 static unsigned 4947 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4948 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4949 bool isPatchPoint, bool hasNest, 4950 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4951 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4952 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4953 bool isPPC64 = Subtarget.isPPC64(); 4954 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4955 bool is64BitELFv1ABI = isPPC64 && isSVR4ABI && !Subtarget.isELFv2ABI(); 4956 bool isAIXABI = Subtarget.isAIXABI(); 4957 4958 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4959 NodeTys.push_back(MVT::Other); // Returns a chain 4960 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4961 4962 unsigned CallOpc = PPCISD::CALL; 4963 4964 bool needIndirectCall = true; 4965 if (!isSVR4ABI || !isPPC64) 4966 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4967 // If this is an absolute destination address, use the munged value. 4968 Callee = SDValue(Dest, 0); 4969 needIndirectCall = false; 4970 } 4971 4972 // PC-relative references to external symbols should go through $stub, unless 4973 // we're building with the leopard linker or later, which automatically 4974 // synthesizes these stubs. 4975 const TargetMachine &TM = DAG.getTarget(); 4976 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4977 const GlobalValue *GV = nullptr; 4978 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4979 GV = G->getGlobal(); 4980 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4981 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4982 4983 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4984 // every direct call is) turn it into a TargetGlobalAddress / 4985 // TargetExternalSymbol node so that legalize doesn't hack it. 4986 if (isFunctionGlobalAddress(Callee)) { 4987 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4988 4989 // A call to a TLS address is actually an indirect call to a 4990 // thread-specific pointer. 4991 unsigned OpFlags = 0; 4992 if (UsePlt) 4993 OpFlags = PPCII::MO_PLT; 4994 4995 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4996 Callee.getValueType(), 0, OpFlags); 4997 needIndirectCall = false; 4998 } 4999 5000 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5001 unsigned char OpFlags = 0; 5002 5003 if (UsePlt) 5004 OpFlags = PPCII::MO_PLT; 5005 5006 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 5007 OpFlags); 5008 needIndirectCall = false; 5009 } 5010 5011 if (isPatchPoint) { 5012 // We'll form an invalid direct call when lowering a patchpoint; the full 5013 // sequence for an indirect call is complicated, and many of the 5014 // instructions introduced might have side effects (and, thus, can't be 5015 // removed later). The call itself will be removed as soon as the 5016 // argument/return lowering is complete, so the fact that it has the wrong 5017 // kind of operands should not really matter. 5018 needIndirectCall = false; 5019 } 5020 5021 if (needIndirectCall) { 5022 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 5023 // to do the call, we can't use PPCISD::CALL. 5024 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 5025 5026 if (is64BitELFv1ABI) { 5027 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5028 // entry point, but to the function descriptor (the function entry point 5029 // address is part of the function descriptor though). 5030 // The function descriptor is a three doubleword structure with the 5031 // following fields: function entry point, TOC base address and 5032 // environment pointer. 5033 // Thus for a call through a function pointer, the following actions need 5034 // to be performed: 5035 // 1. Save the TOC of the caller in the TOC save area of its stack 5036 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5037 // 2. Load the address of the function entry point from the function 5038 // descriptor. 5039 // 3. Load the TOC of the callee from the function descriptor into r2. 5040 // 4. Load the environment pointer from the function descriptor into 5041 // r11. 5042 // 5. Branch to the function entry point address. 5043 // 6. On return of the callee, the TOC of the caller needs to be 5044 // restored (this is done in FinishCall()). 5045 // 5046 // The loads are scheduled at the beginning of the call sequence, and the 5047 // register copies are flagged together to ensure that no other 5048 // operations can be scheduled in between. E.g. without flagging the 5049 // copies together, a TOC access in the caller could be scheduled between 5050 // the assignment of the callee TOC and the branch to the callee, which 5051 // results in the TOC access going through the TOC of the callee instead 5052 // of going through the TOC of the caller, which leads to incorrect code. 5053 5054 // Load the address of the function entry point from the function 5055 // descriptor. 5056 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 5057 if (LDChain.getValueType() == MVT::Glue) 5058 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 5059 5060 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5061 ? (MachineMemOperand::MODereferenceable | 5062 MachineMemOperand::MOInvariant) 5063 : MachineMemOperand::MONone; 5064 5065 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5066 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 5067 /* Alignment = */ 8, MMOFlags); 5068 5069 // Load environment pointer into r11. 5070 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 5071 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 5072 SDValue LoadEnvPtr = 5073 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 5074 /* Alignment = */ 8, MMOFlags); 5075 5076 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 5077 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 5078 SDValue TOCPtr = 5079 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 5080 /* Alignment = */ 8, MMOFlags); 5081 5082 setUsesTOCBasePtr(DAG); 5083 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 5084 InFlag); 5085 Chain = TOCVal.getValue(0); 5086 InFlag = TOCVal.getValue(1); 5087 5088 // If the function call has an explicit 'nest' parameter, it takes the 5089 // place of the environment pointer. 5090 if (!hasNest) { 5091 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 5092 InFlag); 5093 5094 Chain = EnvVal.getValue(0); 5095 InFlag = EnvVal.getValue(1); 5096 } 5097 5098 MTCTROps[0] = Chain; 5099 MTCTROps[1] = LoadFuncPtr; 5100 MTCTROps[2] = InFlag; 5101 } 5102 5103 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 5104 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 5105 InFlag = Chain.getValue(1); 5106 5107 NodeTys.clear(); 5108 NodeTys.push_back(MVT::Other); 5109 NodeTys.push_back(MVT::Glue); 5110 Ops.push_back(Chain); 5111 CallOpc = PPCISD::BCTRL; 5112 Callee.setNode(nullptr); 5113 // Add use of X11 (holding environment pointer) 5114 if (is64BitELFv1ABI && !hasNest) 5115 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 5116 // Add CTR register as callee so a bctr can be emitted later. 5117 if (isTailCall) 5118 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 5119 } 5120 5121 // If this is a direct call, pass the chain and the callee. 5122 if (Callee.getNode()) { 5123 Ops.push_back(Chain); 5124 Ops.push_back(Callee); 5125 } 5126 // If this is a tail call add stack pointer delta. 5127 if (isTailCall) 5128 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5129 5130 // Add argument registers to the end of the list so that they are known live 5131 // into the call. 5132 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5133 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5134 RegsToPass[i].second.getValueType())); 5135 5136 // All calls, in the AIX ABI and 64-bit ELF ABIs, need the TOC register 5137 // live into the call. 5138 // We do need to reserve R2/X2 to appease the verifier for the PATCHPOINT. 5139 if ((isSVR4ABI && isPPC64) || isAIXABI) { 5140 setUsesTOCBasePtr(DAG); 5141 5142 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5143 // no way to mark dependencies as implicit here. 5144 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5145 if (!isPatchPoint) 5146 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::X2 5147 : PPC::R2, PtrVT)); 5148 } 5149 5150 return CallOpc; 5151 } 5152 5153 SDValue PPCTargetLowering::LowerCallResult( 5154 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5155 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5156 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5157 SmallVector<CCValAssign, 16> RVLocs; 5158 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5159 *DAG.getContext()); 5160 5161 CCRetInfo.AnalyzeCallResult( 5162 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5163 ? RetCC_PPC_Cold 5164 : RetCC_PPC); 5165 5166 // Copy all of the result registers out of their specified physreg. 5167 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5168 CCValAssign &VA = RVLocs[i]; 5169 assert(VA.isRegLoc() && "Can only return in registers!"); 5170 5171 SDValue Val; 5172 5173 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5174 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5175 InFlag); 5176 Chain = Lo.getValue(1); 5177 InFlag = Lo.getValue(2); 5178 VA = RVLocs[++i]; // skip ahead to next loc 5179 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5180 InFlag); 5181 Chain = Hi.getValue(1); 5182 InFlag = Hi.getValue(2); 5183 if (!Subtarget.isLittleEndian()) 5184 std::swap (Lo, Hi); 5185 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5186 } else { 5187 Val = DAG.getCopyFromReg(Chain, dl, 5188 VA.getLocReg(), VA.getLocVT(), InFlag); 5189 Chain = Val.getValue(1); 5190 InFlag = Val.getValue(2); 5191 } 5192 5193 switch (VA.getLocInfo()) { 5194 default: llvm_unreachable("Unknown loc info!"); 5195 case CCValAssign::Full: break; 5196 case CCValAssign::AExt: 5197 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5198 break; 5199 case CCValAssign::ZExt: 5200 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5201 DAG.getValueType(VA.getValVT())); 5202 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5203 break; 5204 case CCValAssign::SExt: 5205 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5206 DAG.getValueType(VA.getValVT())); 5207 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5208 break; 5209 } 5210 5211 InVals.push_back(Val); 5212 } 5213 5214 return Chain; 5215 } 5216 5217 SDValue PPCTargetLowering::FinishCall( 5218 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5219 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5220 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 5221 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5222 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5223 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5224 std::vector<EVT> NodeTys; 5225 SmallVector<SDValue, 8> Ops; 5226 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 5227 SPDiff, isTailCall, isPatchPoint, hasNest, 5228 RegsToPass, Ops, NodeTys, CS, Subtarget); 5229 5230 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5231 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5232 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5233 5234 // When performing tail call optimization the callee pops its arguments off 5235 // the stack. Account for this here so these bytes can be pushed back on in 5236 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5237 int BytesCalleePops = 5238 (CallConv == CallingConv::Fast && 5239 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5240 5241 // Add a register mask operand representing the call-preserved registers. 5242 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5243 const uint32_t *Mask = 5244 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5245 assert(Mask && "Missing call preserved mask for calling convention"); 5246 Ops.push_back(DAG.getRegisterMask(Mask)); 5247 5248 if (InFlag.getNode()) 5249 Ops.push_back(InFlag); 5250 5251 // Emit tail call. 5252 if (isTailCall) { 5253 assert(((Callee.getOpcode() == ISD::Register && 5254 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5255 Callee.getOpcode() == ISD::TargetExternalSymbol || 5256 Callee.getOpcode() == ISD::TargetGlobalAddress || 5257 isa<ConstantSDNode>(Callee)) && 5258 "Expecting an global address, external symbol, absolute value or register"); 5259 5260 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5261 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5262 } 5263 5264 // Add a NOP immediately after the branch instruction when using the 64-bit 5265 // SVR4 or the AIX ABI. 5266 // At link time, if caller and callee are in a different module and 5267 // thus have a different TOC, the call will be replaced with a call to a stub 5268 // function which saves the current TOC, loads the TOC of the callee and 5269 // branches to the callee. The NOP will be replaced with a load instruction 5270 // which restores the TOC of the caller from the TOC save slot of the current 5271 // stack frame. If caller and callee belong to the same module (and have the 5272 // same TOC), the NOP will remain unchanged, or become some other NOP. 5273 5274 MachineFunction &MF = DAG.getMachineFunction(); 5275 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5276 if (!isTailCall && !isPatchPoint && 5277 ((Subtarget.isSVR4ABI() && Subtarget.isPPC64()) || 5278 Subtarget.isAIXABI())) { 5279 if (CallOpc == PPCISD::BCTRL) { 5280 if (Subtarget.isAIXABI()) 5281 report_fatal_error("Indirect call on AIX is not implemented."); 5282 5283 // This is a call through a function pointer. 5284 // Restore the caller TOC from the save area into R2. 5285 // See PrepareCall() for more information about calls through function 5286 // pointers in the 64-bit SVR4 ABI. 5287 // We are using a target-specific load with r2 hard coded, because the 5288 // result of a target-independent load would never go directly into r2, 5289 // since r2 is a reserved register (which prevents the register allocator 5290 // from allocating it), resulting in an additional register being 5291 // allocated and an unnecessary move instruction being generated. 5292 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5293 5294 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5295 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5296 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5297 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5298 5299 // The address needs to go after the chain input but before the flag (or 5300 // any other variadic arguments). 5301 Ops.insert(std::next(Ops.begin()), AddTOC); 5302 } else if (CallOpc == PPCISD::CALL && 5303 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5304 // Otherwise insert NOP for non-local calls. 5305 CallOpc = PPCISD::CALL_NOP; 5306 } 5307 } 5308 5309 if (Subtarget.isAIXABI() && isFunctionGlobalAddress(Callee)) { 5310 // On AIX, direct function calls reference the symbol for the function's 5311 // entry point, which is named by inserting a "." before the function's 5312 // C-linkage name. 5313 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5314 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5315 MCSymbol *S = Context.getOrCreateSymbol(Twine(".") + 5316 Twine(G->getGlobal()->getName())); 5317 Callee = DAG.getMCSymbol(S, PtrVT); 5318 // Replace the GlobalAddressSDNode Callee with the MCSymbolSDNode. 5319 Ops[1] = Callee; 5320 } 5321 5322 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5323 InFlag = Chain.getValue(1); 5324 5325 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5326 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5327 InFlag, dl); 5328 if (!Ins.empty()) 5329 InFlag = Chain.getValue(1); 5330 5331 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5332 Ins, dl, DAG, InVals); 5333 } 5334 5335 SDValue 5336 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5337 SmallVectorImpl<SDValue> &InVals) const { 5338 SelectionDAG &DAG = CLI.DAG; 5339 SDLoc &dl = CLI.DL; 5340 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5341 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5342 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5343 SDValue Chain = CLI.Chain; 5344 SDValue Callee = CLI.Callee; 5345 bool &isTailCall = CLI.IsTailCall; 5346 CallingConv::ID CallConv = CLI.CallConv; 5347 bool isVarArg = CLI.IsVarArg; 5348 bool isPatchPoint = CLI.IsPatchPoint; 5349 ImmutableCallSite CS = CLI.CS; 5350 5351 if (isTailCall) { 5352 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5353 isTailCall = false; 5354 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5355 isTailCall = 5356 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5357 isVarArg, Outs, Ins, DAG); 5358 else 5359 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5360 Ins, DAG); 5361 if (isTailCall) { 5362 ++NumTailCalls; 5363 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5364 ++NumSiblingCalls; 5365 5366 assert(isa<GlobalAddressSDNode>(Callee) && 5367 "Callee should be an llvm::Function object."); 5368 LLVM_DEBUG( 5369 const GlobalValue *GV = 5370 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5371 const unsigned Width = 5372 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5373 dbgs() << "TCO caller: " 5374 << left_justify(DAG.getMachineFunction().getName(), Width) 5375 << ", callee linkage: " << GV->getVisibility() << ", " 5376 << GV->getLinkage() << "\n"); 5377 } 5378 } 5379 5380 if (!isTailCall && CS && CS.isMustTailCall()) 5381 report_fatal_error("failed to perform tail call elimination on a call " 5382 "site marked musttail"); 5383 5384 // When long calls (i.e. indirect calls) are always used, calls are always 5385 // made via function pointer. If we have a function name, first translate it 5386 // into a pointer. 5387 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5388 !isTailCall) 5389 Callee = LowerGlobalAddress(Callee, DAG); 5390 5391 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5392 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5393 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5394 dl, DAG, InVals, CS); 5395 5396 if (Subtarget.isSVR4ABI()) 5397 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5398 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5399 dl, DAG, InVals, CS); 5400 5401 if (Subtarget.isAIXABI()) 5402 return LowerCall_AIX(Chain, Callee, CallConv, isVarArg, 5403 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5404 dl, DAG, InVals, CS); 5405 5406 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5407 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5408 dl, DAG, InVals, CS); 5409 } 5410 5411 SDValue PPCTargetLowering::LowerCall_32SVR4( 5412 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5413 bool isTailCall, bool isPatchPoint, 5414 const SmallVectorImpl<ISD::OutputArg> &Outs, 5415 const SmallVectorImpl<SDValue> &OutVals, 5416 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5417 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5418 ImmutableCallSite CS) const { 5419 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5420 // of the 32-bit SVR4 ABI stack frame layout. 5421 5422 assert((CallConv == CallingConv::C || 5423 CallConv == CallingConv::Cold || 5424 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5425 5426 unsigned PtrByteSize = 4; 5427 5428 MachineFunction &MF = DAG.getMachineFunction(); 5429 5430 // Mark this function as potentially containing a function that contains a 5431 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5432 // and restoring the callers stack pointer in this functions epilog. This is 5433 // done because by tail calling the called function might overwrite the value 5434 // in this function's (MF) stack pointer stack slot 0(SP). 5435 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5436 CallConv == CallingConv::Fast) 5437 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5438 5439 // Count how many bytes are to be pushed on the stack, including the linkage 5440 // area, parameter list area and the part of the local variable space which 5441 // contains copies of aggregates which are passed by value. 5442 5443 // Assign locations to all of the outgoing arguments. 5444 SmallVector<CCValAssign, 16> ArgLocs; 5445 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5446 5447 // Reserve space for the linkage area on the stack. 5448 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5449 PtrByteSize); 5450 if (useSoftFloat()) 5451 CCInfo.PreAnalyzeCallOperands(Outs); 5452 5453 if (isVarArg) { 5454 // Handle fixed and variable vector arguments differently. 5455 // Fixed vector arguments go into registers as long as registers are 5456 // available. Variable vector arguments always go into memory. 5457 unsigned NumArgs = Outs.size(); 5458 5459 for (unsigned i = 0; i != NumArgs; ++i) { 5460 MVT ArgVT = Outs[i].VT; 5461 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5462 bool Result; 5463 5464 if (Outs[i].IsFixed) { 5465 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5466 CCInfo); 5467 } else { 5468 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5469 ArgFlags, CCInfo); 5470 } 5471 5472 if (Result) { 5473 #ifndef NDEBUG 5474 errs() << "Call operand #" << i << " has unhandled type " 5475 << EVT(ArgVT).getEVTString() << "\n"; 5476 #endif 5477 llvm_unreachable(nullptr); 5478 } 5479 } 5480 } else { 5481 // All arguments are treated the same. 5482 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5483 } 5484 CCInfo.clearWasPPCF128(); 5485 5486 // Assign locations to all of the outgoing aggregate by value arguments. 5487 SmallVector<CCValAssign, 16> ByValArgLocs; 5488 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5489 5490 // Reserve stack space for the allocations in CCInfo. 5491 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5492 5493 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5494 5495 // Size of the linkage area, parameter list area and the part of the local 5496 // space variable where copies of aggregates which are passed by value are 5497 // stored. 5498 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5499 5500 // Calculate by how many bytes the stack has to be adjusted in case of tail 5501 // call optimization. 5502 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5503 5504 // Adjust the stack pointer for the new arguments... 5505 // These operations are automatically eliminated by the prolog/epilog pass 5506 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5507 SDValue CallSeqStart = Chain; 5508 5509 // Load the return address and frame pointer so it can be moved somewhere else 5510 // later. 5511 SDValue LROp, FPOp; 5512 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5513 5514 // Set up a copy of the stack pointer for use loading and storing any 5515 // arguments that may not fit in the registers available for argument 5516 // passing. 5517 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5518 5519 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5520 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5521 SmallVector<SDValue, 8> MemOpChains; 5522 5523 bool seenFloatArg = false; 5524 // Walk the register/memloc assignments, inserting copies/loads. 5525 // i - Tracks the index into the list of registers allocated for the call 5526 // RealArgIdx - Tracks the index into the list of actual function arguments 5527 // j - Tracks the index into the list of byval arguments 5528 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5529 i != e; 5530 ++i, ++RealArgIdx) { 5531 CCValAssign &VA = ArgLocs[i]; 5532 SDValue Arg = OutVals[RealArgIdx]; 5533 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5534 5535 if (Flags.isByVal()) { 5536 // Argument is an aggregate which is passed by value, thus we need to 5537 // create a copy of it in the local variable space of the current stack 5538 // frame (which is the stack frame of the caller) and pass the address of 5539 // this copy to the callee. 5540 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5541 CCValAssign &ByValVA = ByValArgLocs[j++]; 5542 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5543 5544 // Memory reserved in the local variable space of the callers stack frame. 5545 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5546 5547 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5548 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5549 StackPtr, PtrOff); 5550 5551 // Create a copy of the argument in the local area of the current 5552 // stack frame. 5553 SDValue MemcpyCall = 5554 CreateCopyOfByValArgument(Arg, PtrOff, 5555 CallSeqStart.getNode()->getOperand(0), 5556 Flags, DAG, dl); 5557 5558 // This must go outside the CALLSEQ_START..END. 5559 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5560 SDLoc(MemcpyCall)); 5561 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5562 NewCallSeqStart.getNode()); 5563 Chain = CallSeqStart = NewCallSeqStart; 5564 5565 // Pass the address of the aggregate copy on the stack either in a 5566 // physical register or in the parameter list area of the current stack 5567 // frame to the callee. 5568 Arg = PtrOff; 5569 } 5570 5571 // When useCRBits() is true, there can be i1 arguments. 5572 // It is because getRegisterType(MVT::i1) => MVT::i1, 5573 // and for other integer types getRegisterType() => MVT::i32. 5574 // Extend i1 and ensure callee will get i32. 5575 if (Arg.getValueType() == MVT::i1) 5576 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5577 dl, MVT::i32, Arg); 5578 5579 if (VA.isRegLoc()) { 5580 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5581 // Put argument in a physical register. 5582 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5583 bool IsLE = Subtarget.isLittleEndian(); 5584 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5585 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5586 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5587 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5588 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5589 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5590 SVal.getValue(0))); 5591 } else 5592 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5593 } else { 5594 // Put argument in the parameter list area of the current stack frame. 5595 assert(VA.isMemLoc()); 5596 unsigned LocMemOffset = VA.getLocMemOffset(); 5597 5598 if (!isTailCall) { 5599 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5600 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5601 StackPtr, PtrOff); 5602 5603 MemOpChains.push_back( 5604 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5605 } else { 5606 // Calculate and remember argument location. 5607 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5608 TailCallArguments); 5609 } 5610 } 5611 } 5612 5613 if (!MemOpChains.empty()) 5614 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5615 5616 // Build a sequence of copy-to-reg nodes chained together with token chain 5617 // and flag operands which copy the outgoing args into the appropriate regs. 5618 SDValue InFlag; 5619 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5620 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5621 RegsToPass[i].second, InFlag); 5622 InFlag = Chain.getValue(1); 5623 } 5624 5625 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5626 // registers. 5627 if (isVarArg) { 5628 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5629 SDValue Ops[] = { Chain, InFlag }; 5630 5631 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5632 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5633 5634 InFlag = Chain.getValue(1); 5635 } 5636 5637 if (isTailCall) 5638 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5639 TailCallArguments); 5640 5641 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5642 /* unused except on PPC64 ELFv1 */ false, DAG, 5643 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5644 NumBytes, Ins, InVals, CS); 5645 } 5646 5647 // Copy an argument into memory, being careful to do this outside the 5648 // call sequence for the call to which the argument belongs. 5649 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5650 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5651 SelectionDAG &DAG, const SDLoc &dl) const { 5652 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5653 CallSeqStart.getNode()->getOperand(0), 5654 Flags, DAG, dl); 5655 // The MEMCPY must go outside the CALLSEQ_START..END. 5656 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5657 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5658 SDLoc(MemcpyCall)); 5659 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5660 NewCallSeqStart.getNode()); 5661 return NewCallSeqStart; 5662 } 5663 5664 SDValue PPCTargetLowering::LowerCall_64SVR4( 5665 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5666 bool isTailCall, bool isPatchPoint, 5667 const SmallVectorImpl<ISD::OutputArg> &Outs, 5668 const SmallVectorImpl<SDValue> &OutVals, 5669 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5670 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5671 ImmutableCallSite CS) const { 5672 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5673 bool isLittleEndian = Subtarget.isLittleEndian(); 5674 unsigned NumOps = Outs.size(); 5675 bool hasNest = false; 5676 bool IsSibCall = false; 5677 5678 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5679 unsigned PtrByteSize = 8; 5680 5681 MachineFunction &MF = DAG.getMachineFunction(); 5682 5683 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5684 IsSibCall = true; 5685 5686 // Mark this function as potentially containing a function that contains a 5687 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5688 // and restoring the callers stack pointer in this functions epilog. This is 5689 // done because by tail calling the called function might overwrite the value 5690 // in this function's (MF) stack pointer stack slot 0(SP). 5691 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5692 CallConv == CallingConv::Fast) 5693 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5694 5695 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5696 "fastcc not supported on varargs functions"); 5697 5698 // Count how many bytes are to be pushed on the stack, including the linkage 5699 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5700 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5701 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5702 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5703 unsigned NumBytes = LinkageSize; 5704 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5705 unsigned &QFPR_idx = FPR_idx; 5706 5707 static const MCPhysReg GPR[] = { 5708 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5709 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5710 }; 5711 static const MCPhysReg VR[] = { 5712 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5713 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5714 }; 5715 5716 const unsigned NumGPRs = array_lengthof(GPR); 5717 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5718 const unsigned NumVRs = array_lengthof(VR); 5719 const unsigned NumQFPRs = NumFPRs; 5720 5721 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5722 // can be passed to the callee in registers. 5723 // For the fast calling convention, there is another check below. 5724 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5725 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5726 if (!HasParameterArea) { 5727 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5728 unsigned AvailableFPRs = NumFPRs; 5729 unsigned AvailableVRs = NumVRs; 5730 unsigned NumBytesTmp = NumBytes; 5731 for (unsigned i = 0; i != NumOps; ++i) { 5732 if (Outs[i].Flags.isNest()) continue; 5733 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5734 PtrByteSize, LinkageSize, ParamAreaSize, 5735 NumBytesTmp, AvailableFPRs, AvailableVRs, 5736 Subtarget.hasQPX())) 5737 HasParameterArea = true; 5738 } 5739 } 5740 5741 // When using the fast calling convention, we don't provide backing for 5742 // arguments that will be in registers. 5743 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5744 5745 // Avoid allocating parameter area for fastcc functions if all the arguments 5746 // can be passed in the registers. 5747 if (CallConv == CallingConv::Fast) 5748 HasParameterArea = false; 5749 5750 // Add up all the space actually used. 5751 for (unsigned i = 0; i != NumOps; ++i) { 5752 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5753 EVT ArgVT = Outs[i].VT; 5754 EVT OrigVT = Outs[i].ArgVT; 5755 5756 if (Flags.isNest()) 5757 continue; 5758 5759 if (CallConv == CallingConv::Fast) { 5760 if (Flags.isByVal()) { 5761 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5762 if (NumGPRsUsed > NumGPRs) 5763 HasParameterArea = true; 5764 } else { 5765 switch (ArgVT.getSimpleVT().SimpleTy) { 5766 default: llvm_unreachable("Unexpected ValueType for argument!"); 5767 case MVT::i1: 5768 case MVT::i32: 5769 case MVT::i64: 5770 if (++NumGPRsUsed <= NumGPRs) 5771 continue; 5772 break; 5773 case MVT::v4i32: 5774 case MVT::v8i16: 5775 case MVT::v16i8: 5776 case MVT::v2f64: 5777 case MVT::v2i64: 5778 case MVT::v1i128: 5779 case MVT::f128: 5780 if (++NumVRsUsed <= NumVRs) 5781 continue; 5782 break; 5783 case MVT::v4f32: 5784 // When using QPX, this is handled like a FP register, otherwise, it 5785 // is an Altivec register. 5786 if (Subtarget.hasQPX()) { 5787 if (++NumFPRsUsed <= NumFPRs) 5788 continue; 5789 } else { 5790 if (++NumVRsUsed <= NumVRs) 5791 continue; 5792 } 5793 break; 5794 case MVT::f32: 5795 case MVT::f64: 5796 case MVT::v4f64: // QPX 5797 case MVT::v4i1: // QPX 5798 if (++NumFPRsUsed <= NumFPRs) 5799 continue; 5800 break; 5801 } 5802 HasParameterArea = true; 5803 } 5804 } 5805 5806 /* Respect alignment of argument on the stack. */ 5807 unsigned Align = 5808 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5809 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5810 5811 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5812 if (Flags.isInConsecutiveRegsLast()) 5813 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5814 } 5815 5816 unsigned NumBytesActuallyUsed = NumBytes; 5817 5818 // In the old ELFv1 ABI, 5819 // the prolog code of the callee may store up to 8 GPR argument registers to 5820 // the stack, allowing va_start to index over them in memory if its varargs. 5821 // Because we cannot tell if this is needed on the caller side, we have to 5822 // conservatively assume that it is needed. As such, make sure we have at 5823 // least enough stack space for the caller to store the 8 GPRs. 5824 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5825 // really requires memory operands, e.g. a vararg function. 5826 if (HasParameterArea) 5827 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5828 else 5829 NumBytes = LinkageSize; 5830 5831 // Tail call needs the stack to be aligned. 5832 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5833 CallConv == CallingConv::Fast) 5834 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5835 5836 int SPDiff = 0; 5837 5838 // Calculate by how many bytes the stack has to be adjusted in case of tail 5839 // call optimization. 5840 if (!IsSibCall) 5841 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5842 5843 // To protect arguments on the stack from being clobbered in a tail call, 5844 // force all the loads to happen before doing any other lowering. 5845 if (isTailCall) 5846 Chain = DAG.getStackArgumentTokenFactor(Chain); 5847 5848 // Adjust the stack pointer for the new arguments... 5849 // These operations are automatically eliminated by the prolog/epilog pass 5850 if (!IsSibCall) 5851 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5852 SDValue CallSeqStart = Chain; 5853 5854 // Load the return address and frame pointer so it can be move somewhere else 5855 // later. 5856 SDValue LROp, FPOp; 5857 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5858 5859 // Set up a copy of the stack pointer for use loading and storing any 5860 // arguments that may not fit in the registers available for argument 5861 // passing. 5862 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5863 5864 // Figure out which arguments are going to go in registers, and which in 5865 // memory. Also, if this is a vararg function, floating point operations 5866 // must be stored to our stack, and loaded into integer regs as well, if 5867 // any integer regs are available for argument passing. 5868 unsigned ArgOffset = LinkageSize; 5869 5870 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5871 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5872 5873 SmallVector<SDValue, 8> MemOpChains; 5874 for (unsigned i = 0; i != NumOps; ++i) { 5875 SDValue Arg = OutVals[i]; 5876 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5877 EVT ArgVT = Outs[i].VT; 5878 EVT OrigVT = Outs[i].ArgVT; 5879 5880 // PtrOff will be used to store the current argument to the stack if a 5881 // register cannot be found for it. 5882 SDValue PtrOff; 5883 5884 // We re-align the argument offset for each argument, except when using the 5885 // fast calling convention, when we need to make sure we do that only when 5886 // we'll actually use a stack slot. 5887 auto ComputePtrOff = [&]() { 5888 /* Respect alignment of argument on the stack. */ 5889 unsigned Align = 5890 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5891 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5892 5893 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5894 5895 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5896 }; 5897 5898 if (CallConv != CallingConv::Fast) { 5899 ComputePtrOff(); 5900 5901 /* Compute GPR index associated with argument offset. */ 5902 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5903 GPR_idx = std::min(GPR_idx, NumGPRs); 5904 } 5905 5906 // Promote integers to 64-bit values. 5907 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5908 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5909 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5910 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5911 } 5912 5913 // FIXME memcpy is used way more than necessary. Correctness first. 5914 // Note: "by value" is code for passing a structure by value, not 5915 // basic types. 5916 if (Flags.isByVal()) { 5917 // Note: Size includes alignment padding, so 5918 // struct x { short a; char b; } 5919 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5920 // These are the proper values we need for right-justifying the 5921 // aggregate in a parameter register. 5922 unsigned Size = Flags.getByValSize(); 5923 5924 // An empty aggregate parameter takes up no storage and no 5925 // registers. 5926 if (Size == 0) 5927 continue; 5928 5929 if (CallConv == CallingConv::Fast) 5930 ComputePtrOff(); 5931 5932 // All aggregates smaller than 8 bytes must be passed right-justified. 5933 if (Size==1 || Size==2 || Size==4) { 5934 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5935 if (GPR_idx != NumGPRs) { 5936 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5937 MachinePointerInfo(), VT); 5938 MemOpChains.push_back(Load.getValue(1)); 5939 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5940 5941 ArgOffset += PtrByteSize; 5942 continue; 5943 } 5944 } 5945 5946 if (GPR_idx == NumGPRs && Size < 8) { 5947 SDValue AddPtr = PtrOff; 5948 if (!isLittleEndian) { 5949 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5950 PtrOff.getValueType()); 5951 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5952 } 5953 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5954 CallSeqStart, 5955 Flags, DAG, dl); 5956 ArgOffset += PtrByteSize; 5957 continue; 5958 } 5959 // Copy entire object into memory. There are cases where gcc-generated 5960 // code assumes it is there, even if it could be put entirely into 5961 // registers. (This is not what the doc says.) 5962 5963 // FIXME: The above statement is likely due to a misunderstanding of the 5964 // documents. All arguments must be copied into the parameter area BY 5965 // THE CALLEE in the event that the callee takes the address of any 5966 // formal argument. That has not yet been implemented. However, it is 5967 // reasonable to use the stack area as a staging area for the register 5968 // load. 5969 5970 // Skip this for small aggregates, as we will use the same slot for a 5971 // right-justified copy, below. 5972 if (Size >= 8) 5973 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5974 CallSeqStart, 5975 Flags, DAG, dl); 5976 5977 // When a register is available, pass a small aggregate right-justified. 5978 if (Size < 8 && GPR_idx != NumGPRs) { 5979 // The easiest way to get this right-justified in a register 5980 // is to copy the structure into the rightmost portion of a 5981 // local variable slot, then load the whole slot into the 5982 // register. 5983 // FIXME: The memcpy seems to produce pretty awful code for 5984 // small aggregates, particularly for packed ones. 5985 // FIXME: It would be preferable to use the slot in the 5986 // parameter save area instead of a new local variable. 5987 SDValue AddPtr = PtrOff; 5988 if (!isLittleEndian) { 5989 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5990 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5991 } 5992 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5993 CallSeqStart, 5994 Flags, DAG, dl); 5995 5996 // Load the slot into the register. 5997 SDValue Load = 5998 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5999 MemOpChains.push_back(Load.getValue(1)); 6000 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6001 6002 // Done with this argument. 6003 ArgOffset += PtrByteSize; 6004 continue; 6005 } 6006 6007 // For aggregates larger than PtrByteSize, copy the pieces of the 6008 // object that fit into registers from the parameter save area. 6009 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6010 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6011 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6012 if (GPR_idx != NumGPRs) { 6013 SDValue Load = 6014 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6015 MemOpChains.push_back(Load.getValue(1)); 6016 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6017 ArgOffset += PtrByteSize; 6018 } else { 6019 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6020 break; 6021 } 6022 } 6023 continue; 6024 } 6025 6026 switch (Arg.getSimpleValueType().SimpleTy) { 6027 default: llvm_unreachable("Unexpected ValueType for argument!"); 6028 case MVT::i1: 6029 case MVT::i32: 6030 case MVT::i64: 6031 if (Flags.isNest()) { 6032 // The 'nest' parameter, if any, is passed in R11. 6033 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6034 hasNest = true; 6035 break; 6036 } 6037 6038 // These can be scalar arguments or elements of an integer array type 6039 // passed directly. Clang may use those instead of "byval" aggregate 6040 // types to avoid forcing arguments to memory unnecessarily. 6041 if (GPR_idx != NumGPRs) { 6042 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6043 } else { 6044 if (CallConv == CallingConv::Fast) 6045 ComputePtrOff(); 6046 6047 assert(HasParameterArea && 6048 "Parameter area must exist to pass an argument in memory."); 6049 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6050 true, isTailCall, false, MemOpChains, 6051 TailCallArguments, dl); 6052 if (CallConv == CallingConv::Fast) 6053 ArgOffset += PtrByteSize; 6054 } 6055 if (CallConv != CallingConv::Fast) 6056 ArgOffset += PtrByteSize; 6057 break; 6058 case MVT::f32: 6059 case MVT::f64: { 6060 // These can be scalar arguments or elements of a float array type 6061 // passed directly. The latter are used to implement ELFv2 homogenous 6062 // float aggregates. 6063 6064 // Named arguments go into FPRs first, and once they overflow, the 6065 // remaining arguments go into GPRs and then the parameter save area. 6066 // Unnamed arguments for vararg functions always go to GPRs and 6067 // then the parameter save area. For now, put all arguments to vararg 6068 // routines always in both locations (FPR *and* GPR or stack slot). 6069 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 6070 bool NeededLoad = false; 6071 6072 // First load the argument into the next available FPR. 6073 if (FPR_idx != NumFPRs) 6074 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6075 6076 // Next, load the argument into GPR or stack slot if needed. 6077 if (!NeedGPROrStack) 6078 ; 6079 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 6080 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6081 // once we support fp <-> gpr moves. 6082 6083 // In the non-vararg case, this can only ever happen in the 6084 // presence of f32 array types, since otherwise we never run 6085 // out of FPRs before running out of GPRs. 6086 SDValue ArgVal; 6087 6088 // Double values are always passed in a single GPR. 6089 if (Arg.getValueType() != MVT::f32) { 6090 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6091 6092 // Non-array float values are extended and passed in a GPR. 6093 } else if (!Flags.isInConsecutiveRegs()) { 6094 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6095 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6096 6097 // If we have an array of floats, we collect every odd element 6098 // together with its predecessor into one GPR. 6099 } else if (ArgOffset % PtrByteSize != 0) { 6100 SDValue Lo, Hi; 6101 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6102 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6103 if (!isLittleEndian) 6104 std::swap(Lo, Hi); 6105 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6106 6107 // The final element, if even, goes into the first half of a GPR. 6108 } else if (Flags.isInConsecutiveRegsLast()) { 6109 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6110 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6111 if (!isLittleEndian) 6112 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6113 DAG.getConstant(32, dl, MVT::i32)); 6114 6115 // Non-final even elements are skipped; they will be handled 6116 // together the with subsequent argument on the next go-around. 6117 } else 6118 ArgVal = SDValue(); 6119 6120 if (ArgVal.getNode()) 6121 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6122 } else { 6123 if (CallConv == CallingConv::Fast) 6124 ComputePtrOff(); 6125 6126 // Single-precision floating-point values are mapped to the 6127 // second (rightmost) word of the stack doubleword. 6128 if (Arg.getValueType() == MVT::f32 && 6129 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6130 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6131 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6132 } 6133 6134 assert(HasParameterArea && 6135 "Parameter area must exist to pass an argument in memory."); 6136 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6137 true, isTailCall, false, MemOpChains, 6138 TailCallArguments, dl); 6139 6140 NeededLoad = true; 6141 } 6142 // When passing an array of floats, the array occupies consecutive 6143 // space in the argument area; only round up to the next doubleword 6144 // at the end of the array. Otherwise, each float takes 8 bytes. 6145 if (CallConv != CallingConv::Fast || NeededLoad) { 6146 ArgOffset += (Arg.getValueType() == MVT::f32 && 6147 Flags.isInConsecutiveRegs()) ? 4 : 8; 6148 if (Flags.isInConsecutiveRegsLast()) 6149 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6150 } 6151 break; 6152 } 6153 case MVT::v4f32: 6154 case MVT::v4i32: 6155 case MVT::v8i16: 6156 case MVT::v16i8: 6157 case MVT::v2f64: 6158 case MVT::v2i64: 6159 case MVT::v1i128: 6160 case MVT::f128: 6161 if (!Subtarget.hasQPX()) { 6162 // These can be scalar arguments or elements of a vector array type 6163 // passed directly. The latter are used to implement ELFv2 homogenous 6164 // vector aggregates. 6165 6166 // For a varargs call, named arguments go into VRs or on the stack as 6167 // usual; unnamed arguments always go to the stack or the corresponding 6168 // GPRs when within range. For now, we always put the value in both 6169 // locations (or even all three). 6170 if (isVarArg) { 6171 assert(HasParameterArea && 6172 "Parameter area must exist if we have a varargs call."); 6173 // We could elide this store in the case where the object fits 6174 // entirely in R registers. Maybe later. 6175 SDValue Store = 6176 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6177 MemOpChains.push_back(Store); 6178 if (VR_idx != NumVRs) { 6179 SDValue Load = 6180 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6181 MemOpChains.push_back(Load.getValue(1)); 6182 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6183 } 6184 ArgOffset += 16; 6185 for (unsigned i=0; i<16; i+=PtrByteSize) { 6186 if (GPR_idx == NumGPRs) 6187 break; 6188 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6189 DAG.getConstant(i, dl, PtrVT)); 6190 SDValue Load = 6191 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6192 MemOpChains.push_back(Load.getValue(1)); 6193 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6194 } 6195 break; 6196 } 6197 6198 // Non-varargs Altivec params go into VRs or on the stack. 6199 if (VR_idx != NumVRs) { 6200 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6201 } else { 6202 if (CallConv == CallingConv::Fast) 6203 ComputePtrOff(); 6204 6205 assert(HasParameterArea && 6206 "Parameter area must exist to pass an argument in memory."); 6207 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6208 true, isTailCall, true, MemOpChains, 6209 TailCallArguments, dl); 6210 if (CallConv == CallingConv::Fast) 6211 ArgOffset += 16; 6212 } 6213 6214 if (CallConv != CallingConv::Fast) 6215 ArgOffset += 16; 6216 break; 6217 } // not QPX 6218 6219 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6220 "Invalid QPX parameter type"); 6221 6222 LLVM_FALLTHROUGH; 6223 case MVT::v4f64: 6224 case MVT::v4i1: { 6225 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6226 if (isVarArg) { 6227 assert(HasParameterArea && 6228 "Parameter area must exist if we have a varargs call."); 6229 // We could elide this store in the case where the object fits 6230 // entirely in R registers. Maybe later. 6231 SDValue Store = 6232 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6233 MemOpChains.push_back(Store); 6234 if (QFPR_idx != NumQFPRs) { 6235 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6236 PtrOff, MachinePointerInfo()); 6237 MemOpChains.push_back(Load.getValue(1)); 6238 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6239 } 6240 ArgOffset += (IsF32 ? 16 : 32); 6241 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6242 if (GPR_idx == NumGPRs) 6243 break; 6244 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6245 DAG.getConstant(i, dl, PtrVT)); 6246 SDValue Load = 6247 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6248 MemOpChains.push_back(Load.getValue(1)); 6249 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6250 } 6251 break; 6252 } 6253 6254 // Non-varargs QPX params go into registers or on the stack. 6255 if (QFPR_idx != NumQFPRs) { 6256 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6257 } else { 6258 if (CallConv == CallingConv::Fast) 6259 ComputePtrOff(); 6260 6261 assert(HasParameterArea && 6262 "Parameter area must exist to pass an argument in memory."); 6263 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6264 true, isTailCall, true, MemOpChains, 6265 TailCallArguments, dl); 6266 if (CallConv == CallingConv::Fast) 6267 ArgOffset += (IsF32 ? 16 : 32); 6268 } 6269 6270 if (CallConv != CallingConv::Fast) 6271 ArgOffset += (IsF32 ? 16 : 32); 6272 break; 6273 } 6274 } 6275 } 6276 6277 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6278 "mismatch in size of parameter area"); 6279 (void)NumBytesActuallyUsed; 6280 6281 if (!MemOpChains.empty()) 6282 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6283 6284 // Check if this is an indirect call (MTCTR/BCTRL). 6285 // See PrepareCall() for more information about calls through function 6286 // pointers in the 64-bit SVR4 ABI. 6287 if (!isTailCall && !isPatchPoint && 6288 !isFunctionGlobalAddress(Callee) && 6289 !isa<ExternalSymbolSDNode>(Callee)) { 6290 // Load r2 into a virtual register and store it to the TOC save area. 6291 setUsesTOCBasePtr(DAG); 6292 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6293 // TOC save area offset. 6294 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6295 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6296 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6297 Chain = DAG.getStore( 6298 Val.getValue(1), dl, Val, AddPtr, 6299 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6300 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6301 // This does not mean the MTCTR instruction must use R12; it's easier 6302 // to model this as an extra parameter, so do that. 6303 if (isELFv2ABI && !isPatchPoint) 6304 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6305 } 6306 6307 // Build a sequence of copy-to-reg nodes chained together with token chain 6308 // and flag operands which copy the outgoing args into the appropriate regs. 6309 SDValue InFlag; 6310 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6311 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6312 RegsToPass[i].second, InFlag); 6313 InFlag = Chain.getValue(1); 6314 } 6315 6316 if (isTailCall && !IsSibCall) 6317 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6318 TailCallArguments); 6319 6320 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6321 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6322 SPDiff, NumBytes, Ins, InVals, CS); 6323 } 6324 6325 SDValue PPCTargetLowering::LowerCall_Darwin( 6326 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6327 bool isTailCall, bool isPatchPoint, 6328 const SmallVectorImpl<ISD::OutputArg> &Outs, 6329 const SmallVectorImpl<SDValue> &OutVals, 6330 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6331 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6332 ImmutableCallSite CS) const { 6333 unsigned NumOps = Outs.size(); 6334 6335 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6336 bool isPPC64 = PtrVT == MVT::i64; 6337 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6338 6339 MachineFunction &MF = DAG.getMachineFunction(); 6340 6341 // Mark this function as potentially containing a function that contains a 6342 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6343 // and restoring the callers stack pointer in this functions epilog. This is 6344 // done because by tail calling the called function might overwrite the value 6345 // in this function's (MF) stack pointer stack slot 0(SP). 6346 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6347 CallConv == CallingConv::Fast) 6348 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6349 6350 // Count how many bytes are to be pushed on the stack, including the linkage 6351 // area, and parameter passing area. We start with 24/48 bytes, which is 6352 // prereserved space for [SP][CR][LR][3 x unused]. 6353 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6354 unsigned NumBytes = LinkageSize; 6355 6356 // Add up all the space actually used. 6357 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6358 // they all go in registers, but we must reserve stack space for them for 6359 // possible use by the caller. In varargs or 64-bit calls, parameters are 6360 // assigned stack space in order, with padding so Altivec parameters are 6361 // 16-byte aligned. 6362 unsigned nAltivecParamsAtEnd = 0; 6363 for (unsigned i = 0; i != NumOps; ++i) { 6364 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6365 EVT ArgVT = Outs[i].VT; 6366 // Varargs Altivec parameters are padded to a 16 byte boundary. 6367 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6368 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6369 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6370 if (!isVarArg && !isPPC64) { 6371 // Non-varargs Altivec parameters go after all the non-Altivec 6372 // parameters; handle those later so we know how much padding we need. 6373 nAltivecParamsAtEnd++; 6374 continue; 6375 } 6376 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6377 NumBytes = ((NumBytes+15)/16)*16; 6378 } 6379 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6380 } 6381 6382 // Allow for Altivec parameters at the end, if needed. 6383 if (nAltivecParamsAtEnd) { 6384 NumBytes = ((NumBytes+15)/16)*16; 6385 NumBytes += 16*nAltivecParamsAtEnd; 6386 } 6387 6388 // The prolog code of the callee may store up to 8 GPR argument registers to 6389 // the stack, allowing va_start to index over them in memory if its varargs. 6390 // Because we cannot tell if this is needed on the caller side, we have to 6391 // conservatively assume that it is needed. As such, make sure we have at 6392 // least enough stack space for the caller to store the 8 GPRs. 6393 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6394 6395 // Tail call needs the stack to be aligned. 6396 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6397 CallConv == CallingConv::Fast) 6398 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6399 6400 // Calculate by how many bytes the stack has to be adjusted in case of tail 6401 // call optimization. 6402 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6403 6404 // To protect arguments on the stack from being clobbered in a tail call, 6405 // force all the loads to happen before doing any other lowering. 6406 if (isTailCall) 6407 Chain = DAG.getStackArgumentTokenFactor(Chain); 6408 6409 // Adjust the stack pointer for the new arguments... 6410 // These operations are automatically eliminated by the prolog/epilog pass 6411 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6412 SDValue CallSeqStart = Chain; 6413 6414 // Load the return address and frame pointer so it can be move somewhere else 6415 // later. 6416 SDValue LROp, FPOp; 6417 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6418 6419 // Set up a copy of the stack pointer for use loading and storing any 6420 // arguments that may not fit in the registers available for argument 6421 // passing. 6422 SDValue StackPtr; 6423 if (isPPC64) 6424 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6425 else 6426 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6427 6428 // Figure out which arguments are going to go in registers, and which in 6429 // memory. Also, if this is a vararg function, floating point operations 6430 // must be stored to our stack, and loaded into integer regs as well, if 6431 // any integer regs are available for argument passing. 6432 unsigned ArgOffset = LinkageSize; 6433 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6434 6435 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6436 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6437 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6438 }; 6439 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6440 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6441 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6442 }; 6443 static const MCPhysReg VR[] = { 6444 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6445 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6446 }; 6447 const unsigned NumGPRs = array_lengthof(GPR_32); 6448 const unsigned NumFPRs = 13; 6449 const unsigned NumVRs = array_lengthof(VR); 6450 6451 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6452 6453 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6454 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6455 6456 SmallVector<SDValue, 8> MemOpChains; 6457 for (unsigned i = 0; i != NumOps; ++i) { 6458 SDValue Arg = OutVals[i]; 6459 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6460 6461 // PtrOff will be used to store the current argument to the stack if a 6462 // register cannot be found for it. 6463 SDValue PtrOff; 6464 6465 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6466 6467 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6468 6469 // On PPC64, promote integers to 64-bit values. 6470 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6471 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6472 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6473 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6474 } 6475 6476 // FIXME memcpy is used way more than necessary. Correctness first. 6477 // Note: "by value" is code for passing a structure by value, not 6478 // basic types. 6479 if (Flags.isByVal()) { 6480 unsigned Size = Flags.getByValSize(); 6481 // Very small objects are passed right-justified. Everything else is 6482 // passed left-justified. 6483 if (Size==1 || Size==2) { 6484 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6485 if (GPR_idx != NumGPRs) { 6486 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6487 MachinePointerInfo(), VT); 6488 MemOpChains.push_back(Load.getValue(1)); 6489 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6490 6491 ArgOffset += PtrByteSize; 6492 } else { 6493 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6494 PtrOff.getValueType()); 6495 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6496 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6497 CallSeqStart, 6498 Flags, DAG, dl); 6499 ArgOffset += PtrByteSize; 6500 } 6501 continue; 6502 } 6503 // Copy entire object into memory. There are cases where gcc-generated 6504 // code assumes it is there, even if it could be put entirely into 6505 // registers. (This is not what the doc says.) 6506 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6507 CallSeqStart, 6508 Flags, DAG, dl); 6509 6510 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6511 // copy the pieces of the object that fit into registers from the 6512 // parameter save area. 6513 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6514 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6515 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6516 if (GPR_idx != NumGPRs) { 6517 SDValue Load = 6518 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6519 MemOpChains.push_back(Load.getValue(1)); 6520 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6521 ArgOffset += PtrByteSize; 6522 } else { 6523 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6524 break; 6525 } 6526 } 6527 continue; 6528 } 6529 6530 switch (Arg.getSimpleValueType().SimpleTy) { 6531 default: llvm_unreachable("Unexpected ValueType for argument!"); 6532 case MVT::i1: 6533 case MVT::i32: 6534 case MVT::i64: 6535 if (GPR_idx != NumGPRs) { 6536 if (Arg.getValueType() == MVT::i1) 6537 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6538 6539 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6540 } else { 6541 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6542 isPPC64, isTailCall, false, MemOpChains, 6543 TailCallArguments, dl); 6544 } 6545 ArgOffset += PtrByteSize; 6546 break; 6547 case MVT::f32: 6548 case MVT::f64: 6549 if (FPR_idx != NumFPRs) { 6550 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6551 6552 if (isVarArg) { 6553 SDValue Store = 6554 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6555 MemOpChains.push_back(Store); 6556 6557 // Float varargs are always shadowed in available integer registers 6558 if (GPR_idx != NumGPRs) { 6559 SDValue Load = 6560 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6561 MemOpChains.push_back(Load.getValue(1)); 6562 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6563 } 6564 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6565 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6566 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6567 SDValue Load = 6568 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6569 MemOpChains.push_back(Load.getValue(1)); 6570 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6571 } 6572 } else { 6573 // If we have any FPRs remaining, we may also have GPRs remaining. 6574 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6575 // GPRs. 6576 if (GPR_idx != NumGPRs) 6577 ++GPR_idx; 6578 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6579 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6580 ++GPR_idx; 6581 } 6582 } else 6583 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6584 isPPC64, isTailCall, false, MemOpChains, 6585 TailCallArguments, dl); 6586 if (isPPC64) 6587 ArgOffset += 8; 6588 else 6589 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6590 break; 6591 case MVT::v4f32: 6592 case MVT::v4i32: 6593 case MVT::v8i16: 6594 case MVT::v16i8: 6595 if (isVarArg) { 6596 // These go aligned on the stack, or in the corresponding R registers 6597 // when within range. The Darwin PPC ABI doc claims they also go in 6598 // V registers; in fact gcc does this only for arguments that are 6599 // prototyped, not for those that match the ... We do it for all 6600 // arguments, seems to work. 6601 while (ArgOffset % 16 !=0) { 6602 ArgOffset += PtrByteSize; 6603 if (GPR_idx != NumGPRs) 6604 GPR_idx++; 6605 } 6606 // We could elide this store in the case where the object fits 6607 // entirely in R registers. Maybe later. 6608 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6609 DAG.getConstant(ArgOffset, dl, PtrVT)); 6610 SDValue Store = 6611 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6612 MemOpChains.push_back(Store); 6613 if (VR_idx != NumVRs) { 6614 SDValue Load = 6615 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6616 MemOpChains.push_back(Load.getValue(1)); 6617 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6618 } 6619 ArgOffset += 16; 6620 for (unsigned i=0; i<16; i+=PtrByteSize) { 6621 if (GPR_idx == NumGPRs) 6622 break; 6623 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6624 DAG.getConstant(i, dl, PtrVT)); 6625 SDValue Load = 6626 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6627 MemOpChains.push_back(Load.getValue(1)); 6628 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6629 } 6630 break; 6631 } 6632 6633 // Non-varargs Altivec params generally go in registers, but have 6634 // stack space allocated at the end. 6635 if (VR_idx != NumVRs) { 6636 // Doesn't have GPR space allocated. 6637 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6638 } else if (nAltivecParamsAtEnd==0) { 6639 // We are emitting Altivec params in order. 6640 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6641 isPPC64, isTailCall, true, MemOpChains, 6642 TailCallArguments, dl); 6643 ArgOffset += 16; 6644 } 6645 break; 6646 } 6647 } 6648 // If all Altivec parameters fit in registers, as they usually do, 6649 // they get stack space following the non-Altivec parameters. We 6650 // don't track this here because nobody below needs it. 6651 // If there are more Altivec parameters than fit in registers emit 6652 // the stores here. 6653 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6654 unsigned j = 0; 6655 // Offset is aligned; skip 1st 12 params which go in V registers. 6656 ArgOffset = ((ArgOffset+15)/16)*16; 6657 ArgOffset += 12*16; 6658 for (unsigned i = 0; i != NumOps; ++i) { 6659 SDValue Arg = OutVals[i]; 6660 EVT ArgType = Outs[i].VT; 6661 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6662 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6663 if (++j > NumVRs) { 6664 SDValue PtrOff; 6665 // We are emitting Altivec params in order. 6666 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6667 isPPC64, isTailCall, true, MemOpChains, 6668 TailCallArguments, dl); 6669 ArgOffset += 16; 6670 } 6671 } 6672 } 6673 } 6674 6675 if (!MemOpChains.empty()) 6676 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6677 6678 // On Darwin, R12 must contain the address of an indirect callee. This does 6679 // not mean the MTCTR instruction must use R12; it's easier to model this as 6680 // an extra parameter, so do that. 6681 if (!isTailCall && 6682 !isFunctionGlobalAddress(Callee) && 6683 !isa<ExternalSymbolSDNode>(Callee) && 6684 !isBLACompatibleAddress(Callee, DAG)) 6685 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6686 PPC::R12), Callee)); 6687 6688 // Build a sequence of copy-to-reg nodes chained together with token chain 6689 // and flag operands which copy the outgoing args into the appropriate regs. 6690 SDValue InFlag; 6691 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6692 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6693 RegsToPass[i].second, InFlag); 6694 InFlag = Chain.getValue(1); 6695 } 6696 6697 if (isTailCall) 6698 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6699 TailCallArguments); 6700 6701 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6702 /* unused except on PPC64 ELFv1 */ false, DAG, 6703 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6704 NumBytes, Ins, InVals, CS); 6705 } 6706 6707 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6708 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6709 CCState &State) { 6710 6711 if (ValVT == MVT::f128) 6712 report_fatal_error("f128 is unimplemented on AIX."); 6713 6714 if (ArgFlags.isByVal()) 6715 report_fatal_error("Passing structure by value is unimplemented."); 6716 6717 if (ArgFlags.isSRet()) 6718 report_fatal_error("Struct return arguments are unimplemented."); 6719 6720 if (ArgFlags.isNest()) 6721 report_fatal_error("Nest arguments are unimplemented."); 6722 6723 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6724 State.getMachineFunction().getSubtarget()); 6725 const bool IsPPC64 = Subtarget.isPPC64(); 6726 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6727 6728 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6729 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6730 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6731 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6732 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6733 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6734 6735 // Arguments always reserve parameter save area. 6736 switch (ValVT.SimpleTy) { 6737 default: 6738 report_fatal_error("Unhandled value type for argument."); 6739 case MVT::i64: 6740 // i64 arguments should have been split to i32 for PPC32. 6741 assert(IsPPC64 && "PPC32 should have split i64 values."); 6742 LLVM_FALLTHROUGH; 6743 case MVT::i1: 6744 case MVT::i32: 6745 State.AllocateStack(PtrByteSize, PtrByteSize); 6746 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6747 MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6748 // Promote integers if needed. 6749 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6750 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6751 : CCValAssign::LocInfo::ZExt; 6752 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6753 } 6754 else 6755 report_fatal_error("Handling of placing parameters on the stack is " 6756 "unimplemented!"); 6757 return false; 6758 6759 case MVT::f32: 6760 case MVT::f64: { 6761 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6762 const unsigned StoreSize = LocVT.getStoreSize(); 6763 // Floats are always 4-byte aligned in the PSA on AIX. 6764 // This includes f64 in 64-bit mode for ABI compatibility. 6765 State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 6766 if (unsigned Reg = State.AllocateReg(FPR)) 6767 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::f64, LocInfo)); 6768 else 6769 report_fatal_error("Handling of placing parameters on the stack is " 6770 "unimplemented!"); 6771 6772 // f32 reserves 1 GPR in both PPC32 and PPC64. 6773 // f64 reserves 2 GPRs in PPC32 and 1 GPR in PPC64. 6774 for (unsigned i = 0; i < StoreSize; i += PtrByteSize) 6775 State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32); 6776 return false; 6777 } 6778 } 6779 } 6780 6781 SDValue PPCTargetLowering::LowerCall_AIX( 6782 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6783 bool isTailCall, bool isPatchPoint, 6784 const SmallVectorImpl<ISD::OutputArg> &Outs, 6785 const SmallVectorImpl<SDValue> &OutVals, 6786 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6787 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6788 ImmutableCallSite CS) const { 6789 6790 assert((CallConv == CallingConv::C || 6791 CallConv == CallingConv::Cold || 6792 CallConv == CallingConv::Fast) && "Unexpected calling convention!"); 6793 6794 if (isVarArg || isPatchPoint) 6795 report_fatal_error("This call type is unimplemented on AIX."); 6796 6797 if (!isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 6798 report_fatal_error("Handling of indirect call is unimplemented!"); 6799 6800 const PPCSubtarget& Subtarget = 6801 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 6802 if (Subtarget.hasQPX()) 6803 report_fatal_error("QPX is not supported on AIX."); 6804 if (Subtarget.hasAltivec()) 6805 report_fatal_error("Altivec support is unimplemented on AIX."); 6806 6807 MachineFunction &MF = DAG.getMachineFunction(); 6808 SmallVector<CCValAssign, 16> ArgLocs; 6809 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6810 6811 // Reserve space for the linkage save area (LSA) on the stack. 6812 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 6813 // [SP][CR][LR][2 x reserved][TOC]. 6814 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 6815 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6816 const unsigned PtrByteSize = Subtarget.isPPC64() ? 8 : 4; 6817 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 6818 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 6819 6820 // The prolog code of the callee may store up to 8 GPR argument registers to 6821 // the stack, allowing va_start to index over them in memory if the callee 6822 // is variadic. 6823 // Because we cannot tell if this is needed on the caller side, we have to 6824 // conservatively assume that it is needed. As such, make sure we have at 6825 // least enough stack space for the caller to store the 8 GPRs. 6826 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 6827 const unsigned NumBytes = LinkageSize + MinParameterSaveAreaSize; 6828 6829 // Adjust the stack pointer for the new arguments... 6830 // These operations are automatically eliminated by the prolog/epilog pass. 6831 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6832 SDValue CallSeqStart = Chain; 6833 6834 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6835 6836 for (CCValAssign &VA : ArgLocs) { 6837 SDValue Arg = OutVals[VA.getValNo()]; 6838 6839 switch (VA.getLocInfo()) { 6840 default: report_fatal_error("Unexpected argument extension type."); 6841 case CCValAssign::Full: break; 6842 case CCValAssign::ZExt: 6843 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6844 break; 6845 case CCValAssign::SExt: 6846 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6847 break; 6848 } 6849 6850 if (VA.isRegLoc()) 6851 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 6852 6853 if (VA.isMemLoc()) 6854 report_fatal_error("Handling of placing parameters on the stack is " 6855 "unimplemented!"); 6856 } 6857 6858 // Build a sequence of copy-to-reg nodes chained together with token chain 6859 // and flag operands which copy the outgoing args into the appropriate regs. 6860 SDValue InFlag; 6861 for (auto Reg : RegsToPass) { 6862 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 6863 InFlag = Chain.getValue(1); 6864 } 6865 6866 const int SPDiff = 0; 6867 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6868 /* unused except on PPC64 ELFv1 */ false, DAG, RegsToPass, 6869 InFlag, Chain, CallSeqStart, Callee, SPDiff, NumBytes, Ins, 6870 InVals, CS); 6871 } 6872 6873 bool 6874 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6875 MachineFunction &MF, bool isVarArg, 6876 const SmallVectorImpl<ISD::OutputArg> &Outs, 6877 LLVMContext &Context) const { 6878 SmallVector<CCValAssign, 16> RVLocs; 6879 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6880 return CCInfo.CheckReturn( 6881 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6882 ? RetCC_PPC_Cold 6883 : RetCC_PPC); 6884 } 6885 6886 SDValue 6887 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6888 bool isVarArg, 6889 const SmallVectorImpl<ISD::OutputArg> &Outs, 6890 const SmallVectorImpl<SDValue> &OutVals, 6891 const SDLoc &dl, SelectionDAG &DAG) const { 6892 SmallVector<CCValAssign, 16> RVLocs; 6893 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6894 *DAG.getContext()); 6895 CCInfo.AnalyzeReturn(Outs, 6896 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6897 ? RetCC_PPC_Cold 6898 : RetCC_PPC); 6899 6900 SDValue Flag; 6901 SmallVector<SDValue, 4> RetOps(1, Chain); 6902 6903 // Copy the result values into the output registers. 6904 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 6905 CCValAssign &VA = RVLocs[i]; 6906 assert(VA.isRegLoc() && "Can only return in registers!"); 6907 6908 SDValue Arg = OutVals[RealResIdx]; 6909 6910 switch (VA.getLocInfo()) { 6911 default: llvm_unreachable("Unknown loc info!"); 6912 case CCValAssign::Full: break; 6913 case CCValAssign::AExt: 6914 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6915 break; 6916 case CCValAssign::ZExt: 6917 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6918 break; 6919 case CCValAssign::SExt: 6920 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6921 break; 6922 } 6923 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 6924 bool isLittleEndian = Subtarget.isLittleEndian(); 6925 // Legalize ret f64 -> ret 2 x i32. 6926 SDValue SVal = 6927 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 6928 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 6929 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 6930 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6931 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 6932 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 6933 Flag = Chain.getValue(1); 6934 VA = RVLocs[++i]; // skip ahead to next loc 6935 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 6936 } else 6937 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6938 Flag = Chain.getValue(1); 6939 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6940 } 6941 6942 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6943 const MCPhysReg *I = 6944 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6945 if (I) { 6946 for (; *I; ++I) { 6947 6948 if (PPC::G8RCRegClass.contains(*I)) 6949 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6950 else if (PPC::F8RCRegClass.contains(*I)) 6951 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6952 else if (PPC::CRRCRegClass.contains(*I)) 6953 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6954 else if (PPC::VRRCRegClass.contains(*I)) 6955 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6956 else 6957 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6958 } 6959 } 6960 6961 RetOps[0] = Chain; // Update chain. 6962 6963 // Add the flag if we have it. 6964 if (Flag.getNode()) 6965 RetOps.push_back(Flag); 6966 6967 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6968 } 6969 6970 SDValue 6971 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6972 SelectionDAG &DAG) const { 6973 SDLoc dl(Op); 6974 6975 // Get the correct type for integers. 6976 EVT IntVT = Op.getValueType(); 6977 6978 // Get the inputs. 6979 SDValue Chain = Op.getOperand(0); 6980 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6981 // Build a DYNAREAOFFSET node. 6982 SDValue Ops[2] = {Chain, FPSIdx}; 6983 SDVTList VTs = DAG.getVTList(IntVT); 6984 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6985 } 6986 6987 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6988 SelectionDAG &DAG) const { 6989 // When we pop the dynamic allocation we need to restore the SP link. 6990 SDLoc dl(Op); 6991 6992 // Get the correct type for pointers. 6993 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6994 6995 // Construct the stack pointer operand. 6996 bool isPPC64 = Subtarget.isPPC64(); 6997 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6998 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6999 7000 // Get the operands for the STACKRESTORE. 7001 SDValue Chain = Op.getOperand(0); 7002 SDValue SaveSP = Op.getOperand(1); 7003 7004 // Load the old link SP. 7005 SDValue LoadLinkSP = 7006 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7007 7008 // Restore the stack pointer. 7009 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7010 7011 // Store the old link SP. 7012 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7013 } 7014 7015 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7016 MachineFunction &MF = DAG.getMachineFunction(); 7017 bool isPPC64 = Subtarget.isPPC64(); 7018 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7019 7020 // Get current frame pointer save index. The users of this index will be 7021 // primarily DYNALLOC instructions. 7022 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7023 int RASI = FI->getReturnAddrSaveIndex(); 7024 7025 // If the frame pointer save index hasn't been defined yet. 7026 if (!RASI) { 7027 // Find out what the fix offset of the frame pointer save area. 7028 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7029 // Allocate the frame index for frame pointer save area. 7030 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7031 // Save the result. 7032 FI->setReturnAddrSaveIndex(RASI); 7033 } 7034 return DAG.getFrameIndex(RASI, PtrVT); 7035 } 7036 7037 SDValue 7038 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7039 MachineFunction &MF = DAG.getMachineFunction(); 7040 bool isPPC64 = Subtarget.isPPC64(); 7041 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7042 7043 // Get current frame pointer save index. The users of this index will be 7044 // primarily DYNALLOC instructions. 7045 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7046 int FPSI = FI->getFramePointerSaveIndex(); 7047 7048 // If the frame pointer save index hasn't been defined yet. 7049 if (!FPSI) { 7050 // Find out what the fix offset of the frame pointer save area. 7051 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7052 // Allocate the frame index for frame pointer save area. 7053 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7054 // Save the result. 7055 FI->setFramePointerSaveIndex(FPSI); 7056 } 7057 return DAG.getFrameIndex(FPSI, PtrVT); 7058 } 7059 7060 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7061 SelectionDAG &DAG) const { 7062 // Get the inputs. 7063 SDValue Chain = Op.getOperand(0); 7064 SDValue Size = Op.getOperand(1); 7065 SDLoc dl(Op); 7066 7067 // Get the correct type for pointers. 7068 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7069 // Negate the size. 7070 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7071 DAG.getConstant(0, dl, PtrVT), Size); 7072 // Construct a node for the frame pointer save index. 7073 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7074 // Build a DYNALLOC node. 7075 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7076 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7077 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7078 } 7079 7080 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7081 SelectionDAG &DAG) const { 7082 MachineFunction &MF = DAG.getMachineFunction(); 7083 7084 bool isPPC64 = Subtarget.isPPC64(); 7085 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7086 7087 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7088 return DAG.getFrameIndex(FI, PtrVT); 7089 } 7090 7091 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7092 SelectionDAG &DAG) const { 7093 SDLoc DL(Op); 7094 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7095 DAG.getVTList(MVT::i32, MVT::Other), 7096 Op.getOperand(0), Op.getOperand(1)); 7097 } 7098 7099 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7100 SelectionDAG &DAG) const { 7101 SDLoc DL(Op); 7102 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7103 Op.getOperand(0), Op.getOperand(1)); 7104 } 7105 7106 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7107 if (Op.getValueType().isVector()) 7108 return LowerVectorLoad(Op, DAG); 7109 7110 assert(Op.getValueType() == MVT::i1 && 7111 "Custom lowering only for i1 loads"); 7112 7113 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7114 7115 SDLoc dl(Op); 7116 LoadSDNode *LD = cast<LoadSDNode>(Op); 7117 7118 SDValue Chain = LD->getChain(); 7119 SDValue BasePtr = LD->getBasePtr(); 7120 MachineMemOperand *MMO = LD->getMemOperand(); 7121 7122 SDValue NewLD = 7123 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7124 BasePtr, MVT::i8, MMO); 7125 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7126 7127 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7128 return DAG.getMergeValues(Ops, dl); 7129 } 7130 7131 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7132 if (Op.getOperand(1).getValueType().isVector()) 7133 return LowerVectorStore(Op, DAG); 7134 7135 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7136 "Custom lowering only for i1 stores"); 7137 7138 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7139 7140 SDLoc dl(Op); 7141 StoreSDNode *ST = cast<StoreSDNode>(Op); 7142 7143 SDValue Chain = ST->getChain(); 7144 SDValue BasePtr = ST->getBasePtr(); 7145 SDValue Value = ST->getValue(); 7146 MachineMemOperand *MMO = ST->getMemOperand(); 7147 7148 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7149 Value); 7150 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7151 } 7152 7153 // FIXME: Remove this once the ANDI glue bug is fixed: 7154 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7155 assert(Op.getValueType() == MVT::i1 && 7156 "Custom lowering only for i1 results"); 7157 7158 SDLoc DL(Op); 7159 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 7160 Op.getOperand(0)); 7161 } 7162 7163 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7164 SelectionDAG &DAG) const { 7165 7166 // Implements a vector truncate that fits in a vector register as a shuffle. 7167 // We want to legalize vector truncates down to where the source fits in 7168 // a vector register (and target is therefore smaller than vector register 7169 // size). At that point legalization will try to custom lower the sub-legal 7170 // result and get here - where we can contain the truncate as a single target 7171 // operation. 7172 7173 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7174 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7175 // 7176 // We will implement it for big-endian ordering as this (where x denotes 7177 // undefined): 7178 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7179 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7180 // 7181 // The same operation in little-endian ordering will be: 7182 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7183 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7184 7185 assert(Op.getValueType().isVector() && "Vector type expected."); 7186 7187 SDLoc DL(Op); 7188 SDValue N1 = Op.getOperand(0); 7189 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7190 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7191 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7192 7193 EVT TrgVT = Op.getValueType(); 7194 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7195 EVT EltVT = TrgVT.getVectorElementType(); 7196 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7197 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7198 7199 // First list the elements we want to keep. 7200 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7201 SmallVector<int, 16> ShuffV; 7202 if (Subtarget.isLittleEndian()) 7203 for (unsigned i = 0; i < TrgNumElts; ++i) 7204 ShuffV.push_back(i * SizeMult); 7205 else 7206 for (unsigned i = 1; i <= TrgNumElts; ++i) 7207 ShuffV.push_back(i * SizeMult - 1); 7208 7209 // Populate the remaining elements with undefs. 7210 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7211 // ShuffV.push_back(i + WideNumElts); 7212 ShuffV.push_back(WideNumElts + 1); 7213 7214 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7215 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7216 } 7217 7218 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7219 /// possible. 7220 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7221 // Not FP? Not a fsel. 7222 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7223 !Op.getOperand(2).getValueType().isFloatingPoint()) 7224 return Op; 7225 7226 bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath; 7227 bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath; 7228 // We might be able to do better than this under some circumstances, but in 7229 // general, fsel-based lowering of select is a finite-math-only optimization. 7230 // For more information, see section F.3 of the 2.06 ISA specification. 7231 // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the 7232 // presence of infinities. 7233 if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs)) 7234 return Op; 7235 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7236 7237 EVT ResVT = Op.getValueType(); 7238 EVT CmpVT = Op.getOperand(0).getValueType(); 7239 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7240 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7241 SDLoc dl(Op); 7242 7243 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7244 switch (CC) { 7245 default: 7246 // Not a min/max but with finite math, we may still be able to use fsel. 7247 if (HasNoInfs && HasNoNaNs) 7248 break; 7249 return Op; 7250 case ISD::SETOGT: 7251 case ISD::SETGT: 7252 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7253 case ISD::SETOLT: 7254 case ISD::SETLT: 7255 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7256 } 7257 } 7258 7259 // TODO: Propagate flags from the select rather than global settings. 7260 SDNodeFlags Flags; 7261 Flags.setNoInfs(true); 7262 Flags.setNoNaNs(true); 7263 7264 // If the RHS of the comparison is a 0.0, we don't need to do the 7265 // subtraction at all. 7266 SDValue Sel1; 7267 if (isFloatingPointZero(RHS)) 7268 switch (CC) { 7269 default: break; // SETUO etc aren't handled by fsel. 7270 case ISD::SETNE: 7271 std::swap(TV, FV); 7272 LLVM_FALLTHROUGH; 7273 case ISD::SETEQ: 7274 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7275 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7276 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7277 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7278 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7279 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7280 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7281 case ISD::SETULT: 7282 case ISD::SETLT: 7283 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7284 LLVM_FALLTHROUGH; 7285 case ISD::SETOGE: 7286 case ISD::SETGE: 7287 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7288 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7289 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7290 case ISD::SETUGT: 7291 case ISD::SETGT: 7292 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7293 LLVM_FALLTHROUGH; 7294 case ISD::SETOLE: 7295 case ISD::SETLE: 7296 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7297 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7298 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7299 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7300 } 7301 7302 SDValue Cmp; 7303 switch (CC) { 7304 default: break; // SETUO etc aren't handled by fsel. 7305 case ISD::SETNE: 7306 std::swap(TV, FV); 7307 LLVM_FALLTHROUGH; 7308 case ISD::SETEQ: 7309 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7310 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7311 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7312 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7313 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7314 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7315 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7316 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7317 case ISD::SETULT: 7318 case ISD::SETLT: 7319 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7320 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7321 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7322 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7323 case ISD::SETOGE: 7324 case ISD::SETGE: 7325 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7326 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7327 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7328 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7329 case ISD::SETUGT: 7330 case ISD::SETGT: 7331 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7332 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7333 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7334 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7335 case ISD::SETOLE: 7336 case ISD::SETLE: 7337 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7338 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7339 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7340 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7341 } 7342 return Op; 7343 } 7344 7345 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7346 SelectionDAG &DAG, 7347 const SDLoc &dl) const { 7348 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7349 SDValue Src = Op.getOperand(0); 7350 if (Src.getValueType() == MVT::f32) 7351 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7352 7353 SDValue Tmp; 7354 switch (Op.getSimpleValueType().SimpleTy) { 7355 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7356 case MVT::i32: 7357 Tmp = DAG.getNode( 7358 Op.getOpcode() == ISD::FP_TO_SINT 7359 ? PPCISD::FCTIWZ 7360 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7361 dl, MVT::f64, Src); 7362 break; 7363 case MVT::i64: 7364 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7365 "i64 FP_TO_UINT is supported only with FPCVT"); 7366 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7367 PPCISD::FCTIDUZ, 7368 dl, MVT::f64, Src); 7369 break; 7370 } 7371 7372 // Convert the FP value to an int value through memory. 7373 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7374 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7375 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7376 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7377 MachinePointerInfo MPI = 7378 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7379 7380 // Emit a store to the stack slot. 7381 SDValue Chain; 7382 if (i32Stack) { 7383 MachineFunction &MF = DAG.getMachineFunction(); 7384 MachineMemOperand *MMO = 7385 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7386 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7387 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7388 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7389 } else 7390 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7391 7392 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7393 // add in a bias on big endian. 7394 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7395 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7396 DAG.getConstant(4, dl, FIPtr.getValueType())); 7397 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7398 } 7399 7400 RLI.Chain = Chain; 7401 RLI.Ptr = FIPtr; 7402 RLI.MPI = MPI; 7403 } 7404 7405 /// Custom lowers floating point to integer conversions to use 7406 /// the direct move instructions available in ISA 2.07 to avoid the 7407 /// need for load/store combinations. 7408 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7409 SelectionDAG &DAG, 7410 const SDLoc &dl) const { 7411 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7412 SDValue Src = Op.getOperand(0); 7413 7414 if (Src.getValueType() == MVT::f32) 7415 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7416 7417 SDValue Tmp; 7418 switch (Op.getSimpleValueType().SimpleTy) { 7419 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7420 case MVT::i32: 7421 Tmp = DAG.getNode( 7422 Op.getOpcode() == ISD::FP_TO_SINT 7423 ? PPCISD::FCTIWZ 7424 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7425 dl, MVT::f64, Src); 7426 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7427 break; 7428 case MVT::i64: 7429 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7430 "i64 FP_TO_UINT is supported only with FPCVT"); 7431 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7432 PPCISD::FCTIDUZ, 7433 dl, MVT::f64, Src); 7434 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7435 break; 7436 } 7437 return Tmp; 7438 } 7439 7440 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7441 const SDLoc &dl) const { 7442 7443 // FP to INT conversions are legal for f128. 7444 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7445 return Op; 7446 7447 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7448 // PPC (the libcall is not available). 7449 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7450 if (Op.getValueType() == MVT::i32) { 7451 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7452 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7453 MVT::f64, Op.getOperand(0), 7454 DAG.getIntPtrConstant(0, dl)); 7455 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7456 MVT::f64, Op.getOperand(0), 7457 DAG.getIntPtrConstant(1, dl)); 7458 7459 // Add the two halves of the long double in round-to-zero mode. 7460 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7461 7462 // Now use a smaller FP_TO_SINT. 7463 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7464 } 7465 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7466 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7467 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7468 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7469 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7470 // FIXME: generated code sucks. 7471 // TODO: Are there fast-math-flags to propagate to this FSUB? 7472 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7473 Op.getOperand(0), Tmp); 7474 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7475 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7476 DAG.getConstant(0x80000000, dl, MVT::i32)); 7477 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7478 Op.getOperand(0)); 7479 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7480 ISD::SETGE); 7481 } 7482 } 7483 7484 return SDValue(); 7485 } 7486 7487 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7488 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7489 7490 ReuseLoadInfo RLI; 7491 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7492 7493 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7494 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7495 } 7496 7497 // We're trying to insert a regular store, S, and then a load, L. If the 7498 // incoming value, O, is a load, we might just be able to have our load use the 7499 // address used by O. However, we don't know if anything else will store to 7500 // that address before we can load from it. To prevent this situation, we need 7501 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7502 // the same chain operand as O, we create a token factor from the chain results 7503 // of O and L, and we replace all uses of O's chain result with that token 7504 // factor (see spliceIntoChain below for this last part). 7505 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7506 ReuseLoadInfo &RLI, 7507 SelectionDAG &DAG, 7508 ISD::LoadExtType ET) const { 7509 SDLoc dl(Op); 7510 if (ET == ISD::NON_EXTLOAD && 7511 (Op.getOpcode() == ISD::FP_TO_UINT || 7512 Op.getOpcode() == ISD::FP_TO_SINT) && 7513 isOperationLegalOrCustom(Op.getOpcode(), 7514 Op.getOperand(0).getValueType())) { 7515 7516 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7517 return true; 7518 } 7519 7520 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7521 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7522 LD->isNonTemporal()) 7523 return false; 7524 if (LD->getMemoryVT() != MemVT) 7525 return false; 7526 7527 RLI.Ptr = LD->getBasePtr(); 7528 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7529 assert(LD->getAddressingMode() == ISD::PRE_INC && 7530 "Non-pre-inc AM on PPC?"); 7531 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7532 LD->getOffset()); 7533 } 7534 7535 RLI.Chain = LD->getChain(); 7536 RLI.MPI = LD->getPointerInfo(); 7537 RLI.IsDereferenceable = LD->isDereferenceable(); 7538 RLI.IsInvariant = LD->isInvariant(); 7539 RLI.Alignment = LD->getAlignment(); 7540 RLI.AAInfo = LD->getAAInfo(); 7541 RLI.Ranges = LD->getRanges(); 7542 7543 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7544 return true; 7545 } 7546 7547 // Given the head of the old chain, ResChain, insert a token factor containing 7548 // it and NewResChain, and make users of ResChain now be users of that token 7549 // factor. 7550 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7551 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7552 SDValue NewResChain, 7553 SelectionDAG &DAG) const { 7554 if (!ResChain) 7555 return; 7556 7557 SDLoc dl(NewResChain); 7558 7559 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7560 NewResChain, DAG.getUNDEF(MVT::Other)); 7561 assert(TF.getNode() != NewResChain.getNode() && 7562 "A new TF really is required here"); 7563 7564 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7565 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7566 } 7567 7568 /// Analyze profitability of direct move 7569 /// prefer float load to int load plus direct move 7570 /// when there is no integer use of int load 7571 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7572 SDNode *Origin = Op.getOperand(0).getNode(); 7573 if (Origin->getOpcode() != ISD::LOAD) 7574 return true; 7575 7576 // If there is no LXSIBZX/LXSIHZX, like Power8, 7577 // prefer direct move if the memory size is 1 or 2 bytes. 7578 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7579 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7580 return true; 7581 7582 for (SDNode::use_iterator UI = Origin->use_begin(), 7583 UE = Origin->use_end(); 7584 UI != UE; ++UI) { 7585 7586 // Only look at the users of the loaded value. 7587 if (UI.getUse().get().getResNo() != 0) 7588 continue; 7589 7590 if (UI->getOpcode() != ISD::SINT_TO_FP && 7591 UI->getOpcode() != ISD::UINT_TO_FP) 7592 return true; 7593 } 7594 7595 return false; 7596 } 7597 7598 /// Custom lowers integer to floating point conversions to use 7599 /// the direct move instructions available in ISA 2.07 to avoid the 7600 /// need for load/store combinations. 7601 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7602 SelectionDAG &DAG, 7603 const SDLoc &dl) const { 7604 assert((Op.getValueType() == MVT::f32 || 7605 Op.getValueType() == MVT::f64) && 7606 "Invalid floating point type as target of conversion"); 7607 assert(Subtarget.hasFPCVT() && 7608 "Int to FP conversions with direct moves require FPCVT"); 7609 SDValue FP; 7610 SDValue Src = Op.getOperand(0); 7611 bool SinglePrec = Op.getValueType() == MVT::f32; 7612 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7613 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7614 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7615 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7616 7617 if (WordInt) { 7618 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7619 dl, MVT::f64, Src); 7620 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7621 } 7622 else { 7623 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7624 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7625 } 7626 7627 return FP; 7628 } 7629 7630 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7631 7632 EVT VecVT = Vec.getValueType(); 7633 assert(VecVT.isVector() && "Expected a vector type."); 7634 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7635 7636 EVT EltVT = VecVT.getVectorElementType(); 7637 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7638 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7639 7640 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7641 SmallVector<SDValue, 16> Ops(NumConcat); 7642 Ops[0] = Vec; 7643 SDValue UndefVec = DAG.getUNDEF(VecVT); 7644 for (unsigned i = 1; i < NumConcat; ++i) 7645 Ops[i] = UndefVec; 7646 7647 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7648 } 7649 7650 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7651 const SDLoc &dl) const { 7652 7653 unsigned Opc = Op.getOpcode(); 7654 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7655 "Unexpected conversion type"); 7656 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7657 "Supports conversions to v2f64/v4f32 only."); 7658 7659 bool SignedConv = Opc == ISD::SINT_TO_FP; 7660 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7661 7662 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7663 EVT WideVT = Wide.getValueType(); 7664 unsigned WideNumElts = WideVT.getVectorNumElements(); 7665 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7666 7667 SmallVector<int, 16> ShuffV; 7668 for (unsigned i = 0; i < WideNumElts; ++i) 7669 ShuffV.push_back(i + WideNumElts); 7670 7671 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7672 int SaveElts = FourEltRes ? 4 : 2; 7673 if (Subtarget.isLittleEndian()) 7674 for (int i = 0; i < SaveElts; i++) 7675 ShuffV[i * Stride] = i; 7676 else 7677 for (int i = 1; i <= SaveElts; i++) 7678 ShuffV[i * Stride - 1] = i - 1; 7679 7680 SDValue ShuffleSrc2 = 7681 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 7682 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7683 unsigned ExtendOp = 7684 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 7685 7686 SDValue Extend; 7687 if (!Subtarget.hasP9Altivec() && SignedConv) { 7688 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 7689 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 7690 DAG.getValueType(Op.getOperand(0).getValueType())); 7691 } else 7692 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 7693 7694 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7695 } 7696 7697 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7698 SelectionDAG &DAG) const { 7699 SDLoc dl(Op); 7700 7701 EVT InVT = Op.getOperand(0).getValueType(); 7702 EVT OutVT = Op.getValueType(); 7703 if (OutVT.isVector() && OutVT.isFloatingPoint() && 7704 isOperationCustom(Op.getOpcode(), InVT)) 7705 return LowerINT_TO_FPVector(Op, DAG, dl); 7706 7707 // Conversions to f128 are legal. 7708 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7709 return Op; 7710 7711 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7712 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7713 return SDValue(); 7714 7715 SDValue Value = Op.getOperand(0); 7716 // The values are now known to be -1 (false) or 1 (true). To convert this 7717 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7718 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7719 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7720 7721 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7722 7723 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7724 7725 if (Op.getValueType() != MVT::v4f64) 7726 Value = DAG.getNode(ISD::FP_ROUND, dl, 7727 Op.getValueType(), Value, 7728 DAG.getIntPtrConstant(1, dl)); 7729 return Value; 7730 } 7731 7732 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7733 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7734 return SDValue(); 7735 7736 if (Op.getOperand(0).getValueType() == MVT::i1) 7737 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7738 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7739 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7740 7741 // If we have direct moves, we can do all the conversion, skip the store/load 7742 // however, without FPCVT we can't do most conversions. 7743 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7744 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7745 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7746 7747 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7748 "UINT_TO_FP is supported only with FPCVT"); 7749 7750 // If we have FCFIDS, then use it when converting to single-precision. 7751 // Otherwise, convert to double-precision and then round. 7752 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7753 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7754 : PPCISD::FCFIDS) 7755 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7756 : PPCISD::FCFID); 7757 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7758 ? MVT::f32 7759 : MVT::f64; 7760 7761 if (Op.getOperand(0).getValueType() == MVT::i64) { 7762 SDValue SINT = Op.getOperand(0); 7763 // When converting to single-precision, we actually need to convert 7764 // to double-precision first and then round to single-precision. 7765 // To avoid double-rounding effects during that operation, we have 7766 // to prepare the input operand. Bits that might be truncated when 7767 // converting to double-precision are replaced by a bit that won't 7768 // be lost at this stage, but is below the single-precision rounding 7769 // position. 7770 // 7771 // However, if -enable-unsafe-fp-math is in effect, accept double 7772 // rounding to avoid the extra overhead. 7773 if (Op.getValueType() == MVT::f32 && 7774 !Subtarget.hasFPCVT() && 7775 !DAG.getTarget().Options.UnsafeFPMath) { 7776 7777 // Twiddle input to make sure the low 11 bits are zero. (If this 7778 // is the case, we are guaranteed the value will fit into the 53 bit 7779 // mantissa of an IEEE double-precision value without rounding.) 7780 // If any of those low 11 bits were not zero originally, make sure 7781 // bit 12 (value 2048) is set instead, so that the final rounding 7782 // to single-precision gets the correct result. 7783 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7784 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7785 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7786 Round, DAG.getConstant(2047, dl, MVT::i64)); 7787 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7788 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7789 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7790 7791 // However, we cannot use that value unconditionally: if the magnitude 7792 // of the input value is small, the bit-twiddling we did above might 7793 // end up visibly changing the output. Fortunately, in that case, we 7794 // don't need to twiddle bits since the original input will convert 7795 // exactly to double-precision floating-point already. Therefore, 7796 // construct a conditional to use the original value if the top 11 7797 // bits are all sign-bit copies, and use the rounded value computed 7798 // above otherwise. 7799 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7800 SINT, DAG.getConstant(53, dl, MVT::i32)); 7801 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7802 Cond, DAG.getConstant(1, dl, MVT::i64)); 7803 Cond = DAG.getSetCC(dl, MVT::i32, 7804 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7805 7806 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7807 } 7808 7809 ReuseLoadInfo RLI; 7810 SDValue Bits; 7811 7812 MachineFunction &MF = DAG.getMachineFunction(); 7813 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7814 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7815 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7816 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7817 } else if (Subtarget.hasLFIWAX() && 7818 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7819 MachineMemOperand *MMO = 7820 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7821 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7822 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7823 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7824 DAG.getVTList(MVT::f64, MVT::Other), 7825 Ops, MVT::i32, MMO); 7826 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7827 } else if (Subtarget.hasFPCVT() && 7828 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7829 MachineMemOperand *MMO = 7830 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7831 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7832 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7833 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7834 DAG.getVTList(MVT::f64, MVT::Other), 7835 Ops, MVT::i32, MMO); 7836 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7837 } else if (((Subtarget.hasLFIWAX() && 7838 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7839 (Subtarget.hasFPCVT() && 7840 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7841 SINT.getOperand(0).getValueType() == MVT::i32) { 7842 MachineFrameInfo &MFI = MF.getFrameInfo(); 7843 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7844 7845 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7846 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7847 7848 SDValue Store = 7849 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7850 MachinePointerInfo::getFixedStack( 7851 DAG.getMachineFunction(), FrameIdx)); 7852 7853 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7854 "Expected an i32 store"); 7855 7856 RLI.Ptr = FIdx; 7857 RLI.Chain = Store; 7858 RLI.MPI = 7859 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7860 RLI.Alignment = 4; 7861 7862 MachineMemOperand *MMO = 7863 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7864 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7865 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7866 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7867 PPCISD::LFIWZX : PPCISD::LFIWAX, 7868 dl, DAG.getVTList(MVT::f64, MVT::Other), 7869 Ops, MVT::i32, MMO); 7870 } else 7871 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7872 7873 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7874 7875 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7876 FP = DAG.getNode(ISD::FP_ROUND, dl, 7877 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7878 return FP; 7879 } 7880 7881 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7882 "Unhandled INT_TO_FP type in custom expander!"); 7883 // Since we only generate this in 64-bit mode, we can take advantage of 7884 // 64-bit registers. In particular, sign extend the input value into the 7885 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7886 // then lfd it and fcfid it. 7887 MachineFunction &MF = DAG.getMachineFunction(); 7888 MachineFrameInfo &MFI = MF.getFrameInfo(); 7889 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7890 7891 SDValue Ld; 7892 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7893 ReuseLoadInfo RLI; 7894 bool ReusingLoad; 7895 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7896 DAG))) { 7897 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7898 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7899 7900 SDValue Store = 7901 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7902 MachinePointerInfo::getFixedStack( 7903 DAG.getMachineFunction(), FrameIdx)); 7904 7905 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7906 "Expected an i32 store"); 7907 7908 RLI.Ptr = FIdx; 7909 RLI.Chain = Store; 7910 RLI.MPI = 7911 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7912 RLI.Alignment = 4; 7913 } 7914 7915 MachineMemOperand *MMO = 7916 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7917 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7918 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7919 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7920 PPCISD::LFIWZX : PPCISD::LFIWAX, 7921 dl, DAG.getVTList(MVT::f64, MVT::Other), 7922 Ops, MVT::i32, MMO); 7923 if (ReusingLoad) 7924 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7925 } else { 7926 assert(Subtarget.isPPC64() && 7927 "i32->FP without LFIWAX supported only on PPC64"); 7928 7929 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7930 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7931 7932 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7933 Op.getOperand(0)); 7934 7935 // STD the extended value into the stack slot. 7936 SDValue Store = DAG.getStore( 7937 DAG.getEntryNode(), dl, Ext64, FIdx, 7938 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7939 7940 // Load the value as a double. 7941 Ld = DAG.getLoad( 7942 MVT::f64, dl, Store, FIdx, 7943 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7944 } 7945 7946 // FCFID it and return it. 7947 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7948 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7949 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7950 DAG.getIntPtrConstant(0, dl)); 7951 return FP; 7952 } 7953 7954 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7955 SelectionDAG &DAG) const { 7956 SDLoc dl(Op); 7957 /* 7958 The rounding mode is in bits 30:31 of FPSR, and has the following 7959 settings: 7960 00 Round to nearest 7961 01 Round to 0 7962 10 Round to +inf 7963 11 Round to -inf 7964 7965 FLT_ROUNDS, on the other hand, expects the following: 7966 -1 Undefined 7967 0 Round to 0 7968 1 Round to nearest 7969 2 Round to +inf 7970 3 Round to -inf 7971 7972 To perform the conversion, we do: 7973 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7974 */ 7975 7976 MachineFunction &MF = DAG.getMachineFunction(); 7977 EVT VT = Op.getValueType(); 7978 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7979 7980 // Save FP Control Word to register 7981 EVT NodeTys[] = { 7982 MVT::f64, // return register 7983 MVT::Glue // unused in this context 7984 }; 7985 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7986 7987 // Save FP register to stack slot 7988 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7989 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7990 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7991 MachinePointerInfo()); 7992 7993 // Load FP Control Word from low 32 bits of stack slot. 7994 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7995 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7996 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7997 7998 // Transform as necessary 7999 SDValue CWD1 = 8000 DAG.getNode(ISD::AND, dl, MVT::i32, 8001 CWD, DAG.getConstant(3, dl, MVT::i32)); 8002 SDValue CWD2 = 8003 DAG.getNode(ISD::SRL, dl, MVT::i32, 8004 DAG.getNode(ISD::AND, dl, MVT::i32, 8005 DAG.getNode(ISD::XOR, dl, MVT::i32, 8006 CWD, DAG.getConstant(3, dl, MVT::i32)), 8007 DAG.getConstant(3, dl, MVT::i32)), 8008 DAG.getConstant(1, dl, MVT::i32)); 8009 8010 SDValue RetVal = 8011 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8012 8013 return DAG.getNode((VT.getSizeInBits() < 16 ? 8014 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 8015 } 8016 8017 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8018 EVT VT = Op.getValueType(); 8019 unsigned BitWidth = VT.getSizeInBits(); 8020 SDLoc dl(Op); 8021 assert(Op.getNumOperands() == 3 && 8022 VT == Op.getOperand(1).getValueType() && 8023 "Unexpected SHL!"); 8024 8025 // Expand into a bunch of logical ops. Note that these ops 8026 // depend on the PPC behavior for oversized shift amounts. 8027 SDValue Lo = Op.getOperand(0); 8028 SDValue Hi = Op.getOperand(1); 8029 SDValue Amt = Op.getOperand(2); 8030 EVT AmtVT = Amt.getValueType(); 8031 8032 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8033 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8034 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8035 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8036 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8037 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8038 DAG.getConstant(-BitWidth, dl, AmtVT)); 8039 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8040 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8041 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8042 SDValue OutOps[] = { OutLo, OutHi }; 8043 return DAG.getMergeValues(OutOps, dl); 8044 } 8045 8046 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8047 EVT VT = Op.getValueType(); 8048 SDLoc dl(Op); 8049 unsigned BitWidth = VT.getSizeInBits(); 8050 assert(Op.getNumOperands() == 3 && 8051 VT == Op.getOperand(1).getValueType() && 8052 "Unexpected SRL!"); 8053 8054 // Expand into a bunch of logical ops. Note that these ops 8055 // depend on the PPC behavior for oversized shift amounts. 8056 SDValue Lo = Op.getOperand(0); 8057 SDValue Hi = Op.getOperand(1); 8058 SDValue Amt = Op.getOperand(2); 8059 EVT AmtVT = Amt.getValueType(); 8060 8061 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8062 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8063 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8064 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8065 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8066 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8067 DAG.getConstant(-BitWidth, dl, AmtVT)); 8068 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8069 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8070 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8071 SDValue OutOps[] = { OutLo, OutHi }; 8072 return DAG.getMergeValues(OutOps, dl); 8073 } 8074 8075 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8076 SDLoc dl(Op); 8077 EVT VT = Op.getValueType(); 8078 unsigned BitWidth = VT.getSizeInBits(); 8079 assert(Op.getNumOperands() == 3 && 8080 VT == Op.getOperand(1).getValueType() && 8081 "Unexpected SRA!"); 8082 8083 // Expand into a bunch of logical ops, followed by a select_cc. 8084 SDValue Lo = Op.getOperand(0); 8085 SDValue Hi = Op.getOperand(1); 8086 SDValue Amt = Op.getOperand(2); 8087 EVT AmtVT = Amt.getValueType(); 8088 8089 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8090 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8091 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8092 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8093 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8094 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8095 DAG.getConstant(-BitWidth, dl, AmtVT)); 8096 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8097 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8098 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8099 Tmp4, Tmp6, ISD::SETLE); 8100 SDValue OutOps[] = { OutLo, OutHi }; 8101 return DAG.getMergeValues(OutOps, dl); 8102 } 8103 8104 //===----------------------------------------------------------------------===// 8105 // Vector related lowering. 8106 // 8107 8108 /// BuildSplatI - Build a canonical splati of Val with an element size of 8109 /// SplatSize. Cast the result to VT. 8110 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8111 SelectionDAG &DAG, const SDLoc &dl) { 8112 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 8113 8114 static const MVT VTys[] = { // canonical VT to use for each size. 8115 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8116 }; 8117 8118 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8119 8120 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8121 if (Val == -1) 8122 SplatSize = 1; 8123 8124 EVT CanonicalVT = VTys[SplatSize-1]; 8125 8126 // Build a canonical splat for this value. 8127 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8128 } 8129 8130 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8131 /// specified intrinsic ID. 8132 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8133 const SDLoc &dl, EVT DestVT = MVT::Other) { 8134 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8135 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8136 DAG.getConstant(IID, dl, MVT::i32), Op); 8137 } 8138 8139 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8140 /// specified intrinsic ID. 8141 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8142 SelectionDAG &DAG, const SDLoc &dl, 8143 EVT DestVT = MVT::Other) { 8144 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8145 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8146 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8147 } 8148 8149 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8150 /// specified intrinsic ID. 8151 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8152 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8153 EVT DestVT = MVT::Other) { 8154 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8155 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8156 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8157 } 8158 8159 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8160 /// amount. The result has the specified value type. 8161 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8162 SelectionDAG &DAG, const SDLoc &dl) { 8163 // Force LHS/RHS to be the right type. 8164 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8165 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8166 8167 int Ops[16]; 8168 for (unsigned i = 0; i != 16; ++i) 8169 Ops[i] = i + Amt; 8170 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8171 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8172 } 8173 8174 /// Do we have an efficient pattern in a .td file for this node? 8175 /// 8176 /// \param V - pointer to the BuildVectorSDNode being matched 8177 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8178 /// 8179 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8180 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8181 /// the opposite is true (expansion is beneficial) are: 8182 /// - The node builds a vector out of integers that are not 32 or 64-bits 8183 /// - The node builds a vector out of constants 8184 /// - The node is a "load-and-splat" 8185 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8186 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8187 bool HasDirectMove, 8188 bool HasP8Vector) { 8189 EVT VecVT = V->getValueType(0); 8190 bool RightType = VecVT == MVT::v2f64 || 8191 (HasP8Vector && VecVT == MVT::v4f32) || 8192 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8193 if (!RightType) 8194 return false; 8195 8196 bool IsSplat = true; 8197 bool IsLoad = false; 8198 SDValue Op0 = V->getOperand(0); 8199 8200 // This function is called in a block that confirms the node is not a constant 8201 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8202 // different constants. 8203 if (V->isConstant()) 8204 return false; 8205 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8206 if (V->getOperand(i).isUndef()) 8207 return false; 8208 // We want to expand nodes that represent load-and-splat even if the 8209 // loaded value is a floating point truncation or conversion to int. 8210 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8211 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8212 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8213 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8214 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8215 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8216 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8217 IsLoad = true; 8218 // If the operands are different or the input is not a load and has more 8219 // uses than just this BV node, then it isn't a splat. 8220 if (V->getOperand(i) != Op0 || 8221 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8222 IsSplat = false; 8223 } 8224 return !(IsSplat && IsLoad); 8225 } 8226 8227 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8228 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8229 8230 SDLoc dl(Op); 8231 SDValue Op0 = Op->getOperand(0); 8232 8233 if (!EnableQuadPrecision || 8234 (Op.getValueType() != MVT::f128 ) || 8235 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8236 (Op0.getOperand(0).getValueType() != MVT::i64) || 8237 (Op0.getOperand(1).getValueType() != MVT::i64)) 8238 return SDValue(); 8239 8240 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8241 Op0.getOperand(1)); 8242 } 8243 8244 static const SDValue *getNormalLoadInput(const SDValue &Op) { 8245 const SDValue *InputLoad = &Op; 8246 if (InputLoad->getOpcode() == ISD::BITCAST) 8247 InputLoad = &InputLoad->getOperand(0); 8248 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 8249 InputLoad = &InputLoad->getOperand(0); 8250 if (InputLoad->getOpcode() != ISD::LOAD) 8251 return nullptr; 8252 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8253 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8254 } 8255 8256 // If this is a case we can't handle, return null and let the default 8257 // expansion code take care of it. If we CAN select this case, and if it 8258 // selects to a single instruction, return Op. Otherwise, if we can codegen 8259 // this case more efficiently than a constant pool load, lower it to the 8260 // sequence of ops that should be used. 8261 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8262 SelectionDAG &DAG) const { 8263 SDLoc dl(Op); 8264 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8265 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8266 8267 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 8268 // We first build an i32 vector, load it into a QPX register, 8269 // then convert it to a floating-point vector and compare it 8270 // to a zero vector to get the boolean result. 8271 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8272 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8273 MachinePointerInfo PtrInfo = 8274 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8275 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8276 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8277 8278 assert(BVN->getNumOperands() == 4 && 8279 "BUILD_VECTOR for v4i1 does not have 4 operands"); 8280 8281 bool IsConst = true; 8282 for (unsigned i = 0; i < 4; ++i) { 8283 if (BVN->getOperand(i).isUndef()) continue; 8284 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 8285 IsConst = false; 8286 break; 8287 } 8288 } 8289 8290 if (IsConst) { 8291 Constant *One = 8292 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 8293 Constant *NegOne = 8294 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 8295 8296 Constant *CV[4]; 8297 for (unsigned i = 0; i < 4; ++i) { 8298 if (BVN->getOperand(i).isUndef()) 8299 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 8300 else if (isNullConstant(BVN->getOperand(i))) 8301 CV[i] = NegOne; 8302 else 8303 CV[i] = One; 8304 } 8305 8306 Constant *CP = ConstantVector::get(CV); 8307 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 8308 16 /* alignment */); 8309 8310 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 8311 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 8312 return DAG.getMemIntrinsicNode( 8313 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 8314 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 8315 } 8316 8317 SmallVector<SDValue, 4> Stores; 8318 for (unsigned i = 0; i < 4; ++i) { 8319 if (BVN->getOperand(i).isUndef()) continue; 8320 8321 unsigned Offset = 4*i; 8322 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8323 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8324 8325 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 8326 if (StoreSize > 4) { 8327 Stores.push_back( 8328 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 8329 PtrInfo.getWithOffset(Offset), MVT::i32)); 8330 } else { 8331 SDValue StoreValue = BVN->getOperand(i); 8332 if (StoreSize < 4) 8333 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 8334 8335 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 8336 PtrInfo.getWithOffset(Offset))); 8337 } 8338 } 8339 8340 SDValue StoreChain; 8341 if (!Stores.empty()) 8342 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8343 else 8344 StoreChain = DAG.getEntryNode(); 8345 8346 // Now load from v4i32 into the QPX register; this will extend it to 8347 // v4i64 but not yet convert it to a floating point. Nevertheless, this 8348 // is typed as v4f64 because the QPX register integer states are not 8349 // explicitly represented. 8350 8351 SDValue Ops[] = {StoreChain, 8352 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 8353 FIdx}; 8354 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 8355 8356 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 8357 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8358 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8359 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 8360 LoadedVect); 8361 8362 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 8363 8364 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 8365 } 8366 8367 // All other QPX vectors are handled by generic code. 8368 if (Subtarget.hasQPX()) 8369 return SDValue(); 8370 8371 // Check if this is a splat of a constant value. 8372 APInt APSplatBits, APSplatUndef; 8373 unsigned SplatBitSize; 8374 bool HasAnyUndefs; 8375 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8376 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8377 SplatBitSize > 32) { 8378 8379 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 8380 // Handle load-and-splat patterns as we have instructions that will do this 8381 // in one go. 8382 if (InputLoad && DAG.isSplatValue(Op, true)) { 8383 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8384 8385 // We have handling for 4 and 8 byte elements. 8386 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 8387 8388 // Checking for a single use of this load, we have to check for vector 8389 // width (128 bits) / ElementSize uses (since each operand of the 8390 // BUILD_VECTOR is a separate use of the value. 8391 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 8392 ((Subtarget.hasVSX() && ElementSize == 64) || 8393 (Subtarget.hasP9Vector() && ElementSize == 32))) { 8394 SDValue Ops[] = { 8395 LD->getChain(), // Chain 8396 LD->getBasePtr(), // Ptr 8397 DAG.getValueType(Op.getValueType()) // VT 8398 }; 8399 return 8400 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 8401 DAG.getVTList(Op.getValueType(), MVT::Other), 8402 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8403 } 8404 } 8405 8406 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8407 // lowered to VSX instructions under certain conditions. 8408 // Without VSX, there is no pattern more efficient than expanding the node. 8409 if (Subtarget.hasVSX() && 8410 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8411 Subtarget.hasP8Vector())) 8412 return Op; 8413 return SDValue(); 8414 } 8415 8416 unsigned SplatBits = APSplatBits.getZExtValue(); 8417 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8418 unsigned SplatSize = SplatBitSize / 8; 8419 8420 // First, handle single instruction cases. 8421 8422 // All zeros? 8423 if (SplatBits == 0) { 8424 // Canonicalize all zero vectors to be v4i32. 8425 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8426 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8427 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8428 } 8429 return Op; 8430 } 8431 8432 // We have XXSPLTIB for constant splats one byte wide 8433 if (Subtarget.hasP9Vector() && SplatSize == 1) { 8434 // This is a splat of 1-byte elements with some elements potentially undef. 8435 // Rather than trying to match undef in the SDAG patterns, ensure that all 8436 // elements are the same constant. 8437 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 8438 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 8439 dl, MVT::i32)); 8440 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 8441 if (Op.getValueType() != MVT::v16i8) 8442 return DAG.getBitcast(Op.getValueType(), NewBV); 8443 return NewBV; 8444 } 8445 8446 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 8447 // detect that constant splats like v8i16: 0xABAB are really just splats 8448 // of a 1-byte constant. In this case, we need to convert the node to a 8449 // splat of v16i8 and a bitcast. 8450 if (Op.getValueType() != MVT::v16i8) 8451 return DAG.getBitcast(Op.getValueType(), 8452 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 8453 8454 return Op; 8455 } 8456 8457 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8458 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8459 (32-SplatBitSize)); 8460 if (SextVal >= -16 && SextVal <= 15) 8461 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8462 8463 // Two instruction sequences. 8464 8465 // If this value is in the range [-32,30] and is even, use: 8466 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8467 // If this value is in the range [17,31] and is odd, use: 8468 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8469 // If this value is in the range [-31,-17] and is odd, use: 8470 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8471 // Note the last two are three-instruction sequences. 8472 if (SextVal >= -32 && SextVal <= 31) { 8473 // To avoid having these optimizations undone by constant folding, 8474 // we convert to a pseudo that will be expanded later into one of 8475 // the above forms. 8476 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8477 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8478 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8479 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8480 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8481 if (VT == Op.getValueType()) 8482 return RetVal; 8483 else 8484 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8485 } 8486 8487 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8488 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8489 // for fneg/fabs. 8490 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8491 // Make -1 and vspltisw -1: 8492 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8493 8494 // Make the VSLW intrinsic, computing 0x8000_0000. 8495 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8496 OnesV, DAG, dl); 8497 8498 // xor by OnesV to invert it. 8499 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8500 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8501 } 8502 8503 // Check to see if this is a wide variety of vsplti*, binop self cases. 8504 static const signed char SplatCsts[] = { 8505 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8506 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8507 }; 8508 8509 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8510 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8511 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8512 int i = SplatCsts[idx]; 8513 8514 // Figure out what shift amount will be used by altivec if shifted by i in 8515 // this splat size. 8516 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8517 8518 // vsplti + shl self. 8519 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8520 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8521 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8522 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8523 Intrinsic::ppc_altivec_vslw 8524 }; 8525 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8526 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8527 } 8528 8529 // vsplti + srl self. 8530 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8531 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8532 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8533 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8534 Intrinsic::ppc_altivec_vsrw 8535 }; 8536 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8537 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8538 } 8539 8540 // vsplti + sra self. 8541 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8542 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8543 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8544 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8545 Intrinsic::ppc_altivec_vsraw 8546 }; 8547 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8548 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8549 } 8550 8551 // vsplti + rol self. 8552 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8553 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8554 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8555 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8556 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8557 Intrinsic::ppc_altivec_vrlw 8558 }; 8559 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8560 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8561 } 8562 8563 // t = vsplti c, result = vsldoi t, t, 1 8564 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8565 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8566 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8567 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8568 } 8569 // t = vsplti c, result = vsldoi t, t, 2 8570 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8571 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8572 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8573 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8574 } 8575 // t = vsplti c, result = vsldoi t, t, 3 8576 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8577 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8578 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8579 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8580 } 8581 } 8582 8583 return SDValue(); 8584 } 8585 8586 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8587 /// the specified operations to build the shuffle. 8588 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8589 SDValue RHS, SelectionDAG &DAG, 8590 const SDLoc &dl) { 8591 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8592 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8593 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8594 8595 enum { 8596 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8597 OP_VMRGHW, 8598 OP_VMRGLW, 8599 OP_VSPLTISW0, 8600 OP_VSPLTISW1, 8601 OP_VSPLTISW2, 8602 OP_VSPLTISW3, 8603 OP_VSLDOI4, 8604 OP_VSLDOI8, 8605 OP_VSLDOI12 8606 }; 8607 8608 if (OpNum == OP_COPY) { 8609 if (LHSID == (1*9+2)*9+3) return LHS; 8610 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8611 return RHS; 8612 } 8613 8614 SDValue OpLHS, OpRHS; 8615 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8616 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8617 8618 int ShufIdxs[16]; 8619 switch (OpNum) { 8620 default: llvm_unreachable("Unknown i32 permute!"); 8621 case OP_VMRGHW: 8622 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8623 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8624 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8625 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8626 break; 8627 case OP_VMRGLW: 8628 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8629 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8630 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8631 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8632 break; 8633 case OP_VSPLTISW0: 8634 for (unsigned i = 0; i != 16; ++i) 8635 ShufIdxs[i] = (i&3)+0; 8636 break; 8637 case OP_VSPLTISW1: 8638 for (unsigned i = 0; i != 16; ++i) 8639 ShufIdxs[i] = (i&3)+4; 8640 break; 8641 case OP_VSPLTISW2: 8642 for (unsigned i = 0; i != 16; ++i) 8643 ShufIdxs[i] = (i&3)+8; 8644 break; 8645 case OP_VSPLTISW3: 8646 for (unsigned i = 0; i != 16; ++i) 8647 ShufIdxs[i] = (i&3)+12; 8648 break; 8649 case OP_VSLDOI4: 8650 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8651 case OP_VSLDOI8: 8652 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8653 case OP_VSLDOI12: 8654 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8655 } 8656 EVT VT = OpLHS.getValueType(); 8657 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8658 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8659 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8660 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8661 } 8662 8663 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8664 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8665 /// SDValue. 8666 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8667 SelectionDAG &DAG) const { 8668 const unsigned BytesInVector = 16; 8669 bool IsLE = Subtarget.isLittleEndian(); 8670 SDLoc dl(N); 8671 SDValue V1 = N->getOperand(0); 8672 SDValue V2 = N->getOperand(1); 8673 unsigned ShiftElts = 0, InsertAtByte = 0; 8674 bool Swap = false; 8675 8676 // Shifts required to get the byte we want at element 7. 8677 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8678 0, 15, 14, 13, 12, 11, 10, 9}; 8679 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8680 1, 2, 3, 4, 5, 6, 7, 8}; 8681 8682 ArrayRef<int> Mask = N->getMask(); 8683 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8684 8685 // For each mask element, find out if we're just inserting something 8686 // from V2 into V1 or vice versa. 8687 // Possible permutations inserting an element from V2 into V1: 8688 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8689 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8690 // ... 8691 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8692 // Inserting from V1 into V2 will be similar, except mask range will be 8693 // [16,31]. 8694 8695 bool FoundCandidate = false; 8696 // If both vector operands for the shuffle are the same vector, the mask 8697 // will contain only elements from the first one and the second one will be 8698 // undef. 8699 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8700 // Go through the mask of half-words to find an element that's being moved 8701 // from one vector to the other. 8702 for (unsigned i = 0; i < BytesInVector; ++i) { 8703 unsigned CurrentElement = Mask[i]; 8704 // If 2nd operand is undefined, we should only look for element 7 in the 8705 // Mask. 8706 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8707 continue; 8708 8709 bool OtherElementsInOrder = true; 8710 // Examine the other elements in the Mask to see if they're in original 8711 // order. 8712 for (unsigned j = 0; j < BytesInVector; ++j) { 8713 if (j == i) 8714 continue; 8715 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8716 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8717 // in which we always assume we're always picking from the 1st operand. 8718 int MaskOffset = 8719 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8720 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8721 OtherElementsInOrder = false; 8722 break; 8723 } 8724 } 8725 // If other elements are in original order, we record the number of shifts 8726 // we need to get the element we want into element 7. Also record which byte 8727 // in the vector we should insert into. 8728 if (OtherElementsInOrder) { 8729 // If 2nd operand is undefined, we assume no shifts and no swapping. 8730 if (V2.isUndef()) { 8731 ShiftElts = 0; 8732 Swap = false; 8733 } else { 8734 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8735 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8736 : BigEndianShifts[CurrentElement & 0xF]; 8737 Swap = CurrentElement < BytesInVector; 8738 } 8739 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8740 FoundCandidate = true; 8741 break; 8742 } 8743 } 8744 8745 if (!FoundCandidate) 8746 return SDValue(); 8747 8748 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8749 // optionally with VECSHL if shift is required. 8750 if (Swap) 8751 std::swap(V1, V2); 8752 if (V2.isUndef()) 8753 V2 = V1; 8754 if (ShiftElts) { 8755 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8756 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8757 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8758 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8759 } 8760 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8761 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8762 } 8763 8764 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8765 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8766 /// SDValue. 8767 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8768 SelectionDAG &DAG) const { 8769 const unsigned NumHalfWords = 8; 8770 const unsigned BytesInVector = NumHalfWords * 2; 8771 // Check that the shuffle is on half-words. 8772 if (!isNByteElemShuffleMask(N, 2, 1)) 8773 return SDValue(); 8774 8775 bool IsLE = Subtarget.isLittleEndian(); 8776 SDLoc dl(N); 8777 SDValue V1 = N->getOperand(0); 8778 SDValue V2 = N->getOperand(1); 8779 unsigned ShiftElts = 0, InsertAtByte = 0; 8780 bool Swap = false; 8781 8782 // Shifts required to get the half-word we want at element 3. 8783 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8784 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8785 8786 uint32_t Mask = 0; 8787 uint32_t OriginalOrderLow = 0x1234567; 8788 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8789 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8790 // 32-bit space, only need 4-bit nibbles per element. 8791 for (unsigned i = 0; i < NumHalfWords; ++i) { 8792 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8793 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8794 } 8795 8796 // For each mask element, find out if we're just inserting something 8797 // from V2 into V1 or vice versa. Possible permutations inserting an element 8798 // from V2 into V1: 8799 // X, 1, 2, 3, 4, 5, 6, 7 8800 // 0, X, 2, 3, 4, 5, 6, 7 8801 // 0, 1, X, 3, 4, 5, 6, 7 8802 // 0, 1, 2, X, 4, 5, 6, 7 8803 // 0, 1, 2, 3, X, 5, 6, 7 8804 // 0, 1, 2, 3, 4, X, 6, 7 8805 // 0, 1, 2, 3, 4, 5, X, 7 8806 // 0, 1, 2, 3, 4, 5, 6, X 8807 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8808 8809 bool FoundCandidate = false; 8810 // Go through the mask of half-words to find an element that's being moved 8811 // from one vector to the other. 8812 for (unsigned i = 0; i < NumHalfWords; ++i) { 8813 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8814 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8815 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8816 uint32_t TargetOrder = 0x0; 8817 8818 // If both vector operands for the shuffle are the same vector, the mask 8819 // will contain only elements from the first one and the second one will be 8820 // undef. 8821 if (V2.isUndef()) { 8822 ShiftElts = 0; 8823 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8824 TargetOrder = OriginalOrderLow; 8825 Swap = false; 8826 // Skip if not the correct element or mask of other elements don't equal 8827 // to our expected order. 8828 if (MaskOneElt == VINSERTHSrcElem && 8829 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8830 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8831 FoundCandidate = true; 8832 break; 8833 } 8834 } else { // If both operands are defined. 8835 // Target order is [8,15] if the current mask is between [0,7]. 8836 TargetOrder = 8837 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8838 // Skip if mask of other elements don't equal our expected order. 8839 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8840 // We only need the last 3 bits for the number of shifts. 8841 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8842 : BigEndianShifts[MaskOneElt & 0x7]; 8843 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8844 Swap = MaskOneElt < NumHalfWords; 8845 FoundCandidate = true; 8846 break; 8847 } 8848 } 8849 } 8850 8851 if (!FoundCandidate) 8852 return SDValue(); 8853 8854 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8855 // optionally with VECSHL if shift is required. 8856 if (Swap) 8857 std::swap(V1, V2); 8858 if (V2.isUndef()) 8859 V2 = V1; 8860 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8861 if (ShiftElts) { 8862 // Double ShiftElts because we're left shifting on v16i8 type. 8863 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8864 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8865 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8866 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8867 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8868 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8869 } 8870 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8871 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8872 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8873 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8874 } 8875 8876 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8877 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8878 /// return the code it can be lowered into. Worst case, it can always be 8879 /// lowered into a vperm. 8880 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8881 SelectionDAG &DAG) const { 8882 SDLoc dl(Op); 8883 SDValue V1 = Op.getOperand(0); 8884 SDValue V2 = Op.getOperand(1); 8885 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8886 EVT VT = Op.getValueType(); 8887 bool isLittleEndian = Subtarget.isLittleEndian(); 8888 8889 unsigned ShiftElts, InsertAtByte; 8890 bool Swap = false; 8891 8892 // If this is a load-and-splat, we can do that with a single instruction 8893 // in some cases. However if the load has multiple uses, we don't want to 8894 // combine it because that will just produce multiple loads. 8895 const SDValue *InputLoad = getNormalLoadInput(V1); 8896 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 8897 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 8898 InputLoad->hasOneUse()) { 8899 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 8900 int SplatIdx = 8901 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 8902 8903 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8904 // For 4-byte load-and-splat, we need Power9. 8905 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 8906 uint64_t Offset = 0; 8907 if (IsFourByte) 8908 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 8909 else 8910 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 8911 SDValue BasePtr = LD->getBasePtr(); 8912 if (Offset != 0) 8913 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 8914 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 8915 SDValue Ops[] = { 8916 LD->getChain(), // Chain 8917 BasePtr, // BasePtr 8918 DAG.getValueType(Op.getValueType()) // VT 8919 }; 8920 SDVTList VTL = 8921 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 8922 SDValue LdSplt = 8923 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 8924 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8925 if (LdSplt.getValueType() != SVOp->getValueType(0)) 8926 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 8927 return LdSplt; 8928 } 8929 } 8930 if (Subtarget.hasP9Vector() && 8931 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8932 isLittleEndian)) { 8933 if (Swap) 8934 std::swap(V1, V2); 8935 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8936 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8937 if (ShiftElts) { 8938 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8939 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8940 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8941 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8942 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8943 } 8944 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8945 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8946 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8947 } 8948 8949 if (Subtarget.hasP9Altivec()) { 8950 SDValue NewISDNode; 8951 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8952 return NewISDNode; 8953 8954 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8955 return NewISDNode; 8956 } 8957 8958 if (Subtarget.hasVSX() && 8959 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8960 if (Swap) 8961 std::swap(V1, V2); 8962 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8963 SDValue Conv2 = 8964 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8965 8966 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8967 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8968 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8969 } 8970 8971 if (Subtarget.hasVSX() && 8972 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8973 if (Swap) 8974 std::swap(V1, V2); 8975 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8976 SDValue Conv2 = 8977 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8978 8979 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8980 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8981 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8982 } 8983 8984 if (Subtarget.hasP9Vector()) { 8985 if (PPC::isXXBRHShuffleMask(SVOp)) { 8986 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8987 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8988 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8989 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8990 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8991 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8992 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8993 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8994 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8995 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8996 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8997 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8998 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8999 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 9000 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9001 } 9002 } 9003 9004 if (Subtarget.hasVSX()) { 9005 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9006 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9007 9008 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9009 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9010 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9011 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9012 } 9013 9014 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9015 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9016 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9017 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9018 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9019 } 9020 } 9021 9022 if (Subtarget.hasQPX()) { 9023 if (VT.getVectorNumElements() != 4) 9024 return SDValue(); 9025 9026 if (V2.isUndef()) V2 = V1; 9027 9028 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9029 if (AlignIdx != -1) { 9030 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9031 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9032 } else if (SVOp->isSplat()) { 9033 int SplatIdx = SVOp->getSplatIndex(); 9034 if (SplatIdx >= 4) { 9035 std::swap(V1, V2); 9036 SplatIdx -= 4; 9037 } 9038 9039 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9040 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9041 } 9042 9043 // Lower this into a qvgpci/qvfperm pair. 9044 9045 // Compute the qvgpci literal 9046 unsigned idx = 0; 9047 for (unsigned i = 0; i < 4; ++i) { 9048 int m = SVOp->getMaskElt(i); 9049 unsigned mm = m >= 0 ? (unsigned) m : i; 9050 idx |= mm << (3-i)*3; 9051 } 9052 9053 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9054 DAG.getConstant(idx, dl, MVT::i32)); 9055 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9056 } 9057 9058 // Cases that are handled by instructions that take permute immediates 9059 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9060 // selected by the instruction selector. 9061 if (V2.isUndef()) { 9062 if (PPC::isSplatShuffleMask(SVOp, 1) || 9063 PPC::isSplatShuffleMask(SVOp, 2) || 9064 PPC::isSplatShuffleMask(SVOp, 4) || 9065 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9066 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9067 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9068 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9069 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9070 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9071 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9072 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9073 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9074 (Subtarget.hasP8Altivec() && ( 9075 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9076 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9077 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9078 return Op; 9079 } 9080 } 9081 9082 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9083 // and produce a fixed permutation. If any of these match, do not lower to 9084 // VPERM. 9085 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9086 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9087 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9088 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9089 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9090 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9091 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9092 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9093 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9094 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9095 (Subtarget.hasP8Altivec() && ( 9096 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9097 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9098 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9099 return Op; 9100 9101 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9102 // perfect shuffle table to emit an optimal matching sequence. 9103 ArrayRef<int> PermMask = SVOp->getMask(); 9104 9105 unsigned PFIndexes[4]; 9106 bool isFourElementShuffle = true; 9107 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9108 unsigned EltNo = 8; // Start out undef. 9109 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9110 if (PermMask[i*4+j] < 0) 9111 continue; // Undef, ignore it. 9112 9113 unsigned ByteSource = PermMask[i*4+j]; 9114 if ((ByteSource & 3) != j) { 9115 isFourElementShuffle = false; 9116 break; 9117 } 9118 9119 if (EltNo == 8) { 9120 EltNo = ByteSource/4; 9121 } else if (EltNo != ByteSource/4) { 9122 isFourElementShuffle = false; 9123 break; 9124 } 9125 } 9126 PFIndexes[i] = EltNo; 9127 } 9128 9129 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9130 // perfect shuffle vector to determine if it is cost effective to do this as 9131 // discrete instructions, or whether we should use a vperm. 9132 // For now, we skip this for little endian until such time as we have a 9133 // little-endian perfect shuffle table. 9134 if (isFourElementShuffle && !isLittleEndian) { 9135 // Compute the index in the perfect shuffle table. 9136 unsigned PFTableIndex = 9137 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9138 9139 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9140 unsigned Cost = (PFEntry >> 30); 9141 9142 // Determining when to avoid vperm is tricky. Many things affect the cost 9143 // of vperm, particularly how many times the perm mask needs to be computed. 9144 // For example, if the perm mask can be hoisted out of a loop or is already 9145 // used (perhaps because there are multiple permutes with the same shuffle 9146 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9147 // the loop requires an extra register. 9148 // 9149 // As a compromise, we only emit discrete instructions if the shuffle can be 9150 // generated in 3 or fewer operations. When we have loop information 9151 // available, if this block is within a loop, we should avoid using vperm 9152 // for 3-operation perms and use a constant pool load instead. 9153 if (Cost < 3) 9154 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9155 } 9156 9157 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9158 // vector that will get spilled to the constant pool. 9159 if (V2.isUndef()) V2 = V1; 9160 9161 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9162 // that it is in input element units, not in bytes. Convert now. 9163 9164 // For little endian, the order of the input vectors is reversed, and 9165 // the permutation mask is complemented with respect to 31. This is 9166 // necessary to produce proper semantics with the big-endian-biased vperm 9167 // instruction. 9168 EVT EltVT = V1.getValueType().getVectorElementType(); 9169 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9170 9171 SmallVector<SDValue, 16> ResultMask; 9172 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9173 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9174 9175 for (unsigned j = 0; j != BytesPerElement; ++j) 9176 if (isLittleEndian) 9177 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9178 dl, MVT::i32)); 9179 else 9180 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9181 MVT::i32)); 9182 } 9183 9184 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9185 if (isLittleEndian) 9186 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9187 V2, V1, VPermMask); 9188 else 9189 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9190 V1, V2, VPermMask); 9191 } 9192 9193 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9194 /// vector comparison. If it is, return true and fill in Opc/isDot with 9195 /// information about the intrinsic. 9196 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9197 bool &isDot, const PPCSubtarget &Subtarget) { 9198 unsigned IntrinsicID = 9199 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9200 CompareOpc = -1; 9201 isDot = false; 9202 switch (IntrinsicID) { 9203 default: 9204 return false; 9205 // Comparison predicates. 9206 case Intrinsic::ppc_altivec_vcmpbfp_p: 9207 CompareOpc = 966; 9208 isDot = true; 9209 break; 9210 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9211 CompareOpc = 198; 9212 isDot = true; 9213 break; 9214 case Intrinsic::ppc_altivec_vcmpequb_p: 9215 CompareOpc = 6; 9216 isDot = true; 9217 break; 9218 case Intrinsic::ppc_altivec_vcmpequh_p: 9219 CompareOpc = 70; 9220 isDot = true; 9221 break; 9222 case Intrinsic::ppc_altivec_vcmpequw_p: 9223 CompareOpc = 134; 9224 isDot = true; 9225 break; 9226 case Intrinsic::ppc_altivec_vcmpequd_p: 9227 if (Subtarget.hasP8Altivec()) { 9228 CompareOpc = 199; 9229 isDot = true; 9230 } else 9231 return false; 9232 break; 9233 case Intrinsic::ppc_altivec_vcmpneb_p: 9234 case Intrinsic::ppc_altivec_vcmpneh_p: 9235 case Intrinsic::ppc_altivec_vcmpnew_p: 9236 case Intrinsic::ppc_altivec_vcmpnezb_p: 9237 case Intrinsic::ppc_altivec_vcmpnezh_p: 9238 case Intrinsic::ppc_altivec_vcmpnezw_p: 9239 if (Subtarget.hasP9Altivec()) { 9240 switch (IntrinsicID) { 9241 default: 9242 llvm_unreachable("Unknown comparison intrinsic."); 9243 case Intrinsic::ppc_altivec_vcmpneb_p: 9244 CompareOpc = 7; 9245 break; 9246 case Intrinsic::ppc_altivec_vcmpneh_p: 9247 CompareOpc = 71; 9248 break; 9249 case Intrinsic::ppc_altivec_vcmpnew_p: 9250 CompareOpc = 135; 9251 break; 9252 case Intrinsic::ppc_altivec_vcmpnezb_p: 9253 CompareOpc = 263; 9254 break; 9255 case Intrinsic::ppc_altivec_vcmpnezh_p: 9256 CompareOpc = 327; 9257 break; 9258 case Intrinsic::ppc_altivec_vcmpnezw_p: 9259 CompareOpc = 391; 9260 break; 9261 } 9262 isDot = true; 9263 } else 9264 return false; 9265 break; 9266 case Intrinsic::ppc_altivec_vcmpgefp_p: 9267 CompareOpc = 454; 9268 isDot = true; 9269 break; 9270 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9271 CompareOpc = 710; 9272 isDot = true; 9273 break; 9274 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9275 CompareOpc = 774; 9276 isDot = true; 9277 break; 9278 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9279 CompareOpc = 838; 9280 isDot = true; 9281 break; 9282 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9283 CompareOpc = 902; 9284 isDot = true; 9285 break; 9286 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9287 if (Subtarget.hasP8Altivec()) { 9288 CompareOpc = 967; 9289 isDot = true; 9290 } else 9291 return false; 9292 break; 9293 case Intrinsic::ppc_altivec_vcmpgtub_p: 9294 CompareOpc = 518; 9295 isDot = true; 9296 break; 9297 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9298 CompareOpc = 582; 9299 isDot = true; 9300 break; 9301 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9302 CompareOpc = 646; 9303 isDot = true; 9304 break; 9305 case Intrinsic::ppc_altivec_vcmpgtud_p: 9306 if (Subtarget.hasP8Altivec()) { 9307 CompareOpc = 711; 9308 isDot = true; 9309 } else 9310 return false; 9311 break; 9312 9313 // VSX predicate comparisons use the same infrastructure 9314 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9315 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9316 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9317 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9318 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9319 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9320 if (Subtarget.hasVSX()) { 9321 switch (IntrinsicID) { 9322 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9323 CompareOpc = 99; 9324 break; 9325 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9326 CompareOpc = 115; 9327 break; 9328 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9329 CompareOpc = 107; 9330 break; 9331 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9332 CompareOpc = 67; 9333 break; 9334 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9335 CompareOpc = 83; 9336 break; 9337 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9338 CompareOpc = 75; 9339 break; 9340 } 9341 isDot = true; 9342 } else 9343 return false; 9344 break; 9345 9346 // Normal Comparisons. 9347 case Intrinsic::ppc_altivec_vcmpbfp: 9348 CompareOpc = 966; 9349 break; 9350 case Intrinsic::ppc_altivec_vcmpeqfp: 9351 CompareOpc = 198; 9352 break; 9353 case Intrinsic::ppc_altivec_vcmpequb: 9354 CompareOpc = 6; 9355 break; 9356 case Intrinsic::ppc_altivec_vcmpequh: 9357 CompareOpc = 70; 9358 break; 9359 case Intrinsic::ppc_altivec_vcmpequw: 9360 CompareOpc = 134; 9361 break; 9362 case Intrinsic::ppc_altivec_vcmpequd: 9363 if (Subtarget.hasP8Altivec()) 9364 CompareOpc = 199; 9365 else 9366 return false; 9367 break; 9368 case Intrinsic::ppc_altivec_vcmpneb: 9369 case Intrinsic::ppc_altivec_vcmpneh: 9370 case Intrinsic::ppc_altivec_vcmpnew: 9371 case Intrinsic::ppc_altivec_vcmpnezb: 9372 case Intrinsic::ppc_altivec_vcmpnezh: 9373 case Intrinsic::ppc_altivec_vcmpnezw: 9374 if (Subtarget.hasP9Altivec()) 9375 switch (IntrinsicID) { 9376 default: 9377 llvm_unreachable("Unknown comparison intrinsic."); 9378 case Intrinsic::ppc_altivec_vcmpneb: 9379 CompareOpc = 7; 9380 break; 9381 case Intrinsic::ppc_altivec_vcmpneh: 9382 CompareOpc = 71; 9383 break; 9384 case Intrinsic::ppc_altivec_vcmpnew: 9385 CompareOpc = 135; 9386 break; 9387 case Intrinsic::ppc_altivec_vcmpnezb: 9388 CompareOpc = 263; 9389 break; 9390 case Intrinsic::ppc_altivec_vcmpnezh: 9391 CompareOpc = 327; 9392 break; 9393 case Intrinsic::ppc_altivec_vcmpnezw: 9394 CompareOpc = 391; 9395 break; 9396 } 9397 else 9398 return false; 9399 break; 9400 case Intrinsic::ppc_altivec_vcmpgefp: 9401 CompareOpc = 454; 9402 break; 9403 case Intrinsic::ppc_altivec_vcmpgtfp: 9404 CompareOpc = 710; 9405 break; 9406 case Intrinsic::ppc_altivec_vcmpgtsb: 9407 CompareOpc = 774; 9408 break; 9409 case Intrinsic::ppc_altivec_vcmpgtsh: 9410 CompareOpc = 838; 9411 break; 9412 case Intrinsic::ppc_altivec_vcmpgtsw: 9413 CompareOpc = 902; 9414 break; 9415 case Intrinsic::ppc_altivec_vcmpgtsd: 9416 if (Subtarget.hasP8Altivec()) 9417 CompareOpc = 967; 9418 else 9419 return false; 9420 break; 9421 case Intrinsic::ppc_altivec_vcmpgtub: 9422 CompareOpc = 518; 9423 break; 9424 case Intrinsic::ppc_altivec_vcmpgtuh: 9425 CompareOpc = 582; 9426 break; 9427 case Intrinsic::ppc_altivec_vcmpgtuw: 9428 CompareOpc = 646; 9429 break; 9430 case Intrinsic::ppc_altivec_vcmpgtud: 9431 if (Subtarget.hasP8Altivec()) 9432 CompareOpc = 711; 9433 else 9434 return false; 9435 break; 9436 } 9437 return true; 9438 } 9439 9440 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 9441 /// lower, do it, otherwise return null. 9442 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 9443 SelectionDAG &DAG) const { 9444 unsigned IntrinsicID = 9445 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9446 9447 SDLoc dl(Op); 9448 9449 if (IntrinsicID == Intrinsic::thread_pointer) { 9450 // Reads the thread pointer register, used for __builtin_thread_pointer. 9451 if (Subtarget.isPPC64()) 9452 return DAG.getRegister(PPC::X13, MVT::i64); 9453 return DAG.getRegister(PPC::R2, MVT::i32); 9454 } 9455 9456 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9457 // opcode number of the comparison. 9458 int CompareOpc; 9459 bool isDot; 9460 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9461 return SDValue(); // Don't custom lower most intrinsics. 9462 9463 // If this is a non-dot comparison, make the VCMP node and we are done. 9464 if (!isDot) { 9465 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9466 Op.getOperand(1), Op.getOperand(2), 9467 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9468 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9469 } 9470 9471 // Create the PPCISD altivec 'dot' comparison node. 9472 SDValue Ops[] = { 9473 Op.getOperand(2), // LHS 9474 Op.getOperand(3), // RHS 9475 DAG.getConstant(CompareOpc, dl, MVT::i32) 9476 }; 9477 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9478 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9479 9480 // Now that we have the comparison, emit a copy from the CR to a GPR. 9481 // This is flagged to the above dot comparison. 9482 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9483 DAG.getRegister(PPC::CR6, MVT::i32), 9484 CompNode.getValue(1)); 9485 9486 // Unpack the result based on how the target uses it. 9487 unsigned BitNo; // Bit # of CR6. 9488 bool InvertBit; // Invert result? 9489 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9490 default: // Can't happen, don't crash on invalid number though. 9491 case 0: // Return the value of the EQ bit of CR6. 9492 BitNo = 0; InvertBit = false; 9493 break; 9494 case 1: // Return the inverted value of the EQ bit of CR6. 9495 BitNo = 0; InvertBit = true; 9496 break; 9497 case 2: // Return the value of the LT bit of CR6. 9498 BitNo = 2; InvertBit = false; 9499 break; 9500 case 3: // Return the inverted value of the LT bit of CR6. 9501 BitNo = 2; InvertBit = true; 9502 break; 9503 } 9504 9505 // Shift the bit into the low position. 9506 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9507 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9508 // Isolate the bit. 9509 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9510 DAG.getConstant(1, dl, MVT::i32)); 9511 9512 // If we are supposed to, toggle the bit. 9513 if (InvertBit) 9514 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9515 DAG.getConstant(1, dl, MVT::i32)); 9516 return Flags; 9517 } 9518 9519 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9520 SelectionDAG &DAG) const { 9521 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9522 // the beginning of the argument list. 9523 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9524 SDLoc DL(Op); 9525 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9526 case Intrinsic::ppc_cfence: { 9527 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9528 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9529 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9530 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9531 Op.getOperand(ArgStart + 1)), 9532 Op.getOperand(0)), 9533 0); 9534 } 9535 default: 9536 break; 9537 } 9538 return SDValue(); 9539 } 9540 9541 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9542 // Check for a DIV with the same operands as this REM. 9543 for (auto UI : Op.getOperand(1)->uses()) { 9544 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9545 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9546 if (UI->getOperand(0) == Op.getOperand(0) && 9547 UI->getOperand(1) == Op.getOperand(1)) 9548 return SDValue(); 9549 } 9550 return Op; 9551 } 9552 9553 // Lower scalar BSWAP64 to xxbrd. 9554 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9555 SDLoc dl(Op); 9556 // MTVSRDD 9557 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9558 Op.getOperand(0)); 9559 // XXBRD 9560 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9561 // MFVSRD 9562 int VectorIndex = 0; 9563 if (Subtarget.isLittleEndian()) 9564 VectorIndex = 1; 9565 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9566 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9567 return Op; 9568 } 9569 9570 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9571 // compared to a value that is atomically loaded (atomic loads zero-extend). 9572 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9573 SelectionDAG &DAG) const { 9574 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9575 "Expecting an atomic compare-and-swap here."); 9576 SDLoc dl(Op); 9577 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9578 EVT MemVT = AtomicNode->getMemoryVT(); 9579 if (MemVT.getSizeInBits() >= 32) 9580 return Op; 9581 9582 SDValue CmpOp = Op.getOperand(2); 9583 // If this is already correctly zero-extended, leave it alone. 9584 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9585 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9586 return Op; 9587 9588 // Clear the high bits of the compare operand. 9589 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9590 SDValue NewCmpOp = 9591 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9592 DAG.getConstant(MaskVal, dl, MVT::i32)); 9593 9594 // Replace the existing compare operand with the properly zero-extended one. 9595 SmallVector<SDValue, 4> Ops; 9596 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9597 Ops.push_back(AtomicNode->getOperand(i)); 9598 Ops[2] = NewCmpOp; 9599 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9600 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9601 auto NodeTy = 9602 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9603 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9604 } 9605 9606 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9607 SelectionDAG &DAG) const { 9608 SDLoc dl(Op); 9609 // Create a stack slot that is 16-byte aligned. 9610 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9611 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9612 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9613 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9614 9615 // Store the input value into Value#0 of the stack slot. 9616 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9617 MachinePointerInfo()); 9618 // Load it out. 9619 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9620 } 9621 9622 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9623 SelectionDAG &DAG) const { 9624 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9625 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9626 9627 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9628 // We have legal lowering for constant indices but not for variable ones. 9629 if (!C) 9630 return SDValue(); 9631 9632 EVT VT = Op.getValueType(); 9633 SDLoc dl(Op); 9634 SDValue V1 = Op.getOperand(0); 9635 SDValue V2 = Op.getOperand(1); 9636 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9637 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9638 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9639 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9640 unsigned InsertAtElement = C->getZExtValue(); 9641 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9642 if (Subtarget.isLittleEndian()) { 9643 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9644 } 9645 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9646 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9647 } 9648 return Op; 9649 } 9650 9651 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9652 SelectionDAG &DAG) const { 9653 SDLoc dl(Op); 9654 SDNode *N = Op.getNode(); 9655 9656 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9657 "Unknown extract_vector_elt type"); 9658 9659 SDValue Value = N->getOperand(0); 9660 9661 // The first part of this is like the store lowering except that we don't 9662 // need to track the chain. 9663 9664 // The values are now known to be -1 (false) or 1 (true). To convert this 9665 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9666 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9667 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9668 9669 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9670 // understand how to form the extending load. 9671 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9672 9673 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9674 9675 // Now convert to an integer and store. 9676 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9677 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9678 Value); 9679 9680 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9681 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9682 MachinePointerInfo PtrInfo = 9683 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9684 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9685 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9686 9687 SDValue StoreChain = DAG.getEntryNode(); 9688 SDValue Ops[] = {StoreChain, 9689 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9690 Value, FIdx}; 9691 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9692 9693 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9694 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9695 9696 // Extract the value requested. 9697 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9698 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9699 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9700 9701 SDValue IntVal = 9702 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9703 9704 if (!Subtarget.useCRBits()) 9705 return IntVal; 9706 9707 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9708 } 9709 9710 /// Lowering for QPX v4i1 loads 9711 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9712 SelectionDAG &DAG) const { 9713 SDLoc dl(Op); 9714 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9715 SDValue LoadChain = LN->getChain(); 9716 SDValue BasePtr = LN->getBasePtr(); 9717 9718 if (Op.getValueType() == MVT::v4f64 || 9719 Op.getValueType() == MVT::v4f32) { 9720 EVT MemVT = LN->getMemoryVT(); 9721 unsigned Alignment = LN->getAlignment(); 9722 9723 // If this load is properly aligned, then it is legal. 9724 if (Alignment >= MemVT.getStoreSize()) 9725 return Op; 9726 9727 EVT ScalarVT = Op.getValueType().getScalarType(), 9728 ScalarMemVT = MemVT.getScalarType(); 9729 unsigned Stride = ScalarMemVT.getStoreSize(); 9730 9731 SDValue Vals[4], LoadChains[4]; 9732 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9733 SDValue Load; 9734 if (ScalarVT != ScalarMemVT) 9735 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9736 BasePtr, 9737 LN->getPointerInfo().getWithOffset(Idx * Stride), 9738 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9739 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9740 else 9741 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9742 LN->getPointerInfo().getWithOffset(Idx * Stride), 9743 MinAlign(Alignment, Idx * Stride), 9744 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9745 9746 if (Idx == 0 && LN->isIndexed()) { 9747 assert(LN->getAddressingMode() == ISD::PRE_INC && 9748 "Unknown addressing mode on vector load"); 9749 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9750 LN->getAddressingMode()); 9751 } 9752 9753 Vals[Idx] = Load; 9754 LoadChains[Idx] = Load.getValue(1); 9755 9756 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9757 DAG.getConstant(Stride, dl, 9758 BasePtr.getValueType())); 9759 } 9760 9761 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9762 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9763 9764 if (LN->isIndexed()) { 9765 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9766 return DAG.getMergeValues(RetOps, dl); 9767 } 9768 9769 SDValue RetOps[] = { Value, TF }; 9770 return DAG.getMergeValues(RetOps, dl); 9771 } 9772 9773 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9774 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9775 9776 // To lower v4i1 from a byte array, we load the byte elements of the 9777 // vector and then reuse the BUILD_VECTOR logic. 9778 9779 SDValue VectElmts[4], VectElmtChains[4]; 9780 for (unsigned i = 0; i < 4; ++i) { 9781 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9782 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9783 9784 VectElmts[i] = DAG.getExtLoad( 9785 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9786 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9787 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9788 VectElmtChains[i] = VectElmts[i].getValue(1); 9789 } 9790 9791 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9792 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9793 9794 SDValue RVals[] = { Value, LoadChain }; 9795 return DAG.getMergeValues(RVals, dl); 9796 } 9797 9798 /// Lowering for QPX v4i1 stores 9799 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9800 SelectionDAG &DAG) const { 9801 SDLoc dl(Op); 9802 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9803 SDValue StoreChain = SN->getChain(); 9804 SDValue BasePtr = SN->getBasePtr(); 9805 SDValue Value = SN->getValue(); 9806 9807 if (Value.getValueType() == MVT::v4f64 || 9808 Value.getValueType() == MVT::v4f32) { 9809 EVT MemVT = SN->getMemoryVT(); 9810 unsigned Alignment = SN->getAlignment(); 9811 9812 // If this store is properly aligned, then it is legal. 9813 if (Alignment >= MemVT.getStoreSize()) 9814 return Op; 9815 9816 EVT ScalarVT = Value.getValueType().getScalarType(), 9817 ScalarMemVT = MemVT.getScalarType(); 9818 unsigned Stride = ScalarMemVT.getStoreSize(); 9819 9820 SDValue Stores[4]; 9821 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9822 SDValue Ex = DAG.getNode( 9823 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9824 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9825 SDValue Store; 9826 if (ScalarVT != ScalarMemVT) 9827 Store = 9828 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9829 SN->getPointerInfo().getWithOffset(Idx * Stride), 9830 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9831 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9832 else 9833 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9834 SN->getPointerInfo().getWithOffset(Idx * Stride), 9835 MinAlign(Alignment, Idx * Stride), 9836 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9837 9838 if (Idx == 0 && SN->isIndexed()) { 9839 assert(SN->getAddressingMode() == ISD::PRE_INC && 9840 "Unknown addressing mode on vector store"); 9841 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9842 SN->getAddressingMode()); 9843 } 9844 9845 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9846 DAG.getConstant(Stride, dl, 9847 BasePtr.getValueType())); 9848 Stores[Idx] = Store; 9849 } 9850 9851 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9852 9853 if (SN->isIndexed()) { 9854 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9855 return DAG.getMergeValues(RetOps, dl); 9856 } 9857 9858 return TF; 9859 } 9860 9861 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9862 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9863 9864 // The values are now known to be -1 (false) or 1 (true). To convert this 9865 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9866 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9867 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9868 9869 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9870 // understand how to form the extending load. 9871 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9872 9873 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9874 9875 // Now convert to an integer and store. 9876 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9877 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9878 Value); 9879 9880 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9881 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9882 MachinePointerInfo PtrInfo = 9883 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9884 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9885 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9886 9887 SDValue Ops[] = {StoreChain, 9888 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9889 Value, FIdx}; 9890 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9891 9892 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9893 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9894 9895 // Move data into the byte array. 9896 SDValue Loads[4], LoadChains[4]; 9897 for (unsigned i = 0; i < 4; ++i) { 9898 unsigned Offset = 4*i; 9899 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9900 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9901 9902 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9903 PtrInfo.getWithOffset(Offset)); 9904 LoadChains[i] = Loads[i].getValue(1); 9905 } 9906 9907 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9908 9909 SDValue Stores[4]; 9910 for (unsigned i = 0; i < 4; ++i) { 9911 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9912 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9913 9914 Stores[i] = DAG.getTruncStore( 9915 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9916 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9917 SN->getAAInfo()); 9918 } 9919 9920 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9921 9922 return StoreChain; 9923 } 9924 9925 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9926 SDLoc dl(Op); 9927 if (Op.getValueType() == MVT::v4i32) { 9928 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9929 9930 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9931 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9932 9933 SDValue RHSSwap = // = vrlw RHS, 16 9934 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9935 9936 // Shrinkify inputs to v8i16. 9937 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9938 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9939 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9940 9941 // Low parts multiplied together, generating 32-bit results (we ignore the 9942 // top parts). 9943 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9944 LHS, RHS, DAG, dl, MVT::v4i32); 9945 9946 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9947 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9948 // Shift the high parts up 16 bits. 9949 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9950 Neg16, DAG, dl); 9951 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9952 } else if (Op.getValueType() == MVT::v8i16) { 9953 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9954 9955 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9956 9957 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9958 LHS, RHS, Zero, DAG, dl); 9959 } else if (Op.getValueType() == MVT::v16i8) { 9960 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9961 bool isLittleEndian = Subtarget.isLittleEndian(); 9962 9963 // Multiply the even 8-bit parts, producing 16-bit sums. 9964 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9965 LHS, RHS, DAG, dl, MVT::v8i16); 9966 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9967 9968 // Multiply the odd 8-bit parts, producing 16-bit sums. 9969 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9970 LHS, RHS, DAG, dl, MVT::v8i16); 9971 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9972 9973 // Merge the results together. Because vmuleub and vmuloub are 9974 // instructions with a big-endian bias, we must reverse the 9975 // element numbering and reverse the meaning of "odd" and "even" 9976 // when generating little endian code. 9977 int Ops[16]; 9978 for (unsigned i = 0; i != 8; ++i) { 9979 if (isLittleEndian) { 9980 Ops[i*2 ] = 2*i; 9981 Ops[i*2+1] = 2*i+16; 9982 } else { 9983 Ops[i*2 ] = 2*i+1; 9984 Ops[i*2+1] = 2*i+1+16; 9985 } 9986 } 9987 if (isLittleEndian) 9988 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9989 else 9990 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9991 } else { 9992 llvm_unreachable("Unknown mul to lower!"); 9993 } 9994 } 9995 9996 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 9997 9998 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 9999 10000 EVT VT = Op.getValueType(); 10001 assert(VT.isVector() && 10002 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10003 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10004 VT == MVT::v16i8) && 10005 "Unexpected vector element type!"); 10006 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10007 "Current subtarget doesn't support smax v2i64!"); 10008 10009 // For vector abs, it can be lowered to: 10010 // abs x 10011 // ==> 10012 // y = -x 10013 // smax(x, y) 10014 10015 SDLoc dl(Op); 10016 SDValue X = Op.getOperand(0); 10017 SDValue Zero = DAG.getConstant(0, dl, VT); 10018 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10019 10020 // SMAX patch https://reviews.llvm.org/D47332 10021 // hasn't landed yet, so use intrinsic first here. 10022 // TODO: Should use SMAX directly once SMAX patch landed 10023 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10024 if (VT == MVT::v2i64) 10025 BifID = Intrinsic::ppc_altivec_vmaxsd; 10026 else if (VT == MVT::v8i16) 10027 BifID = Intrinsic::ppc_altivec_vmaxsh; 10028 else if (VT == MVT::v16i8) 10029 BifID = Intrinsic::ppc_altivec_vmaxsb; 10030 10031 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10032 } 10033 10034 // Custom lowering for fpext vf32 to v2f64 10035 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10036 10037 assert(Op.getOpcode() == ISD::FP_EXTEND && 10038 "Should only be called for ISD::FP_EXTEND"); 10039 10040 // We only want to custom lower an extend from v2f32 to v2f64. 10041 if (Op.getValueType() != MVT::v2f64 || 10042 Op.getOperand(0).getValueType() != MVT::v2f32) 10043 return SDValue(); 10044 10045 SDLoc dl(Op); 10046 SDValue Op0 = Op.getOperand(0); 10047 10048 switch (Op0.getOpcode()) { 10049 default: 10050 return SDValue(); 10051 case ISD::EXTRACT_SUBVECTOR: { 10052 assert(Op0.getNumOperands() == 2 && 10053 isa<ConstantSDNode>(Op0->getOperand(1)) && 10054 "Node should have 2 operands with second one being a constant!"); 10055 10056 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10057 return SDValue(); 10058 10059 // Custom lower is only done for high or low doubleword. 10060 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10061 if (Idx % 2 != 0) 10062 return SDValue(); 10063 10064 // Since input is v4f32, at this point Idx is either 0 or 2. 10065 // Shift to get the doubleword position we want. 10066 int DWord = Idx >> 1; 10067 10068 // High and low word positions are different on little endian. 10069 if (Subtarget.isLittleEndian()) 10070 DWord ^= 0x1; 10071 10072 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10073 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10074 } 10075 case ISD::FADD: 10076 case ISD::FMUL: 10077 case ISD::FSUB: { 10078 SDValue NewLoad[2]; 10079 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10080 // Ensure both input are loads. 10081 SDValue LdOp = Op0.getOperand(i); 10082 if (LdOp.getOpcode() != ISD::LOAD) 10083 return SDValue(); 10084 // Generate new load node. 10085 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10086 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10087 NewLoad[i] = DAG.getMemIntrinsicNode( 10088 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10089 LD->getMemoryVT(), LD->getMemOperand()); 10090 } 10091 SDValue NewOp = 10092 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10093 NewLoad[1], Op0.getNode()->getFlags()); 10094 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10095 DAG.getConstant(0, dl, MVT::i32)); 10096 } 10097 case ISD::LOAD: { 10098 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10099 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10100 SDValue NewLd = DAG.getMemIntrinsicNode( 10101 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10102 LD->getMemoryVT(), LD->getMemOperand()); 10103 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10104 DAG.getConstant(0, dl, MVT::i32)); 10105 } 10106 } 10107 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10108 } 10109 10110 /// LowerOperation - Provide custom lowering hooks for some operations. 10111 /// 10112 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10113 switch (Op.getOpcode()) { 10114 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10115 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10116 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10117 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10118 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10119 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10120 case ISD::SETCC: return LowerSETCC(Op, DAG); 10121 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10122 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10123 10124 // Variable argument lowering. 10125 case ISD::VASTART: return LowerVASTART(Op, DAG); 10126 case ISD::VAARG: return LowerVAARG(Op, DAG); 10127 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10128 10129 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10130 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10131 case ISD::GET_DYNAMIC_AREA_OFFSET: 10132 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10133 10134 // Exception handling lowering. 10135 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10136 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10137 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10138 10139 case ISD::LOAD: return LowerLOAD(Op, DAG); 10140 case ISD::STORE: return LowerSTORE(Op, DAG); 10141 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10142 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10143 case ISD::FP_TO_UINT: 10144 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10145 case ISD::UINT_TO_FP: 10146 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10147 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10148 10149 // Lower 64-bit shifts. 10150 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10151 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10152 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10153 10154 // Vector-related lowering. 10155 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10156 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10157 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10158 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10159 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10160 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10161 case ISD::MUL: return LowerMUL(Op, DAG); 10162 case ISD::ABS: return LowerABS(Op, DAG); 10163 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10164 10165 // For counter-based loop handling. 10166 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10167 10168 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10169 10170 // Frame & Return address. 10171 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10172 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10173 10174 case ISD::INTRINSIC_VOID: 10175 return LowerINTRINSIC_VOID(Op, DAG); 10176 case ISD::SREM: 10177 case ISD::UREM: 10178 return LowerREM(Op, DAG); 10179 case ISD::BSWAP: 10180 return LowerBSWAP(Op, DAG); 10181 case ISD::ATOMIC_CMP_SWAP: 10182 return LowerATOMIC_CMP_SWAP(Op, DAG); 10183 } 10184 } 10185 10186 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10187 SmallVectorImpl<SDValue>&Results, 10188 SelectionDAG &DAG) const { 10189 SDLoc dl(N); 10190 switch (N->getOpcode()) { 10191 default: 10192 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10193 case ISD::READCYCLECOUNTER: { 10194 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10195 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10196 10197 Results.push_back(RTB); 10198 Results.push_back(RTB.getValue(1)); 10199 Results.push_back(RTB.getValue(2)); 10200 break; 10201 } 10202 case ISD::INTRINSIC_W_CHAIN: { 10203 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10204 Intrinsic::loop_decrement) 10205 break; 10206 10207 assert(N->getValueType(0) == MVT::i1 && 10208 "Unexpected result type for CTR decrement intrinsic"); 10209 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10210 N->getValueType(0)); 10211 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10212 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10213 N->getOperand(1)); 10214 10215 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10216 Results.push_back(NewInt.getValue(1)); 10217 break; 10218 } 10219 case ISD::VAARG: { 10220 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10221 return; 10222 10223 EVT VT = N->getValueType(0); 10224 10225 if (VT == MVT::i64) { 10226 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10227 10228 Results.push_back(NewNode); 10229 Results.push_back(NewNode.getValue(1)); 10230 } 10231 return; 10232 } 10233 case ISD::FP_TO_SINT: 10234 case ISD::FP_TO_UINT: 10235 // LowerFP_TO_INT() can only handle f32 and f64. 10236 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10237 return; 10238 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10239 return; 10240 case ISD::TRUNCATE: { 10241 EVT TrgVT = N->getValueType(0); 10242 EVT OpVT = N->getOperand(0).getValueType(); 10243 if (TrgVT.isVector() && 10244 isOperationCustom(N->getOpcode(), TrgVT) && 10245 OpVT.getSizeInBits() <= 128 && 10246 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10247 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10248 return; 10249 } 10250 case ISD::BITCAST: 10251 // Don't handle bitcast here. 10252 return; 10253 } 10254 } 10255 10256 //===----------------------------------------------------------------------===// 10257 // Other Lowering Code 10258 //===----------------------------------------------------------------------===// 10259 10260 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10261 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10262 Function *Func = Intrinsic::getDeclaration(M, Id); 10263 return Builder.CreateCall(Func, {}); 10264 } 10265 10266 // The mappings for emitLeading/TrailingFence is taken from 10267 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10268 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10269 Instruction *Inst, 10270 AtomicOrdering Ord) const { 10271 if (Ord == AtomicOrdering::SequentiallyConsistent) 10272 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10273 if (isReleaseOrStronger(Ord)) 10274 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10275 return nullptr; 10276 } 10277 10278 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10279 Instruction *Inst, 10280 AtomicOrdering Ord) const { 10281 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10282 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10283 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10284 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10285 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10286 return Builder.CreateCall( 10287 Intrinsic::getDeclaration( 10288 Builder.GetInsertBlock()->getParent()->getParent(), 10289 Intrinsic::ppc_cfence, {Inst->getType()}), 10290 {Inst}); 10291 // FIXME: Can use isync for rmw operation. 10292 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10293 } 10294 return nullptr; 10295 } 10296 10297 MachineBasicBlock * 10298 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10299 unsigned AtomicSize, 10300 unsigned BinOpcode, 10301 unsigned CmpOpcode, 10302 unsigned CmpPred) const { 10303 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10304 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10305 10306 auto LoadMnemonic = PPC::LDARX; 10307 auto StoreMnemonic = PPC::STDCX; 10308 switch (AtomicSize) { 10309 default: 10310 llvm_unreachable("Unexpected size of atomic entity"); 10311 case 1: 10312 LoadMnemonic = PPC::LBARX; 10313 StoreMnemonic = PPC::STBCX; 10314 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10315 break; 10316 case 2: 10317 LoadMnemonic = PPC::LHARX; 10318 StoreMnemonic = PPC::STHCX; 10319 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10320 break; 10321 case 4: 10322 LoadMnemonic = PPC::LWARX; 10323 StoreMnemonic = PPC::STWCX; 10324 break; 10325 case 8: 10326 LoadMnemonic = PPC::LDARX; 10327 StoreMnemonic = PPC::STDCX; 10328 break; 10329 } 10330 10331 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10332 MachineFunction *F = BB->getParent(); 10333 MachineFunction::iterator It = ++BB->getIterator(); 10334 10335 Register dest = MI.getOperand(0).getReg(); 10336 Register ptrA = MI.getOperand(1).getReg(); 10337 Register ptrB = MI.getOperand(2).getReg(); 10338 Register incr = MI.getOperand(3).getReg(); 10339 DebugLoc dl = MI.getDebugLoc(); 10340 10341 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10342 MachineBasicBlock *loop2MBB = 10343 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10344 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10345 F->insert(It, loopMBB); 10346 if (CmpOpcode) 10347 F->insert(It, loop2MBB); 10348 F->insert(It, exitMBB); 10349 exitMBB->splice(exitMBB->begin(), BB, 10350 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10351 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10352 10353 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10354 Register TmpReg = (!BinOpcode) ? incr : 10355 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10356 : &PPC::GPRCRegClass); 10357 10358 // thisMBB: 10359 // ... 10360 // fallthrough --> loopMBB 10361 BB->addSuccessor(loopMBB); 10362 10363 // loopMBB: 10364 // l[wd]arx dest, ptr 10365 // add r0, dest, incr 10366 // st[wd]cx. r0, ptr 10367 // bne- loopMBB 10368 // fallthrough --> exitMBB 10369 10370 // For max/min... 10371 // loopMBB: 10372 // l[wd]arx dest, ptr 10373 // cmpl?[wd] incr, dest 10374 // bgt exitMBB 10375 // loop2MBB: 10376 // st[wd]cx. dest, ptr 10377 // bne- loopMBB 10378 // fallthrough --> exitMBB 10379 10380 BB = loopMBB; 10381 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10382 .addReg(ptrA).addReg(ptrB); 10383 if (BinOpcode) 10384 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10385 if (CmpOpcode) { 10386 // Signed comparisons of byte or halfword values must be sign-extended. 10387 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10388 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10389 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10390 ExtReg).addReg(dest); 10391 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10392 .addReg(incr).addReg(ExtReg); 10393 } else 10394 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10395 .addReg(incr).addReg(dest); 10396 10397 BuildMI(BB, dl, TII->get(PPC::BCC)) 10398 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10399 BB->addSuccessor(loop2MBB); 10400 BB->addSuccessor(exitMBB); 10401 BB = loop2MBB; 10402 } 10403 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10404 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10405 BuildMI(BB, dl, TII->get(PPC::BCC)) 10406 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10407 BB->addSuccessor(loopMBB); 10408 BB->addSuccessor(exitMBB); 10409 10410 // exitMBB: 10411 // ... 10412 BB = exitMBB; 10413 return BB; 10414 } 10415 10416 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10417 MachineInstr &MI, MachineBasicBlock *BB, 10418 bool is8bit, // operation 10419 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10420 // If we support part-word atomic mnemonics, just use them 10421 if (Subtarget.hasPartwordAtomics()) 10422 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10423 CmpPred); 10424 10425 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10426 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10427 // In 64 bit mode we have to use 64 bits for addresses, even though the 10428 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10429 // registers without caring whether they're 32 or 64, but here we're 10430 // doing actual arithmetic on the addresses. 10431 bool is64bit = Subtarget.isPPC64(); 10432 bool isLittleEndian = Subtarget.isLittleEndian(); 10433 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10434 10435 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10436 MachineFunction *F = BB->getParent(); 10437 MachineFunction::iterator It = ++BB->getIterator(); 10438 10439 Register dest = MI.getOperand(0).getReg(); 10440 Register ptrA = MI.getOperand(1).getReg(); 10441 Register ptrB = MI.getOperand(2).getReg(); 10442 Register incr = MI.getOperand(3).getReg(); 10443 DebugLoc dl = MI.getDebugLoc(); 10444 10445 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10446 MachineBasicBlock *loop2MBB = 10447 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10448 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10449 F->insert(It, loopMBB); 10450 if (CmpOpcode) 10451 F->insert(It, loop2MBB); 10452 F->insert(It, exitMBB); 10453 exitMBB->splice(exitMBB->begin(), BB, 10454 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10455 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10456 10457 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10458 const TargetRegisterClass *RC = 10459 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10460 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10461 10462 Register PtrReg = RegInfo.createVirtualRegister(RC); 10463 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10464 Register ShiftReg = 10465 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10466 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10467 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10468 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10469 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10470 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10471 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10472 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10473 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10474 Register Ptr1Reg; 10475 Register TmpReg = 10476 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10477 10478 // thisMBB: 10479 // ... 10480 // fallthrough --> loopMBB 10481 BB->addSuccessor(loopMBB); 10482 10483 // The 4-byte load must be aligned, while a char or short may be 10484 // anywhere in the word. Hence all this nasty bookkeeping code. 10485 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10486 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10487 // xori shift, shift1, 24 [16] 10488 // rlwinm ptr, ptr1, 0, 0, 29 10489 // slw incr2, incr, shift 10490 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10491 // slw mask, mask2, shift 10492 // loopMBB: 10493 // lwarx tmpDest, ptr 10494 // add tmp, tmpDest, incr2 10495 // andc tmp2, tmpDest, mask 10496 // and tmp3, tmp, mask 10497 // or tmp4, tmp3, tmp2 10498 // stwcx. tmp4, ptr 10499 // bne- loopMBB 10500 // fallthrough --> exitMBB 10501 // srw dest, tmpDest, shift 10502 if (ptrA != ZeroReg) { 10503 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10504 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10505 .addReg(ptrA) 10506 .addReg(ptrB); 10507 } else { 10508 Ptr1Reg = ptrB; 10509 } 10510 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10511 // mode. 10512 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10513 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10514 .addImm(3) 10515 .addImm(27) 10516 .addImm(is8bit ? 28 : 27); 10517 if (!isLittleEndian) 10518 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10519 .addReg(Shift1Reg) 10520 .addImm(is8bit ? 24 : 16); 10521 if (is64bit) 10522 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10523 .addReg(Ptr1Reg) 10524 .addImm(0) 10525 .addImm(61); 10526 else 10527 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10528 .addReg(Ptr1Reg) 10529 .addImm(0) 10530 .addImm(0) 10531 .addImm(29); 10532 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10533 if (is8bit) 10534 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10535 else { 10536 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10537 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10538 .addReg(Mask3Reg) 10539 .addImm(65535); 10540 } 10541 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10542 .addReg(Mask2Reg) 10543 .addReg(ShiftReg); 10544 10545 BB = loopMBB; 10546 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10547 .addReg(ZeroReg) 10548 .addReg(PtrReg); 10549 if (BinOpcode) 10550 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10551 .addReg(Incr2Reg) 10552 .addReg(TmpDestReg); 10553 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10554 .addReg(TmpDestReg) 10555 .addReg(MaskReg); 10556 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10557 if (CmpOpcode) { 10558 // For unsigned comparisons, we can directly compare the shifted values. 10559 // For signed comparisons we shift and sign extend. 10560 Register SReg = RegInfo.createVirtualRegister(GPRC); 10561 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10562 .addReg(TmpDestReg) 10563 .addReg(MaskReg); 10564 unsigned ValueReg = SReg; 10565 unsigned CmpReg = Incr2Reg; 10566 if (CmpOpcode == PPC::CMPW) { 10567 ValueReg = RegInfo.createVirtualRegister(GPRC); 10568 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10569 .addReg(SReg) 10570 .addReg(ShiftReg); 10571 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 10572 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10573 .addReg(ValueReg); 10574 ValueReg = ValueSReg; 10575 CmpReg = incr; 10576 } 10577 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10578 .addReg(CmpReg) 10579 .addReg(ValueReg); 10580 BuildMI(BB, dl, TII->get(PPC::BCC)) 10581 .addImm(CmpPred) 10582 .addReg(PPC::CR0) 10583 .addMBB(exitMBB); 10584 BB->addSuccessor(loop2MBB); 10585 BB->addSuccessor(exitMBB); 10586 BB = loop2MBB; 10587 } 10588 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10589 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10590 .addReg(Tmp4Reg) 10591 .addReg(ZeroReg) 10592 .addReg(PtrReg); 10593 BuildMI(BB, dl, TII->get(PPC::BCC)) 10594 .addImm(PPC::PRED_NE) 10595 .addReg(PPC::CR0) 10596 .addMBB(loopMBB); 10597 BB->addSuccessor(loopMBB); 10598 BB->addSuccessor(exitMBB); 10599 10600 // exitMBB: 10601 // ... 10602 BB = exitMBB; 10603 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10604 .addReg(TmpDestReg) 10605 .addReg(ShiftReg); 10606 return BB; 10607 } 10608 10609 llvm::MachineBasicBlock * 10610 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10611 MachineBasicBlock *MBB) const { 10612 DebugLoc DL = MI.getDebugLoc(); 10613 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10614 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10615 10616 MachineFunction *MF = MBB->getParent(); 10617 MachineRegisterInfo &MRI = MF->getRegInfo(); 10618 10619 const BasicBlock *BB = MBB->getBasicBlock(); 10620 MachineFunction::iterator I = ++MBB->getIterator(); 10621 10622 Register DstReg = MI.getOperand(0).getReg(); 10623 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10624 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10625 Register mainDstReg = MRI.createVirtualRegister(RC); 10626 Register restoreDstReg = MRI.createVirtualRegister(RC); 10627 10628 MVT PVT = getPointerTy(MF->getDataLayout()); 10629 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10630 "Invalid Pointer Size!"); 10631 // For v = setjmp(buf), we generate 10632 // 10633 // thisMBB: 10634 // SjLjSetup mainMBB 10635 // bl mainMBB 10636 // v_restore = 1 10637 // b sinkMBB 10638 // 10639 // mainMBB: 10640 // buf[LabelOffset] = LR 10641 // v_main = 0 10642 // 10643 // sinkMBB: 10644 // v = phi(main, restore) 10645 // 10646 10647 MachineBasicBlock *thisMBB = MBB; 10648 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10649 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10650 MF->insert(I, mainMBB); 10651 MF->insert(I, sinkMBB); 10652 10653 MachineInstrBuilder MIB; 10654 10655 // Transfer the remainder of BB and its successor edges to sinkMBB. 10656 sinkMBB->splice(sinkMBB->begin(), MBB, 10657 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10658 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10659 10660 // Note that the structure of the jmp_buf used here is not compatible 10661 // with that used by libc, and is not designed to be. Specifically, it 10662 // stores only those 'reserved' registers that LLVM does not otherwise 10663 // understand how to spill. Also, by convention, by the time this 10664 // intrinsic is called, Clang has already stored the frame address in the 10665 // first slot of the buffer and stack address in the third. Following the 10666 // X86 target code, we'll store the jump address in the second slot. We also 10667 // need to save the TOC pointer (R2) to handle jumps between shared 10668 // libraries, and that will be stored in the fourth slot. The thread 10669 // identifier (R13) is not affected. 10670 10671 // thisMBB: 10672 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10673 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10674 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10675 10676 // Prepare IP either in reg. 10677 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10678 Register LabelReg = MRI.createVirtualRegister(PtrRC); 10679 Register BufReg = MI.getOperand(1).getReg(); 10680 10681 if (Subtarget.is64BitELFABI()) { 10682 setUsesTOCBasePtr(*MBB->getParent()); 10683 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10684 .addReg(PPC::X2) 10685 .addImm(TOCOffset) 10686 .addReg(BufReg) 10687 .cloneMemRefs(MI); 10688 } 10689 10690 // Naked functions never have a base pointer, and so we use r1. For all 10691 // other functions, this decision must be delayed until during PEI. 10692 unsigned BaseReg; 10693 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10694 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10695 else 10696 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10697 10698 MIB = BuildMI(*thisMBB, MI, DL, 10699 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10700 .addReg(BaseReg) 10701 .addImm(BPOffset) 10702 .addReg(BufReg) 10703 .cloneMemRefs(MI); 10704 10705 // Setup 10706 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10707 MIB.addRegMask(TRI->getNoPreservedMask()); 10708 10709 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10710 10711 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10712 .addMBB(mainMBB); 10713 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10714 10715 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10716 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10717 10718 // mainMBB: 10719 // mainDstReg = 0 10720 MIB = 10721 BuildMI(mainMBB, DL, 10722 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10723 10724 // Store IP 10725 if (Subtarget.isPPC64()) { 10726 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10727 .addReg(LabelReg) 10728 .addImm(LabelOffset) 10729 .addReg(BufReg); 10730 } else { 10731 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10732 .addReg(LabelReg) 10733 .addImm(LabelOffset) 10734 .addReg(BufReg); 10735 } 10736 MIB.cloneMemRefs(MI); 10737 10738 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10739 mainMBB->addSuccessor(sinkMBB); 10740 10741 // sinkMBB: 10742 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10743 TII->get(PPC::PHI), DstReg) 10744 .addReg(mainDstReg).addMBB(mainMBB) 10745 .addReg(restoreDstReg).addMBB(thisMBB); 10746 10747 MI.eraseFromParent(); 10748 return sinkMBB; 10749 } 10750 10751 MachineBasicBlock * 10752 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10753 MachineBasicBlock *MBB) const { 10754 DebugLoc DL = MI.getDebugLoc(); 10755 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10756 10757 MachineFunction *MF = MBB->getParent(); 10758 MachineRegisterInfo &MRI = MF->getRegInfo(); 10759 10760 MVT PVT = getPointerTy(MF->getDataLayout()); 10761 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10762 "Invalid Pointer Size!"); 10763 10764 const TargetRegisterClass *RC = 10765 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10766 Register Tmp = MRI.createVirtualRegister(RC); 10767 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10768 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10769 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10770 unsigned BP = 10771 (PVT == MVT::i64) 10772 ? PPC::X30 10773 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10774 : PPC::R30); 10775 10776 MachineInstrBuilder MIB; 10777 10778 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10779 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10780 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10781 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10782 10783 Register BufReg = MI.getOperand(0).getReg(); 10784 10785 // Reload FP (the jumped-to function may not have had a 10786 // frame pointer, and if so, then its r31 will be restored 10787 // as necessary). 10788 if (PVT == MVT::i64) { 10789 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10790 .addImm(0) 10791 .addReg(BufReg); 10792 } else { 10793 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10794 .addImm(0) 10795 .addReg(BufReg); 10796 } 10797 MIB.cloneMemRefs(MI); 10798 10799 // Reload IP 10800 if (PVT == MVT::i64) { 10801 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10802 .addImm(LabelOffset) 10803 .addReg(BufReg); 10804 } else { 10805 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10806 .addImm(LabelOffset) 10807 .addReg(BufReg); 10808 } 10809 MIB.cloneMemRefs(MI); 10810 10811 // Reload SP 10812 if (PVT == MVT::i64) { 10813 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10814 .addImm(SPOffset) 10815 .addReg(BufReg); 10816 } else { 10817 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10818 .addImm(SPOffset) 10819 .addReg(BufReg); 10820 } 10821 MIB.cloneMemRefs(MI); 10822 10823 // Reload BP 10824 if (PVT == MVT::i64) { 10825 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10826 .addImm(BPOffset) 10827 .addReg(BufReg); 10828 } else { 10829 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10830 .addImm(BPOffset) 10831 .addReg(BufReg); 10832 } 10833 MIB.cloneMemRefs(MI); 10834 10835 // Reload TOC 10836 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10837 setUsesTOCBasePtr(*MBB->getParent()); 10838 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10839 .addImm(TOCOffset) 10840 .addReg(BufReg) 10841 .cloneMemRefs(MI); 10842 } 10843 10844 // Jump 10845 BuildMI(*MBB, MI, DL, 10846 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10847 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10848 10849 MI.eraseFromParent(); 10850 return MBB; 10851 } 10852 10853 MachineBasicBlock * 10854 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10855 MachineBasicBlock *BB) const { 10856 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10857 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10858 if (Subtarget.is64BitELFABI() && 10859 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10860 // Call lowering should have added an r2 operand to indicate a dependence 10861 // on the TOC base pointer value. It can't however, because there is no 10862 // way to mark the dependence as implicit there, and so the stackmap code 10863 // will confuse it with a regular operand. Instead, add the dependence 10864 // here. 10865 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10866 } 10867 10868 return emitPatchPoint(MI, BB); 10869 } 10870 10871 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10872 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10873 return emitEHSjLjSetJmp(MI, BB); 10874 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10875 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10876 return emitEHSjLjLongJmp(MI, BB); 10877 } 10878 10879 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10880 10881 // To "insert" these instructions we actually have to insert their 10882 // control-flow patterns. 10883 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10884 MachineFunction::iterator It = ++BB->getIterator(); 10885 10886 MachineFunction *F = BB->getParent(); 10887 10888 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10889 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 10890 MI.getOpcode() == PPC::SELECT_I8) { 10891 SmallVector<MachineOperand, 2> Cond; 10892 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10893 MI.getOpcode() == PPC::SELECT_CC_I8) 10894 Cond.push_back(MI.getOperand(4)); 10895 else 10896 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10897 Cond.push_back(MI.getOperand(1)); 10898 10899 DebugLoc dl = MI.getDebugLoc(); 10900 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10901 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10902 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10903 MI.getOpcode() == PPC::SELECT_CC_I8 || 10904 MI.getOpcode() == PPC::SELECT_CC_F4 || 10905 MI.getOpcode() == PPC::SELECT_CC_F8 || 10906 MI.getOpcode() == PPC::SELECT_CC_F16 || 10907 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10908 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10909 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10910 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10911 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10912 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10913 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10914 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 10915 MI.getOpcode() == PPC::SELECT_CC_SPE || 10916 MI.getOpcode() == PPC::SELECT_I4 || 10917 MI.getOpcode() == PPC::SELECT_I8 || 10918 MI.getOpcode() == PPC::SELECT_F4 || 10919 MI.getOpcode() == PPC::SELECT_F8 || 10920 MI.getOpcode() == PPC::SELECT_F16 || 10921 MI.getOpcode() == PPC::SELECT_QFRC || 10922 MI.getOpcode() == PPC::SELECT_QSRC || 10923 MI.getOpcode() == PPC::SELECT_QBRC || 10924 MI.getOpcode() == PPC::SELECT_SPE || 10925 MI.getOpcode() == PPC::SELECT_SPE4 || 10926 MI.getOpcode() == PPC::SELECT_VRRC || 10927 MI.getOpcode() == PPC::SELECT_VSFRC || 10928 MI.getOpcode() == PPC::SELECT_VSSRC || 10929 MI.getOpcode() == PPC::SELECT_VSRC) { 10930 // The incoming instruction knows the destination vreg to set, the 10931 // condition code register to branch on, the true/false values to 10932 // select between, and a branch opcode to use. 10933 10934 // thisMBB: 10935 // ... 10936 // TrueVal = ... 10937 // cmpTY ccX, r1, r2 10938 // bCC copy1MBB 10939 // fallthrough --> copy0MBB 10940 MachineBasicBlock *thisMBB = BB; 10941 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10942 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10943 DebugLoc dl = MI.getDebugLoc(); 10944 F->insert(It, copy0MBB); 10945 F->insert(It, sinkMBB); 10946 10947 // Transfer the remainder of BB and its successor edges to sinkMBB. 10948 sinkMBB->splice(sinkMBB->begin(), BB, 10949 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10950 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10951 10952 // Next, add the true and fallthrough blocks as its successors. 10953 BB->addSuccessor(copy0MBB); 10954 BB->addSuccessor(sinkMBB); 10955 10956 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10957 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10958 MI.getOpcode() == PPC::SELECT_F16 || 10959 MI.getOpcode() == PPC::SELECT_SPE4 || 10960 MI.getOpcode() == PPC::SELECT_SPE || 10961 MI.getOpcode() == PPC::SELECT_QFRC || 10962 MI.getOpcode() == PPC::SELECT_QSRC || 10963 MI.getOpcode() == PPC::SELECT_QBRC || 10964 MI.getOpcode() == PPC::SELECT_VRRC || 10965 MI.getOpcode() == PPC::SELECT_VSFRC || 10966 MI.getOpcode() == PPC::SELECT_VSSRC || 10967 MI.getOpcode() == PPC::SELECT_VSRC) { 10968 BuildMI(BB, dl, TII->get(PPC::BC)) 10969 .addReg(MI.getOperand(1).getReg()) 10970 .addMBB(sinkMBB); 10971 } else { 10972 unsigned SelectPred = MI.getOperand(4).getImm(); 10973 BuildMI(BB, dl, TII->get(PPC::BCC)) 10974 .addImm(SelectPred) 10975 .addReg(MI.getOperand(1).getReg()) 10976 .addMBB(sinkMBB); 10977 } 10978 10979 // copy0MBB: 10980 // %FalseValue = ... 10981 // # fallthrough to sinkMBB 10982 BB = copy0MBB; 10983 10984 // Update machine-CFG edges 10985 BB->addSuccessor(sinkMBB); 10986 10987 // sinkMBB: 10988 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10989 // ... 10990 BB = sinkMBB; 10991 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10992 .addReg(MI.getOperand(3).getReg()) 10993 .addMBB(copy0MBB) 10994 .addReg(MI.getOperand(2).getReg()) 10995 .addMBB(thisMBB); 10996 } else if (MI.getOpcode() == PPC::ReadTB) { 10997 // To read the 64-bit time-base register on a 32-bit target, we read the 10998 // two halves. Should the counter have wrapped while it was being read, we 10999 // need to try again. 11000 // ... 11001 // readLoop: 11002 // mfspr Rx,TBU # load from TBU 11003 // mfspr Ry,TB # load from TB 11004 // mfspr Rz,TBU # load from TBU 11005 // cmpw crX,Rx,Rz # check if 'old'='new' 11006 // bne readLoop # branch if they're not equal 11007 // ... 11008 11009 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11010 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11011 DebugLoc dl = MI.getDebugLoc(); 11012 F->insert(It, readMBB); 11013 F->insert(It, sinkMBB); 11014 11015 // Transfer the remainder of BB and its successor edges to sinkMBB. 11016 sinkMBB->splice(sinkMBB->begin(), BB, 11017 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11018 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11019 11020 BB->addSuccessor(readMBB); 11021 BB = readMBB; 11022 11023 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11024 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11025 Register LoReg = MI.getOperand(0).getReg(); 11026 Register HiReg = MI.getOperand(1).getReg(); 11027 11028 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11029 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11030 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11031 11032 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11033 11034 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11035 .addReg(HiReg) 11036 .addReg(ReadAgainReg); 11037 BuildMI(BB, dl, TII->get(PPC::BCC)) 11038 .addImm(PPC::PRED_NE) 11039 .addReg(CmpReg) 11040 .addMBB(readMBB); 11041 11042 BB->addSuccessor(readMBB); 11043 BB->addSuccessor(sinkMBB); 11044 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11045 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11046 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11047 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11048 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11049 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11050 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11051 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11052 11053 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11054 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11055 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11056 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11057 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11058 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11059 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11060 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11061 11062 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11063 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11064 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11065 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11066 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11067 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11068 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11069 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11070 11071 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11072 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11073 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11074 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11075 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11076 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11077 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11078 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11079 11080 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11081 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11082 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11083 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11084 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11085 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11086 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11087 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11088 11089 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11090 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11091 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11092 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11093 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11094 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11095 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11096 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11097 11098 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11099 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11100 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11101 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11102 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11103 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11104 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11105 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11106 11107 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11108 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11109 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11110 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11111 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11112 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11113 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11114 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11115 11116 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11117 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11118 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11119 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11120 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11121 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11122 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11123 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11124 11125 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11126 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11127 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11128 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11129 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11130 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11131 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11132 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11133 11134 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11135 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11136 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11137 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11138 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11139 BB = EmitAtomicBinary(MI, BB, 4, 0); 11140 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11141 BB = EmitAtomicBinary(MI, BB, 8, 0); 11142 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11143 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11144 (Subtarget.hasPartwordAtomics() && 11145 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11146 (Subtarget.hasPartwordAtomics() && 11147 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11148 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11149 11150 auto LoadMnemonic = PPC::LDARX; 11151 auto StoreMnemonic = PPC::STDCX; 11152 switch (MI.getOpcode()) { 11153 default: 11154 llvm_unreachable("Compare and swap of unknown size"); 11155 case PPC::ATOMIC_CMP_SWAP_I8: 11156 LoadMnemonic = PPC::LBARX; 11157 StoreMnemonic = PPC::STBCX; 11158 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11159 break; 11160 case PPC::ATOMIC_CMP_SWAP_I16: 11161 LoadMnemonic = PPC::LHARX; 11162 StoreMnemonic = PPC::STHCX; 11163 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11164 break; 11165 case PPC::ATOMIC_CMP_SWAP_I32: 11166 LoadMnemonic = PPC::LWARX; 11167 StoreMnemonic = PPC::STWCX; 11168 break; 11169 case PPC::ATOMIC_CMP_SWAP_I64: 11170 LoadMnemonic = PPC::LDARX; 11171 StoreMnemonic = PPC::STDCX; 11172 break; 11173 } 11174 Register dest = MI.getOperand(0).getReg(); 11175 Register ptrA = MI.getOperand(1).getReg(); 11176 Register ptrB = MI.getOperand(2).getReg(); 11177 Register oldval = MI.getOperand(3).getReg(); 11178 Register newval = MI.getOperand(4).getReg(); 11179 DebugLoc dl = MI.getDebugLoc(); 11180 11181 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11182 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11183 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11184 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11185 F->insert(It, loop1MBB); 11186 F->insert(It, loop2MBB); 11187 F->insert(It, midMBB); 11188 F->insert(It, exitMBB); 11189 exitMBB->splice(exitMBB->begin(), BB, 11190 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11191 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11192 11193 // thisMBB: 11194 // ... 11195 // fallthrough --> loopMBB 11196 BB->addSuccessor(loop1MBB); 11197 11198 // loop1MBB: 11199 // l[bhwd]arx dest, ptr 11200 // cmp[wd] dest, oldval 11201 // bne- midMBB 11202 // loop2MBB: 11203 // st[bhwd]cx. newval, ptr 11204 // bne- loopMBB 11205 // b exitBB 11206 // midMBB: 11207 // st[bhwd]cx. dest, ptr 11208 // exitBB: 11209 BB = loop1MBB; 11210 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11211 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11212 .addReg(oldval) 11213 .addReg(dest); 11214 BuildMI(BB, dl, TII->get(PPC::BCC)) 11215 .addImm(PPC::PRED_NE) 11216 .addReg(PPC::CR0) 11217 .addMBB(midMBB); 11218 BB->addSuccessor(loop2MBB); 11219 BB->addSuccessor(midMBB); 11220 11221 BB = loop2MBB; 11222 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11223 .addReg(newval) 11224 .addReg(ptrA) 11225 .addReg(ptrB); 11226 BuildMI(BB, dl, TII->get(PPC::BCC)) 11227 .addImm(PPC::PRED_NE) 11228 .addReg(PPC::CR0) 11229 .addMBB(loop1MBB); 11230 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11231 BB->addSuccessor(loop1MBB); 11232 BB->addSuccessor(exitMBB); 11233 11234 BB = midMBB; 11235 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11236 .addReg(dest) 11237 .addReg(ptrA) 11238 .addReg(ptrB); 11239 BB->addSuccessor(exitMBB); 11240 11241 // exitMBB: 11242 // ... 11243 BB = exitMBB; 11244 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11245 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11246 // We must use 64-bit registers for addresses when targeting 64-bit, 11247 // since we're actually doing arithmetic on them. Other registers 11248 // can be 32-bit. 11249 bool is64bit = Subtarget.isPPC64(); 11250 bool isLittleEndian = Subtarget.isLittleEndian(); 11251 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11252 11253 Register dest = MI.getOperand(0).getReg(); 11254 Register ptrA = MI.getOperand(1).getReg(); 11255 Register ptrB = MI.getOperand(2).getReg(); 11256 Register oldval = MI.getOperand(3).getReg(); 11257 Register newval = MI.getOperand(4).getReg(); 11258 DebugLoc dl = MI.getDebugLoc(); 11259 11260 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11261 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11262 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11263 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11264 F->insert(It, loop1MBB); 11265 F->insert(It, loop2MBB); 11266 F->insert(It, midMBB); 11267 F->insert(It, exitMBB); 11268 exitMBB->splice(exitMBB->begin(), BB, 11269 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11270 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11271 11272 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11273 const TargetRegisterClass *RC = 11274 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11275 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11276 11277 Register PtrReg = RegInfo.createVirtualRegister(RC); 11278 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11279 Register ShiftReg = 11280 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11281 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11282 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11283 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11284 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11285 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11286 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11287 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11288 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11289 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11290 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11291 Register Ptr1Reg; 11292 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11293 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11294 // thisMBB: 11295 // ... 11296 // fallthrough --> loopMBB 11297 BB->addSuccessor(loop1MBB); 11298 11299 // The 4-byte load must be aligned, while a char or short may be 11300 // anywhere in the word. Hence all this nasty bookkeeping code. 11301 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11302 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11303 // xori shift, shift1, 24 [16] 11304 // rlwinm ptr, ptr1, 0, 0, 29 11305 // slw newval2, newval, shift 11306 // slw oldval2, oldval,shift 11307 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11308 // slw mask, mask2, shift 11309 // and newval3, newval2, mask 11310 // and oldval3, oldval2, mask 11311 // loop1MBB: 11312 // lwarx tmpDest, ptr 11313 // and tmp, tmpDest, mask 11314 // cmpw tmp, oldval3 11315 // bne- midMBB 11316 // loop2MBB: 11317 // andc tmp2, tmpDest, mask 11318 // or tmp4, tmp2, newval3 11319 // stwcx. tmp4, ptr 11320 // bne- loop1MBB 11321 // b exitBB 11322 // midMBB: 11323 // stwcx. tmpDest, ptr 11324 // exitBB: 11325 // srw dest, tmpDest, shift 11326 if (ptrA != ZeroReg) { 11327 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11328 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11329 .addReg(ptrA) 11330 .addReg(ptrB); 11331 } else { 11332 Ptr1Reg = ptrB; 11333 } 11334 11335 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11336 // mode. 11337 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11338 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11339 .addImm(3) 11340 .addImm(27) 11341 .addImm(is8bit ? 28 : 27); 11342 if (!isLittleEndian) 11343 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11344 .addReg(Shift1Reg) 11345 .addImm(is8bit ? 24 : 16); 11346 if (is64bit) 11347 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11348 .addReg(Ptr1Reg) 11349 .addImm(0) 11350 .addImm(61); 11351 else 11352 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11353 .addReg(Ptr1Reg) 11354 .addImm(0) 11355 .addImm(0) 11356 .addImm(29); 11357 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11358 .addReg(newval) 11359 .addReg(ShiftReg); 11360 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11361 .addReg(oldval) 11362 .addReg(ShiftReg); 11363 if (is8bit) 11364 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11365 else { 11366 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11367 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11368 .addReg(Mask3Reg) 11369 .addImm(65535); 11370 } 11371 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11372 .addReg(Mask2Reg) 11373 .addReg(ShiftReg); 11374 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11375 .addReg(NewVal2Reg) 11376 .addReg(MaskReg); 11377 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11378 .addReg(OldVal2Reg) 11379 .addReg(MaskReg); 11380 11381 BB = loop1MBB; 11382 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11383 .addReg(ZeroReg) 11384 .addReg(PtrReg); 11385 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11386 .addReg(TmpDestReg) 11387 .addReg(MaskReg); 11388 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11389 .addReg(TmpReg) 11390 .addReg(OldVal3Reg); 11391 BuildMI(BB, dl, TII->get(PPC::BCC)) 11392 .addImm(PPC::PRED_NE) 11393 .addReg(PPC::CR0) 11394 .addMBB(midMBB); 11395 BB->addSuccessor(loop2MBB); 11396 BB->addSuccessor(midMBB); 11397 11398 BB = loop2MBB; 11399 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11400 .addReg(TmpDestReg) 11401 .addReg(MaskReg); 11402 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11403 .addReg(Tmp2Reg) 11404 .addReg(NewVal3Reg); 11405 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11406 .addReg(Tmp4Reg) 11407 .addReg(ZeroReg) 11408 .addReg(PtrReg); 11409 BuildMI(BB, dl, TII->get(PPC::BCC)) 11410 .addImm(PPC::PRED_NE) 11411 .addReg(PPC::CR0) 11412 .addMBB(loop1MBB); 11413 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11414 BB->addSuccessor(loop1MBB); 11415 BB->addSuccessor(exitMBB); 11416 11417 BB = midMBB; 11418 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11419 .addReg(TmpDestReg) 11420 .addReg(ZeroReg) 11421 .addReg(PtrReg); 11422 BB->addSuccessor(exitMBB); 11423 11424 // exitMBB: 11425 // ... 11426 BB = exitMBB; 11427 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11428 .addReg(TmpReg) 11429 .addReg(ShiftReg); 11430 } else if (MI.getOpcode() == PPC::FADDrtz) { 11431 // This pseudo performs an FADD with rounding mode temporarily forced 11432 // to round-to-zero. We emit this via custom inserter since the FPSCR 11433 // is not modeled at the SelectionDAG level. 11434 Register Dest = MI.getOperand(0).getReg(); 11435 Register Src1 = MI.getOperand(1).getReg(); 11436 Register Src2 = MI.getOperand(2).getReg(); 11437 DebugLoc dl = MI.getDebugLoc(); 11438 11439 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11440 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11441 11442 // Save FPSCR value. 11443 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11444 11445 // Set rounding mode to round-to-zero. 11446 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 11447 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 11448 11449 // Perform addition. 11450 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11451 11452 // Restore FPSCR value. 11453 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11454 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11455 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 11456 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11457 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 11458 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11459 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 11460 ? PPC::ANDIo8 11461 : PPC::ANDIo; 11462 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11463 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 11464 11465 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11466 Register Dest = RegInfo.createVirtualRegister( 11467 Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11468 11469 DebugLoc dl = MI.getDebugLoc(); 11470 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 11471 .addReg(MI.getOperand(1).getReg()) 11472 .addImm(1); 11473 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 11474 MI.getOperand(0).getReg()) 11475 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 11476 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11477 DebugLoc Dl = MI.getDebugLoc(); 11478 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11479 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11480 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11481 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11482 MI.getOperand(0).getReg()) 11483 .addReg(CRReg); 11484 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 11485 DebugLoc Dl = MI.getDebugLoc(); 11486 unsigned Imm = MI.getOperand(1).getImm(); 11487 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 11488 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11489 MI.getOperand(0).getReg()) 11490 .addReg(PPC::CR0EQ); 11491 } else if (MI.getOpcode() == PPC::SETRNDi) { 11492 DebugLoc dl = MI.getDebugLoc(); 11493 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11494 11495 // Save FPSCR value. 11496 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11497 11498 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 11499 // the following settings: 11500 // 00 Round to nearest 11501 // 01 Round to 0 11502 // 10 Round to +inf 11503 // 11 Round to -inf 11504 11505 // When the operand is immediate, using the two least significant bits of 11506 // the immediate to set the bits 62:63 of FPSCR. 11507 unsigned Mode = MI.getOperand(1).getImm(); 11508 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 11509 .addImm(31); 11510 11511 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 11512 .addImm(30); 11513 } else if (MI.getOpcode() == PPC::SETRND) { 11514 DebugLoc dl = MI.getDebugLoc(); 11515 11516 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 11517 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 11518 // If the target doesn't have DirectMove, we should use stack to do the 11519 // conversion, because the target doesn't have the instructions like mtvsrd 11520 // or mfvsrd to do this conversion directly. 11521 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 11522 if (Subtarget.hasDirectMove()) { 11523 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 11524 .addReg(SrcReg); 11525 } else { 11526 // Use stack to do the register copy. 11527 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 11528 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11529 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 11530 if (RC == &PPC::F8RCRegClass) { 11531 // Copy register from F8RCRegClass to G8RCRegclass. 11532 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11533 "Unsupported RegClass."); 11534 11535 StoreOp = PPC::STFD; 11536 LoadOp = PPC::LD; 11537 } else { 11538 // Copy register from G8RCRegClass to F8RCRegclass. 11539 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11540 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11541 "Unsupported RegClass."); 11542 } 11543 11544 MachineFrameInfo &MFI = F->getFrameInfo(); 11545 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11546 11547 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11548 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11549 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11550 MFI.getObjectAlignment(FrameIdx)); 11551 11552 // Store the SrcReg into the stack. 11553 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11554 .addReg(SrcReg) 11555 .addImm(0) 11556 .addFrameIndex(FrameIdx) 11557 .addMemOperand(MMOStore); 11558 11559 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11560 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11561 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11562 MFI.getObjectAlignment(FrameIdx)); 11563 11564 // Load from the stack where SrcReg is stored, and save to DestReg, 11565 // so we have done the RegClass conversion from RegClass::SrcReg to 11566 // RegClass::DestReg. 11567 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11568 .addImm(0) 11569 .addFrameIndex(FrameIdx) 11570 .addMemOperand(MMOLoad); 11571 } 11572 }; 11573 11574 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11575 11576 // Save FPSCR value. 11577 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11578 11579 // When the operand is gprc register, use two least significant bits of the 11580 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11581 // 11582 // copy OldFPSCRTmpReg, OldFPSCRReg 11583 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11584 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11585 // copy NewFPSCRReg, NewFPSCRTmpReg 11586 // mtfsf 255, NewFPSCRReg 11587 MachineOperand SrcOp = MI.getOperand(1); 11588 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11589 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11590 11591 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11592 11593 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11594 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11595 11596 // The first operand of INSERT_SUBREG should be a register which has 11597 // subregisters, we only care about its RegClass, so we should use an 11598 // IMPLICIT_DEF register. 11599 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11600 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11601 .addReg(ImDefReg) 11602 .add(SrcOp) 11603 .addImm(1); 11604 11605 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11606 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11607 .addReg(OldFPSCRTmpReg) 11608 .addReg(ExtSrcReg) 11609 .addImm(0) 11610 .addImm(62); 11611 11612 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11613 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11614 11615 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11616 // bits of FPSCR. 11617 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11618 .addImm(255) 11619 .addReg(NewFPSCRReg) 11620 .addImm(0) 11621 .addImm(0); 11622 } else { 11623 llvm_unreachable("Unexpected instr type to insert"); 11624 } 11625 11626 MI.eraseFromParent(); // The pseudo instruction is gone now. 11627 return BB; 11628 } 11629 11630 //===----------------------------------------------------------------------===// 11631 // Target Optimization Hooks 11632 //===----------------------------------------------------------------------===// 11633 11634 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11635 // For the estimates, convergence is quadratic, so we essentially double the 11636 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11637 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11638 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11639 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11640 if (VT.getScalarType() == MVT::f64) 11641 RefinementSteps++; 11642 return RefinementSteps; 11643 } 11644 11645 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11646 int Enabled, int &RefinementSteps, 11647 bool &UseOneConstNR, 11648 bool Reciprocal) const { 11649 EVT VT = Operand.getValueType(); 11650 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11651 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11652 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11653 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11654 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11655 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11656 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11657 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11658 11659 // The Newton-Raphson computation with a single constant does not provide 11660 // enough accuracy on some CPUs. 11661 UseOneConstNR = !Subtarget.needsTwoConstNR(); 11662 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11663 } 11664 return SDValue(); 11665 } 11666 11667 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11668 int Enabled, 11669 int &RefinementSteps) const { 11670 EVT VT = Operand.getValueType(); 11671 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11672 (VT == MVT::f64 && Subtarget.hasFRE()) || 11673 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11674 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11675 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11676 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11677 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11678 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11679 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11680 } 11681 return SDValue(); 11682 } 11683 11684 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11685 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11686 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11687 // enabled for division), this functionality is redundant with the default 11688 // combiner logic (once the division -> reciprocal/multiply transformation 11689 // has taken place). As a result, this matters more for older cores than for 11690 // newer ones. 11691 11692 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11693 // reciprocal if there are two or more FDIVs (for embedded cores with only 11694 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11695 switch (Subtarget.getDarwinDirective()) { 11696 default: 11697 return 3; 11698 case PPC::DIR_440: 11699 case PPC::DIR_A2: 11700 case PPC::DIR_E500: 11701 case PPC::DIR_E500mc: 11702 case PPC::DIR_E5500: 11703 return 2; 11704 } 11705 } 11706 11707 // isConsecutiveLSLoc needs to work even if all adds have not yet been 11708 // collapsed, and so we need to look through chains of them. 11709 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 11710 int64_t& Offset, SelectionDAG &DAG) { 11711 if (DAG.isBaseWithConstantOffset(Loc)) { 11712 Base = Loc.getOperand(0); 11713 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 11714 11715 // The base might itself be a base plus an offset, and if so, accumulate 11716 // that as well. 11717 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 11718 } 11719 } 11720 11721 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 11722 unsigned Bytes, int Dist, 11723 SelectionDAG &DAG) { 11724 if (VT.getSizeInBits() / 8 != Bytes) 11725 return false; 11726 11727 SDValue BaseLoc = Base->getBasePtr(); 11728 if (Loc.getOpcode() == ISD::FrameIndex) { 11729 if (BaseLoc.getOpcode() != ISD::FrameIndex) 11730 return false; 11731 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 11732 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 11733 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 11734 int FS = MFI.getObjectSize(FI); 11735 int BFS = MFI.getObjectSize(BFI); 11736 if (FS != BFS || FS != (int)Bytes) return false; 11737 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 11738 } 11739 11740 SDValue Base1 = Loc, Base2 = BaseLoc; 11741 int64_t Offset1 = 0, Offset2 = 0; 11742 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 11743 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 11744 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 11745 return true; 11746 11747 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11748 const GlobalValue *GV1 = nullptr; 11749 const GlobalValue *GV2 = nullptr; 11750 Offset1 = 0; 11751 Offset2 = 0; 11752 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 11753 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 11754 if (isGA1 && isGA2 && GV1 == GV2) 11755 return Offset1 == (Offset2 + Dist*Bytes); 11756 return false; 11757 } 11758 11759 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11760 // not enforce equality of the chain operands. 11761 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11762 unsigned Bytes, int Dist, 11763 SelectionDAG &DAG) { 11764 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11765 EVT VT = LS->getMemoryVT(); 11766 SDValue Loc = LS->getBasePtr(); 11767 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11768 } 11769 11770 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11771 EVT VT; 11772 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11773 default: return false; 11774 case Intrinsic::ppc_qpx_qvlfd: 11775 case Intrinsic::ppc_qpx_qvlfda: 11776 VT = MVT::v4f64; 11777 break; 11778 case Intrinsic::ppc_qpx_qvlfs: 11779 case Intrinsic::ppc_qpx_qvlfsa: 11780 VT = MVT::v4f32; 11781 break; 11782 case Intrinsic::ppc_qpx_qvlfcd: 11783 case Intrinsic::ppc_qpx_qvlfcda: 11784 VT = MVT::v2f64; 11785 break; 11786 case Intrinsic::ppc_qpx_qvlfcs: 11787 case Intrinsic::ppc_qpx_qvlfcsa: 11788 VT = MVT::v2f32; 11789 break; 11790 case Intrinsic::ppc_qpx_qvlfiwa: 11791 case Intrinsic::ppc_qpx_qvlfiwz: 11792 case Intrinsic::ppc_altivec_lvx: 11793 case Intrinsic::ppc_altivec_lvxl: 11794 case Intrinsic::ppc_vsx_lxvw4x: 11795 case Intrinsic::ppc_vsx_lxvw4x_be: 11796 VT = MVT::v4i32; 11797 break; 11798 case Intrinsic::ppc_vsx_lxvd2x: 11799 case Intrinsic::ppc_vsx_lxvd2x_be: 11800 VT = MVT::v2f64; 11801 break; 11802 case Intrinsic::ppc_altivec_lvebx: 11803 VT = MVT::i8; 11804 break; 11805 case Intrinsic::ppc_altivec_lvehx: 11806 VT = MVT::i16; 11807 break; 11808 case Intrinsic::ppc_altivec_lvewx: 11809 VT = MVT::i32; 11810 break; 11811 } 11812 11813 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 11814 } 11815 11816 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 11817 EVT VT; 11818 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11819 default: return false; 11820 case Intrinsic::ppc_qpx_qvstfd: 11821 case Intrinsic::ppc_qpx_qvstfda: 11822 VT = MVT::v4f64; 11823 break; 11824 case Intrinsic::ppc_qpx_qvstfs: 11825 case Intrinsic::ppc_qpx_qvstfsa: 11826 VT = MVT::v4f32; 11827 break; 11828 case Intrinsic::ppc_qpx_qvstfcd: 11829 case Intrinsic::ppc_qpx_qvstfcda: 11830 VT = MVT::v2f64; 11831 break; 11832 case Intrinsic::ppc_qpx_qvstfcs: 11833 case Intrinsic::ppc_qpx_qvstfcsa: 11834 VT = MVT::v2f32; 11835 break; 11836 case Intrinsic::ppc_qpx_qvstfiw: 11837 case Intrinsic::ppc_qpx_qvstfiwa: 11838 case Intrinsic::ppc_altivec_stvx: 11839 case Intrinsic::ppc_altivec_stvxl: 11840 case Intrinsic::ppc_vsx_stxvw4x: 11841 VT = MVT::v4i32; 11842 break; 11843 case Intrinsic::ppc_vsx_stxvd2x: 11844 VT = MVT::v2f64; 11845 break; 11846 case Intrinsic::ppc_vsx_stxvw4x_be: 11847 VT = MVT::v4i32; 11848 break; 11849 case Intrinsic::ppc_vsx_stxvd2x_be: 11850 VT = MVT::v2f64; 11851 break; 11852 case Intrinsic::ppc_altivec_stvebx: 11853 VT = MVT::i8; 11854 break; 11855 case Intrinsic::ppc_altivec_stvehx: 11856 VT = MVT::i16; 11857 break; 11858 case Intrinsic::ppc_altivec_stvewx: 11859 VT = MVT::i32; 11860 break; 11861 } 11862 11863 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 11864 } 11865 11866 return false; 11867 } 11868 11869 // Return true is there is a nearyby consecutive load to the one provided 11870 // (regardless of alignment). We search up and down the chain, looking though 11871 // token factors and other loads (but nothing else). As a result, a true result 11872 // indicates that it is safe to create a new consecutive load adjacent to the 11873 // load provided. 11874 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 11875 SDValue Chain = LD->getChain(); 11876 EVT VT = LD->getMemoryVT(); 11877 11878 SmallSet<SDNode *, 16> LoadRoots; 11879 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 11880 SmallSet<SDNode *, 16> Visited; 11881 11882 // First, search up the chain, branching to follow all token-factor operands. 11883 // If we find a consecutive load, then we're done, otherwise, record all 11884 // nodes just above the top-level loads and token factors. 11885 while (!Queue.empty()) { 11886 SDNode *ChainNext = Queue.pop_back_val(); 11887 if (!Visited.insert(ChainNext).second) 11888 continue; 11889 11890 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 11891 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11892 return true; 11893 11894 if (!Visited.count(ChainLD->getChain().getNode())) 11895 Queue.push_back(ChainLD->getChain().getNode()); 11896 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 11897 for (const SDUse &O : ChainNext->ops()) 11898 if (!Visited.count(O.getNode())) 11899 Queue.push_back(O.getNode()); 11900 } else 11901 LoadRoots.insert(ChainNext); 11902 } 11903 11904 // Second, search down the chain, starting from the top-level nodes recorded 11905 // in the first phase. These top-level nodes are the nodes just above all 11906 // loads and token factors. Starting with their uses, recursively look though 11907 // all loads (just the chain uses) and token factors to find a consecutive 11908 // load. 11909 Visited.clear(); 11910 Queue.clear(); 11911 11912 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 11913 IE = LoadRoots.end(); I != IE; ++I) { 11914 Queue.push_back(*I); 11915 11916 while (!Queue.empty()) { 11917 SDNode *LoadRoot = Queue.pop_back_val(); 11918 if (!Visited.insert(LoadRoot).second) 11919 continue; 11920 11921 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 11922 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11923 return true; 11924 11925 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 11926 UE = LoadRoot->use_end(); UI != UE; ++UI) 11927 if (((isa<MemSDNode>(*UI) && 11928 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 11929 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 11930 Queue.push_back(*UI); 11931 } 11932 } 11933 11934 return false; 11935 } 11936 11937 /// This function is called when we have proved that a SETCC node can be replaced 11938 /// by subtraction (and other supporting instructions) so that the result of 11939 /// comparison is kept in a GPR instead of CR. This function is purely for 11940 /// codegen purposes and has some flags to guide the codegen process. 11941 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 11942 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 11943 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11944 11945 // Zero extend the operands to the largest legal integer. Originally, they 11946 // must be of a strictly smaller size. 11947 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 11948 DAG.getConstant(Size, DL, MVT::i32)); 11949 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 11950 DAG.getConstant(Size, DL, MVT::i32)); 11951 11952 // Swap if needed. Depends on the condition code. 11953 if (Swap) 11954 std::swap(Op0, Op1); 11955 11956 // Subtract extended integers. 11957 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 11958 11959 // Move the sign bit to the least significant position and zero out the rest. 11960 // Now the least significant bit carries the result of original comparison. 11961 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 11962 DAG.getConstant(Size - 1, DL, MVT::i32)); 11963 auto Final = Shifted; 11964 11965 // Complement the result if needed. Based on the condition code. 11966 if (Complement) 11967 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 11968 DAG.getConstant(1, DL, MVT::i64)); 11969 11970 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11971 } 11972 11973 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11974 DAGCombinerInfo &DCI) const { 11975 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11976 11977 SelectionDAG &DAG = DCI.DAG; 11978 SDLoc DL(N); 11979 11980 // Size of integers being compared has a critical role in the following 11981 // analysis, so we prefer to do this when all types are legal. 11982 if (!DCI.isAfterLegalizeDAG()) 11983 return SDValue(); 11984 11985 // If all users of SETCC extend its value to a legal integer type 11986 // then we replace SETCC with a subtraction 11987 for (SDNode::use_iterator UI = N->use_begin(), 11988 UE = N->use_end(); UI != UE; ++UI) { 11989 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11990 return SDValue(); 11991 } 11992 11993 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11994 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11995 11996 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11997 11998 if (OpSize < Size) { 11999 switch (CC) { 12000 default: break; 12001 case ISD::SETULT: 12002 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12003 case ISD::SETULE: 12004 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12005 case ISD::SETUGT: 12006 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12007 case ISD::SETUGE: 12008 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12009 } 12010 } 12011 12012 return SDValue(); 12013 } 12014 12015 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12016 DAGCombinerInfo &DCI) const { 12017 SelectionDAG &DAG = DCI.DAG; 12018 SDLoc dl(N); 12019 12020 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12021 // If we're tracking CR bits, we need to be careful that we don't have: 12022 // trunc(binary-ops(zext(x), zext(y))) 12023 // or 12024 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12025 // such that we're unnecessarily moving things into GPRs when it would be 12026 // better to keep them in CR bits. 12027 12028 // Note that trunc here can be an actual i1 trunc, or can be the effective 12029 // truncation that comes from a setcc or select_cc. 12030 if (N->getOpcode() == ISD::TRUNCATE && 12031 N->getValueType(0) != MVT::i1) 12032 return SDValue(); 12033 12034 if (N->getOperand(0).getValueType() != MVT::i32 && 12035 N->getOperand(0).getValueType() != MVT::i64) 12036 return SDValue(); 12037 12038 if (N->getOpcode() == ISD::SETCC || 12039 N->getOpcode() == ISD::SELECT_CC) { 12040 // If we're looking at a comparison, then we need to make sure that the 12041 // high bits (all except for the first) don't matter the result. 12042 ISD::CondCode CC = 12043 cast<CondCodeSDNode>(N->getOperand( 12044 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12045 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12046 12047 if (ISD::isSignedIntSetCC(CC)) { 12048 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12049 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12050 return SDValue(); 12051 } else if (ISD::isUnsignedIntSetCC(CC)) { 12052 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12053 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12054 !DAG.MaskedValueIsZero(N->getOperand(1), 12055 APInt::getHighBitsSet(OpBits, OpBits-1))) 12056 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12057 : SDValue()); 12058 } else { 12059 // This is neither a signed nor an unsigned comparison, just make sure 12060 // that the high bits are equal. 12061 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12062 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12063 12064 // We don't really care about what is known about the first bit (if 12065 // anything), so clear it in all masks prior to comparing them. 12066 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12067 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12068 12069 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12070 return SDValue(); 12071 } 12072 } 12073 12074 // We now know that the higher-order bits are irrelevant, we just need to 12075 // make sure that all of the intermediate operations are bit operations, and 12076 // all inputs are extensions. 12077 if (N->getOperand(0).getOpcode() != ISD::AND && 12078 N->getOperand(0).getOpcode() != ISD::OR && 12079 N->getOperand(0).getOpcode() != ISD::XOR && 12080 N->getOperand(0).getOpcode() != ISD::SELECT && 12081 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12082 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12083 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12084 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12085 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12086 return SDValue(); 12087 12088 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12089 N->getOperand(1).getOpcode() != ISD::AND && 12090 N->getOperand(1).getOpcode() != ISD::OR && 12091 N->getOperand(1).getOpcode() != ISD::XOR && 12092 N->getOperand(1).getOpcode() != ISD::SELECT && 12093 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12094 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12095 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12096 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12097 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12098 return SDValue(); 12099 12100 SmallVector<SDValue, 4> Inputs; 12101 SmallVector<SDValue, 8> BinOps, PromOps; 12102 SmallPtrSet<SDNode *, 16> Visited; 12103 12104 for (unsigned i = 0; i < 2; ++i) { 12105 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12106 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12107 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12108 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12109 isa<ConstantSDNode>(N->getOperand(i))) 12110 Inputs.push_back(N->getOperand(i)); 12111 else 12112 BinOps.push_back(N->getOperand(i)); 12113 12114 if (N->getOpcode() == ISD::TRUNCATE) 12115 break; 12116 } 12117 12118 // Visit all inputs, collect all binary operations (and, or, xor and 12119 // select) that are all fed by extensions. 12120 while (!BinOps.empty()) { 12121 SDValue BinOp = BinOps.back(); 12122 BinOps.pop_back(); 12123 12124 if (!Visited.insert(BinOp.getNode()).second) 12125 continue; 12126 12127 PromOps.push_back(BinOp); 12128 12129 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12130 // The condition of the select is not promoted. 12131 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12132 continue; 12133 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12134 continue; 12135 12136 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12137 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12138 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12139 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12140 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12141 Inputs.push_back(BinOp.getOperand(i)); 12142 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12143 BinOp.getOperand(i).getOpcode() == ISD::OR || 12144 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12145 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12146 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12147 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12148 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12149 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12150 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12151 BinOps.push_back(BinOp.getOperand(i)); 12152 } else { 12153 // We have an input that is not an extension or another binary 12154 // operation; we'll abort this transformation. 12155 return SDValue(); 12156 } 12157 } 12158 } 12159 12160 // Make sure that this is a self-contained cluster of operations (which 12161 // is not quite the same thing as saying that everything has only one 12162 // use). 12163 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12164 if (isa<ConstantSDNode>(Inputs[i])) 12165 continue; 12166 12167 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12168 UE = Inputs[i].getNode()->use_end(); 12169 UI != UE; ++UI) { 12170 SDNode *User = *UI; 12171 if (User != N && !Visited.count(User)) 12172 return SDValue(); 12173 12174 // Make sure that we're not going to promote the non-output-value 12175 // operand(s) or SELECT or SELECT_CC. 12176 // FIXME: Although we could sometimes handle this, and it does occur in 12177 // practice that one of the condition inputs to the select is also one of 12178 // the outputs, we currently can't deal with this. 12179 if (User->getOpcode() == ISD::SELECT) { 12180 if (User->getOperand(0) == Inputs[i]) 12181 return SDValue(); 12182 } else if (User->getOpcode() == ISD::SELECT_CC) { 12183 if (User->getOperand(0) == Inputs[i] || 12184 User->getOperand(1) == Inputs[i]) 12185 return SDValue(); 12186 } 12187 } 12188 } 12189 12190 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12191 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12192 UE = PromOps[i].getNode()->use_end(); 12193 UI != UE; ++UI) { 12194 SDNode *User = *UI; 12195 if (User != N && !Visited.count(User)) 12196 return SDValue(); 12197 12198 // Make sure that we're not going to promote the non-output-value 12199 // operand(s) or SELECT or SELECT_CC. 12200 // FIXME: Although we could sometimes handle this, and it does occur in 12201 // practice that one of the condition inputs to the select is also one of 12202 // the outputs, we currently can't deal with this. 12203 if (User->getOpcode() == ISD::SELECT) { 12204 if (User->getOperand(0) == PromOps[i]) 12205 return SDValue(); 12206 } else if (User->getOpcode() == ISD::SELECT_CC) { 12207 if (User->getOperand(0) == PromOps[i] || 12208 User->getOperand(1) == PromOps[i]) 12209 return SDValue(); 12210 } 12211 } 12212 } 12213 12214 // Replace all inputs with the extension operand. 12215 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12216 // Constants may have users outside the cluster of to-be-promoted nodes, 12217 // and so we need to replace those as we do the promotions. 12218 if (isa<ConstantSDNode>(Inputs[i])) 12219 continue; 12220 else 12221 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12222 } 12223 12224 std::list<HandleSDNode> PromOpHandles; 12225 for (auto &PromOp : PromOps) 12226 PromOpHandles.emplace_back(PromOp); 12227 12228 // Replace all operations (these are all the same, but have a different 12229 // (i1) return type). DAG.getNode will validate that the types of 12230 // a binary operator match, so go through the list in reverse so that 12231 // we've likely promoted both operands first. Any intermediate truncations or 12232 // extensions disappear. 12233 while (!PromOpHandles.empty()) { 12234 SDValue PromOp = PromOpHandles.back().getValue(); 12235 PromOpHandles.pop_back(); 12236 12237 if (PromOp.getOpcode() == ISD::TRUNCATE || 12238 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12239 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12240 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12241 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12242 PromOp.getOperand(0).getValueType() != MVT::i1) { 12243 // The operand is not yet ready (see comment below). 12244 PromOpHandles.emplace_front(PromOp); 12245 continue; 12246 } 12247 12248 SDValue RepValue = PromOp.getOperand(0); 12249 if (isa<ConstantSDNode>(RepValue)) 12250 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12251 12252 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12253 continue; 12254 } 12255 12256 unsigned C; 12257 switch (PromOp.getOpcode()) { 12258 default: C = 0; break; 12259 case ISD::SELECT: C = 1; break; 12260 case ISD::SELECT_CC: C = 2; break; 12261 } 12262 12263 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12264 PromOp.getOperand(C).getValueType() != MVT::i1) || 12265 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12266 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12267 // The to-be-promoted operands of this node have not yet been 12268 // promoted (this should be rare because we're going through the 12269 // list backward, but if one of the operands has several users in 12270 // this cluster of to-be-promoted nodes, it is possible). 12271 PromOpHandles.emplace_front(PromOp); 12272 continue; 12273 } 12274 12275 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12276 PromOp.getNode()->op_end()); 12277 12278 // If there are any constant inputs, make sure they're replaced now. 12279 for (unsigned i = 0; i < 2; ++i) 12280 if (isa<ConstantSDNode>(Ops[C+i])) 12281 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12282 12283 DAG.ReplaceAllUsesOfValueWith(PromOp, 12284 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12285 } 12286 12287 // Now we're left with the initial truncation itself. 12288 if (N->getOpcode() == ISD::TRUNCATE) 12289 return N->getOperand(0); 12290 12291 // Otherwise, this is a comparison. The operands to be compared have just 12292 // changed type (to i1), but everything else is the same. 12293 return SDValue(N, 0); 12294 } 12295 12296 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12297 DAGCombinerInfo &DCI) const { 12298 SelectionDAG &DAG = DCI.DAG; 12299 SDLoc dl(N); 12300 12301 // If we're tracking CR bits, we need to be careful that we don't have: 12302 // zext(binary-ops(trunc(x), trunc(y))) 12303 // or 12304 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12305 // such that we're unnecessarily moving things into CR bits that can more 12306 // efficiently stay in GPRs. Note that if we're not certain that the high 12307 // bits are set as required by the final extension, we still may need to do 12308 // some masking to get the proper behavior. 12309 12310 // This same functionality is important on PPC64 when dealing with 12311 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12312 // the return values of functions. Because it is so similar, it is handled 12313 // here as well. 12314 12315 if (N->getValueType(0) != MVT::i32 && 12316 N->getValueType(0) != MVT::i64) 12317 return SDValue(); 12318 12319 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12320 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12321 return SDValue(); 12322 12323 if (N->getOperand(0).getOpcode() != ISD::AND && 12324 N->getOperand(0).getOpcode() != ISD::OR && 12325 N->getOperand(0).getOpcode() != ISD::XOR && 12326 N->getOperand(0).getOpcode() != ISD::SELECT && 12327 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12328 return SDValue(); 12329 12330 SmallVector<SDValue, 4> Inputs; 12331 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12332 SmallPtrSet<SDNode *, 16> Visited; 12333 12334 // Visit all inputs, collect all binary operations (and, or, xor and 12335 // select) that are all fed by truncations. 12336 while (!BinOps.empty()) { 12337 SDValue BinOp = BinOps.back(); 12338 BinOps.pop_back(); 12339 12340 if (!Visited.insert(BinOp.getNode()).second) 12341 continue; 12342 12343 PromOps.push_back(BinOp); 12344 12345 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12346 // The condition of the select is not promoted. 12347 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12348 continue; 12349 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12350 continue; 12351 12352 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12353 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12354 Inputs.push_back(BinOp.getOperand(i)); 12355 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12356 BinOp.getOperand(i).getOpcode() == ISD::OR || 12357 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12358 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12359 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12360 BinOps.push_back(BinOp.getOperand(i)); 12361 } else { 12362 // We have an input that is not a truncation or another binary 12363 // operation; we'll abort this transformation. 12364 return SDValue(); 12365 } 12366 } 12367 } 12368 12369 // The operands of a select that must be truncated when the select is 12370 // promoted because the operand is actually part of the to-be-promoted set. 12371 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12372 12373 // Make sure that this is a self-contained cluster of operations (which 12374 // is not quite the same thing as saying that everything has only one 12375 // use). 12376 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12377 if (isa<ConstantSDNode>(Inputs[i])) 12378 continue; 12379 12380 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12381 UE = Inputs[i].getNode()->use_end(); 12382 UI != UE; ++UI) { 12383 SDNode *User = *UI; 12384 if (User != N && !Visited.count(User)) 12385 return SDValue(); 12386 12387 // If we're going to promote the non-output-value operand(s) or SELECT or 12388 // SELECT_CC, record them for truncation. 12389 if (User->getOpcode() == ISD::SELECT) { 12390 if (User->getOperand(0) == Inputs[i]) 12391 SelectTruncOp[0].insert(std::make_pair(User, 12392 User->getOperand(0).getValueType())); 12393 } else if (User->getOpcode() == ISD::SELECT_CC) { 12394 if (User->getOperand(0) == Inputs[i]) 12395 SelectTruncOp[0].insert(std::make_pair(User, 12396 User->getOperand(0).getValueType())); 12397 if (User->getOperand(1) == Inputs[i]) 12398 SelectTruncOp[1].insert(std::make_pair(User, 12399 User->getOperand(1).getValueType())); 12400 } 12401 } 12402 } 12403 12404 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12405 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12406 UE = PromOps[i].getNode()->use_end(); 12407 UI != UE; ++UI) { 12408 SDNode *User = *UI; 12409 if (User != N && !Visited.count(User)) 12410 return SDValue(); 12411 12412 // If we're going to promote the non-output-value operand(s) or SELECT or 12413 // SELECT_CC, record them for truncation. 12414 if (User->getOpcode() == ISD::SELECT) { 12415 if (User->getOperand(0) == PromOps[i]) 12416 SelectTruncOp[0].insert(std::make_pair(User, 12417 User->getOperand(0).getValueType())); 12418 } else if (User->getOpcode() == ISD::SELECT_CC) { 12419 if (User->getOperand(0) == PromOps[i]) 12420 SelectTruncOp[0].insert(std::make_pair(User, 12421 User->getOperand(0).getValueType())); 12422 if (User->getOperand(1) == PromOps[i]) 12423 SelectTruncOp[1].insert(std::make_pair(User, 12424 User->getOperand(1).getValueType())); 12425 } 12426 } 12427 } 12428 12429 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12430 bool ReallyNeedsExt = false; 12431 if (N->getOpcode() != ISD::ANY_EXTEND) { 12432 // If all of the inputs are not already sign/zero extended, then 12433 // we'll still need to do that at the end. 12434 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12435 if (isa<ConstantSDNode>(Inputs[i])) 12436 continue; 12437 12438 unsigned OpBits = 12439 Inputs[i].getOperand(0).getValueSizeInBits(); 12440 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12441 12442 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12443 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12444 APInt::getHighBitsSet(OpBits, 12445 OpBits-PromBits))) || 12446 (N->getOpcode() == ISD::SIGN_EXTEND && 12447 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12448 (OpBits-(PromBits-1)))) { 12449 ReallyNeedsExt = true; 12450 break; 12451 } 12452 } 12453 } 12454 12455 // Replace all inputs, either with the truncation operand, or a 12456 // truncation or extension to the final output type. 12457 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12458 // Constant inputs need to be replaced with the to-be-promoted nodes that 12459 // use them because they might have users outside of the cluster of 12460 // promoted nodes. 12461 if (isa<ConstantSDNode>(Inputs[i])) 12462 continue; 12463 12464 SDValue InSrc = Inputs[i].getOperand(0); 12465 if (Inputs[i].getValueType() == N->getValueType(0)) 12466 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12467 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12468 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12469 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12470 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12471 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12472 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12473 else 12474 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12475 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12476 } 12477 12478 std::list<HandleSDNode> PromOpHandles; 12479 for (auto &PromOp : PromOps) 12480 PromOpHandles.emplace_back(PromOp); 12481 12482 // Replace all operations (these are all the same, but have a different 12483 // (promoted) return type). DAG.getNode will validate that the types of 12484 // a binary operator match, so go through the list in reverse so that 12485 // we've likely promoted both operands first. 12486 while (!PromOpHandles.empty()) { 12487 SDValue PromOp = PromOpHandles.back().getValue(); 12488 PromOpHandles.pop_back(); 12489 12490 unsigned C; 12491 switch (PromOp.getOpcode()) { 12492 default: C = 0; break; 12493 case ISD::SELECT: C = 1; break; 12494 case ISD::SELECT_CC: C = 2; break; 12495 } 12496 12497 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12498 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12499 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12500 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12501 // The to-be-promoted operands of this node have not yet been 12502 // promoted (this should be rare because we're going through the 12503 // list backward, but if one of the operands has several users in 12504 // this cluster of to-be-promoted nodes, it is possible). 12505 PromOpHandles.emplace_front(PromOp); 12506 continue; 12507 } 12508 12509 // For SELECT and SELECT_CC nodes, we do a similar check for any 12510 // to-be-promoted comparison inputs. 12511 if (PromOp.getOpcode() == ISD::SELECT || 12512 PromOp.getOpcode() == ISD::SELECT_CC) { 12513 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12514 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12515 (SelectTruncOp[1].count(PromOp.getNode()) && 12516 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12517 PromOpHandles.emplace_front(PromOp); 12518 continue; 12519 } 12520 } 12521 12522 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12523 PromOp.getNode()->op_end()); 12524 12525 // If this node has constant inputs, then they'll need to be promoted here. 12526 for (unsigned i = 0; i < 2; ++i) { 12527 if (!isa<ConstantSDNode>(Ops[C+i])) 12528 continue; 12529 if (Ops[C+i].getValueType() == N->getValueType(0)) 12530 continue; 12531 12532 if (N->getOpcode() == ISD::SIGN_EXTEND) 12533 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12534 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12535 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12536 else 12537 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12538 } 12539 12540 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12541 // truncate them again to the original value type. 12542 if (PromOp.getOpcode() == ISD::SELECT || 12543 PromOp.getOpcode() == ISD::SELECT_CC) { 12544 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12545 if (SI0 != SelectTruncOp[0].end()) 12546 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12547 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12548 if (SI1 != SelectTruncOp[1].end()) 12549 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12550 } 12551 12552 DAG.ReplaceAllUsesOfValueWith(PromOp, 12553 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12554 } 12555 12556 // Now we're left with the initial extension itself. 12557 if (!ReallyNeedsExt) 12558 return N->getOperand(0); 12559 12560 // To zero extend, just mask off everything except for the first bit (in the 12561 // i1 case). 12562 if (N->getOpcode() == ISD::ZERO_EXTEND) 12563 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12564 DAG.getConstant(APInt::getLowBitsSet( 12565 N->getValueSizeInBits(0), PromBits), 12566 dl, N->getValueType(0))); 12567 12568 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12569 "Invalid extension type"); 12570 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12571 SDValue ShiftCst = 12572 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12573 return DAG.getNode( 12574 ISD::SRA, dl, N->getValueType(0), 12575 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12576 ShiftCst); 12577 } 12578 12579 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12580 DAGCombinerInfo &DCI) const { 12581 assert(N->getOpcode() == ISD::SETCC && 12582 "Should be called with a SETCC node"); 12583 12584 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12585 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12586 SDValue LHS = N->getOperand(0); 12587 SDValue RHS = N->getOperand(1); 12588 12589 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12590 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12591 LHS.hasOneUse()) 12592 std::swap(LHS, RHS); 12593 12594 // x == 0-y --> x+y == 0 12595 // x != 0-y --> x+y != 0 12596 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12597 RHS.hasOneUse()) { 12598 SDLoc DL(N); 12599 SelectionDAG &DAG = DCI.DAG; 12600 EVT VT = N->getValueType(0); 12601 EVT OpVT = LHS.getValueType(); 12602 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12603 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12604 } 12605 } 12606 12607 return DAGCombineTruncBoolExt(N, DCI); 12608 } 12609 12610 // Is this an extending load from an f32 to an f64? 12611 static bool isFPExtLoad(SDValue Op) { 12612 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12613 return LD->getExtensionType() == ISD::EXTLOAD && 12614 Op.getValueType() == MVT::f64; 12615 return false; 12616 } 12617 12618 /// Reduces the number of fp-to-int conversion when building a vector. 12619 /// 12620 /// If this vector is built out of floating to integer conversions, 12621 /// transform it to a vector built out of floating point values followed by a 12622 /// single floating to integer conversion of the vector. 12623 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12624 /// becomes (fptosi (build_vector ($A, $B, ...))) 12625 SDValue PPCTargetLowering:: 12626 combineElementTruncationToVectorTruncation(SDNode *N, 12627 DAGCombinerInfo &DCI) const { 12628 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12629 "Should be called with a BUILD_VECTOR node"); 12630 12631 SelectionDAG &DAG = DCI.DAG; 12632 SDLoc dl(N); 12633 12634 SDValue FirstInput = N->getOperand(0); 12635 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12636 "The input operand must be an fp-to-int conversion."); 12637 12638 // This combine happens after legalization so the fp_to_[su]i nodes are 12639 // already converted to PPCSISD nodes. 12640 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12641 if (FirstConversion == PPCISD::FCTIDZ || 12642 FirstConversion == PPCISD::FCTIDUZ || 12643 FirstConversion == PPCISD::FCTIWZ || 12644 FirstConversion == PPCISD::FCTIWUZ) { 12645 bool IsSplat = true; 12646 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12647 FirstConversion == PPCISD::FCTIWUZ; 12648 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12649 SmallVector<SDValue, 4> Ops; 12650 EVT TargetVT = N->getValueType(0); 12651 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12652 SDValue NextOp = N->getOperand(i); 12653 if (NextOp.getOpcode() != PPCISD::MFVSR) 12654 return SDValue(); 12655 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12656 if (NextConversion != FirstConversion) 12657 return SDValue(); 12658 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12659 // This is not valid if the input was originally double precision. It is 12660 // also not profitable to do unless this is an extending load in which 12661 // case doing this combine will allow us to combine consecutive loads. 12662 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12663 return SDValue(); 12664 if (N->getOperand(i) != FirstInput) 12665 IsSplat = false; 12666 } 12667 12668 // If this is a splat, we leave it as-is since there will be only a single 12669 // fp-to-int conversion followed by a splat of the integer. This is better 12670 // for 32-bit and smaller ints and neutral for 64-bit ints. 12671 if (IsSplat) 12672 return SDValue(); 12673 12674 // Now that we know we have the right type of node, get its operands 12675 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12676 SDValue In = N->getOperand(i).getOperand(0); 12677 if (Is32Bit) { 12678 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12679 // here, we know that all inputs are extending loads so this is safe). 12680 if (In.isUndef()) 12681 Ops.push_back(DAG.getUNDEF(SrcVT)); 12682 else { 12683 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12684 MVT::f32, In.getOperand(0), 12685 DAG.getIntPtrConstant(1, dl)); 12686 Ops.push_back(Trunc); 12687 } 12688 } else 12689 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12690 } 12691 12692 unsigned Opcode; 12693 if (FirstConversion == PPCISD::FCTIDZ || 12694 FirstConversion == PPCISD::FCTIWZ) 12695 Opcode = ISD::FP_TO_SINT; 12696 else 12697 Opcode = ISD::FP_TO_UINT; 12698 12699 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12700 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12701 return DAG.getNode(Opcode, dl, TargetVT, BV); 12702 } 12703 return SDValue(); 12704 } 12705 12706 /// Reduce the number of loads when building a vector. 12707 /// 12708 /// Building a vector out of multiple loads can be converted to a load 12709 /// of the vector type if the loads are consecutive. If the loads are 12710 /// consecutive but in descending order, a shuffle is added at the end 12711 /// to reorder the vector. 12712 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 12713 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12714 "Should be called with a BUILD_VECTOR node"); 12715 12716 SDLoc dl(N); 12717 12718 // Return early for non byte-sized type, as they can't be consecutive. 12719 if (!N->getValueType(0).getVectorElementType().isByteSized()) 12720 return SDValue(); 12721 12722 bool InputsAreConsecutiveLoads = true; 12723 bool InputsAreReverseConsecutive = true; 12724 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 12725 SDValue FirstInput = N->getOperand(0); 12726 bool IsRoundOfExtLoad = false; 12727 12728 if (FirstInput.getOpcode() == ISD::FP_ROUND && 12729 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 12730 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 12731 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 12732 } 12733 // Not a build vector of (possibly fp_rounded) loads. 12734 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 12735 N->getNumOperands() == 1) 12736 return SDValue(); 12737 12738 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 12739 // If any inputs are fp_round(extload), they all must be. 12740 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 12741 return SDValue(); 12742 12743 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 12744 N->getOperand(i); 12745 if (NextInput.getOpcode() != ISD::LOAD) 12746 return SDValue(); 12747 12748 SDValue PreviousInput = 12749 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 12750 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 12751 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 12752 12753 // If any inputs are fp_round(extload), they all must be. 12754 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 12755 return SDValue(); 12756 12757 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 12758 InputsAreConsecutiveLoads = false; 12759 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 12760 InputsAreReverseConsecutive = false; 12761 12762 // Exit early if the loads are neither consecutive nor reverse consecutive. 12763 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12764 return SDValue(); 12765 } 12766 12767 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12768 "The loads cannot be both consecutive and reverse consecutive."); 12769 12770 SDValue FirstLoadOp = 12771 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12772 SDValue LastLoadOp = 12773 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12774 N->getOperand(N->getNumOperands()-1); 12775 12776 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12777 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12778 if (InputsAreConsecutiveLoads) { 12779 assert(LD1 && "Input needs to be a LoadSDNode."); 12780 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12781 LD1->getBasePtr(), LD1->getPointerInfo(), 12782 LD1->getAlignment()); 12783 } 12784 if (InputsAreReverseConsecutive) { 12785 assert(LDL && "Input needs to be a LoadSDNode."); 12786 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12787 LDL->getBasePtr(), LDL->getPointerInfo(), 12788 LDL->getAlignment()); 12789 SmallVector<int, 16> Ops; 12790 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12791 Ops.push_back(i); 12792 12793 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12794 DAG.getUNDEF(N->getValueType(0)), Ops); 12795 } 12796 return SDValue(); 12797 } 12798 12799 // This function adds the required vector_shuffle needed to get 12800 // the elements of the vector extract in the correct position 12801 // as specified by the CorrectElems encoding. 12802 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12803 SDValue Input, uint64_t Elems, 12804 uint64_t CorrectElems) { 12805 SDLoc dl(N); 12806 12807 unsigned NumElems = Input.getValueType().getVectorNumElements(); 12808 SmallVector<int, 16> ShuffleMask(NumElems, -1); 12809 12810 // Knowing the element indices being extracted from the original 12811 // vector and the order in which they're being inserted, just put 12812 // them at element indices required for the instruction. 12813 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12814 if (DAG.getDataLayout().isLittleEndian()) 12815 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 12816 else 12817 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 12818 CorrectElems = CorrectElems >> 8; 12819 Elems = Elems >> 8; 12820 } 12821 12822 SDValue Shuffle = 12823 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 12824 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 12825 12826 EVT Ty = N->getValueType(0); 12827 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 12828 return BV; 12829 } 12830 12831 // Look for build vector patterns where input operands come from sign 12832 // extended vector_extract elements of specific indices. If the correct indices 12833 // aren't used, add a vector shuffle to fix up the indices and create a new 12834 // PPCISD:SExtVElems node which selects the vector sign extend instructions 12835 // during instruction selection. 12836 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 12837 // This array encodes the indices that the vector sign extend instructions 12838 // extract from when extending from one type to another for both BE and LE. 12839 // The right nibble of each byte corresponds to the LE incides. 12840 // and the left nibble of each byte corresponds to the BE incides. 12841 // For example: 0x3074B8FC byte->word 12842 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 12843 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 12844 // For example: 0x000070F8 byte->double word 12845 // For LE: the allowed indices are: 0x0,0x8 12846 // For BE: the allowed indices are: 0x7,0xF 12847 uint64_t TargetElems[] = { 12848 0x3074B8FC, // b->w 12849 0x000070F8, // b->d 12850 0x10325476, // h->w 12851 0x00003074, // h->d 12852 0x00001032, // w->d 12853 }; 12854 12855 uint64_t Elems = 0; 12856 int Index; 12857 SDValue Input; 12858 12859 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 12860 if (!Op) 12861 return false; 12862 if (Op.getOpcode() != ISD::SIGN_EXTEND && 12863 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 12864 return false; 12865 12866 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 12867 // of the right width. 12868 SDValue Extract = Op.getOperand(0); 12869 if (Extract.getOpcode() == ISD::ANY_EXTEND) 12870 Extract = Extract.getOperand(0); 12871 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12872 return false; 12873 12874 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 12875 if (!ExtOp) 12876 return false; 12877 12878 Index = ExtOp->getZExtValue(); 12879 if (Input && Input != Extract.getOperand(0)) 12880 return false; 12881 12882 if (!Input) 12883 Input = Extract.getOperand(0); 12884 12885 Elems = Elems << 8; 12886 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 12887 Elems |= Index; 12888 12889 return true; 12890 }; 12891 12892 // If the build vector operands aren't sign extended vector extracts, 12893 // of the same input vector, then return. 12894 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12895 if (!isSExtOfVecExtract(N->getOperand(i))) { 12896 return SDValue(); 12897 } 12898 } 12899 12900 // If the vector extract indicies are not correct, add the appropriate 12901 // vector_shuffle. 12902 int TgtElemArrayIdx; 12903 int InputSize = Input.getValueType().getScalarSizeInBits(); 12904 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 12905 if (InputSize + OutputSize == 40) 12906 TgtElemArrayIdx = 0; 12907 else if (InputSize + OutputSize == 72) 12908 TgtElemArrayIdx = 1; 12909 else if (InputSize + OutputSize == 48) 12910 TgtElemArrayIdx = 2; 12911 else if (InputSize + OutputSize == 80) 12912 TgtElemArrayIdx = 3; 12913 else if (InputSize + OutputSize == 96) 12914 TgtElemArrayIdx = 4; 12915 else 12916 return SDValue(); 12917 12918 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 12919 CorrectElems = DAG.getDataLayout().isLittleEndian() 12920 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 12921 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 12922 if (Elems != CorrectElems) { 12923 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 12924 } 12925 12926 // Regular lowering will catch cases where a shuffle is not needed. 12927 return SDValue(); 12928 } 12929 12930 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 12931 DAGCombinerInfo &DCI) const { 12932 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12933 "Should be called with a BUILD_VECTOR node"); 12934 12935 SelectionDAG &DAG = DCI.DAG; 12936 SDLoc dl(N); 12937 12938 if (!Subtarget.hasVSX()) 12939 return SDValue(); 12940 12941 // The target independent DAG combiner will leave a build_vector of 12942 // float-to-int conversions intact. We can generate MUCH better code for 12943 // a float-to-int conversion of a vector of floats. 12944 SDValue FirstInput = N->getOperand(0); 12945 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 12946 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 12947 if (Reduced) 12948 return Reduced; 12949 } 12950 12951 // If we're building a vector out of consecutive loads, just load that 12952 // vector type. 12953 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 12954 if (Reduced) 12955 return Reduced; 12956 12957 // If we're building a vector out of extended elements from another vector 12958 // we have P9 vector integer extend instructions. The code assumes legal 12959 // input types (i.e. it can't handle things like v4i16) so do not run before 12960 // legalization. 12961 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 12962 Reduced = combineBVOfVecSExt(N, DAG); 12963 if (Reduced) 12964 return Reduced; 12965 } 12966 12967 12968 if (N->getValueType(0) != MVT::v2f64) 12969 return SDValue(); 12970 12971 // Looking for: 12972 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 12973 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 12974 FirstInput.getOpcode() != ISD::UINT_TO_FP) 12975 return SDValue(); 12976 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 12977 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 12978 return SDValue(); 12979 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 12980 return SDValue(); 12981 12982 SDValue Ext1 = FirstInput.getOperand(0); 12983 SDValue Ext2 = N->getOperand(1).getOperand(0); 12984 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12985 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12986 return SDValue(); 12987 12988 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 12989 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 12990 if (!Ext1Op || !Ext2Op) 12991 return SDValue(); 12992 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 12993 Ext1.getOperand(0) != Ext2.getOperand(0)) 12994 return SDValue(); 12995 12996 int FirstElem = Ext1Op->getZExtValue(); 12997 int SecondElem = Ext2Op->getZExtValue(); 12998 int SubvecIdx; 12999 if (FirstElem == 0 && SecondElem == 1) 13000 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13001 else if (FirstElem == 2 && SecondElem == 3) 13002 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13003 else 13004 return SDValue(); 13005 13006 SDValue SrcVec = Ext1.getOperand(0); 13007 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13008 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13009 return DAG.getNode(NodeType, dl, MVT::v2f64, 13010 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13011 } 13012 13013 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13014 DAGCombinerInfo &DCI) const { 13015 assert((N->getOpcode() == ISD::SINT_TO_FP || 13016 N->getOpcode() == ISD::UINT_TO_FP) && 13017 "Need an int -> FP conversion node here"); 13018 13019 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13020 return SDValue(); 13021 13022 SelectionDAG &DAG = DCI.DAG; 13023 SDLoc dl(N); 13024 SDValue Op(N, 0); 13025 13026 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13027 // from the hardware. 13028 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13029 return SDValue(); 13030 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13031 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13032 return SDValue(); 13033 13034 SDValue FirstOperand(Op.getOperand(0)); 13035 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13036 (FirstOperand.getValueType() == MVT::i8 || 13037 FirstOperand.getValueType() == MVT::i16); 13038 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13039 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13040 bool DstDouble = Op.getValueType() == MVT::f64; 13041 unsigned ConvOp = Signed ? 13042 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13043 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13044 SDValue WidthConst = 13045 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13046 dl, false); 13047 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13048 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13049 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13050 DAG.getVTList(MVT::f64, MVT::Other), 13051 Ops, MVT::i8, LDN->getMemOperand()); 13052 13053 // For signed conversion, we need to sign-extend the value in the VSR 13054 if (Signed) { 13055 SDValue ExtOps[] = { Ld, WidthConst }; 13056 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13057 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13058 } else 13059 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13060 } 13061 13062 13063 // For i32 intermediate values, unfortunately, the conversion functions 13064 // leave the upper 32 bits of the value are undefined. Within the set of 13065 // scalar instructions, we have no method for zero- or sign-extending the 13066 // value. Thus, we cannot handle i32 intermediate values here. 13067 if (Op.getOperand(0).getValueType() == MVT::i32) 13068 return SDValue(); 13069 13070 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13071 "UINT_TO_FP is supported only with FPCVT"); 13072 13073 // If we have FCFIDS, then use it when converting to single-precision. 13074 // Otherwise, convert to double-precision and then round. 13075 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13076 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13077 : PPCISD::FCFIDS) 13078 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13079 : PPCISD::FCFID); 13080 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13081 ? MVT::f32 13082 : MVT::f64; 13083 13084 // If we're converting from a float, to an int, and back to a float again, 13085 // then we don't need the store/load pair at all. 13086 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13087 Subtarget.hasFPCVT()) || 13088 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13089 SDValue Src = Op.getOperand(0).getOperand(0); 13090 if (Src.getValueType() == MVT::f32) { 13091 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13092 DCI.AddToWorklist(Src.getNode()); 13093 } else if (Src.getValueType() != MVT::f64) { 13094 // Make sure that we don't pick up a ppc_fp128 source value. 13095 return SDValue(); 13096 } 13097 13098 unsigned FCTOp = 13099 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13100 PPCISD::FCTIDUZ; 13101 13102 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13103 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13104 13105 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13106 FP = DAG.getNode(ISD::FP_ROUND, dl, 13107 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13108 DCI.AddToWorklist(FP.getNode()); 13109 } 13110 13111 return FP; 13112 } 13113 13114 return SDValue(); 13115 } 13116 13117 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13118 // builtins) into loads with swaps. 13119 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13120 DAGCombinerInfo &DCI) const { 13121 SelectionDAG &DAG = DCI.DAG; 13122 SDLoc dl(N); 13123 SDValue Chain; 13124 SDValue Base; 13125 MachineMemOperand *MMO; 13126 13127 switch (N->getOpcode()) { 13128 default: 13129 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13130 case ISD::LOAD: { 13131 LoadSDNode *LD = cast<LoadSDNode>(N); 13132 Chain = LD->getChain(); 13133 Base = LD->getBasePtr(); 13134 MMO = LD->getMemOperand(); 13135 // If the MMO suggests this isn't a load of a full vector, leave 13136 // things alone. For a built-in, we have to make the change for 13137 // correctness, so if there is a size problem that will be a bug. 13138 if (MMO->getSize() < 16) 13139 return SDValue(); 13140 break; 13141 } 13142 case ISD::INTRINSIC_W_CHAIN: { 13143 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13144 Chain = Intrin->getChain(); 13145 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13146 // us what we want. Get operand 2 instead. 13147 Base = Intrin->getOperand(2); 13148 MMO = Intrin->getMemOperand(); 13149 break; 13150 } 13151 } 13152 13153 MVT VecTy = N->getValueType(0).getSimpleVT(); 13154 13155 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13156 // aligned and the type is a vector with elements up to 4 bytes 13157 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13158 && VecTy.getScalarSizeInBits() <= 32 ) { 13159 return SDValue(); 13160 } 13161 13162 SDValue LoadOps[] = { Chain, Base }; 13163 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13164 DAG.getVTList(MVT::v2f64, MVT::Other), 13165 LoadOps, MVT::v2f64, MMO); 13166 13167 DCI.AddToWorklist(Load.getNode()); 13168 Chain = Load.getValue(1); 13169 SDValue Swap = DAG.getNode( 13170 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13171 DCI.AddToWorklist(Swap.getNode()); 13172 13173 // Add a bitcast if the resulting load type doesn't match v2f64. 13174 if (VecTy != MVT::v2f64) { 13175 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13176 DCI.AddToWorklist(N.getNode()); 13177 // Package {bitcast value, swap's chain} to match Load's shape. 13178 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13179 N, Swap.getValue(1)); 13180 } 13181 13182 return Swap; 13183 } 13184 13185 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13186 // builtins) into stores with swaps. 13187 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13188 DAGCombinerInfo &DCI) const { 13189 SelectionDAG &DAG = DCI.DAG; 13190 SDLoc dl(N); 13191 SDValue Chain; 13192 SDValue Base; 13193 unsigned SrcOpnd; 13194 MachineMemOperand *MMO; 13195 13196 switch (N->getOpcode()) { 13197 default: 13198 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13199 case ISD::STORE: { 13200 StoreSDNode *ST = cast<StoreSDNode>(N); 13201 Chain = ST->getChain(); 13202 Base = ST->getBasePtr(); 13203 MMO = ST->getMemOperand(); 13204 SrcOpnd = 1; 13205 // If the MMO suggests this isn't a store of a full vector, leave 13206 // things alone. For a built-in, we have to make the change for 13207 // correctness, so if there is a size problem that will be a bug. 13208 if (MMO->getSize() < 16) 13209 return SDValue(); 13210 break; 13211 } 13212 case ISD::INTRINSIC_VOID: { 13213 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13214 Chain = Intrin->getChain(); 13215 // Intrin->getBasePtr() oddly does not get what we want. 13216 Base = Intrin->getOperand(3); 13217 MMO = Intrin->getMemOperand(); 13218 SrcOpnd = 2; 13219 break; 13220 } 13221 } 13222 13223 SDValue Src = N->getOperand(SrcOpnd); 13224 MVT VecTy = Src.getValueType().getSimpleVT(); 13225 13226 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13227 // aligned and the type is a vector with elements up to 4 bytes 13228 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13229 && VecTy.getScalarSizeInBits() <= 32 ) { 13230 return SDValue(); 13231 } 13232 13233 // All stores are done as v2f64 and possible bit cast. 13234 if (VecTy != MVT::v2f64) { 13235 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13236 DCI.AddToWorklist(Src.getNode()); 13237 } 13238 13239 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13240 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13241 DCI.AddToWorklist(Swap.getNode()); 13242 Chain = Swap.getValue(1); 13243 SDValue StoreOps[] = { Chain, Swap, Base }; 13244 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13245 DAG.getVTList(MVT::Other), 13246 StoreOps, VecTy, MMO); 13247 DCI.AddToWorklist(Store.getNode()); 13248 return Store; 13249 } 13250 13251 // Handle DAG combine for STORE (FP_TO_INT F). 13252 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13253 DAGCombinerInfo &DCI) const { 13254 13255 SelectionDAG &DAG = DCI.DAG; 13256 SDLoc dl(N); 13257 unsigned Opcode = N->getOperand(1).getOpcode(); 13258 13259 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13260 && "Not a FP_TO_INT Instruction!"); 13261 13262 SDValue Val = N->getOperand(1).getOperand(0); 13263 EVT Op1VT = N->getOperand(1).getValueType(); 13264 EVT ResVT = Val.getValueType(); 13265 13266 // Floating point types smaller than 32 bits are not legal on Power. 13267 if (ResVT.getScalarSizeInBits() < 32) 13268 return SDValue(); 13269 13270 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13271 bool ValidTypeForStoreFltAsInt = 13272 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13273 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13274 13275 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 13276 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13277 return SDValue(); 13278 13279 // Extend f32 values to f64 13280 if (ResVT.getScalarSizeInBits() == 32) { 13281 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13282 DCI.AddToWorklist(Val.getNode()); 13283 } 13284 13285 // Set signed or unsigned conversion opcode. 13286 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13287 PPCISD::FP_TO_SINT_IN_VSR : 13288 PPCISD::FP_TO_UINT_IN_VSR; 13289 13290 Val = DAG.getNode(ConvOpcode, 13291 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13292 DCI.AddToWorklist(Val.getNode()); 13293 13294 // Set number of bytes being converted. 13295 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13296 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13297 DAG.getIntPtrConstant(ByteSize, dl, false), 13298 DAG.getValueType(Op1VT) }; 13299 13300 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13301 DAG.getVTList(MVT::Other), Ops, 13302 cast<StoreSDNode>(N)->getMemoryVT(), 13303 cast<StoreSDNode>(N)->getMemOperand()); 13304 13305 DCI.AddToWorklist(Val.getNode()); 13306 return Val; 13307 } 13308 13309 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 13310 LSBaseSDNode *LSBase, 13311 DAGCombinerInfo &DCI) const { 13312 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 13313 "Not a reverse memop pattern!"); 13314 13315 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 13316 auto Mask = SVN->getMask(); 13317 int i = 0; 13318 auto I = Mask.rbegin(); 13319 auto E = Mask.rend(); 13320 13321 for (; I != E; ++I) { 13322 if (*I != i) 13323 return false; 13324 i++; 13325 } 13326 return true; 13327 }; 13328 13329 SelectionDAG &DAG = DCI.DAG; 13330 EVT VT = SVN->getValueType(0); 13331 13332 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 13333 return SDValue(); 13334 13335 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 13336 // See comment in PPCVSXSwapRemoval.cpp. 13337 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 13338 if (!Subtarget.hasP9Vector()) 13339 return SDValue(); 13340 13341 if(!IsElementReverse(SVN)) 13342 return SDValue(); 13343 13344 if (LSBase->getOpcode() == ISD::LOAD) { 13345 SDLoc dl(SVN); 13346 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 13347 return DAG.getMemIntrinsicNode( 13348 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 13349 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13350 } 13351 13352 if (LSBase->getOpcode() == ISD::STORE) { 13353 SDLoc dl(LSBase); 13354 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 13355 LSBase->getBasePtr()}; 13356 return DAG.getMemIntrinsicNode( 13357 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 13358 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13359 } 13360 13361 llvm_unreachable("Expected a load or store node here"); 13362 } 13363 13364 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 13365 DAGCombinerInfo &DCI) const { 13366 SelectionDAG &DAG = DCI.DAG; 13367 SDLoc dl(N); 13368 switch (N->getOpcode()) { 13369 default: break; 13370 case ISD::ADD: 13371 return combineADD(N, DCI); 13372 case ISD::SHL: 13373 return combineSHL(N, DCI); 13374 case ISD::SRA: 13375 return combineSRA(N, DCI); 13376 case ISD::SRL: 13377 return combineSRL(N, DCI); 13378 case ISD::MUL: 13379 return combineMUL(N, DCI); 13380 case PPCISD::SHL: 13381 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 13382 return N->getOperand(0); 13383 break; 13384 case PPCISD::SRL: 13385 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 13386 return N->getOperand(0); 13387 break; 13388 case PPCISD::SRA: 13389 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 13390 if (C->isNullValue() || // 0 >>s V -> 0. 13391 C->isAllOnesValue()) // -1 >>s V -> -1. 13392 return N->getOperand(0); 13393 } 13394 break; 13395 case ISD::SIGN_EXTEND: 13396 case ISD::ZERO_EXTEND: 13397 case ISD::ANY_EXTEND: 13398 return DAGCombineExtBoolTrunc(N, DCI); 13399 case ISD::TRUNCATE: 13400 return combineTRUNCATE(N, DCI); 13401 case ISD::SETCC: 13402 if (SDValue CSCC = combineSetCC(N, DCI)) 13403 return CSCC; 13404 LLVM_FALLTHROUGH; 13405 case ISD::SELECT_CC: 13406 return DAGCombineTruncBoolExt(N, DCI); 13407 case ISD::SINT_TO_FP: 13408 case ISD::UINT_TO_FP: 13409 return combineFPToIntToFP(N, DCI); 13410 case ISD::VECTOR_SHUFFLE: 13411 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 13412 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 13413 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 13414 } 13415 break; 13416 case ISD::STORE: { 13417 13418 EVT Op1VT = N->getOperand(1).getValueType(); 13419 unsigned Opcode = N->getOperand(1).getOpcode(); 13420 13421 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 13422 SDValue Val= combineStoreFPToInt(N, DCI); 13423 if (Val) 13424 return Val; 13425 } 13426 13427 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 13428 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 13429 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 13430 if (Val) 13431 return Val; 13432 } 13433 13434 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 13435 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 13436 N->getOperand(1).getNode()->hasOneUse() && 13437 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 13438 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 13439 13440 // STBRX can only handle simple types and it makes no sense to store less 13441 // two bytes in byte-reversed order. 13442 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 13443 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 13444 break; 13445 13446 SDValue BSwapOp = N->getOperand(1).getOperand(0); 13447 // Do an any-extend to 32-bits if this is a half-word input. 13448 if (BSwapOp.getValueType() == MVT::i16) 13449 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 13450 13451 // If the type of BSWAP operand is wider than stored memory width 13452 // it need to be shifted to the right side before STBRX. 13453 if (Op1VT.bitsGT(mVT)) { 13454 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 13455 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 13456 DAG.getConstant(Shift, dl, MVT::i32)); 13457 // Need to truncate if this is a bswap of i64 stored as i32/i16. 13458 if (Op1VT == MVT::i64) 13459 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 13460 } 13461 13462 SDValue Ops[] = { 13463 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 13464 }; 13465 return 13466 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 13467 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 13468 cast<StoreSDNode>(N)->getMemOperand()); 13469 } 13470 13471 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 13472 // So it can increase the chance of CSE constant construction. 13473 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 13474 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 13475 // Need to sign-extended to 64-bits to handle negative values. 13476 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 13477 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 13478 MemVT.getSizeInBits()); 13479 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 13480 13481 // DAG.getTruncStore() can't be used here because it doesn't accept 13482 // the general (base + offset) addressing mode. 13483 // So we use UpdateNodeOperands and setTruncatingStore instead. 13484 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 13485 N->getOperand(3)); 13486 cast<StoreSDNode>(N)->setTruncatingStore(true); 13487 return SDValue(N, 0); 13488 } 13489 13490 // For little endian, VSX stores require generating xxswapd/lxvd2x. 13491 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13492 if (Op1VT.isSimple()) { 13493 MVT StoreVT = Op1VT.getSimpleVT(); 13494 if (Subtarget.needsSwapsForVSXMemOps() && 13495 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 13496 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 13497 return expandVSXStoreForLE(N, DCI); 13498 } 13499 break; 13500 } 13501 case ISD::LOAD: { 13502 LoadSDNode *LD = cast<LoadSDNode>(N); 13503 EVT VT = LD->getValueType(0); 13504 13505 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13506 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13507 if (VT.isSimple()) { 13508 MVT LoadVT = VT.getSimpleVT(); 13509 if (Subtarget.needsSwapsForVSXMemOps() && 13510 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 13511 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 13512 return expandVSXLoadForLE(N, DCI); 13513 } 13514 13515 // We sometimes end up with a 64-bit integer load, from which we extract 13516 // two single-precision floating-point numbers. This happens with 13517 // std::complex<float>, and other similar structures, because of the way we 13518 // canonicalize structure copies. However, if we lack direct moves, 13519 // then the final bitcasts from the extracted integer values to the 13520 // floating-point numbers turn into store/load pairs. Even with direct moves, 13521 // just loading the two floating-point numbers is likely better. 13522 auto ReplaceTwoFloatLoad = [&]() { 13523 if (VT != MVT::i64) 13524 return false; 13525 13526 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 13527 LD->isVolatile()) 13528 return false; 13529 13530 // We're looking for a sequence like this: 13531 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 13532 // t16: i64 = srl t13, Constant:i32<32> 13533 // t17: i32 = truncate t16 13534 // t18: f32 = bitcast t17 13535 // t19: i32 = truncate t13 13536 // t20: f32 = bitcast t19 13537 13538 if (!LD->hasNUsesOfValue(2, 0)) 13539 return false; 13540 13541 auto UI = LD->use_begin(); 13542 while (UI.getUse().getResNo() != 0) ++UI; 13543 SDNode *Trunc = *UI++; 13544 while (UI.getUse().getResNo() != 0) ++UI; 13545 SDNode *RightShift = *UI; 13546 if (Trunc->getOpcode() != ISD::TRUNCATE) 13547 std::swap(Trunc, RightShift); 13548 13549 if (Trunc->getOpcode() != ISD::TRUNCATE || 13550 Trunc->getValueType(0) != MVT::i32 || 13551 !Trunc->hasOneUse()) 13552 return false; 13553 if (RightShift->getOpcode() != ISD::SRL || 13554 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 13555 RightShift->getConstantOperandVal(1) != 32 || 13556 !RightShift->hasOneUse()) 13557 return false; 13558 13559 SDNode *Trunc2 = *RightShift->use_begin(); 13560 if (Trunc2->getOpcode() != ISD::TRUNCATE || 13561 Trunc2->getValueType(0) != MVT::i32 || 13562 !Trunc2->hasOneUse()) 13563 return false; 13564 13565 SDNode *Bitcast = *Trunc->use_begin(); 13566 SDNode *Bitcast2 = *Trunc2->use_begin(); 13567 13568 if (Bitcast->getOpcode() != ISD::BITCAST || 13569 Bitcast->getValueType(0) != MVT::f32) 13570 return false; 13571 if (Bitcast2->getOpcode() != ISD::BITCAST || 13572 Bitcast2->getValueType(0) != MVT::f32) 13573 return false; 13574 13575 if (Subtarget.isLittleEndian()) 13576 std::swap(Bitcast, Bitcast2); 13577 13578 // Bitcast has the second float (in memory-layout order) and Bitcast2 13579 // has the first one. 13580 13581 SDValue BasePtr = LD->getBasePtr(); 13582 if (LD->isIndexed()) { 13583 assert(LD->getAddressingMode() == ISD::PRE_INC && 13584 "Non-pre-inc AM on PPC?"); 13585 BasePtr = 13586 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 13587 LD->getOffset()); 13588 } 13589 13590 auto MMOFlags = 13591 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 13592 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 13593 LD->getPointerInfo(), LD->getAlignment(), 13594 MMOFlags, LD->getAAInfo()); 13595 SDValue AddPtr = 13596 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 13597 BasePtr, DAG.getIntPtrConstant(4, dl)); 13598 SDValue FloatLoad2 = DAG.getLoad( 13599 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 13600 LD->getPointerInfo().getWithOffset(4), 13601 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 13602 13603 if (LD->isIndexed()) { 13604 // Note that DAGCombine should re-form any pre-increment load(s) from 13605 // what is produced here if that makes sense. 13606 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13607 } 13608 13609 DCI.CombineTo(Bitcast2, FloatLoad); 13610 DCI.CombineTo(Bitcast, FloatLoad2); 13611 13612 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13613 SDValue(FloatLoad2.getNode(), 1)); 13614 return true; 13615 }; 13616 13617 if (ReplaceTwoFloatLoad()) 13618 return SDValue(N, 0); 13619 13620 EVT MemVT = LD->getMemoryVT(); 13621 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13622 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13623 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13624 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13625 if (LD->isUnindexed() && VT.isVector() && 13626 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13627 // P8 and later hardware should just use LOAD. 13628 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13629 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13630 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13631 LD->getAlignment() >= ScalarABIAlignment)) && 13632 LD->getAlignment() < ABIAlignment) { 13633 // This is a type-legal unaligned Altivec or QPX load. 13634 SDValue Chain = LD->getChain(); 13635 SDValue Ptr = LD->getBasePtr(); 13636 bool isLittleEndian = Subtarget.isLittleEndian(); 13637 13638 // This implements the loading of unaligned vectors as described in 13639 // the venerable Apple Velocity Engine overview. Specifically: 13640 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13641 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13642 // 13643 // The general idea is to expand a sequence of one or more unaligned 13644 // loads into an alignment-based permutation-control instruction (lvsl 13645 // or lvsr), a series of regular vector loads (which always truncate 13646 // their input address to an aligned address), and a series of 13647 // permutations. The results of these permutations are the requested 13648 // loaded values. The trick is that the last "extra" load is not taken 13649 // from the address you might suspect (sizeof(vector) bytes after the 13650 // last requested load), but rather sizeof(vector) - 1 bytes after the 13651 // last requested vector. The point of this is to avoid a page fault if 13652 // the base address happened to be aligned. This works because if the 13653 // base address is aligned, then adding less than a full vector length 13654 // will cause the last vector in the sequence to be (re)loaded. 13655 // Otherwise, the next vector will be fetched as you might suspect was 13656 // necessary. 13657 13658 // We might be able to reuse the permutation generation from 13659 // a different base address offset from this one by an aligned amount. 13660 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13661 // optimization later. 13662 Intrinsic::ID Intr, IntrLD, IntrPerm; 13663 MVT PermCntlTy, PermTy, LDTy; 13664 if (Subtarget.hasAltivec()) { 13665 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13666 Intrinsic::ppc_altivec_lvsl; 13667 IntrLD = Intrinsic::ppc_altivec_lvx; 13668 IntrPerm = Intrinsic::ppc_altivec_vperm; 13669 PermCntlTy = MVT::v16i8; 13670 PermTy = MVT::v4i32; 13671 LDTy = MVT::v4i32; 13672 } else { 13673 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13674 Intrinsic::ppc_qpx_qvlpcls; 13675 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13676 Intrinsic::ppc_qpx_qvlfs; 13677 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13678 PermCntlTy = MVT::v4f64; 13679 PermTy = MVT::v4f64; 13680 LDTy = MemVT.getSimpleVT(); 13681 } 13682 13683 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13684 13685 // Create the new MMO for the new base load. It is like the original MMO, 13686 // but represents an area in memory almost twice the vector size centered 13687 // on the original address. If the address is unaligned, we might start 13688 // reading up to (sizeof(vector)-1) bytes below the address of the 13689 // original unaligned load. 13690 MachineFunction &MF = DAG.getMachineFunction(); 13691 MachineMemOperand *BaseMMO = 13692 MF.getMachineMemOperand(LD->getMemOperand(), 13693 -(long)MemVT.getStoreSize()+1, 13694 2*MemVT.getStoreSize()-1); 13695 13696 // Create the new base load. 13697 SDValue LDXIntID = 13698 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13699 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13700 SDValue BaseLoad = 13701 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13702 DAG.getVTList(PermTy, MVT::Other), 13703 BaseLoadOps, LDTy, BaseMMO); 13704 13705 // Note that the value of IncOffset (which is provided to the next 13706 // load's pointer info offset value, and thus used to calculate the 13707 // alignment), and the value of IncValue (which is actually used to 13708 // increment the pointer value) are different! This is because we 13709 // require the next load to appear to be aligned, even though it 13710 // is actually offset from the base pointer by a lesser amount. 13711 int IncOffset = VT.getSizeInBits() / 8; 13712 int IncValue = IncOffset; 13713 13714 // Walk (both up and down) the chain looking for another load at the real 13715 // (aligned) offset (the alignment of the other load does not matter in 13716 // this case). If found, then do not use the offset reduction trick, as 13717 // that will prevent the loads from being later combined (as they would 13718 // otherwise be duplicates). 13719 if (!findConsecutiveLoad(LD, DAG)) 13720 --IncValue; 13721 13722 SDValue Increment = 13723 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 13724 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 13725 13726 MachineMemOperand *ExtraMMO = 13727 MF.getMachineMemOperand(LD->getMemOperand(), 13728 1, 2*MemVT.getStoreSize()-1); 13729 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 13730 SDValue ExtraLoad = 13731 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13732 DAG.getVTList(PermTy, MVT::Other), 13733 ExtraLoadOps, LDTy, ExtraMMO); 13734 13735 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13736 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 13737 13738 // Because vperm has a big-endian bias, we must reverse the order 13739 // of the input vectors and complement the permute control vector 13740 // when generating little endian code. We have already handled the 13741 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 13742 // and ExtraLoad here. 13743 SDValue Perm; 13744 if (isLittleEndian) 13745 Perm = BuildIntrinsicOp(IntrPerm, 13746 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 13747 else 13748 Perm = BuildIntrinsicOp(IntrPerm, 13749 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 13750 13751 if (VT != PermTy) 13752 Perm = Subtarget.hasAltivec() ? 13753 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 13754 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 13755 DAG.getTargetConstant(1, dl, MVT::i64)); 13756 // second argument is 1 because this rounding 13757 // is always exact. 13758 13759 // The output of the permutation is our loaded result, the TokenFactor is 13760 // our new chain. 13761 DCI.CombineTo(N, Perm, TF); 13762 return SDValue(N, 0); 13763 } 13764 } 13765 break; 13766 case ISD::INTRINSIC_WO_CHAIN: { 13767 bool isLittleEndian = Subtarget.isLittleEndian(); 13768 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13769 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 13770 : Intrinsic::ppc_altivec_lvsl); 13771 if ((IID == Intr || 13772 IID == Intrinsic::ppc_qpx_qvlpcld || 13773 IID == Intrinsic::ppc_qpx_qvlpcls) && 13774 N->getOperand(1)->getOpcode() == ISD::ADD) { 13775 SDValue Add = N->getOperand(1); 13776 13777 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 13778 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 13779 13780 if (DAG.MaskedValueIsZero(Add->getOperand(1), 13781 APInt::getAllOnesValue(Bits /* alignment */) 13782 .zext(Add.getScalarValueSizeInBits()))) { 13783 SDNode *BasePtr = Add->getOperand(0).getNode(); 13784 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13785 UE = BasePtr->use_end(); 13786 UI != UE; ++UI) { 13787 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13788 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 13789 // We've found another LVSL/LVSR, and this address is an aligned 13790 // multiple of that one. The results will be the same, so use the 13791 // one we've just found instead. 13792 13793 return SDValue(*UI, 0); 13794 } 13795 } 13796 } 13797 13798 if (isa<ConstantSDNode>(Add->getOperand(1))) { 13799 SDNode *BasePtr = Add->getOperand(0).getNode(); 13800 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13801 UE = BasePtr->use_end(); UI != UE; ++UI) { 13802 if (UI->getOpcode() == ISD::ADD && 13803 isa<ConstantSDNode>(UI->getOperand(1)) && 13804 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 13805 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 13806 (1ULL << Bits) == 0) { 13807 SDNode *OtherAdd = *UI; 13808 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 13809 VE = OtherAdd->use_end(); VI != VE; ++VI) { 13810 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13811 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 13812 return SDValue(*VI, 0); 13813 } 13814 } 13815 } 13816 } 13817 } 13818 } 13819 13820 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 13821 // Expose the vabsduw/h/b opportunity for down stream 13822 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 13823 (IID == Intrinsic::ppc_altivec_vmaxsw || 13824 IID == Intrinsic::ppc_altivec_vmaxsh || 13825 IID == Intrinsic::ppc_altivec_vmaxsb)) { 13826 SDValue V1 = N->getOperand(1); 13827 SDValue V2 = N->getOperand(2); 13828 if ((V1.getSimpleValueType() == MVT::v4i32 || 13829 V1.getSimpleValueType() == MVT::v8i16 || 13830 V1.getSimpleValueType() == MVT::v16i8) && 13831 V1.getSimpleValueType() == V2.getSimpleValueType()) { 13832 // (0-a, a) 13833 if (V1.getOpcode() == ISD::SUB && 13834 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 13835 V1.getOperand(1) == V2) { 13836 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 13837 } 13838 // (a, 0-a) 13839 if (V2.getOpcode() == ISD::SUB && 13840 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 13841 V2.getOperand(1) == V1) { 13842 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13843 } 13844 // (x-y, y-x) 13845 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 13846 V1.getOperand(0) == V2.getOperand(1) && 13847 V1.getOperand(1) == V2.getOperand(0)) { 13848 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13849 } 13850 } 13851 } 13852 } 13853 13854 break; 13855 case ISD::INTRINSIC_W_CHAIN: 13856 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13857 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13858 if (Subtarget.needsSwapsForVSXMemOps()) { 13859 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13860 default: 13861 break; 13862 case Intrinsic::ppc_vsx_lxvw4x: 13863 case Intrinsic::ppc_vsx_lxvd2x: 13864 return expandVSXLoadForLE(N, DCI); 13865 } 13866 } 13867 break; 13868 case ISD::INTRINSIC_VOID: 13869 // For little endian, VSX stores require generating xxswapd/stxvd2x. 13870 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13871 if (Subtarget.needsSwapsForVSXMemOps()) { 13872 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13873 default: 13874 break; 13875 case Intrinsic::ppc_vsx_stxvw4x: 13876 case Intrinsic::ppc_vsx_stxvd2x: 13877 return expandVSXStoreForLE(N, DCI); 13878 } 13879 } 13880 break; 13881 case ISD::BSWAP: 13882 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 13883 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 13884 N->getOperand(0).hasOneUse() && 13885 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 13886 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 13887 N->getValueType(0) == MVT::i64))) { 13888 SDValue Load = N->getOperand(0); 13889 LoadSDNode *LD = cast<LoadSDNode>(Load); 13890 // Create the byte-swapping load. 13891 SDValue Ops[] = { 13892 LD->getChain(), // Chain 13893 LD->getBasePtr(), // Ptr 13894 DAG.getValueType(N->getValueType(0)) // VT 13895 }; 13896 SDValue BSLoad = 13897 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 13898 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 13899 MVT::i64 : MVT::i32, MVT::Other), 13900 Ops, LD->getMemoryVT(), LD->getMemOperand()); 13901 13902 // If this is an i16 load, insert the truncate. 13903 SDValue ResVal = BSLoad; 13904 if (N->getValueType(0) == MVT::i16) 13905 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 13906 13907 // First, combine the bswap away. This makes the value produced by the 13908 // load dead. 13909 DCI.CombineTo(N, ResVal); 13910 13911 // Next, combine the load away, we give it a bogus result value but a real 13912 // chain result. The result value is dead because the bswap is dead. 13913 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 13914 13915 // Return N so it doesn't get rechecked! 13916 return SDValue(N, 0); 13917 } 13918 break; 13919 case PPCISD::VCMP: 13920 // If a VCMPo node already exists with exactly the same operands as this 13921 // node, use its result instead of this node (VCMPo computes both a CR6 and 13922 // a normal output). 13923 // 13924 if (!N->getOperand(0).hasOneUse() && 13925 !N->getOperand(1).hasOneUse() && 13926 !N->getOperand(2).hasOneUse()) { 13927 13928 // Scan all of the users of the LHS, looking for VCMPo's that match. 13929 SDNode *VCMPoNode = nullptr; 13930 13931 SDNode *LHSN = N->getOperand(0).getNode(); 13932 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 13933 UI != E; ++UI) 13934 if (UI->getOpcode() == PPCISD::VCMPo && 13935 UI->getOperand(1) == N->getOperand(1) && 13936 UI->getOperand(2) == N->getOperand(2) && 13937 UI->getOperand(0) == N->getOperand(0)) { 13938 VCMPoNode = *UI; 13939 break; 13940 } 13941 13942 // If there is no VCMPo node, or if the flag value has a single use, don't 13943 // transform this. 13944 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 13945 break; 13946 13947 // Look at the (necessarily single) use of the flag value. If it has a 13948 // chain, this transformation is more complex. Note that multiple things 13949 // could use the value result, which we should ignore. 13950 SDNode *FlagUser = nullptr; 13951 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 13952 FlagUser == nullptr; ++UI) { 13953 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 13954 SDNode *User = *UI; 13955 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 13956 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 13957 FlagUser = User; 13958 break; 13959 } 13960 } 13961 } 13962 13963 // If the user is a MFOCRF instruction, we know this is safe. 13964 // Otherwise we give up for right now. 13965 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 13966 return SDValue(VCMPoNode, 0); 13967 } 13968 break; 13969 case ISD::BRCOND: { 13970 SDValue Cond = N->getOperand(1); 13971 SDValue Target = N->getOperand(2); 13972 13973 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13974 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 13975 Intrinsic::loop_decrement) { 13976 13977 // We now need to make the intrinsic dead (it cannot be instruction 13978 // selected). 13979 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 13980 assert(Cond.getNode()->hasOneUse() && 13981 "Counter decrement has more than one use"); 13982 13983 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 13984 N->getOperand(0), Target); 13985 } 13986 } 13987 break; 13988 case ISD::BR_CC: { 13989 // If this is a branch on an altivec predicate comparison, lower this so 13990 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 13991 // lowering is done pre-legalize, because the legalizer lowers the predicate 13992 // compare down to code that is difficult to reassemble. 13993 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13994 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 13995 13996 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 13997 // value. If so, pass-through the AND to get to the intrinsic. 13998 if (LHS.getOpcode() == ISD::AND && 13999 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14000 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14001 Intrinsic::loop_decrement && 14002 isa<ConstantSDNode>(LHS.getOperand(1)) && 14003 !isNullConstant(LHS.getOperand(1))) 14004 LHS = LHS.getOperand(0); 14005 14006 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14007 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14008 Intrinsic::loop_decrement && 14009 isa<ConstantSDNode>(RHS)) { 14010 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14011 "Counter decrement comparison is not EQ or NE"); 14012 14013 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14014 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14015 (CC == ISD::SETNE && !Val); 14016 14017 // We now need to make the intrinsic dead (it cannot be instruction 14018 // selected). 14019 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14020 assert(LHS.getNode()->hasOneUse() && 14021 "Counter decrement has more than one use"); 14022 14023 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14024 N->getOperand(0), N->getOperand(4)); 14025 } 14026 14027 int CompareOpc; 14028 bool isDot; 14029 14030 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14031 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14032 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14033 assert(isDot && "Can't compare against a vector result!"); 14034 14035 // If this is a comparison against something other than 0/1, then we know 14036 // that the condition is never/always true. 14037 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14038 if (Val != 0 && Val != 1) { 14039 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14040 return N->getOperand(0); 14041 // Always !=, turn it into an unconditional branch. 14042 return DAG.getNode(ISD::BR, dl, MVT::Other, 14043 N->getOperand(0), N->getOperand(4)); 14044 } 14045 14046 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14047 14048 // Create the PPCISD altivec 'dot' comparison node. 14049 SDValue Ops[] = { 14050 LHS.getOperand(2), // LHS of compare 14051 LHS.getOperand(3), // RHS of compare 14052 DAG.getConstant(CompareOpc, dl, MVT::i32) 14053 }; 14054 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14055 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14056 14057 // Unpack the result based on how the target uses it. 14058 PPC::Predicate CompOpc; 14059 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14060 default: // Can't happen, don't crash on invalid number though. 14061 case 0: // Branch on the value of the EQ bit of CR6. 14062 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14063 break; 14064 case 1: // Branch on the inverted value of the EQ bit of CR6. 14065 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14066 break; 14067 case 2: // Branch on the value of the LT bit of CR6. 14068 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14069 break; 14070 case 3: // Branch on the inverted value of the LT bit of CR6. 14071 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14072 break; 14073 } 14074 14075 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14076 DAG.getConstant(CompOpc, dl, MVT::i32), 14077 DAG.getRegister(PPC::CR6, MVT::i32), 14078 N->getOperand(4), CompNode.getValue(1)); 14079 } 14080 break; 14081 } 14082 case ISD::BUILD_VECTOR: 14083 return DAGCombineBuildVector(N, DCI); 14084 case ISD::ABS: 14085 return combineABS(N, DCI); 14086 case ISD::VSELECT: 14087 return combineVSelect(N, DCI); 14088 } 14089 14090 return SDValue(); 14091 } 14092 14093 SDValue 14094 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14095 SelectionDAG &DAG, 14096 SmallVectorImpl<SDNode *> &Created) const { 14097 // fold (sdiv X, pow2) 14098 EVT VT = N->getValueType(0); 14099 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14100 return SDValue(); 14101 if ((VT != MVT::i32 && VT != MVT::i64) || 14102 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14103 return SDValue(); 14104 14105 SDLoc DL(N); 14106 SDValue N0 = N->getOperand(0); 14107 14108 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14109 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14110 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14111 14112 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14113 Created.push_back(Op.getNode()); 14114 14115 if (IsNegPow2) { 14116 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14117 Created.push_back(Op.getNode()); 14118 } 14119 14120 return Op; 14121 } 14122 14123 //===----------------------------------------------------------------------===// 14124 // Inline Assembly Support 14125 //===----------------------------------------------------------------------===// 14126 14127 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14128 KnownBits &Known, 14129 const APInt &DemandedElts, 14130 const SelectionDAG &DAG, 14131 unsigned Depth) const { 14132 Known.resetAll(); 14133 switch (Op.getOpcode()) { 14134 default: break; 14135 case PPCISD::LBRX: { 14136 // lhbrx is known to have the top bits cleared out. 14137 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14138 Known.Zero = 0xFFFF0000; 14139 break; 14140 } 14141 case ISD::INTRINSIC_WO_CHAIN: { 14142 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14143 default: break; 14144 case Intrinsic::ppc_altivec_vcmpbfp_p: 14145 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14146 case Intrinsic::ppc_altivec_vcmpequb_p: 14147 case Intrinsic::ppc_altivec_vcmpequh_p: 14148 case Intrinsic::ppc_altivec_vcmpequw_p: 14149 case Intrinsic::ppc_altivec_vcmpequd_p: 14150 case Intrinsic::ppc_altivec_vcmpgefp_p: 14151 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14152 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14153 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14154 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14155 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14156 case Intrinsic::ppc_altivec_vcmpgtub_p: 14157 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14158 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14159 case Intrinsic::ppc_altivec_vcmpgtud_p: 14160 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14161 break; 14162 } 14163 } 14164 } 14165 } 14166 14167 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14168 switch (Subtarget.getDarwinDirective()) { 14169 default: break; 14170 case PPC::DIR_970: 14171 case PPC::DIR_PWR4: 14172 case PPC::DIR_PWR5: 14173 case PPC::DIR_PWR5X: 14174 case PPC::DIR_PWR6: 14175 case PPC::DIR_PWR6X: 14176 case PPC::DIR_PWR7: 14177 case PPC::DIR_PWR8: 14178 case PPC::DIR_PWR9: { 14179 if (!ML) 14180 break; 14181 14182 if (!DisableInnermostLoopAlign32) { 14183 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14184 // so that we can decrease cache misses and branch-prediction misses. 14185 // Actual alignment of the loop will depend on the hotness check and other 14186 // logic in alignBlocks. 14187 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14188 return Align(32); 14189 } 14190 14191 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14192 14193 // For small loops (between 5 and 8 instructions), align to a 32-byte 14194 // boundary so that the entire loop fits in one instruction-cache line. 14195 uint64_t LoopSize = 0; 14196 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14197 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14198 LoopSize += TII->getInstSizeInBytes(*J); 14199 if (LoopSize > 32) 14200 break; 14201 } 14202 14203 if (LoopSize > 16 && LoopSize <= 32) 14204 return Align(32); 14205 14206 break; 14207 } 14208 } 14209 14210 return TargetLowering::getPrefLoopAlignment(ML); 14211 } 14212 14213 /// getConstraintType - Given a constraint, return the type of 14214 /// constraint it is for this target. 14215 PPCTargetLowering::ConstraintType 14216 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14217 if (Constraint.size() == 1) { 14218 switch (Constraint[0]) { 14219 default: break; 14220 case 'b': 14221 case 'r': 14222 case 'f': 14223 case 'd': 14224 case 'v': 14225 case 'y': 14226 return C_RegisterClass; 14227 case 'Z': 14228 // FIXME: While Z does indicate a memory constraint, it specifically 14229 // indicates an r+r address (used in conjunction with the 'y' modifier 14230 // in the replacement string). Currently, we're forcing the base 14231 // register to be r0 in the asm printer (which is interpreted as zero) 14232 // and forming the complete address in the second register. This is 14233 // suboptimal. 14234 return C_Memory; 14235 } 14236 } else if (Constraint == "wc") { // individual CR bits. 14237 return C_RegisterClass; 14238 } else if (Constraint == "wa" || Constraint == "wd" || 14239 Constraint == "wf" || Constraint == "ws" || 14240 Constraint == "wi" || Constraint == "ww") { 14241 return C_RegisterClass; // VSX registers. 14242 } 14243 return TargetLowering::getConstraintType(Constraint); 14244 } 14245 14246 /// Examine constraint type and operand type and determine a weight value. 14247 /// This object must already have been set up with the operand type 14248 /// and the current alternative constraint selected. 14249 TargetLowering::ConstraintWeight 14250 PPCTargetLowering::getSingleConstraintMatchWeight( 14251 AsmOperandInfo &info, const char *constraint) const { 14252 ConstraintWeight weight = CW_Invalid; 14253 Value *CallOperandVal = info.CallOperandVal; 14254 // If we don't have a value, we can't do a match, 14255 // but allow it at the lowest weight. 14256 if (!CallOperandVal) 14257 return CW_Default; 14258 Type *type = CallOperandVal->getType(); 14259 14260 // Look at the constraint type. 14261 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14262 return CW_Register; // an individual CR bit. 14263 else if ((StringRef(constraint) == "wa" || 14264 StringRef(constraint) == "wd" || 14265 StringRef(constraint) == "wf") && 14266 type->isVectorTy()) 14267 return CW_Register; 14268 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14269 return CW_Register; // just hold 64-bit integers data. 14270 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14271 return CW_Register; 14272 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14273 return CW_Register; 14274 14275 switch (*constraint) { 14276 default: 14277 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14278 break; 14279 case 'b': 14280 if (type->isIntegerTy()) 14281 weight = CW_Register; 14282 break; 14283 case 'f': 14284 if (type->isFloatTy()) 14285 weight = CW_Register; 14286 break; 14287 case 'd': 14288 if (type->isDoubleTy()) 14289 weight = CW_Register; 14290 break; 14291 case 'v': 14292 if (type->isVectorTy()) 14293 weight = CW_Register; 14294 break; 14295 case 'y': 14296 weight = CW_Register; 14297 break; 14298 case 'Z': 14299 weight = CW_Memory; 14300 break; 14301 } 14302 return weight; 14303 } 14304 14305 std::pair<unsigned, const TargetRegisterClass *> 14306 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14307 StringRef Constraint, 14308 MVT VT) const { 14309 if (Constraint.size() == 1) { 14310 // GCC RS6000 Constraint Letters 14311 switch (Constraint[0]) { 14312 case 'b': // R1-R31 14313 if (VT == MVT::i64 && Subtarget.isPPC64()) 14314 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 14315 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 14316 case 'r': // R0-R31 14317 if (VT == MVT::i64 && Subtarget.isPPC64()) 14318 return std::make_pair(0U, &PPC::G8RCRegClass); 14319 return std::make_pair(0U, &PPC::GPRCRegClass); 14320 // 'd' and 'f' constraints are both defined to be "the floating point 14321 // registers", where one is for 32-bit and the other for 64-bit. We don't 14322 // really care overly much here so just give them all the same reg classes. 14323 case 'd': 14324 case 'f': 14325 if (Subtarget.hasSPE()) { 14326 if (VT == MVT::f32 || VT == MVT::i32) 14327 return std::make_pair(0U, &PPC::GPRCRegClass); 14328 if (VT == MVT::f64 || VT == MVT::i64) 14329 return std::make_pair(0U, &PPC::SPERCRegClass); 14330 } else { 14331 if (VT == MVT::f32 || VT == MVT::i32) 14332 return std::make_pair(0U, &PPC::F4RCRegClass); 14333 if (VT == MVT::f64 || VT == MVT::i64) 14334 return std::make_pair(0U, &PPC::F8RCRegClass); 14335 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14336 return std::make_pair(0U, &PPC::QFRCRegClass); 14337 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14338 return std::make_pair(0U, &PPC::QSRCRegClass); 14339 } 14340 break; 14341 case 'v': 14342 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14343 return std::make_pair(0U, &PPC::QFRCRegClass); 14344 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14345 return std::make_pair(0U, &PPC::QSRCRegClass); 14346 if (Subtarget.hasAltivec()) 14347 return std::make_pair(0U, &PPC::VRRCRegClass); 14348 break; 14349 case 'y': // crrc 14350 return std::make_pair(0U, &PPC::CRRCRegClass); 14351 } 14352 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 14353 // An individual CR bit. 14354 return std::make_pair(0U, &PPC::CRBITRCRegClass); 14355 } else if ((Constraint == "wa" || Constraint == "wd" || 14356 Constraint == "wf" || Constraint == "wi") && 14357 Subtarget.hasVSX()) { 14358 return std::make_pair(0U, &PPC::VSRCRegClass); 14359 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 14360 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 14361 return std::make_pair(0U, &PPC::VSSRCRegClass); 14362 else 14363 return std::make_pair(0U, &PPC::VSFRCRegClass); 14364 } 14365 14366 std::pair<unsigned, const TargetRegisterClass *> R = 14367 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14368 14369 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 14370 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 14371 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 14372 // register. 14373 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 14374 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 14375 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 14376 PPC::GPRCRegClass.contains(R.first)) 14377 return std::make_pair(TRI->getMatchingSuperReg(R.first, 14378 PPC::sub_32, &PPC::G8RCRegClass), 14379 &PPC::G8RCRegClass); 14380 14381 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 14382 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 14383 R.first = PPC::CR0; 14384 R.second = &PPC::CRRCRegClass; 14385 } 14386 14387 return R; 14388 } 14389 14390 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14391 /// vector. If it is invalid, don't add anything to Ops. 14392 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14393 std::string &Constraint, 14394 std::vector<SDValue>&Ops, 14395 SelectionDAG &DAG) const { 14396 SDValue Result; 14397 14398 // Only support length 1 constraints. 14399 if (Constraint.length() > 1) return; 14400 14401 char Letter = Constraint[0]; 14402 switch (Letter) { 14403 default: break; 14404 case 'I': 14405 case 'J': 14406 case 'K': 14407 case 'L': 14408 case 'M': 14409 case 'N': 14410 case 'O': 14411 case 'P': { 14412 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 14413 if (!CST) return; // Must be an immediate to match. 14414 SDLoc dl(Op); 14415 int64_t Value = CST->getSExtValue(); 14416 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 14417 // numbers are printed as such. 14418 switch (Letter) { 14419 default: llvm_unreachable("Unknown constraint letter!"); 14420 case 'I': // "I" is a signed 16-bit constant. 14421 if (isInt<16>(Value)) 14422 Result = DAG.getTargetConstant(Value, dl, TCVT); 14423 break; 14424 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 14425 if (isShiftedUInt<16, 16>(Value)) 14426 Result = DAG.getTargetConstant(Value, dl, TCVT); 14427 break; 14428 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 14429 if (isShiftedInt<16, 16>(Value)) 14430 Result = DAG.getTargetConstant(Value, dl, TCVT); 14431 break; 14432 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 14433 if (isUInt<16>(Value)) 14434 Result = DAG.getTargetConstant(Value, dl, TCVT); 14435 break; 14436 case 'M': // "M" is a constant that is greater than 31. 14437 if (Value > 31) 14438 Result = DAG.getTargetConstant(Value, dl, TCVT); 14439 break; 14440 case 'N': // "N" is a positive constant that is an exact power of two. 14441 if (Value > 0 && isPowerOf2_64(Value)) 14442 Result = DAG.getTargetConstant(Value, dl, TCVT); 14443 break; 14444 case 'O': // "O" is the constant zero. 14445 if (Value == 0) 14446 Result = DAG.getTargetConstant(Value, dl, TCVT); 14447 break; 14448 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 14449 if (isInt<16>(-Value)) 14450 Result = DAG.getTargetConstant(Value, dl, TCVT); 14451 break; 14452 } 14453 break; 14454 } 14455 } 14456 14457 if (Result.getNode()) { 14458 Ops.push_back(Result); 14459 return; 14460 } 14461 14462 // Handle standard constraint letters. 14463 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14464 } 14465 14466 // isLegalAddressingMode - Return true if the addressing mode represented 14467 // by AM is legal for this target, for a load/store of the specified type. 14468 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14469 const AddrMode &AM, Type *Ty, 14470 unsigned AS, Instruction *I) const { 14471 // PPC does not allow r+i addressing modes for vectors! 14472 if (Ty->isVectorTy() && AM.BaseOffs != 0) 14473 return false; 14474 14475 // PPC allows a sign-extended 16-bit immediate field. 14476 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 14477 return false; 14478 14479 // No global is ever allowed as a base. 14480 if (AM.BaseGV) 14481 return false; 14482 14483 // PPC only support r+r, 14484 switch (AM.Scale) { 14485 case 0: // "r+i" or just "i", depending on HasBaseReg. 14486 break; 14487 case 1: 14488 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 14489 return false; 14490 // Otherwise we have r+r or r+i. 14491 break; 14492 case 2: 14493 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 14494 return false; 14495 // Allow 2*r as r+r. 14496 break; 14497 default: 14498 // No other scales are supported. 14499 return false; 14500 } 14501 14502 return true; 14503 } 14504 14505 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 14506 SelectionDAG &DAG) const { 14507 MachineFunction &MF = DAG.getMachineFunction(); 14508 MachineFrameInfo &MFI = MF.getFrameInfo(); 14509 MFI.setReturnAddressIsTaken(true); 14510 14511 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 14512 return SDValue(); 14513 14514 SDLoc dl(Op); 14515 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14516 14517 // Make sure the function does not optimize away the store of the RA to 14518 // the stack. 14519 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 14520 FuncInfo->setLRStoreRequired(); 14521 bool isPPC64 = Subtarget.isPPC64(); 14522 auto PtrVT = getPointerTy(MF.getDataLayout()); 14523 14524 if (Depth > 0) { 14525 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 14526 SDValue Offset = 14527 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 14528 isPPC64 ? MVT::i64 : MVT::i32); 14529 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 14530 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 14531 MachinePointerInfo()); 14532 } 14533 14534 // Just load the return address off the stack. 14535 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 14536 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 14537 MachinePointerInfo()); 14538 } 14539 14540 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 14541 SelectionDAG &DAG) const { 14542 SDLoc dl(Op); 14543 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14544 14545 MachineFunction &MF = DAG.getMachineFunction(); 14546 MachineFrameInfo &MFI = MF.getFrameInfo(); 14547 MFI.setFrameAddressIsTaken(true); 14548 14549 EVT PtrVT = getPointerTy(MF.getDataLayout()); 14550 bool isPPC64 = PtrVT == MVT::i64; 14551 14552 // Naked functions never have a frame pointer, and so we use r1. For all 14553 // other functions, this decision must be delayed until during PEI. 14554 unsigned FrameReg; 14555 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 14556 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 14557 else 14558 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 14559 14560 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 14561 PtrVT); 14562 while (Depth--) 14563 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 14564 FrameAddr, MachinePointerInfo()); 14565 return FrameAddr; 14566 } 14567 14568 // FIXME? Maybe this could be a TableGen attribute on some registers and 14569 // this table could be generated automatically from RegInfo. 14570 Register PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 14571 const MachineFunction &MF) const { 14572 bool isPPC64 = Subtarget.isPPC64(); 14573 bool IsDarwinABI = Subtarget.isDarwinABI(); 14574 14575 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 14576 (!isPPC64 && VT != MVT::i32)) 14577 report_fatal_error("Invalid register global variable type"); 14578 14579 bool is64Bit = isPPC64 && VT == MVT::i64; 14580 Register Reg = StringSwitch<Register>(RegName) 14581 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 14582 .Case("r2", (IsDarwinABI || isPPC64) ? Register() : PPC::R2) 14583 .Case("r13", (!isPPC64 && IsDarwinABI) ? Register() : 14584 (is64Bit ? PPC::X13 : PPC::R13)) 14585 .Default(Register()); 14586 14587 if (Reg) 14588 return Reg; 14589 report_fatal_error("Invalid register name global variable"); 14590 } 14591 14592 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 14593 // 32-bit SVR4 ABI access everything as got-indirect. 14594 if (Subtarget.is32BitELFABI()) 14595 return true; 14596 14597 // AIX accesses everything indirectly through the TOC, which is similar to 14598 // the GOT. 14599 if (Subtarget.isAIXABI()) 14600 return true; 14601 14602 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 14603 // If it is small or large code model, module locals are accessed 14604 // indirectly by loading their address from .toc/.got. 14605 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 14606 return true; 14607 14608 // JumpTable and BlockAddress are accessed as got-indirect. 14609 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 14610 return true; 14611 14612 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 14613 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 14614 14615 return false; 14616 } 14617 14618 bool 14619 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14620 // The PowerPC target isn't yet aware of offsets. 14621 return false; 14622 } 14623 14624 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14625 const CallInst &I, 14626 MachineFunction &MF, 14627 unsigned Intrinsic) const { 14628 switch (Intrinsic) { 14629 case Intrinsic::ppc_qpx_qvlfd: 14630 case Intrinsic::ppc_qpx_qvlfs: 14631 case Intrinsic::ppc_qpx_qvlfcd: 14632 case Intrinsic::ppc_qpx_qvlfcs: 14633 case Intrinsic::ppc_qpx_qvlfiwa: 14634 case Intrinsic::ppc_qpx_qvlfiwz: 14635 case Intrinsic::ppc_altivec_lvx: 14636 case Intrinsic::ppc_altivec_lvxl: 14637 case Intrinsic::ppc_altivec_lvebx: 14638 case Intrinsic::ppc_altivec_lvehx: 14639 case Intrinsic::ppc_altivec_lvewx: 14640 case Intrinsic::ppc_vsx_lxvd2x: 14641 case Intrinsic::ppc_vsx_lxvw4x: { 14642 EVT VT; 14643 switch (Intrinsic) { 14644 case Intrinsic::ppc_altivec_lvebx: 14645 VT = MVT::i8; 14646 break; 14647 case Intrinsic::ppc_altivec_lvehx: 14648 VT = MVT::i16; 14649 break; 14650 case Intrinsic::ppc_altivec_lvewx: 14651 VT = MVT::i32; 14652 break; 14653 case Intrinsic::ppc_vsx_lxvd2x: 14654 VT = MVT::v2f64; 14655 break; 14656 case Intrinsic::ppc_qpx_qvlfd: 14657 VT = MVT::v4f64; 14658 break; 14659 case Intrinsic::ppc_qpx_qvlfs: 14660 VT = MVT::v4f32; 14661 break; 14662 case Intrinsic::ppc_qpx_qvlfcd: 14663 VT = MVT::v2f64; 14664 break; 14665 case Intrinsic::ppc_qpx_qvlfcs: 14666 VT = MVT::v2f32; 14667 break; 14668 default: 14669 VT = MVT::v4i32; 14670 break; 14671 } 14672 14673 Info.opc = ISD::INTRINSIC_W_CHAIN; 14674 Info.memVT = VT; 14675 Info.ptrVal = I.getArgOperand(0); 14676 Info.offset = -VT.getStoreSize()+1; 14677 Info.size = 2*VT.getStoreSize()-1; 14678 Info.align = Align::None(); 14679 Info.flags = MachineMemOperand::MOLoad; 14680 return true; 14681 } 14682 case Intrinsic::ppc_qpx_qvlfda: 14683 case Intrinsic::ppc_qpx_qvlfsa: 14684 case Intrinsic::ppc_qpx_qvlfcda: 14685 case Intrinsic::ppc_qpx_qvlfcsa: 14686 case Intrinsic::ppc_qpx_qvlfiwaa: 14687 case Intrinsic::ppc_qpx_qvlfiwza: { 14688 EVT VT; 14689 switch (Intrinsic) { 14690 case Intrinsic::ppc_qpx_qvlfda: 14691 VT = MVT::v4f64; 14692 break; 14693 case Intrinsic::ppc_qpx_qvlfsa: 14694 VT = MVT::v4f32; 14695 break; 14696 case Intrinsic::ppc_qpx_qvlfcda: 14697 VT = MVT::v2f64; 14698 break; 14699 case Intrinsic::ppc_qpx_qvlfcsa: 14700 VT = MVT::v2f32; 14701 break; 14702 default: 14703 VT = MVT::v4i32; 14704 break; 14705 } 14706 14707 Info.opc = ISD::INTRINSIC_W_CHAIN; 14708 Info.memVT = VT; 14709 Info.ptrVal = I.getArgOperand(0); 14710 Info.offset = 0; 14711 Info.size = VT.getStoreSize(); 14712 Info.align = Align::None(); 14713 Info.flags = MachineMemOperand::MOLoad; 14714 return true; 14715 } 14716 case Intrinsic::ppc_qpx_qvstfd: 14717 case Intrinsic::ppc_qpx_qvstfs: 14718 case Intrinsic::ppc_qpx_qvstfcd: 14719 case Intrinsic::ppc_qpx_qvstfcs: 14720 case Intrinsic::ppc_qpx_qvstfiw: 14721 case Intrinsic::ppc_altivec_stvx: 14722 case Intrinsic::ppc_altivec_stvxl: 14723 case Intrinsic::ppc_altivec_stvebx: 14724 case Intrinsic::ppc_altivec_stvehx: 14725 case Intrinsic::ppc_altivec_stvewx: 14726 case Intrinsic::ppc_vsx_stxvd2x: 14727 case Intrinsic::ppc_vsx_stxvw4x: { 14728 EVT VT; 14729 switch (Intrinsic) { 14730 case Intrinsic::ppc_altivec_stvebx: 14731 VT = MVT::i8; 14732 break; 14733 case Intrinsic::ppc_altivec_stvehx: 14734 VT = MVT::i16; 14735 break; 14736 case Intrinsic::ppc_altivec_stvewx: 14737 VT = MVT::i32; 14738 break; 14739 case Intrinsic::ppc_vsx_stxvd2x: 14740 VT = MVT::v2f64; 14741 break; 14742 case Intrinsic::ppc_qpx_qvstfd: 14743 VT = MVT::v4f64; 14744 break; 14745 case Intrinsic::ppc_qpx_qvstfs: 14746 VT = MVT::v4f32; 14747 break; 14748 case Intrinsic::ppc_qpx_qvstfcd: 14749 VT = MVT::v2f64; 14750 break; 14751 case Intrinsic::ppc_qpx_qvstfcs: 14752 VT = MVT::v2f32; 14753 break; 14754 default: 14755 VT = MVT::v4i32; 14756 break; 14757 } 14758 14759 Info.opc = ISD::INTRINSIC_VOID; 14760 Info.memVT = VT; 14761 Info.ptrVal = I.getArgOperand(1); 14762 Info.offset = -VT.getStoreSize()+1; 14763 Info.size = 2*VT.getStoreSize()-1; 14764 Info.align = Align::None(); 14765 Info.flags = MachineMemOperand::MOStore; 14766 return true; 14767 } 14768 case Intrinsic::ppc_qpx_qvstfda: 14769 case Intrinsic::ppc_qpx_qvstfsa: 14770 case Intrinsic::ppc_qpx_qvstfcda: 14771 case Intrinsic::ppc_qpx_qvstfcsa: 14772 case Intrinsic::ppc_qpx_qvstfiwa: { 14773 EVT VT; 14774 switch (Intrinsic) { 14775 case Intrinsic::ppc_qpx_qvstfda: 14776 VT = MVT::v4f64; 14777 break; 14778 case Intrinsic::ppc_qpx_qvstfsa: 14779 VT = MVT::v4f32; 14780 break; 14781 case Intrinsic::ppc_qpx_qvstfcda: 14782 VT = MVT::v2f64; 14783 break; 14784 case Intrinsic::ppc_qpx_qvstfcsa: 14785 VT = MVT::v2f32; 14786 break; 14787 default: 14788 VT = MVT::v4i32; 14789 break; 14790 } 14791 14792 Info.opc = ISD::INTRINSIC_VOID; 14793 Info.memVT = VT; 14794 Info.ptrVal = I.getArgOperand(1); 14795 Info.offset = 0; 14796 Info.size = VT.getStoreSize(); 14797 Info.align = Align::None(); 14798 Info.flags = MachineMemOperand::MOStore; 14799 return true; 14800 } 14801 default: 14802 break; 14803 } 14804 14805 return false; 14806 } 14807 14808 /// getOptimalMemOpType - Returns the target specific optimal type for load 14809 /// and store operations as a result of memset, memcpy, and memmove 14810 /// lowering. If DstAlign is zero that means it's safe to destination 14811 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 14812 /// means there isn't a need to check it against alignment requirement, 14813 /// probably because the source does not need to be loaded. If 'IsMemset' is 14814 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 14815 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 14816 /// source is constant so it does not need to be loaded. 14817 /// It returns EVT::Other if the type should be determined using generic 14818 /// target-independent logic. 14819 EVT PPCTargetLowering::getOptimalMemOpType( 14820 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 14821 bool ZeroMemset, bool MemcpyStrSrc, 14822 const AttributeList &FuncAttributes) const { 14823 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 14824 // When expanding a memset, require at least two QPX instructions to cover 14825 // the cost of loading the value to be stored from the constant pool. 14826 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 14827 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 14828 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 14829 return MVT::v4f64; 14830 } 14831 14832 // We should use Altivec/VSX loads and stores when available. For unaligned 14833 // addresses, unaligned VSX loads are only fast starting with the P8. 14834 if (Subtarget.hasAltivec() && Size >= 16 && 14835 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 14836 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 14837 return MVT::v4i32; 14838 } 14839 14840 if (Subtarget.isPPC64()) { 14841 return MVT::i64; 14842 } 14843 14844 return MVT::i32; 14845 } 14846 14847 /// Returns true if it is beneficial to convert a load of a constant 14848 /// to just the constant itself. 14849 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14850 Type *Ty) const { 14851 assert(Ty->isIntegerTy()); 14852 14853 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 14854 return !(BitSize == 0 || BitSize > 64); 14855 } 14856 14857 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 14858 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14859 return false; 14860 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 14861 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 14862 return NumBits1 == 64 && NumBits2 == 32; 14863 } 14864 14865 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 14866 if (!VT1.isInteger() || !VT2.isInteger()) 14867 return false; 14868 unsigned NumBits1 = VT1.getSizeInBits(); 14869 unsigned NumBits2 = VT2.getSizeInBits(); 14870 return NumBits1 == 64 && NumBits2 == 32; 14871 } 14872 14873 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14874 // Generally speaking, zexts are not free, but they are free when they can be 14875 // folded with other operations. 14876 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 14877 EVT MemVT = LD->getMemoryVT(); 14878 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 14879 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 14880 (LD->getExtensionType() == ISD::NON_EXTLOAD || 14881 LD->getExtensionType() == ISD::ZEXTLOAD)) 14882 return true; 14883 } 14884 14885 // FIXME: Add other cases... 14886 // - 32-bit shifts with a zext to i64 14887 // - zext after ctlz, bswap, etc. 14888 // - zext after and by a constant mask 14889 14890 return TargetLowering::isZExtFree(Val, VT2); 14891 } 14892 14893 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 14894 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 14895 "invalid fpext types"); 14896 // Extending to float128 is not free. 14897 if (DestVT == MVT::f128) 14898 return false; 14899 return true; 14900 } 14901 14902 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14903 return isInt<16>(Imm) || isUInt<16>(Imm); 14904 } 14905 14906 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14907 return isInt<16>(Imm) || isUInt<16>(Imm); 14908 } 14909 14910 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 14911 unsigned, 14912 unsigned, 14913 MachineMemOperand::Flags, 14914 bool *Fast) const { 14915 if (DisablePPCUnaligned) 14916 return false; 14917 14918 // PowerPC supports unaligned memory access for simple non-vector types. 14919 // Although accessing unaligned addresses is not as efficient as accessing 14920 // aligned addresses, it is generally more efficient than manual expansion, 14921 // and generally only traps for software emulation when crossing page 14922 // boundaries. 14923 14924 if (!VT.isSimple()) 14925 return false; 14926 14927 if (VT.getSimpleVT().isVector()) { 14928 if (Subtarget.hasVSX()) { 14929 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 14930 VT != MVT::v4f32 && VT != MVT::v4i32) 14931 return false; 14932 } else { 14933 return false; 14934 } 14935 } 14936 14937 if (VT == MVT::ppcf128) 14938 return false; 14939 14940 if (Fast) 14941 *Fast = true; 14942 14943 return true; 14944 } 14945 14946 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 14947 VT = VT.getScalarType(); 14948 14949 if (!VT.isSimple()) 14950 return false; 14951 14952 switch (VT.getSimpleVT().SimpleTy) { 14953 case MVT::f32: 14954 case MVT::f64: 14955 return true; 14956 case MVT::f128: 14957 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 14958 default: 14959 break; 14960 } 14961 14962 return false; 14963 } 14964 14965 const MCPhysReg * 14966 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 14967 // LR is a callee-save register, but we must treat it as clobbered by any call 14968 // site. Hence we include LR in the scratch registers, which are in turn added 14969 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 14970 // to CTR, which is used by any indirect call. 14971 static const MCPhysReg ScratchRegs[] = { 14972 PPC::X12, PPC::LR8, PPC::CTR8, 0 14973 }; 14974 14975 return ScratchRegs; 14976 } 14977 14978 unsigned PPCTargetLowering::getExceptionPointerRegister( 14979 const Constant *PersonalityFn) const { 14980 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 14981 } 14982 14983 unsigned PPCTargetLowering::getExceptionSelectorRegister( 14984 const Constant *PersonalityFn) const { 14985 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 14986 } 14987 14988 bool 14989 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 14990 EVT VT , unsigned DefinedValues) const { 14991 if (VT == MVT::v2i64) 14992 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 14993 14994 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 14995 return true; 14996 14997 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 14998 } 14999 15000 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15001 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15002 return TargetLowering::getSchedulingPreference(N); 15003 15004 return Sched::ILP; 15005 } 15006 15007 // Create a fast isel object. 15008 FastISel * 15009 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15010 const TargetLibraryInfo *LibInfo) const { 15011 return PPC::createFastISel(FuncInfo, LibInfo); 15012 } 15013 15014 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15015 if (Subtarget.isDarwinABI()) return; 15016 if (!Subtarget.isPPC64()) return; 15017 15018 // Update IsSplitCSR in PPCFunctionInfo 15019 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 15020 PFI->setIsSplitCSR(true); 15021 } 15022 15023 void PPCTargetLowering::insertCopiesSplitCSR( 15024 MachineBasicBlock *Entry, 15025 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15026 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 15027 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15028 if (!IStart) 15029 return; 15030 15031 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 15032 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15033 MachineBasicBlock::iterator MBBI = Entry->begin(); 15034 for (const MCPhysReg *I = IStart; *I; ++I) { 15035 const TargetRegisterClass *RC = nullptr; 15036 if (PPC::G8RCRegClass.contains(*I)) 15037 RC = &PPC::G8RCRegClass; 15038 else if (PPC::F8RCRegClass.contains(*I)) 15039 RC = &PPC::F8RCRegClass; 15040 else if (PPC::CRRCRegClass.contains(*I)) 15041 RC = &PPC::CRRCRegClass; 15042 else if (PPC::VRRCRegClass.contains(*I)) 15043 RC = &PPC::VRRCRegClass; 15044 else 15045 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15046 15047 Register NewVR = MRI->createVirtualRegister(RC); 15048 // Create copy from CSR to a virtual register. 15049 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15050 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15051 // nounwind. If we want to generalize this later, we may need to emit 15052 // CFI pseudo-instructions. 15053 assert(Entry->getParent()->getFunction().hasFnAttribute( 15054 Attribute::NoUnwind) && 15055 "Function should be nounwind in insertCopiesSplitCSR!"); 15056 Entry->addLiveIn(*I); 15057 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15058 .addReg(*I); 15059 15060 // Insert the copy-back instructions right before the terminator. 15061 for (auto *Exit : Exits) 15062 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15063 TII->get(TargetOpcode::COPY), *I) 15064 .addReg(NewVR); 15065 } 15066 } 15067 15068 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15069 bool PPCTargetLowering::useLoadStackGuardNode() const { 15070 if (!Subtarget.isTargetLinux()) 15071 return TargetLowering::useLoadStackGuardNode(); 15072 return true; 15073 } 15074 15075 // Override to disable global variable loading on Linux. 15076 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15077 if (!Subtarget.isTargetLinux()) 15078 return TargetLowering::insertSSPDeclarations(M); 15079 } 15080 15081 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15082 bool ForCodeSize) const { 15083 if (!VT.isSimple() || !Subtarget.hasVSX()) 15084 return false; 15085 15086 switch(VT.getSimpleVT().SimpleTy) { 15087 default: 15088 // For FP types that are currently not supported by PPC backend, return 15089 // false. Examples: f16, f80. 15090 return false; 15091 case MVT::f32: 15092 case MVT::f64: 15093 case MVT::ppcf128: 15094 return Imm.isPosZero(); 15095 } 15096 } 15097 15098 // For vector shift operation op, fold 15099 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15100 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15101 SelectionDAG &DAG) { 15102 SDValue N0 = N->getOperand(0); 15103 SDValue N1 = N->getOperand(1); 15104 EVT VT = N0.getValueType(); 15105 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15106 unsigned Opcode = N->getOpcode(); 15107 unsigned TargetOpcode; 15108 15109 switch (Opcode) { 15110 default: 15111 llvm_unreachable("Unexpected shift operation"); 15112 case ISD::SHL: 15113 TargetOpcode = PPCISD::SHL; 15114 break; 15115 case ISD::SRL: 15116 TargetOpcode = PPCISD::SRL; 15117 break; 15118 case ISD::SRA: 15119 TargetOpcode = PPCISD::SRA; 15120 break; 15121 } 15122 15123 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15124 N1->getOpcode() == ISD::AND) 15125 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15126 if (Mask->getZExtValue() == OpSizeInBits - 1) 15127 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15128 15129 return SDValue(); 15130 } 15131 15132 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15133 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15134 return Value; 15135 15136 SDValue N0 = N->getOperand(0); 15137 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15138 if (!Subtarget.isISA3_0() || 15139 N0.getOpcode() != ISD::SIGN_EXTEND || 15140 N0.getOperand(0).getValueType() != MVT::i32 || 15141 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15142 return SDValue(); 15143 15144 // We can't save an operation here if the value is already extended, and 15145 // the existing shift is easier to combine. 15146 SDValue ExtsSrc = N0.getOperand(0); 15147 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15148 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15149 return SDValue(); 15150 15151 SDLoc DL(N0); 15152 SDValue ShiftBy = SDValue(CN1, 0); 15153 // We want the shift amount to be i32 on the extswli, but the shift could 15154 // have an i64. 15155 if (ShiftBy.getValueType() == MVT::i64) 15156 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15157 15158 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15159 ShiftBy); 15160 } 15161 15162 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15163 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15164 return Value; 15165 15166 return SDValue(); 15167 } 15168 15169 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15170 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15171 return Value; 15172 15173 return SDValue(); 15174 } 15175 15176 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15177 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15178 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15179 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15180 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15181 const PPCSubtarget &Subtarget) { 15182 if (!Subtarget.isPPC64()) 15183 return SDValue(); 15184 15185 SDValue LHS = N->getOperand(0); 15186 SDValue RHS = N->getOperand(1); 15187 15188 auto isZextOfCompareWithConstant = [](SDValue Op) { 15189 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15190 Op.getValueType() != MVT::i64) 15191 return false; 15192 15193 SDValue Cmp = Op.getOperand(0); 15194 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15195 Cmp.getOperand(0).getValueType() != MVT::i64) 15196 return false; 15197 15198 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15199 int64_t NegConstant = 0 - Constant->getSExtValue(); 15200 // Due to the limitations of the addi instruction, 15201 // -C is required to be [-32768, 32767]. 15202 return isInt<16>(NegConstant); 15203 } 15204 15205 return false; 15206 }; 15207 15208 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15209 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15210 15211 // If there is a pattern, canonicalize a zext operand to the RHS. 15212 if (LHSHasPattern && !RHSHasPattern) 15213 std::swap(LHS, RHS); 15214 else if (!LHSHasPattern && !RHSHasPattern) 15215 return SDValue(); 15216 15217 SDLoc DL(N); 15218 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15219 SDValue Cmp = RHS.getOperand(0); 15220 SDValue Z = Cmp.getOperand(0); 15221 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15222 15223 assert(Constant && "Constant Should not be a null pointer."); 15224 int64_t NegConstant = 0 - Constant->getSExtValue(); 15225 15226 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15227 default: break; 15228 case ISD::SETNE: { 15229 // when C == 0 15230 // --> addze X, (addic Z, -1).carry 15231 // / 15232 // add X, (zext(setne Z, C))-- 15233 // \ when -32768 <= -C <= 32767 && C != 0 15234 // --> addze X, (addic (addi Z, -C), -1).carry 15235 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15236 DAG.getConstant(NegConstant, DL, MVT::i64)); 15237 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15238 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15239 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15240 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15241 SDValue(Addc.getNode(), 1)); 15242 } 15243 case ISD::SETEQ: { 15244 // when C == 0 15245 // --> addze X, (subfic Z, 0).carry 15246 // / 15247 // add X, (zext(sete Z, C))-- 15248 // \ when -32768 <= -C <= 32767 && C != 0 15249 // --> addze X, (subfic (addi Z, -C), 0).carry 15250 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15251 DAG.getConstant(NegConstant, DL, MVT::i64)); 15252 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15253 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15254 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15255 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15256 SDValue(Subc.getNode(), 1)); 15257 } 15258 } 15259 15260 return SDValue(); 15261 } 15262 15263 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 15264 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 15265 return Value; 15266 15267 return SDValue(); 15268 } 15269 15270 // Detect TRUNCATE operations on bitcasts of float128 values. 15271 // What we are looking for here is the situtation where we extract a subset 15272 // of bits from a 128 bit float. 15273 // This can be of two forms: 15274 // 1) BITCAST of f128 feeding TRUNCATE 15275 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 15276 // The reason this is required is because we do not have a legal i128 type 15277 // and so we want to prevent having to store the f128 and then reload part 15278 // of it. 15279 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 15280 DAGCombinerInfo &DCI) const { 15281 // If we are using CRBits then try that first. 15282 if (Subtarget.useCRBits()) { 15283 // Check if CRBits did anything and return that if it did. 15284 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 15285 return CRTruncValue; 15286 } 15287 15288 SDLoc dl(N); 15289 SDValue Op0 = N->getOperand(0); 15290 15291 // Looking for a truncate of i128 to i64. 15292 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 15293 return SDValue(); 15294 15295 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 15296 15297 // SRL feeding TRUNCATE. 15298 if (Op0.getOpcode() == ISD::SRL) { 15299 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 15300 // The right shift has to be by 64 bits. 15301 if (!ConstNode || ConstNode->getZExtValue() != 64) 15302 return SDValue(); 15303 15304 // Switch the element number to extract. 15305 EltToExtract = EltToExtract ? 0 : 1; 15306 // Update Op0 past the SRL. 15307 Op0 = Op0.getOperand(0); 15308 } 15309 15310 // BITCAST feeding a TRUNCATE possibly via SRL. 15311 if (Op0.getOpcode() == ISD::BITCAST && 15312 Op0.getValueType() == MVT::i128 && 15313 Op0.getOperand(0).getValueType() == MVT::f128) { 15314 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 15315 return DCI.DAG.getNode( 15316 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 15317 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 15318 } 15319 return SDValue(); 15320 } 15321 15322 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 15323 SelectionDAG &DAG = DCI.DAG; 15324 15325 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 15326 if (!ConstOpOrElement) 15327 return SDValue(); 15328 15329 // An imul is usually smaller than the alternative sequence for legal type. 15330 if (DAG.getMachineFunction().getFunction().hasMinSize() && 15331 isOperationLegal(ISD::MUL, N->getValueType(0))) 15332 return SDValue(); 15333 15334 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 15335 switch (this->Subtarget.getDarwinDirective()) { 15336 default: 15337 // TODO: enhance the condition for subtarget before pwr8 15338 return false; 15339 case PPC::DIR_PWR8: 15340 // type mul add shl 15341 // scalar 4 1 1 15342 // vector 7 2 2 15343 return true; 15344 case PPC::DIR_PWR9: 15345 // type mul add shl 15346 // scalar 5 2 2 15347 // vector 7 2 2 15348 15349 // The cycle RATIO of related operations are showed as a table above. 15350 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 15351 // scalar and vector type. For 2 instrs patterns, add/sub + shl 15352 // are 4, it is always profitable; but for 3 instrs patterns 15353 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 15354 // So we should only do it for vector type. 15355 return IsAddOne && IsNeg ? VT.isVector() : true; 15356 } 15357 }; 15358 15359 EVT VT = N->getValueType(0); 15360 SDLoc DL(N); 15361 15362 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 15363 bool IsNeg = MulAmt.isNegative(); 15364 APInt MulAmtAbs = MulAmt.abs(); 15365 15366 if ((MulAmtAbs - 1).isPowerOf2()) { 15367 // (mul x, 2^N + 1) => (add (shl x, N), x) 15368 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 15369 15370 if (!IsProfitable(IsNeg, true, VT)) 15371 return SDValue(); 15372 15373 SDValue Op0 = N->getOperand(0); 15374 SDValue Op1 = 15375 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15376 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 15377 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 15378 15379 if (!IsNeg) 15380 return Res; 15381 15382 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 15383 } else if ((MulAmtAbs + 1).isPowerOf2()) { 15384 // (mul x, 2^N - 1) => (sub (shl x, N), x) 15385 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 15386 15387 if (!IsProfitable(IsNeg, false, VT)) 15388 return SDValue(); 15389 15390 SDValue Op0 = N->getOperand(0); 15391 SDValue Op1 = 15392 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15393 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 15394 15395 if (!IsNeg) 15396 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 15397 else 15398 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 15399 15400 } else { 15401 return SDValue(); 15402 } 15403 } 15404 15405 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 15406 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 15407 if (!Subtarget.is64BitELFABI()) 15408 return false; 15409 15410 // If not a tail call then no need to proceed. 15411 if (!CI->isTailCall()) 15412 return false; 15413 15414 // If tail calls are disabled for the caller then we are done. 15415 const Function *Caller = CI->getParent()->getParent(); 15416 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 15417 if (Attr.getValueAsString() == "true") 15418 return false; 15419 15420 // If sibling calls have been disabled and tail-calls aren't guaranteed 15421 // there is no reason to duplicate. 15422 auto &TM = getTargetMachine(); 15423 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 15424 return false; 15425 15426 // Can't tail call a function called indirectly, or if it has variadic args. 15427 const Function *Callee = CI->getCalledFunction(); 15428 if (!Callee || Callee->isVarArg()) 15429 return false; 15430 15431 // Make sure the callee and caller calling conventions are eligible for tco. 15432 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 15433 CI->getCallingConv())) 15434 return false; 15435 15436 // If the function is local then we have a good chance at tail-calling it 15437 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 15438 } 15439 15440 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 15441 if (!Subtarget.hasVSX()) 15442 return false; 15443 if (Subtarget.hasP9Vector() && VT == MVT::f128) 15444 return true; 15445 return VT == MVT::f32 || VT == MVT::f64 || 15446 VT == MVT::v4f32 || VT == MVT::v2f64; 15447 } 15448 15449 bool PPCTargetLowering:: 15450 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 15451 const Value *Mask = AndI.getOperand(1); 15452 // If the mask is suitable for andi. or andis. we should sink the and. 15453 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 15454 // Can't handle constants wider than 64-bits. 15455 if (CI->getBitWidth() > 64) 15456 return false; 15457 int64_t ConstVal = CI->getZExtValue(); 15458 return isUInt<16>(ConstVal) || 15459 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 15460 } 15461 15462 // For non-constant masks, we can always use the record-form and. 15463 return true; 15464 } 15465 15466 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 15467 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 15468 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 15469 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 15470 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 15471 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 15472 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 15473 assert(Subtarget.hasP9Altivec() && 15474 "Only combine this when P9 altivec supported!"); 15475 EVT VT = N->getValueType(0); 15476 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15477 return SDValue(); 15478 15479 SelectionDAG &DAG = DCI.DAG; 15480 SDLoc dl(N); 15481 if (N->getOperand(0).getOpcode() == ISD::SUB) { 15482 // Even for signed integers, if it's known to be positive (as signed 15483 // integer) due to zero-extended inputs. 15484 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 15485 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 15486 if ((SubOpcd0 == ISD::ZERO_EXTEND || 15487 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 15488 (SubOpcd1 == ISD::ZERO_EXTEND || 15489 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 15490 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15491 N->getOperand(0)->getOperand(0), 15492 N->getOperand(0)->getOperand(1), 15493 DAG.getTargetConstant(0, dl, MVT::i32)); 15494 } 15495 15496 // For type v4i32, it can be optimized with xvnegsp + vabsduw 15497 if (N->getOperand(0).getValueType() == MVT::v4i32 && 15498 N->getOperand(0).hasOneUse()) { 15499 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15500 N->getOperand(0)->getOperand(0), 15501 N->getOperand(0)->getOperand(1), 15502 DAG.getTargetConstant(1, dl, MVT::i32)); 15503 } 15504 } 15505 15506 return SDValue(); 15507 } 15508 15509 // For type v4i32/v8ii16/v16i8, transform 15510 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 15511 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 15512 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 15513 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 15514 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 15515 DAGCombinerInfo &DCI) const { 15516 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 15517 assert(Subtarget.hasP9Altivec() && 15518 "Only combine this when P9 altivec supported!"); 15519 15520 SelectionDAG &DAG = DCI.DAG; 15521 SDLoc dl(N); 15522 SDValue Cond = N->getOperand(0); 15523 SDValue TrueOpnd = N->getOperand(1); 15524 SDValue FalseOpnd = N->getOperand(2); 15525 EVT VT = N->getOperand(1).getValueType(); 15526 15527 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 15528 FalseOpnd.getOpcode() != ISD::SUB) 15529 return SDValue(); 15530 15531 // ABSD only available for type v4i32/v8i16/v16i8 15532 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15533 return SDValue(); 15534 15535 // At least to save one more dependent computation 15536 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 15537 return SDValue(); 15538 15539 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15540 15541 // Can only handle unsigned comparison here 15542 switch (CC) { 15543 default: 15544 return SDValue(); 15545 case ISD::SETUGT: 15546 case ISD::SETUGE: 15547 break; 15548 case ISD::SETULT: 15549 case ISD::SETULE: 15550 std::swap(TrueOpnd, FalseOpnd); 15551 break; 15552 } 15553 15554 SDValue CmpOpnd1 = Cond.getOperand(0); 15555 SDValue CmpOpnd2 = Cond.getOperand(1); 15556 15557 // SETCC CmpOpnd1 CmpOpnd2 cond 15558 // TrueOpnd = CmpOpnd1 - CmpOpnd2 15559 // FalseOpnd = CmpOpnd2 - CmpOpnd1 15560 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 15561 TrueOpnd.getOperand(1) == CmpOpnd2 && 15562 FalseOpnd.getOperand(0) == CmpOpnd2 && 15563 FalseOpnd.getOperand(1) == CmpOpnd1) { 15564 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 15565 CmpOpnd1, CmpOpnd2, 15566 DAG.getTargetConstant(0, dl, MVT::i32)); 15567 } 15568 15569 return SDValue(); 15570 } 15571