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/TargetLoweringObjectFileImpl.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallSite.h" 59 #include "llvm/IR/CallingConv.h" 60 #include "llvm/IR/Constant.h" 61 #include "llvm/IR/Constants.h" 62 #include "llvm/IR/DataLayout.h" 63 #include "llvm/IR/DebugLoc.h" 64 #include "llvm/IR/DerivedTypes.h" 65 #include "llvm/IR/Function.h" 66 #include "llvm/IR/GlobalValue.h" 67 #include "llvm/IR/IRBuilder.h" 68 #include "llvm/IR/Instructions.h" 69 #include "llvm/IR/Intrinsics.h" 70 #include "llvm/IR/IntrinsicsPowerPC.h" 71 #include "llvm/IR/Module.h" 72 #include "llvm/IR/Type.h" 73 #include "llvm/IR/Use.h" 74 #include "llvm/IR/Value.h" 75 #include "llvm/MC/MCContext.h" 76 #include "llvm/MC/MCExpr.h" 77 #include "llvm/MC/MCRegisterInfo.h" 78 #include "llvm/MC/MCSymbolXCOFF.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/BranchProbability.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/CodeGen.h" 83 #include "llvm/Support/CommandLine.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/Format.h" 88 #include "llvm/Support/KnownBits.h" 89 #include "llvm/Support/MachineValueType.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Target/TargetMachine.h" 93 #include "llvm/Target/TargetOptions.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <cstdint> 97 #include <iterator> 98 #include <list> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 104 #define DEBUG_TYPE "ppc-lowering" 105 106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 108 109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 111 112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 114 115 static cl::opt<bool> DisableSCO("disable-ppc-sco", 116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 117 118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 120 121 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 122 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 123 124 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 125 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 126 127 STATISTIC(NumTailCalls, "Number of tail calls"); 128 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 129 130 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 131 132 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 133 134 // FIXME: Remove this once the bug has been fixed! 135 extern cl::opt<bool> ANDIGlueBug; 136 137 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 138 const PPCSubtarget &STI) 139 : TargetLowering(TM), Subtarget(STI) { 140 // Use _setjmp/_longjmp instead of setjmp/longjmp. 141 setUseUnderscoreSetJmp(true); 142 setUseUnderscoreLongJmp(true); 143 144 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 145 // arguments are at least 4/8 bytes aligned. 146 bool isPPC64 = Subtarget.isPPC64(); 147 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 148 149 // Set up the register classes. 150 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 151 if (!useSoftFloat()) { 152 if (hasSPE()) { 153 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 154 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 155 } else { 156 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 157 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 158 } 159 } 160 161 // Match BITREVERSE to customized fast code sequence in the td file. 162 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 163 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 164 165 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 166 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 167 168 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 169 for (MVT VT : MVT::integer_valuetypes()) { 170 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 171 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 172 } 173 174 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 175 176 // PowerPC has pre-inc load and store's. 177 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 178 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 179 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 180 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 181 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 182 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 183 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 184 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 185 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 186 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 187 if (!Subtarget.hasSPE()) { 188 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 189 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 190 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 191 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 192 } 193 194 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 195 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 196 for (MVT VT : ScalarIntVTs) { 197 setOperationAction(ISD::ADDC, VT, Legal); 198 setOperationAction(ISD::ADDE, VT, Legal); 199 setOperationAction(ISD::SUBC, VT, Legal); 200 setOperationAction(ISD::SUBE, VT, Legal); 201 } 202 203 if (Subtarget.useCRBits()) { 204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 205 206 if (isPPC64 || Subtarget.hasFPCVT()) { 207 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 208 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 209 isPPC64 ? MVT::i64 : MVT::i32); 210 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 211 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 212 isPPC64 ? MVT::i64 : MVT::i32); 213 } else { 214 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 215 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 216 } 217 218 // PowerPC does not support direct load/store of condition registers. 219 setOperationAction(ISD::LOAD, MVT::i1, Custom); 220 setOperationAction(ISD::STORE, MVT::i1, Custom); 221 222 // FIXME: Remove this once the ANDI glue bug is fixed: 223 if (ANDIGlueBug) 224 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 225 226 for (MVT VT : MVT::integer_valuetypes()) { 227 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 228 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 229 setTruncStoreAction(VT, MVT::i1, Expand); 230 } 231 232 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 233 } 234 235 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 236 // PPC (the libcall is not available). 237 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 238 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 239 240 // We do not currently implement these libm ops for PowerPC. 241 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 242 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 243 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 244 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 245 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 246 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 247 248 // PowerPC has no SREM/UREM instructions unless we are on P9 249 // On P9 we may use a hardware instruction to compute the remainder. 250 // The instructions are not legalized directly because in the cases where the 251 // result of both the remainder and the division is required it is more 252 // efficient to compute the remainder from the result of the division rather 253 // than use the remainder instruction. 254 if (Subtarget.isISA3_0()) { 255 setOperationAction(ISD::SREM, MVT::i32, Custom); 256 setOperationAction(ISD::UREM, MVT::i32, Custom); 257 setOperationAction(ISD::SREM, MVT::i64, Custom); 258 setOperationAction(ISD::UREM, MVT::i64, Custom); 259 } else { 260 setOperationAction(ISD::SREM, MVT::i32, Expand); 261 setOperationAction(ISD::UREM, MVT::i32, Expand); 262 setOperationAction(ISD::SREM, MVT::i64, Expand); 263 setOperationAction(ISD::UREM, MVT::i64, Expand); 264 } 265 266 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 267 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 268 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 269 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 270 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 271 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 272 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 273 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 274 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 275 276 // We don't support sin/cos/sqrt/fmod/pow 277 setOperationAction(ISD::FSIN , MVT::f64, Expand); 278 setOperationAction(ISD::FCOS , MVT::f64, Expand); 279 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 280 setOperationAction(ISD::FREM , MVT::f64, Expand); 281 setOperationAction(ISD::FPOW , MVT::f64, Expand); 282 setOperationAction(ISD::FSIN , MVT::f32, Expand); 283 setOperationAction(ISD::FCOS , MVT::f32, Expand); 284 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 285 setOperationAction(ISD::FREM , MVT::f32, Expand); 286 setOperationAction(ISD::FPOW , MVT::f32, Expand); 287 if (Subtarget.hasSPE()) { 288 setOperationAction(ISD::FMA , MVT::f64, Expand); 289 setOperationAction(ISD::FMA , MVT::f32, Expand); 290 } else { 291 setOperationAction(ISD::FMA , MVT::f64, Legal); 292 setOperationAction(ISD::FMA , MVT::f32, Legal); 293 } 294 295 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 296 297 // If we're enabling GP optimizations, use hardware square root 298 if (!Subtarget.hasFSQRT() && 299 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 300 Subtarget.hasFRE())) 301 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 302 303 if (!Subtarget.hasFSQRT() && 304 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 305 Subtarget.hasFRES())) 306 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 307 308 if (Subtarget.hasFCPSGN()) { 309 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 310 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 311 } else { 312 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 313 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 314 } 315 316 if (Subtarget.hasFPRND()) { 317 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 318 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 319 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 320 setOperationAction(ISD::FROUND, MVT::f64, Legal); 321 322 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 323 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 324 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 325 setOperationAction(ISD::FROUND, MVT::f32, Legal); 326 } 327 328 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 329 // to speed up scalar BSWAP64. 330 // CTPOP or CTTZ were introduced in P8/P9 respectively 331 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 332 if (Subtarget.hasP9Vector()) 333 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 334 else 335 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 336 if (Subtarget.isISA3_0()) { 337 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 338 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 339 } else { 340 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 341 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 342 } 343 344 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 345 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 346 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 347 } else { 348 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 349 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 350 } 351 352 // PowerPC does not have ROTR 353 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 354 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 355 356 if (!Subtarget.useCRBits()) { 357 // PowerPC does not have Select 358 setOperationAction(ISD::SELECT, MVT::i32, Expand); 359 setOperationAction(ISD::SELECT, MVT::i64, Expand); 360 setOperationAction(ISD::SELECT, MVT::f32, Expand); 361 setOperationAction(ISD::SELECT, MVT::f64, Expand); 362 } 363 364 // PowerPC wants to turn select_cc of FP into fsel when possible. 365 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 366 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 367 368 // PowerPC wants to optimize integer setcc a bit 369 if (!Subtarget.useCRBits()) 370 setOperationAction(ISD::SETCC, MVT::i32, Custom); 371 372 // PowerPC does not have BRCOND which requires SetCC 373 if (!Subtarget.useCRBits()) 374 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 375 376 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 377 378 if (Subtarget.hasSPE()) { 379 // SPE has built-in conversions 380 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 381 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 382 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 383 } else { 384 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 385 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 386 387 // PowerPC does not have [U|S]INT_TO_FP 388 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 389 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 390 } 391 392 if (Subtarget.hasDirectMove() && isPPC64) { 393 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 394 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 395 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 396 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 397 } else { 398 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 399 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 400 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 401 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 402 } 403 404 // We cannot sextinreg(i1). Expand to shifts. 405 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 406 407 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 408 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 409 // support continuation, user-level threading, and etc.. As a result, no 410 // other SjLj exception interfaces are implemented and please don't build 411 // your own exception handling based on them. 412 // LLVM/Clang supports zero-cost DWARF exception handling. 413 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 414 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 415 416 // We want to legalize GlobalAddress and ConstantPool nodes into the 417 // appropriate instructions to materialize the address. 418 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 419 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 420 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 421 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 422 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 423 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 424 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 425 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 426 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 427 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 428 429 // TRAP is legal. 430 setOperationAction(ISD::TRAP, MVT::Other, Legal); 431 432 // TRAMPOLINE is custom lowered. 433 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 434 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 435 436 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 437 setOperationAction(ISD::VASTART , MVT::Other, Custom); 438 439 if (Subtarget.is64BitELFABI()) { 440 // VAARG always uses double-word chunks, so promote anything smaller. 441 setOperationAction(ISD::VAARG, MVT::i1, Promote); 442 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 443 setOperationAction(ISD::VAARG, MVT::i8, Promote); 444 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 445 setOperationAction(ISD::VAARG, MVT::i16, Promote); 446 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 447 setOperationAction(ISD::VAARG, MVT::i32, Promote); 448 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 449 setOperationAction(ISD::VAARG, MVT::Other, Expand); 450 } else if (Subtarget.is32BitELFABI()) { 451 // VAARG is custom lowered with the 32-bit SVR4 ABI. 452 setOperationAction(ISD::VAARG, MVT::Other, Custom); 453 setOperationAction(ISD::VAARG, MVT::i64, Custom); 454 } else 455 setOperationAction(ISD::VAARG, MVT::Other, Expand); 456 457 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 458 if (Subtarget.is32BitELFABI()) 459 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 460 else 461 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 462 463 // Use the default implementation. 464 setOperationAction(ISD::VAEND , MVT::Other, Expand); 465 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 466 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 467 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 468 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 469 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 470 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 471 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 472 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 473 474 // We want to custom lower some of our intrinsics. 475 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 476 477 // To handle counter-based loop conditions. 478 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 479 480 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 481 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 482 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 483 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 484 485 // Comparisons that require checking two conditions. 486 if (Subtarget.hasSPE()) { 487 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 488 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 489 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 490 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 491 } 492 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 493 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 494 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 495 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 496 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 497 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 498 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 499 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 500 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 501 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 502 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 503 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 504 505 if (Subtarget.has64BitSupport()) { 506 // They also have instructions for converting between i64 and fp. 507 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 508 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 509 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 510 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 511 // This is just the low 32 bits of a (signed) fp->i64 conversion. 512 // We cannot do this with Promote because i64 is not a legal type. 513 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 514 515 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 516 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 517 } else { 518 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 519 if (Subtarget.hasSPE()) 520 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 521 else 522 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 523 } 524 525 // With the instructions enabled under FPCVT, we can do everything. 526 if (Subtarget.hasFPCVT()) { 527 if (Subtarget.has64BitSupport()) { 528 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 529 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 530 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 531 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 532 } 533 534 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 535 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 536 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 537 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 538 } 539 540 if (Subtarget.use64BitRegs()) { 541 // 64-bit PowerPC implementations can support i64 types directly 542 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 543 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 544 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 545 // 64-bit PowerPC wants to expand i128 shifts itself. 546 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 547 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 548 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 549 } else { 550 // 32-bit PowerPC wants to expand i64 shifts itself. 551 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 552 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 553 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 554 } 555 556 if (Subtarget.hasVSX()) { 557 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 558 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 559 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 560 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 561 } 562 563 if (Subtarget.hasAltivec()) { 564 // First set operation action for all vector types to expand. Then we 565 // will selectively turn on ones that can be effectively codegen'd. 566 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 567 // add/sub are legal for all supported vector VT's. 568 setOperationAction(ISD::ADD, VT, Legal); 569 setOperationAction(ISD::SUB, VT, Legal); 570 571 // For v2i64, these are only valid with P8Vector. This is corrected after 572 // the loop. 573 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 574 setOperationAction(ISD::SMAX, VT, Legal); 575 setOperationAction(ISD::SMIN, VT, Legal); 576 setOperationAction(ISD::UMAX, VT, Legal); 577 setOperationAction(ISD::UMIN, VT, Legal); 578 } 579 else { 580 setOperationAction(ISD::SMAX, VT, Expand); 581 setOperationAction(ISD::SMIN, VT, Expand); 582 setOperationAction(ISD::UMAX, VT, Expand); 583 setOperationAction(ISD::UMIN, VT, Expand); 584 } 585 586 if (Subtarget.hasVSX()) { 587 setOperationAction(ISD::FMAXNUM, VT, Legal); 588 setOperationAction(ISD::FMINNUM, VT, Legal); 589 } 590 591 // Vector instructions introduced in P8 592 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 593 setOperationAction(ISD::CTPOP, VT, Legal); 594 setOperationAction(ISD::CTLZ, VT, Legal); 595 } 596 else { 597 setOperationAction(ISD::CTPOP, VT, Expand); 598 setOperationAction(ISD::CTLZ, VT, Expand); 599 } 600 601 // Vector instructions introduced in P9 602 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 603 setOperationAction(ISD::CTTZ, VT, Legal); 604 else 605 setOperationAction(ISD::CTTZ, VT, Expand); 606 607 // We promote all shuffles to v16i8. 608 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 609 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 610 611 // We promote all non-typed operations to v4i32. 612 setOperationAction(ISD::AND , VT, Promote); 613 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 614 setOperationAction(ISD::OR , VT, Promote); 615 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 616 setOperationAction(ISD::XOR , VT, Promote); 617 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 618 setOperationAction(ISD::LOAD , VT, Promote); 619 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 620 setOperationAction(ISD::SELECT, VT, Promote); 621 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 622 setOperationAction(ISD::VSELECT, VT, Legal); 623 setOperationAction(ISD::SELECT_CC, VT, Promote); 624 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 625 setOperationAction(ISD::STORE, VT, Promote); 626 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 627 628 // No other operations are legal. 629 setOperationAction(ISD::MUL , VT, Expand); 630 setOperationAction(ISD::SDIV, VT, Expand); 631 setOperationAction(ISD::SREM, VT, Expand); 632 setOperationAction(ISD::UDIV, VT, Expand); 633 setOperationAction(ISD::UREM, VT, Expand); 634 setOperationAction(ISD::FDIV, VT, Expand); 635 setOperationAction(ISD::FREM, VT, Expand); 636 setOperationAction(ISD::FNEG, VT, Expand); 637 setOperationAction(ISD::FSQRT, VT, Expand); 638 setOperationAction(ISD::FLOG, VT, Expand); 639 setOperationAction(ISD::FLOG10, VT, Expand); 640 setOperationAction(ISD::FLOG2, VT, Expand); 641 setOperationAction(ISD::FEXP, VT, Expand); 642 setOperationAction(ISD::FEXP2, VT, Expand); 643 setOperationAction(ISD::FSIN, VT, Expand); 644 setOperationAction(ISD::FCOS, VT, Expand); 645 setOperationAction(ISD::FABS, VT, Expand); 646 setOperationAction(ISD::FFLOOR, VT, Expand); 647 setOperationAction(ISD::FCEIL, VT, Expand); 648 setOperationAction(ISD::FTRUNC, VT, Expand); 649 setOperationAction(ISD::FRINT, VT, Expand); 650 setOperationAction(ISD::FNEARBYINT, VT, Expand); 651 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 652 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 653 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 654 setOperationAction(ISD::MULHU, VT, Expand); 655 setOperationAction(ISD::MULHS, VT, Expand); 656 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 657 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 658 setOperationAction(ISD::UDIVREM, VT, Expand); 659 setOperationAction(ISD::SDIVREM, VT, Expand); 660 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 661 setOperationAction(ISD::FPOW, VT, Expand); 662 setOperationAction(ISD::BSWAP, VT, Expand); 663 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 664 setOperationAction(ISD::ROTL, VT, Expand); 665 setOperationAction(ISD::ROTR, VT, Expand); 666 667 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 668 setTruncStoreAction(VT, InnerVT, Expand); 669 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 670 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 671 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 672 } 673 } 674 if (!Subtarget.hasP8Vector()) { 675 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 676 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 677 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 678 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 679 } 680 681 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 682 setOperationAction(ISD::ABS, VT, Custom); 683 684 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 685 // with merges, splats, etc. 686 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 687 688 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 689 // are cheap, so handle them before they get expanded to scalar. 690 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 691 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 692 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 693 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 694 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 695 696 setOperationAction(ISD::AND , MVT::v4i32, Legal); 697 setOperationAction(ISD::OR , MVT::v4i32, Legal); 698 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 699 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 700 setOperationAction(ISD::SELECT, MVT::v4i32, 701 Subtarget.useCRBits() ? Legal : Expand); 702 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 703 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 704 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 705 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 706 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 707 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 708 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 709 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 710 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 711 712 // Without hasP8Altivec set, v2i64 SMAX isn't available. 713 // But ABS custom lowering requires SMAX support. 714 if (!Subtarget.hasP8Altivec()) 715 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 716 717 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 718 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 719 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 720 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 721 722 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 723 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 724 725 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 726 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 727 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 728 } 729 730 if (Subtarget.hasP8Altivec()) 731 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 732 else 733 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 734 735 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 736 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 737 738 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 739 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 740 741 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 742 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 743 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 744 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 745 746 // Altivec does not contain unordered floating-point compare instructions 747 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 748 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 749 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 750 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 751 752 if (Subtarget.hasVSX()) { 753 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 754 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 755 if (Subtarget.hasP8Vector()) { 756 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 757 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 758 } 759 if (Subtarget.hasDirectMove() && isPPC64) { 760 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 761 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 762 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 763 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 764 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 765 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 766 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 767 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 768 } 769 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 770 771 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 772 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 773 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 774 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 775 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 776 777 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 778 779 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 780 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 781 782 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 783 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 784 785 // Share the Altivec comparison restrictions. 786 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 787 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 788 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 789 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 790 791 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 792 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 793 794 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 795 796 if (Subtarget.hasP8Vector()) 797 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 798 799 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 800 801 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 802 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 803 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 804 805 if (Subtarget.hasP8Altivec()) { 806 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 807 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 808 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 809 810 // 128 bit shifts can be accomplished via 3 instructions for SHL and 811 // SRL, but not for SRA because of the instructions available: 812 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 813 // doing 814 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 815 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 816 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 817 818 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 819 } 820 else { 821 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 822 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 823 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 824 825 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 826 827 // VSX v2i64 only supports non-arithmetic operations. 828 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 829 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 830 } 831 832 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 833 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 834 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 835 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 836 837 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 838 839 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 840 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 841 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 842 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 843 844 // Custom handling for partial vectors of integers converted to 845 // floating point. We already have optimal handling for v2i32 through 846 // the DAG combine, so those aren't necessary. 847 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 848 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 849 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 850 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 851 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 852 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 853 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 854 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 855 856 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 857 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 858 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 859 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 860 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 861 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 862 863 if (Subtarget.hasDirectMove()) 864 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 865 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 866 867 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 868 } 869 870 if (Subtarget.hasP8Altivec()) { 871 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 872 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 873 } 874 875 if (Subtarget.hasP9Vector()) { 876 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 877 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 878 879 // 128 bit shifts can be accomplished via 3 instructions for SHL and 880 // SRL, but not for SRA because of the instructions available: 881 // VS{RL} and VS{RL}O. 882 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 883 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 884 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 885 886 if (EnableQuadPrecision) { 887 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 888 setOperationAction(ISD::FADD, MVT::f128, Legal); 889 setOperationAction(ISD::FSUB, MVT::f128, Legal); 890 setOperationAction(ISD::FDIV, MVT::f128, Legal); 891 setOperationAction(ISD::FMUL, MVT::f128, Legal); 892 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 893 // No extending loads to f128 on PPC. 894 for (MVT FPT : MVT::fp_valuetypes()) 895 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 896 setOperationAction(ISD::FMA, MVT::f128, Legal); 897 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 898 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 899 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 900 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 901 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 902 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 903 904 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 905 setOperationAction(ISD::FRINT, MVT::f128, Legal); 906 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 907 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 908 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 909 setOperationAction(ISD::FROUND, MVT::f128, Legal); 910 911 setOperationAction(ISD::SELECT, MVT::f128, Expand); 912 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 913 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 914 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 915 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 916 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 917 // No implementation for these ops for PowerPC. 918 setOperationAction(ISD::FSIN , MVT::f128, Expand); 919 setOperationAction(ISD::FCOS , MVT::f128, Expand); 920 setOperationAction(ISD::FPOW, MVT::f128, Expand); 921 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 922 setOperationAction(ISD::FREM, MVT::f128, Expand); 923 } 924 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 925 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 926 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 927 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 928 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 929 } 930 931 if (Subtarget.hasP9Altivec()) { 932 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 933 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 934 935 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 936 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 937 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 938 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 939 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 940 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 941 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 942 } 943 } 944 945 if (Subtarget.hasQPX()) { 946 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 947 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 948 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 949 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 950 951 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 952 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 953 954 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 955 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 956 957 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 958 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 959 960 if (!Subtarget.useCRBits()) 961 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 962 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 963 964 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 965 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 966 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 967 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 968 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 969 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 970 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 971 972 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 973 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 974 975 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 976 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 977 978 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 979 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 980 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 981 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 982 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 983 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 984 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 985 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 986 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 987 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 988 989 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 990 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 991 992 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 993 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 994 995 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 996 997 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 998 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 999 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1000 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1001 1002 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1003 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1004 1005 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1006 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1007 1008 if (!Subtarget.useCRBits()) 1009 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1010 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1011 1012 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1013 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1014 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1015 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1016 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1017 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1018 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1019 1020 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1021 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1022 1023 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1024 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1025 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1026 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1027 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1028 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1029 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1030 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1031 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1032 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1033 1034 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1035 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1036 1037 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1038 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1039 1040 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1041 1042 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1043 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1044 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1045 1046 if (!Subtarget.useCRBits()) 1047 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1048 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1049 1050 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1051 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1052 1053 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1054 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1055 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1056 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1057 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1058 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1059 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1060 1061 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1062 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1063 1064 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1065 1066 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1067 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1068 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1069 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1070 1071 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1072 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1073 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1074 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1075 1076 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1077 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1078 1079 // These need to set FE_INEXACT, and so cannot be vectorized here. 1080 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1081 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1082 1083 if (TM.Options.UnsafeFPMath) { 1084 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1085 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1086 1087 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1088 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1089 } else { 1090 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1091 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1092 1093 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1094 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1095 } 1096 } 1097 1098 if (Subtarget.has64BitSupport()) 1099 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1100 1101 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1102 1103 if (!isPPC64) { 1104 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1105 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1106 } 1107 1108 setBooleanContents(ZeroOrOneBooleanContent); 1109 1110 if (Subtarget.hasAltivec()) { 1111 // Altivec instructions set fields to all zeros or all ones. 1112 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1113 } 1114 1115 if (!isPPC64) { 1116 // These libcalls are not available in 32-bit. 1117 setLibcallName(RTLIB::SHL_I128, nullptr); 1118 setLibcallName(RTLIB::SRL_I128, nullptr); 1119 setLibcallName(RTLIB::SRA_I128, nullptr); 1120 } 1121 1122 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1123 1124 // We have target-specific dag combine patterns for the following nodes: 1125 setTargetDAGCombine(ISD::ADD); 1126 setTargetDAGCombine(ISD::SHL); 1127 setTargetDAGCombine(ISD::SRA); 1128 setTargetDAGCombine(ISD::SRL); 1129 setTargetDAGCombine(ISD::MUL); 1130 setTargetDAGCombine(ISD::SINT_TO_FP); 1131 setTargetDAGCombine(ISD::BUILD_VECTOR); 1132 if (Subtarget.hasFPCVT()) 1133 setTargetDAGCombine(ISD::UINT_TO_FP); 1134 setTargetDAGCombine(ISD::LOAD); 1135 setTargetDAGCombine(ISD::STORE); 1136 setTargetDAGCombine(ISD::BR_CC); 1137 if (Subtarget.useCRBits()) 1138 setTargetDAGCombine(ISD::BRCOND); 1139 setTargetDAGCombine(ISD::BSWAP); 1140 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1141 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1142 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1143 1144 setTargetDAGCombine(ISD::SIGN_EXTEND); 1145 setTargetDAGCombine(ISD::ZERO_EXTEND); 1146 setTargetDAGCombine(ISD::ANY_EXTEND); 1147 1148 setTargetDAGCombine(ISD::TRUNCATE); 1149 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1150 1151 1152 if (Subtarget.useCRBits()) { 1153 setTargetDAGCombine(ISD::TRUNCATE); 1154 setTargetDAGCombine(ISD::SETCC); 1155 setTargetDAGCombine(ISD::SELECT_CC); 1156 } 1157 1158 // Use reciprocal estimates. 1159 if (TM.Options.UnsafeFPMath) { 1160 setTargetDAGCombine(ISD::FDIV); 1161 setTargetDAGCombine(ISD::FSQRT); 1162 } 1163 1164 if (Subtarget.hasP9Altivec()) { 1165 setTargetDAGCombine(ISD::ABS); 1166 setTargetDAGCombine(ISD::VSELECT); 1167 } 1168 1169 // Darwin long double math library functions have $LDBL128 appended. 1170 if (Subtarget.isDarwin()) { 1171 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1172 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1173 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1174 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1175 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1176 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1177 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1178 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1179 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1180 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1181 } 1182 1183 if (EnableQuadPrecision) { 1184 setLibcallName(RTLIB::LOG_F128, "logf128"); 1185 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1186 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1187 setLibcallName(RTLIB::EXP_F128, "expf128"); 1188 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1189 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1190 setLibcallName(RTLIB::COS_F128, "cosf128"); 1191 setLibcallName(RTLIB::POW_F128, "powf128"); 1192 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1193 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1194 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1195 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1196 } 1197 1198 // With 32 condition bits, we don't need to sink (and duplicate) compares 1199 // aggressively in CodeGenPrep. 1200 if (Subtarget.useCRBits()) { 1201 setHasMultipleConditionRegisters(); 1202 setJumpIsExpensive(); 1203 } 1204 1205 setMinFunctionAlignment(Align(4)); 1206 if (Subtarget.isDarwin()) 1207 setPrefFunctionAlignment(Align(16)); 1208 1209 switch (Subtarget.getCPUDirective()) { 1210 default: break; 1211 case PPC::DIR_970: 1212 case PPC::DIR_A2: 1213 case PPC::DIR_E500: 1214 case PPC::DIR_E500mc: 1215 case PPC::DIR_E5500: 1216 case PPC::DIR_PWR4: 1217 case PPC::DIR_PWR5: 1218 case PPC::DIR_PWR5X: 1219 case PPC::DIR_PWR6: 1220 case PPC::DIR_PWR6X: 1221 case PPC::DIR_PWR7: 1222 case PPC::DIR_PWR8: 1223 case PPC::DIR_PWR9: 1224 case PPC::DIR_PWR_FUTURE: 1225 setPrefLoopAlignment(Align(16)); 1226 setPrefFunctionAlignment(Align(16)); 1227 break; 1228 } 1229 1230 if (Subtarget.enableMachineScheduler()) 1231 setSchedulingPreference(Sched::Source); 1232 else 1233 setSchedulingPreference(Sched::Hybrid); 1234 1235 computeRegisterProperties(STI.getRegisterInfo()); 1236 1237 // The Freescale cores do better with aggressive inlining of memcpy and 1238 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1239 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1240 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1241 MaxStoresPerMemset = 32; 1242 MaxStoresPerMemsetOptSize = 16; 1243 MaxStoresPerMemcpy = 32; 1244 MaxStoresPerMemcpyOptSize = 8; 1245 MaxStoresPerMemmove = 32; 1246 MaxStoresPerMemmoveOptSize = 8; 1247 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1248 // The A2 also benefits from (very) aggressive inlining of memcpy and 1249 // friends. The overhead of a the function call, even when warm, can be 1250 // over one hundred cycles. 1251 MaxStoresPerMemset = 128; 1252 MaxStoresPerMemcpy = 128; 1253 MaxStoresPerMemmove = 128; 1254 MaxLoadsPerMemcmp = 128; 1255 } else { 1256 MaxLoadsPerMemcmp = 8; 1257 MaxLoadsPerMemcmpOptSize = 4; 1258 } 1259 } 1260 1261 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1262 /// the desired ByVal argument alignment. 1263 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1264 unsigned MaxMaxAlign) { 1265 if (MaxAlign == MaxMaxAlign) 1266 return; 1267 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1268 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1269 MaxAlign = 32; 1270 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1271 MaxAlign = 16; 1272 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1273 unsigned EltAlign = 0; 1274 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1275 if (EltAlign > MaxAlign) 1276 MaxAlign = EltAlign; 1277 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1278 for (auto *EltTy : STy->elements()) { 1279 unsigned EltAlign = 0; 1280 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1281 if (EltAlign > MaxAlign) 1282 MaxAlign = EltAlign; 1283 if (MaxAlign == MaxMaxAlign) 1284 break; 1285 } 1286 } 1287 } 1288 1289 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1290 /// function arguments in the caller parameter area. 1291 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1292 const DataLayout &DL) const { 1293 // Darwin passes everything on 4 byte boundary. 1294 if (Subtarget.isDarwin()) 1295 return 4; 1296 1297 // 16byte and wider vectors are passed on 16byte boundary. 1298 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1299 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1300 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1301 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1302 return Align; 1303 } 1304 1305 bool PPCTargetLowering::useSoftFloat() const { 1306 return Subtarget.useSoftFloat(); 1307 } 1308 1309 bool PPCTargetLowering::hasSPE() const { 1310 return Subtarget.hasSPE(); 1311 } 1312 1313 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1314 return VT.isScalarInteger(); 1315 } 1316 1317 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1318 switch ((PPCISD::NodeType)Opcode) { 1319 case PPCISD::FIRST_NUMBER: break; 1320 case PPCISD::FSEL: return "PPCISD::FSEL"; 1321 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1322 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1323 case PPCISD::FCFID: return "PPCISD::FCFID"; 1324 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1325 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1326 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1327 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1328 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1329 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1330 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1331 case PPCISD::FP_TO_UINT_IN_VSR: 1332 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1333 case PPCISD::FP_TO_SINT_IN_VSR: 1334 return "PPCISD::FP_TO_SINT_IN_VSR"; 1335 case PPCISD::FRE: return "PPCISD::FRE"; 1336 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1337 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1338 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1339 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1340 case PPCISD::VPERM: return "PPCISD::VPERM"; 1341 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1342 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1343 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1344 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1345 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1346 case PPCISD::CMPB: return "PPCISD::CMPB"; 1347 case PPCISD::Hi: return "PPCISD::Hi"; 1348 case PPCISD::Lo: return "PPCISD::Lo"; 1349 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1350 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1351 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1352 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1353 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1354 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1355 case PPCISD::SRL: return "PPCISD::SRL"; 1356 case PPCISD::SRA: return "PPCISD::SRA"; 1357 case PPCISD::SHL: return "PPCISD::SHL"; 1358 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1359 case PPCISD::CALL: return "PPCISD::CALL"; 1360 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1361 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1362 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1363 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1364 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1365 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1366 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1367 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1368 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1369 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1370 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1371 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1372 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1373 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1374 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1375 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1376 case PPCISD::VCMP: return "PPCISD::VCMP"; 1377 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1378 case PPCISD::LBRX: return "PPCISD::LBRX"; 1379 case PPCISD::STBRX: return "PPCISD::STBRX"; 1380 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1381 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1382 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1383 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1384 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1385 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1386 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1387 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1388 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1389 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1390 case PPCISD::ST_VSR_SCAL_INT: 1391 return "PPCISD::ST_VSR_SCAL_INT"; 1392 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1393 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1394 case PPCISD::BDZ: return "PPCISD::BDZ"; 1395 case PPCISD::MFFS: return "PPCISD::MFFS"; 1396 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1397 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1398 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1399 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1400 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1401 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1402 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1403 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1404 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1405 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1406 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1407 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1408 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1409 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1410 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1411 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1412 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1413 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1414 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1415 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1416 case PPCISD::SC: return "PPCISD::SC"; 1417 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1418 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1419 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1420 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1421 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1422 case PPCISD::VABSD: return "PPCISD::VABSD"; 1423 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1424 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1425 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1426 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1427 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1428 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1429 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1430 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1431 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1432 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1433 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1434 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1435 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1436 } 1437 return nullptr; 1438 } 1439 1440 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1441 EVT VT) const { 1442 if (!VT.isVector()) 1443 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1444 1445 if (Subtarget.hasQPX()) 1446 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1447 1448 return VT.changeVectorElementTypeToInteger(); 1449 } 1450 1451 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1452 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1453 return true; 1454 } 1455 1456 //===----------------------------------------------------------------------===// 1457 // Node matching predicates, for use by the tblgen matching code. 1458 //===----------------------------------------------------------------------===// 1459 1460 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1461 static bool isFloatingPointZero(SDValue Op) { 1462 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1463 return CFP->getValueAPF().isZero(); 1464 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1465 // Maybe this has already been legalized into the constant pool? 1466 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1467 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1468 return CFP->getValueAPF().isZero(); 1469 } 1470 return false; 1471 } 1472 1473 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1474 /// true if Op is undef or if it matches the specified value. 1475 static bool isConstantOrUndef(int Op, int Val) { 1476 return Op < 0 || Op == Val; 1477 } 1478 1479 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1480 /// VPKUHUM instruction. 1481 /// The ShuffleKind distinguishes between big-endian operations with 1482 /// two different inputs (0), either-endian operations with two identical 1483 /// inputs (1), and little-endian operations with two different inputs (2). 1484 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1485 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1486 SelectionDAG &DAG) { 1487 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1488 if (ShuffleKind == 0) { 1489 if (IsLE) 1490 return false; 1491 for (unsigned i = 0; i != 16; ++i) 1492 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1493 return false; 1494 } else if (ShuffleKind == 2) { 1495 if (!IsLE) 1496 return false; 1497 for (unsigned i = 0; i != 16; ++i) 1498 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1499 return false; 1500 } else if (ShuffleKind == 1) { 1501 unsigned j = IsLE ? 0 : 1; 1502 for (unsigned i = 0; i != 8; ++i) 1503 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1504 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1505 return false; 1506 } 1507 return true; 1508 } 1509 1510 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1511 /// VPKUWUM instruction. 1512 /// The ShuffleKind distinguishes between big-endian operations with 1513 /// two different inputs (0), either-endian operations with two identical 1514 /// inputs (1), and little-endian operations with two different inputs (2). 1515 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1516 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1517 SelectionDAG &DAG) { 1518 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1519 if (ShuffleKind == 0) { 1520 if (IsLE) 1521 return false; 1522 for (unsigned i = 0; i != 16; i += 2) 1523 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1524 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1525 return false; 1526 } else if (ShuffleKind == 2) { 1527 if (!IsLE) 1528 return false; 1529 for (unsigned i = 0; i != 16; i += 2) 1530 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1531 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1532 return false; 1533 } else if (ShuffleKind == 1) { 1534 unsigned j = IsLE ? 0 : 2; 1535 for (unsigned i = 0; i != 8; i += 2) 1536 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1537 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1538 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1539 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1540 return false; 1541 } 1542 return true; 1543 } 1544 1545 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1546 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1547 /// current subtarget. 1548 /// 1549 /// The ShuffleKind distinguishes between big-endian operations with 1550 /// two different inputs (0), either-endian operations with two identical 1551 /// inputs (1), and little-endian operations with two different inputs (2). 1552 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1553 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1554 SelectionDAG &DAG) { 1555 const PPCSubtarget& Subtarget = 1556 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1557 if (!Subtarget.hasP8Vector()) 1558 return false; 1559 1560 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1561 if (ShuffleKind == 0) { 1562 if (IsLE) 1563 return false; 1564 for (unsigned i = 0; i != 16; i += 4) 1565 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1566 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1567 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1568 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1569 return false; 1570 } else if (ShuffleKind == 2) { 1571 if (!IsLE) 1572 return false; 1573 for (unsigned i = 0; i != 16; i += 4) 1574 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1575 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1576 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1577 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1578 return false; 1579 } else if (ShuffleKind == 1) { 1580 unsigned j = IsLE ? 0 : 4; 1581 for (unsigned i = 0; i != 8; i += 4) 1582 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1583 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1584 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1585 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1586 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1587 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1588 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1589 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1590 return false; 1591 } 1592 return true; 1593 } 1594 1595 /// isVMerge - Common function, used to match vmrg* shuffles. 1596 /// 1597 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1598 unsigned LHSStart, unsigned RHSStart) { 1599 if (N->getValueType(0) != MVT::v16i8) 1600 return false; 1601 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1602 "Unsupported merge size!"); 1603 1604 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1605 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1606 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1607 LHSStart+j+i*UnitSize) || 1608 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1609 RHSStart+j+i*UnitSize)) 1610 return false; 1611 } 1612 return true; 1613 } 1614 1615 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1616 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1617 /// The ShuffleKind distinguishes between big-endian merges with two 1618 /// different inputs (0), either-endian merges with two identical inputs (1), 1619 /// and little-endian merges with two different inputs (2). For the latter, 1620 /// the input operands are swapped (see PPCInstrAltivec.td). 1621 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1622 unsigned ShuffleKind, SelectionDAG &DAG) { 1623 if (DAG.getDataLayout().isLittleEndian()) { 1624 if (ShuffleKind == 1) // unary 1625 return isVMerge(N, UnitSize, 0, 0); 1626 else if (ShuffleKind == 2) // swapped 1627 return isVMerge(N, UnitSize, 0, 16); 1628 else 1629 return false; 1630 } else { 1631 if (ShuffleKind == 1) // unary 1632 return isVMerge(N, UnitSize, 8, 8); 1633 else if (ShuffleKind == 0) // normal 1634 return isVMerge(N, UnitSize, 8, 24); 1635 else 1636 return false; 1637 } 1638 } 1639 1640 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1641 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1642 /// The ShuffleKind distinguishes between big-endian merges with two 1643 /// different inputs (0), either-endian merges with two identical inputs (1), 1644 /// and little-endian merges with two different inputs (2). For the latter, 1645 /// the input operands are swapped (see PPCInstrAltivec.td). 1646 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1647 unsigned ShuffleKind, SelectionDAG &DAG) { 1648 if (DAG.getDataLayout().isLittleEndian()) { 1649 if (ShuffleKind == 1) // unary 1650 return isVMerge(N, UnitSize, 8, 8); 1651 else if (ShuffleKind == 2) // swapped 1652 return isVMerge(N, UnitSize, 8, 24); 1653 else 1654 return false; 1655 } else { 1656 if (ShuffleKind == 1) // unary 1657 return isVMerge(N, UnitSize, 0, 0); 1658 else if (ShuffleKind == 0) // normal 1659 return isVMerge(N, UnitSize, 0, 16); 1660 else 1661 return false; 1662 } 1663 } 1664 1665 /** 1666 * Common function used to match vmrgew and vmrgow shuffles 1667 * 1668 * The indexOffset determines whether to look for even or odd words in 1669 * the shuffle mask. This is based on the of the endianness of the target 1670 * machine. 1671 * - Little Endian: 1672 * - Use offset of 0 to check for odd elements 1673 * - Use offset of 4 to check for even elements 1674 * - Big Endian: 1675 * - Use offset of 0 to check for even elements 1676 * - Use offset of 4 to check for odd elements 1677 * A detailed description of the vector element ordering for little endian and 1678 * big endian can be found at 1679 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1680 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1681 * compiler differences mean to you 1682 * 1683 * The mask to the shuffle vector instruction specifies the indices of the 1684 * elements from the two input vectors to place in the result. The elements are 1685 * numbered in array-access order, starting with the first vector. These vectors 1686 * are always of type v16i8, thus each vector will contain 16 elements of size 1687 * 8. More info on the shuffle vector can be found in the 1688 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1689 * Language Reference. 1690 * 1691 * The RHSStartValue indicates whether the same input vectors are used (unary) 1692 * or two different input vectors are used, based on the following: 1693 * - If the instruction uses the same vector for both inputs, the range of the 1694 * indices will be 0 to 15. In this case, the RHSStart value passed should 1695 * be 0. 1696 * - If the instruction has two different vectors then the range of the 1697 * indices will be 0 to 31. In this case, the RHSStart value passed should 1698 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1699 * to 31 specify elements in the second vector). 1700 * 1701 * \param[in] N The shuffle vector SD Node to analyze 1702 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1703 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1704 * vector to the shuffle_vector instruction 1705 * \return true iff this shuffle vector represents an even or odd word merge 1706 */ 1707 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1708 unsigned RHSStartValue) { 1709 if (N->getValueType(0) != MVT::v16i8) 1710 return false; 1711 1712 for (unsigned i = 0; i < 2; ++i) 1713 for (unsigned j = 0; j < 4; ++j) 1714 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1715 i*RHSStartValue+j+IndexOffset) || 1716 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1717 i*RHSStartValue+j+IndexOffset+8)) 1718 return false; 1719 return true; 1720 } 1721 1722 /** 1723 * Determine if the specified shuffle mask is suitable for the vmrgew or 1724 * vmrgow instructions. 1725 * 1726 * \param[in] N The shuffle vector SD Node to analyze 1727 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1728 * \param[in] ShuffleKind Identify the type of merge: 1729 * - 0 = big-endian merge with two different inputs; 1730 * - 1 = either-endian merge with two identical inputs; 1731 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1732 * little-endian merges). 1733 * \param[in] DAG The current SelectionDAG 1734 * \return true iff this shuffle mask 1735 */ 1736 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1737 unsigned ShuffleKind, SelectionDAG &DAG) { 1738 if (DAG.getDataLayout().isLittleEndian()) { 1739 unsigned indexOffset = CheckEven ? 4 : 0; 1740 if (ShuffleKind == 1) // Unary 1741 return isVMerge(N, indexOffset, 0); 1742 else if (ShuffleKind == 2) // swapped 1743 return isVMerge(N, indexOffset, 16); 1744 else 1745 return false; 1746 } 1747 else { 1748 unsigned indexOffset = CheckEven ? 0 : 4; 1749 if (ShuffleKind == 1) // Unary 1750 return isVMerge(N, indexOffset, 0); 1751 else if (ShuffleKind == 0) // Normal 1752 return isVMerge(N, indexOffset, 16); 1753 else 1754 return false; 1755 } 1756 return false; 1757 } 1758 1759 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1760 /// amount, otherwise return -1. 1761 /// The ShuffleKind distinguishes between big-endian operations with two 1762 /// different inputs (0), either-endian operations with two identical inputs 1763 /// (1), and little-endian operations with two different inputs (2). For the 1764 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1765 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1766 SelectionDAG &DAG) { 1767 if (N->getValueType(0) != MVT::v16i8) 1768 return -1; 1769 1770 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1771 1772 // Find the first non-undef value in the shuffle mask. 1773 unsigned i; 1774 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1775 /*search*/; 1776 1777 if (i == 16) return -1; // all undef. 1778 1779 // Otherwise, check to see if the rest of the elements are consecutively 1780 // numbered from this value. 1781 unsigned ShiftAmt = SVOp->getMaskElt(i); 1782 if (ShiftAmt < i) return -1; 1783 1784 ShiftAmt -= i; 1785 bool isLE = DAG.getDataLayout().isLittleEndian(); 1786 1787 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1788 // Check the rest of the elements to see if they are consecutive. 1789 for (++i; i != 16; ++i) 1790 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1791 return -1; 1792 } else if (ShuffleKind == 1) { 1793 // Check the rest of the elements to see if they are consecutive. 1794 for (++i; i != 16; ++i) 1795 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1796 return -1; 1797 } else 1798 return -1; 1799 1800 if (isLE) 1801 ShiftAmt = 16 - ShiftAmt; 1802 1803 return ShiftAmt; 1804 } 1805 1806 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1807 /// specifies a splat of a single element that is suitable for input to 1808 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1809 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1810 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1811 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1812 1813 // The consecutive indices need to specify an element, not part of two 1814 // different elements. So abandon ship early if this isn't the case. 1815 if (N->getMaskElt(0) % EltSize != 0) 1816 return false; 1817 1818 // This is a splat operation if each element of the permute is the same, and 1819 // if the value doesn't reference the second vector. 1820 unsigned ElementBase = N->getMaskElt(0); 1821 1822 // FIXME: Handle UNDEF elements too! 1823 if (ElementBase >= 16) 1824 return false; 1825 1826 // Check that the indices are consecutive, in the case of a multi-byte element 1827 // splatted with a v16i8 mask. 1828 for (unsigned i = 1; i != EltSize; ++i) 1829 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1830 return false; 1831 1832 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1833 if (N->getMaskElt(i) < 0) continue; 1834 for (unsigned j = 0; j != EltSize; ++j) 1835 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1836 return false; 1837 } 1838 return true; 1839 } 1840 1841 /// Check that the mask is shuffling N byte elements. Within each N byte 1842 /// element of the mask, the indices could be either in increasing or 1843 /// decreasing order as long as they are consecutive. 1844 /// \param[in] N the shuffle vector SD Node to analyze 1845 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1846 /// Word/DoubleWord/QuadWord). 1847 /// \param[in] StepLen the delta indices number among the N byte element, if 1848 /// the mask is in increasing/decreasing order then it is 1/-1. 1849 /// \return true iff the mask is shuffling N byte elements. 1850 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1851 int StepLen) { 1852 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1853 "Unexpected element width."); 1854 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1855 1856 unsigned NumOfElem = 16 / Width; 1857 unsigned MaskVal[16]; // Width is never greater than 16 1858 for (unsigned i = 0; i < NumOfElem; ++i) { 1859 MaskVal[0] = N->getMaskElt(i * Width); 1860 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1861 return false; 1862 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1863 return false; 1864 } 1865 1866 for (unsigned int j = 1; j < Width; ++j) { 1867 MaskVal[j] = N->getMaskElt(i * Width + j); 1868 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1869 return false; 1870 } 1871 } 1872 } 1873 1874 return true; 1875 } 1876 1877 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1878 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1879 if (!isNByteElemShuffleMask(N, 4, 1)) 1880 return false; 1881 1882 // Now we look at mask elements 0,4,8,12 1883 unsigned M0 = N->getMaskElt(0) / 4; 1884 unsigned M1 = N->getMaskElt(4) / 4; 1885 unsigned M2 = N->getMaskElt(8) / 4; 1886 unsigned M3 = N->getMaskElt(12) / 4; 1887 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1888 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1889 1890 // Below, let H and L be arbitrary elements of the shuffle mask 1891 // where H is in the range [4,7] and L is in the range [0,3]. 1892 // H, 1, 2, 3 or L, 5, 6, 7 1893 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1894 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1895 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1896 InsertAtByte = IsLE ? 12 : 0; 1897 Swap = M0 < 4; 1898 return true; 1899 } 1900 // 0, H, 2, 3 or 4, L, 6, 7 1901 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1902 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1903 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1904 InsertAtByte = IsLE ? 8 : 4; 1905 Swap = M1 < 4; 1906 return true; 1907 } 1908 // 0, 1, H, 3 or 4, 5, L, 7 1909 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1910 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1911 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1912 InsertAtByte = IsLE ? 4 : 8; 1913 Swap = M2 < 4; 1914 return true; 1915 } 1916 // 0, 1, 2, H or 4, 5, 6, L 1917 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1918 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1919 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1920 InsertAtByte = IsLE ? 0 : 12; 1921 Swap = M3 < 4; 1922 return true; 1923 } 1924 1925 // If both vector operands for the shuffle are the same vector, the mask will 1926 // contain only elements from the first one and the second one will be undef. 1927 if (N->getOperand(1).isUndef()) { 1928 ShiftElts = 0; 1929 Swap = true; 1930 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1931 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1932 InsertAtByte = IsLE ? 12 : 0; 1933 return true; 1934 } 1935 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1936 InsertAtByte = IsLE ? 8 : 4; 1937 return true; 1938 } 1939 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1940 InsertAtByte = IsLE ? 4 : 8; 1941 return true; 1942 } 1943 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1944 InsertAtByte = IsLE ? 0 : 12; 1945 return true; 1946 } 1947 } 1948 1949 return false; 1950 } 1951 1952 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1953 bool &Swap, bool IsLE) { 1954 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1955 // Ensure each byte index of the word is consecutive. 1956 if (!isNByteElemShuffleMask(N, 4, 1)) 1957 return false; 1958 1959 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1960 unsigned M0 = N->getMaskElt(0) / 4; 1961 unsigned M1 = N->getMaskElt(4) / 4; 1962 unsigned M2 = N->getMaskElt(8) / 4; 1963 unsigned M3 = N->getMaskElt(12) / 4; 1964 1965 // If both vector operands for the shuffle are the same vector, the mask will 1966 // contain only elements from the first one and the second one will be undef. 1967 if (N->getOperand(1).isUndef()) { 1968 assert(M0 < 4 && "Indexing into an undef vector?"); 1969 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1970 return false; 1971 1972 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1973 Swap = false; 1974 return true; 1975 } 1976 1977 // Ensure each word index of the ShuffleVector Mask is consecutive. 1978 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1979 return false; 1980 1981 if (IsLE) { 1982 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1983 // Input vectors don't need to be swapped if the leading element 1984 // of the result is one of the 3 left elements of the second vector 1985 // (or if there is no shift to be done at all). 1986 Swap = false; 1987 ShiftElts = (8 - M0) % 8; 1988 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1989 // Input vectors need to be swapped if the leading element 1990 // of the result is one of the 3 left elements of the first vector 1991 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1992 Swap = true; 1993 ShiftElts = (4 - M0) % 4; 1994 } 1995 1996 return true; 1997 } else { // BE 1998 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1999 // Input vectors don't need to be swapped if the leading element 2000 // of the result is one of the 4 elements of the first vector. 2001 Swap = false; 2002 ShiftElts = M0; 2003 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2004 // Input vectors need to be swapped if the leading element 2005 // of the result is one of the 4 elements of the right vector. 2006 Swap = true; 2007 ShiftElts = M0 - 4; 2008 } 2009 2010 return true; 2011 } 2012 } 2013 2014 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2015 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2016 2017 if (!isNByteElemShuffleMask(N, Width, -1)) 2018 return false; 2019 2020 for (int i = 0; i < 16; i += Width) 2021 if (N->getMaskElt(i) != i + Width - 1) 2022 return false; 2023 2024 return true; 2025 } 2026 2027 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2028 return isXXBRShuffleMaskHelper(N, 2); 2029 } 2030 2031 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2032 return isXXBRShuffleMaskHelper(N, 4); 2033 } 2034 2035 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2036 return isXXBRShuffleMaskHelper(N, 8); 2037 } 2038 2039 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2040 return isXXBRShuffleMaskHelper(N, 16); 2041 } 2042 2043 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2044 /// if the inputs to the instruction should be swapped and set \p DM to the 2045 /// value for the immediate. 2046 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2047 /// AND element 0 of the result comes from the first input (LE) or second input 2048 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2049 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2050 /// mask. 2051 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2052 bool &Swap, bool IsLE) { 2053 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2054 2055 // Ensure each byte index of the double word is consecutive. 2056 if (!isNByteElemShuffleMask(N, 8, 1)) 2057 return false; 2058 2059 unsigned M0 = N->getMaskElt(0) / 8; 2060 unsigned M1 = N->getMaskElt(8) / 8; 2061 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2062 2063 // If both vector operands for the shuffle are the same vector, the mask will 2064 // contain only elements from the first one and the second one will be undef. 2065 if (N->getOperand(1).isUndef()) { 2066 if ((M0 | M1) < 2) { 2067 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2068 Swap = false; 2069 return true; 2070 } else 2071 return false; 2072 } 2073 2074 if (IsLE) { 2075 if (M0 > 1 && M1 < 2) { 2076 Swap = false; 2077 } else if (M0 < 2 && M1 > 1) { 2078 M0 = (M0 + 2) % 4; 2079 M1 = (M1 + 2) % 4; 2080 Swap = true; 2081 } else 2082 return false; 2083 2084 // Note: if control flow comes here that means Swap is already set above 2085 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2086 return true; 2087 } else { // BE 2088 if (M0 < 2 && M1 > 1) { 2089 Swap = false; 2090 } else if (M0 > 1 && M1 < 2) { 2091 M0 = (M0 + 2) % 4; 2092 M1 = (M1 + 2) % 4; 2093 Swap = true; 2094 } else 2095 return false; 2096 2097 // Note: if control flow comes here that means Swap is already set above 2098 DM = (M0 << 1) + (M1 & 1); 2099 return true; 2100 } 2101 } 2102 2103 2104 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2105 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2106 /// elements are counted from the left of the vector register). 2107 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2108 SelectionDAG &DAG) { 2109 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2110 assert(isSplatShuffleMask(SVOp, EltSize)); 2111 if (DAG.getDataLayout().isLittleEndian()) 2112 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2113 else 2114 return SVOp->getMaskElt(0) / EltSize; 2115 } 2116 2117 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2118 /// by using a vspltis[bhw] instruction of the specified element size, return 2119 /// the constant being splatted. The ByteSize field indicates the number of 2120 /// bytes of each element [124] -> [bhw]. 2121 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2122 SDValue OpVal(nullptr, 0); 2123 2124 // If ByteSize of the splat is bigger than the element size of the 2125 // build_vector, then we have a case where we are checking for a splat where 2126 // multiple elements of the buildvector are folded together into a single 2127 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2128 unsigned EltSize = 16/N->getNumOperands(); 2129 if (EltSize < ByteSize) { 2130 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2131 SDValue UniquedVals[4]; 2132 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2133 2134 // See if all of the elements in the buildvector agree across. 2135 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2136 if (N->getOperand(i).isUndef()) continue; 2137 // If the element isn't a constant, bail fully out. 2138 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2139 2140 if (!UniquedVals[i&(Multiple-1)].getNode()) 2141 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2142 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2143 return SDValue(); // no match. 2144 } 2145 2146 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2147 // either constant or undef values that are identical for each chunk. See 2148 // if these chunks can form into a larger vspltis*. 2149 2150 // Check to see if all of the leading entries are either 0 or -1. If 2151 // neither, then this won't fit into the immediate field. 2152 bool LeadingZero = true; 2153 bool LeadingOnes = true; 2154 for (unsigned i = 0; i != Multiple-1; ++i) { 2155 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2156 2157 LeadingZero &= isNullConstant(UniquedVals[i]); 2158 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2159 } 2160 // Finally, check the least significant entry. 2161 if (LeadingZero) { 2162 if (!UniquedVals[Multiple-1].getNode()) 2163 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2164 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2165 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2166 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2167 } 2168 if (LeadingOnes) { 2169 if (!UniquedVals[Multiple-1].getNode()) 2170 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2171 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2172 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2173 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2174 } 2175 2176 return SDValue(); 2177 } 2178 2179 // Check to see if this buildvec has a single non-undef value in its elements. 2180 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2181 if (N->getOperand(i).isUndef()) continue; 2182 if (!OpVal.getNode()) 2183 OpVal = N->getOperand(i); 2184 else if (OpVal != N->getOperand(i)) 2185 return SDValue(); 2186 } 2187 2188 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2189 2190 unsigned ValSizeInBytes = EltSize; 2191 uint64_t Value = 0; 2192 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2193 Value = CN->getZExtValue(); 2194 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2195 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2196 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2197 } 2198 2199 // If the splat value is larger than the element value, then we can never do 2200 // this splat. The only case that we could fit the replicated bits into our 2201 // immediate field for would be zero, and we prefer to use vxor for it. 2202 if (ValSizeInBytes < ByteSize) return SDValue(); 2203 2204 // If the element value is larger than the splat value, check if it consists 2205 // of a repeated bit pattern of size ByteSize. 2206 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2207 return SDValue(); 2208 2209 // Properly sign extend the value. 2210 int MaskVal = SignExtend32(Value, ByteSize * 8); 2211 2212 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2213 if (MaskVal == 0) return SDValue(); 2214 2215 // Finally, if this value fits in a 5 bit sext field, return it 2216 if (SignExtend32<5>(MaskVal) == MaskVal) 2217 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2218 return SDValue(); 2219 } 2220 2221 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2222 /// amount, otherwise return -1. 2223 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2224 EVT VT = N->getValueType(0); 2225 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2226 return -1; 2227 2228 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2229 2230 // Find the first non-undef value in the shuffle mask. 2231 unsigned i; 2232 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2233 /*search*/; 2234 2235 if (i == 4) return -1; // all undef. 2236 2237 // Otherwise, check to see if the rest of the elements are consecutively 2238 // numbered from this value. 2239 unsigned ShiftAmt = SVOp->getMaskElt(i); 2240 if (ShiftAmt < i) return -1; 2241 ShiftAmt -= i; 2242 2243 // Check the rest of the elements to see if they are consecutive. 2244 for (++i; i != 4; ++i) 2245 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2246 return -1; 2247 2248 return ShiftAmt; 2249 } 2250 2251 //===----------------------------------------------------------------------===// 2252 // Addressing Mode Selection 2253 //===----------------------------------------------------------------------===// 2254 2255 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2256 /// or 64-bit immediate, and if the value can be accurately represented as a 2257 /// sign extension from a 16-bit value. If so, this returns true and the 2258 /// immediate. 2259 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2260 if (!isa<ConstantSDNode>(N)) 2261 return false; 2262 2263 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2264 if (N->getValueType(0) == MVT::i32) 2265 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2266 else 2267 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2268 } 2269 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2270 return isIntS16Immediate(Op.getNode(), Imm); 2271 } 2272 2273 2274 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2275 /// be represented as an indexed [r+r] operation. 2276 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2277 SDValue &Index, 2278 SelectionDAG &DAG) const { 2279 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2280 UI != E; ++UI) { 2281 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2282 if (Memop->getMemoryVT() == MVT::f64) { 2283 Base = N.getOperand(0); 2284 Index = N.getOperand(1); 2285 return true; 2286 } 2287 } 2288 } 2289 return false; 2290 } 2291 2292 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2293 /// can be represented as an indexed [r+r] operation. Returns false if it 2294 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2295 /// non-zero and N can be represented by a base register plus a signed 16-bit 2296 /// displacement, make a more precise judgement by checking (displacement % \p 2297 /// EncodingAlignment). 2298 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2299 SDValue &Index, SelectionDAG &DAG, 2300 unsigned EncodingAlignment) const { 2301 int16_t imm = 0; 2302 if (N.getOpcode() == ISD::ADD) { 2303 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2304 // SPE load/store can only handle 8-bit offsets. 2305 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2306 return true; 2307 if (isIntS16Immediate(N.getOperand(1), imm) && 2308 (!EncodingAlignment || !(imm % EncodingAlignment))) 2309 return false; // r+i 2310 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2311 return false; // r+i 2312 2313 Base = N.getOperand(0); 2314 Index = N.getOperand(1); 2315 return true; 2316 } else if (N.getOpcode() == ISD::OR) { 2317 if (isIntS16Immediate(N.getOperand(1), imm) && 2318 (!EncodingAlignment || !(imm % EncodingAlignment))) 2319 return false; // r+i can fold it if we can. 2320 2321 // If this is an or of disjoint bitfields, we can codegen this as an add 2322 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2323 // disjoint. 2324 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2325 2326 if (LHSKnown.Zero.getBoolValue()) { 2327 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2328 // If all of the bits are known zero on the LHS or RHS, the add won't 2329 // carry. 2330 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2331 Base = N.getOperand(0); 2332 Index = N.getOperand(1); 2333 return true; 2334 } 2335 } 2336 } 2337 2338 return false; 2339 } 2340 2341 // If we happen to be doing an i64 load or store into a stack slot that has 2342 // less than a 4-byte alignment, then the frame-index elimination may need to 2343 // use an indexed load or store instruction (because the offset may not be a 2344 // multiple of 4). The extra register needed to hold the offset comes from the 2345 // register scavenger, and it is possible that the scavenger will need to use 2346 // an emergency spill slot. As a result, we need to make sure that a spill slot 2347 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2348 // stack slot. 2349 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2350 // FIXME: This does not handle the LWA case. 2351 if (VT != MVT::i64) 2352 return; 2353 2354 // NOTE: We'll exclude negative FIs here, which come from argument 2355 // lowering, because there are no known test cases triggering this problem 2356 // using packed structures (or similar). We can remove this exclusion if 2357 // we find such a test case. The reason why this is so test-case driven is 2358 // because this entire 'fixup' is only to prevent crashes (from the 2359 // register scavenger) on not-really-valid inputs. For example, if we have: 2360 // %a = alloca i1 2361 // %b = bitcast i1* %a to i64* 2362 // store i64* a, i64 b 2363 // then the store should really be marked as 'align 1', but is not. If it 2364 // were marked as 'align 1' then the indexed form would have been 2365 // instruction-selected initially, and the problem this 'fixup' is preventing 2366 // won't happen regardless. 2367 if (FrameIdx < 0) 2368 return; 2369 2370 MachineFunction &MF = DAG.getMachineFunction(); 2371 MachineFrameInfo &MFI = MF.getFrameInfo(); 2372 2373 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2374 if (Align >= 4) 2375 return; 2376 2377 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2378 FuncInfo->setHasNonRISpills(); 2379 } 2380 2381 /// Returns true if the address N can be represented by a base register plus 2382 /// a signed 16-bit displacement [r+imm], and if it is not better 2383 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2384 /// displacements that are multiples of that value. 2385 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2386 SDValue &Base, 2387 SelectionDAG &DAG, 2388 unsigned EncodingAlignment) const { 2389 // FIXME dl should come from parent load or store, not from address 2390 SDLoc dl(N); 2391 // If this can be more profitably realized as r+r, fail. 2392 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2393 return false; 2394 2395 if (N.getOpcode() == ISD::ADD) { 2396 int16_t imm = 0; 2397 if (isIntS16Immediate(N.getOperand(1), imm) && 2398 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2399 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2400 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2401 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2402 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2403 } else { 2404 Base = N.getOperand(0); 2405 } 2406 return true; // [r+i] 2407 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2408 // Match LOAD (ADD (X, Lo(G))). 2409 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2410 && "Cannot handle constant offsets yet!"); 2411 Disp = N.getOperand(1).getOperand(0); // The global address. 2412 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2413 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2414 Disp.getOpcode() == ISD::TargetConstantPool || 2415 Disp.getOpcode() == ISD::TargetJumpTable); 2416 Base = N.getOperand(0); 2417 return true; // [&g+r] 2418 } 2419 } else if (N.getOpcode() == ISD::OR) { 2420 int16_t imm = 0; 2421 if (isIntS16Immediate(N.getOperand(1), imm) && 2422 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2423 // If this is an or of disjoint bitfields, we can codegen this as an add 2424 // (for better address arithmetic) if the LHS and RHS of the OR are 2425 // provably disjoint. 2426 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2427 2428 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2429 // If all of the bits are known zero on the LHS or RHS, the add won't 2430 // carry. 2431 if (FrameIndexSDNode *FI = 2432 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2433 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2434 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2435 } else { 2436 Base = N.getOperand(0); 2437 } 2438 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2439 return true; 2440 } 2441 } 2442 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2443 // Loading from a constant address. 2444 2445 // If this address fits entirely in a 16-bit sext immediate field, codegen 2446 // this as "d, 0" 2447 int16_t Imm; 2448 if (isIntS16Immediate(CN, Imm) && 2449 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2450 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2451 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2452 CN->getValueType(0)); 2453 return true; 2454 } 2455 2456 // Handle 32-bit sext immediates with LIS + addr mode. 2457 if ((CN->getValueType(0) == MVT::i32 || 2458 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2459 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2460 int Addr = (int)CN->getZExtValue(); 2461 2462 // Otherwise, break this down into an LIS + disp. 2463 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2464 2465 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2466 MVT::i32); 2467 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2468 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2469 return true; 2470 } 2471 } 2472 2473 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2474 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2475 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2476 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2477 } else 2478 Base = N; 2479 return true; // [r+0] 2480 } 2481 2482 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2483 /// represented as an indexed [r+r] operation. 2484 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2485 SDValue &Index, 2486 SelectionDAG &DAG) const { 2487 // Check to see if we can easily represent this as an [r+r] address. This 2488 // will fail if it thinks that the address is more profitably represented as 2489 // reg+imm, e.g. where imm = 0. 2490 if (SelectAddressRegReg(N, Base, Index, DAG)) 2491 return true; 2492 2493 // If the address is the result of an add, we will utilize the fact that the 2494 // address calculation includes an implicit add. However, we can reduce 2495 // register pressure if we do not materialize a constant just for use as the 2496 // index register. We only get rid of the add if it is not an add of a 2497 // value and a 16-bit signed constant and both have a single use. 2498 int16_t imm = 0; 2499 if (N.getOpcode() == ISD::ADD && 2500 (!isIntS16Immediate(N.getOperand(1), imm) || 2501 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2502 Base = N.getOperand(0); 2503 Index = N.getOperand(1); 2504 return true; 2505 } 2506 2507 // Otherwise, do it the hard way, using R0 as the base register. 2508 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2509 N.getValueType()); 2510 Index = N; 2511 return true; 2512 } 2513 2514 /// Returns true if we should use a direct load into vector instruction 2515 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2516 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2517 2518 // If there are any other uses other than scalar to vector, then we should 2519 // keep it as a scalar load -> direct move pattern to prevent multiple 2520 // loads. 2521 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2522 if (!LD) 2523 return false; 2524 2525 EVT MemVT = LD->getMemoryVT(); 2526 if (!MemVT.isSimple()) 2527 return false; 2528 switch(MemVT.getSimpleVT().SimpleTy) { 2529 case MVT::i64: 2530 break; 2531 case MVT::i32: 2532 if (!ST.hasP8Vector()) 2533 return false; 2534 break; 2535 case MVT::i16: 2536 case MVT::i8: 2537 if (!ST.hasP9Vector()) 2538 return false; 2539 break; 2540 default: 2541 return false; 2542 } 2543 2544 SDValue LoadedVal(N, 0); 2545 if (!LoadedVal.hasOneUse()) 2546 return false; 2547 2548 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2549 UI != UE; ++UI) 2550 if (UI.getUse().get().getResNo() == 0 && 2551 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2552 return false; 2553 2554 return true; 2555 } 2556 2557 /// getPreIndexedAddressParts - returns true by value, base pointer and 2558 /// offset pointer and addressing mode by reference if the node's address 2559 /// can be legally represented as pre-indexed load / store address. 2560 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2561 SDValue &Offset, 2562 ISD::MemIndexedMode &AM, 2563 SelectionDAG &DAG) const { 2564 if (DisablePPCPreinc) return false; 2565 2566 bool isLoad = true; 2567 SDValue Ptr; 2568 EVT VT; 2569 unsigned Alignment; 2570 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2571 Ptr = LD->getBasePtr(); 2572 VT = LD->getMemoryVT(); 2573 Alignment = LD->getAlignment(); 2574 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2575 Ptr = ST->getBasePtr(); 2576 VT = ST->getMemoryVT(); 2577 Alignment = ST->getAlignment(); 2578 isLoad = false; 2579 } else 2580 return false; 2581 2582 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2583 // instructions because we can fold these into a more efficient instruction 2584 // instead, (such as LXSD). 2585 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2586 return false; 2587 } 2588 2589 // PowerPC doesn't have preinc load/store instructions for vectors (except 2590 // for QPX, which does have preinc r+r forms). 2591 if (VT.isVector()) { 2592 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2593 return false; 2594 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2595 AM = ISD::PRE_INC; 2596 return true; 2597 } 2598 } 2599 2600 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2601 // Common code will reject creating a pre-inc form if the base pointer 2602 // is a frame index, or if N is a store and the base pointer is either 2603 // the same as or a predecessor of the value being stored. Check for 2604 // those situations here, and try with swapped Base/Offset instead. 2605 bool Swap = false; 2606 2607 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2608 Swap = true; 2609 else if (!isLoad) { 2610 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2611 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2612 Swap = true; 2613 } 2614 2615 if (Swap) 2616 std::swap(Base, Offset); 2617 2618 AM = ISD::PRE_INC; 2619 return true; 2620 } 2621 2622 // LDU/STU can only handle immediates that are a multiple of 4. 2623 if (VT != MVT::i64) { 2624 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2625 return false; 2626 } else { 2627 // LDU/STU need an address with at least 4-byte alignment. 2628 if (Alignment < 4) 2629 return false; 2630 2631 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2632 return false; 2633 } 2634 2635 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2636 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2637 // sext i32 to i64 when addr mode is r+i. 2638 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2639 LD->getExtensionType() == ISD::SEXTLOAD && 2640 isa<ConstantSDNode>(Offset)) 2641 return false; 2642 } 2643 2644 AM = ISD::PRE_INC; 2645 return true; 2646 } 2647 2648 //===----------------------------------------------------------------------===// 2649 // LowerOperation implementation 2650 //===----------------------------------------------------------------------===// 2651 2652 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2653 /// and LoOpFlags to the target MO flags. 2654 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2655 unsigned &HiOpFlags, unsigned &LoOpFlags, 2656 const GlobalValue *GV = nullptr) { 2657 HiOpFlags = PPCII::MO_HA; 2658 LoOpFlags = PPCII::MO_LO; 2659 2660 // Don't use the pic base if not in PIC relocation model. 2661 if (IsPIC) { 2662 HiOpFlags |= PPCII::MO_PIC_FLAG; 2663 LoOpFlags |= PPCII::MO_PIC_FLAG; 2664 } 2665 2666 // If this is a reference to a global value that requires a non-lazy-ptr, make 2667 // sure that instruction lowering adds it. 2668 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2669 HiOpFlags |= PPCII::MO_NLP_FLAG; 2670 LoOpFlags |= PPCII::MO_NLP_FLAG; 2671 2672 if (GV->hasHiddenVisibility()) { 2673 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2674 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2675 } 2676 } 2677 } 2678 2679 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2680 SelectionDAG &DAG) { 2681 SDLoc DL(HiPart); 2682 EVT PtrVT = HiPart.getValueType(); 2683 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2684 2685 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2686 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2687 2688 // With PIC, the first instruction is actually "GR+hi(&G)". 2689 if (isPIC) 2690 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2691 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2692 2693 // Generate non-pic code that has direct accesses to the constant pool. 2694 // The address of the global is just (hi(&g)+lo(&g)). 2695 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2696 } 2697 2698 static void setUsesTOCBasePtr(MachineFunction &MF) { 2699 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2700 FuncInfo->setUsesTOCBasePtr(); 2701 } 2702 2703 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2704 setUsesTOCBasePtr(DAG.getMachineFunction()); 2705 } 2706 2707 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2708 SDValue GA) const { 2709 const bool Is64Bit = Subtarget.isPPC64(); 2710 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2711 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2712 : Subtarget.isAIXABI() 2713 ? DAG.getRegister(PPC::R2, VT) 2714 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2715 SDValue Ops[] = { GA, Reg }; 2716 return DAG.getMemIntrinsicNode( 2717 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2718 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2719 MachineMemOperand::MOLoad); 2720 } 2721 2722 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2723 SelectionDAG &DAG) const { 2724 EVT PtrVT = Op.getValueType(); 2725 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2726 const Constant *C = CP->getConstVal(); 2727 2728 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2729 // The actual address of the GlobalValue is stored in the TOC. 2730 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2731 setUsesTOCBasePtr(DAG); 2732 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2733 return getTOCEntry(DAG, SDLoc(CP), GA); 2734 } 2735 2736 unsigned MOHiFlag, MOLoFlag; 2737 bool IsPIC = isPositionIndependent(); 2738 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2739 2740 if (IsPIC && Subtarget.isSVR4ABI()) { 2741 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2742 PPCII::MO_PIC_FLAG); 2743 return getTOCEntry(DAG, SDLoc(CP), GA); 2744 } 2745 2746 SDValue CPIHi = 2747 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2748 SDValue CPILo = 2749 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2750 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2751 } 2752 2753 // For 64-bit PowerPC, prefer the more compact relative encodings. 2754 // This trades 32 bits per jump table entry for one or two instructions 2755 // on the jump site. 2756 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2757 if (isJumpTableRelative()) 2758 return MachineJumpTableInfo::EK_LabelDifference32; 2759 2760 return TargetLowering::getJumpTableEncoding(); 2761 } 2762 2763 bool PPCTargetLowering::isJumpTableRelative() const { 2764 if (UseAbsoluteJumpTables) 2765 return false; 2766 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2767 return true; 2768 return TargetLowering::isJumpTableRelative(); 2769 } 2770 2771 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2772 SelectionDAG &DAG) const { 2773 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2774 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2775 2776 switch (getTargetMachine().getCodeModel()) { 2777 case CodeModel::Small: 2778 case CodeModel::Medium: 2779 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2780 default: 2781 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2782 getPointerTy(DAG.getDataLayout())); 2783 } 2784 } 2785 2786 const MCExpr * 2787 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2788 unsigned JTI, 2789 MCContext &Ctx) const { 2790 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2791 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2792 2793 switch (getTargetMachine().getCodeModel()) { 2794 case CodeModel::Small: 2795 case CodeModel::Medium: 2796 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2797 default: 2798 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2799 } 2800 } 2801 2802 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2803 EVT PtrVT = Op.getValueType(); 2804 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2805 2806 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2807 // The actual address of the GlobalValue is stored in the TOC. 2808 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2809 setUsesTOCBasePtr(DAG); 2810 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2811 return getTOCEntry(DAG, SDLoc(JT), GA); 2812 } 2813 2814 unsigned MOHiFlag, MOLoFlag; 2815 bool IsPIC = isPositionIndependent(); 2816 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2817 2818 if (IsPIC && Subtarget.isSVR4ABI()) { 2819 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2820 PPCII::MO_PIC_FLAG); 2821 return getTOCEntry(DAG, SDLoc(GA), GA); 2822 } 2823 2824 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2825 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2826 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2827 } 2828 2829 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2830 SelectionDAG &DAG) const { 2831 EVT PtrVT = Op.getValueType(); 2832 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2833 const BlockAddress *BA = BASDN->getBlockAddress(); 2834 2835 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2836 // The actual BlockAddress is stored in the TOC. 2837 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2838 setUsesTOCBasePtr(DAG); 2839 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2840 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2841 } 2842 2843 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2844 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2845 return getTOCEntry( 2846 DAG, SDLoc(BASDN), 2847 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2848 2849 unsigned MOHiFlag, MOLoFlag; 2850 bool IsPIC = isPositionIndependent(); 2851 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2852 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2853 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2854 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2855 } 2856 2857 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2858 SelectionDAG &DAG) const { 2859 // FIXME: TLS addresses currently use medium model code sequences, 2860 // which is the most useful form. Eventually support for small and 2861 // large models could be added if users need it, at the cost of 2862 // additional complexity. 2863 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2864 if (DAG.getTarget().useEmulatedTLS()) 2865 return LowerToTLSEmulatedModel(GA, DAG); 2866 2867 SDLoc dl(GA); 2868 const GlobalValue *GV = GA->getGlobal(); 2869 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2870 bool is64bit = Subtarget.isPPC64(); 2871 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2872 PICLevel::Level picLevel = M->getPICLevel(); 2873 2874 const TargetMachine &TM = getTargetMachine(); 2875 TLSModel::Model Model = TM.getTLSModel(GV); 2876 2877 if (Model == TLSModel::LocalExec) { 2878 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2879 PPCII::MO_TPREL_HA); 2880 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2881 PPCII::MO_TPREL_LO); 2882 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2883 : DAG.getRegister(PPC::R2, MVT::i32); 2884 2885 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2886 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2887 } 2888 2889 if (Model == TLSModel::InitialExec) { 2890 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2891 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2892 PPCII::MO_TLS); 2893 SDValue GOTPtr; 2894 if (is64bit) { 2895 setUsesTOCBasePtr(DAG); 2896 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2897 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2898 PtrVT, GOTReg, TGA); 2899 } else { 2900 if (!TM.isPositionIndependent()) 2901 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2902 else 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 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2908 PtrVT, TGA, GOTPtr); 2909 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2910 } 2911 2912 if (Model == TLSModel::GeneralDynamic) { 2913 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2914 SDValue GOTPtr; 2915 if (is64bit) { 2916 setUsesTOCBasePtr(DAG); 2917 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2918 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2919 GOTReg, TGA); 2920 } else { 2921 if (picLevel == PICLevel::SmallPIC) 2922 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2923 else 2924 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2925 } 2926 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2927 GOTPtr, TGA, TGA); 2928 } 2929 2930 if (Model == TLSModel::LocalDynamic) { 2931 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2932 SDValue GOTPtr; 2933 if (is64bit) { 2934 setUsesTOCBasePtr(DAG); 2935 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2936 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2937 GOTReg, TGA); 2938 } else { 2939 if (picLevel == PICLevel::SmallPIC) 2940 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2941 else 2942 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2943 } 2944 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2945 PtrVT, GOTPtr, TGA, TGA); 2946 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2947 PtrVT, TLSAddr, TGA); 2948 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2949 } 2950 2951 llvm_unreachable("Unknown TLS model!"); 2952 } 2953 2954 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2955 SelectionDAG &DAG) const { 2956 EVT PtrVT = Op.getValueType(); 2957 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2958 SDLoc DL(GSDN); 2959 const GlobalValue *GV = GSDN->getGlobal(); 2960 2961 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 2962 // The actual address of the GlobalValue is stored in the TOC. 2963 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2964 setUsesTOCBasePtr(DAG); 2965 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2966 return getTOCEntry(DAG, DL, GA); 2967 } 2968 2969 unsigned MOHiFlag, MOLoFlag; 2970 bool IsPIC = isPositionIndependent(); 2971 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2972 2973 if (IsPIC && Subtarget.isSVR4ABI()) { 2974 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2975 GSDN->getOffset(), 2976 PPCII::MO_PIC_FLAG); 2977 return getTOCEntry(DAG, DL, GA); 2978 } 2979 2980 SDValue GAHi = 2981 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2982 SDValue GALo = 2983 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2984 2985 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2986 2987 // If the global reference is actually to a non-lazy-pointer, we have to do an 2988 // extra load to get the address of the global. 2989 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2990 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2991 return Ptr; 2992 } 2993 2994 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2995 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2996 SDLoc dl(Op); 2997 2998 if (Op.getValueType() == MVT::v2i64) { 2999 // When the operands themselves are v2i64 values, we need to do something 3000 // special because VSX has no underlying comparison operations for these. 3001 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3002 // Equality can be handled by casting to the legal type for Altivec 3003 // comparisons, everything else needs to be expanded. 3004 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3005 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3006 DAG.getSetCC(dl, MVT::v4i32, 3007 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3008 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3009 CC)); 3010 } 3011 3012 return SDValue(); 3013 } 3014 3015 // We handle most of these in the usual way. 3016 return Op; 3017 } 3018 3019 // If we're comparing for equality to zero, expose the fact that this is 3020 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3021 // fold the new nodes. 3022 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3023 return V; 3024 3025 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3026 // Leave comparisons against 0 and -1 alone for now, since they're usually 3027 // optimized. FIXME: revisit this when we can custom lower all setcc 3028 // optimizations. 3029 if (C->isAllOnesValue() || C->isNullValue()) 3030 return SDValue(); 3031 } 3032 3033 // If we have an integer seteq/setne, turn it into a compare against zero 3034 // by xor'ing the rhs with the lhs, which is faster than setting a 3035 // condition register, reading it back out, and masking the correct bit. The 3036 // normal approach here uses sub to do this instead of xor. Using xor exposes 3037 // the result to other bit-twiddling opportunities. 3038 EVT LHSVT = Op.getOperand(0).getValueType(); 3039 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3040 EVT VT = Op.getValueType(); 3041 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3042 Op.getOperand(1)); 3043 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3044 } 3045 return SDValue(); 3046 } 3047 3048 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3049 SDNode *Node = Op.getNode(); 3050 EVT VT = Node->getValueType(0); 3051 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3052 SDValue InChain = Node->getOperand(0); 3053 SDValue VAListPtr = Node->getOperand(1); 3054 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3055 SDLoc dl(Node); 3056 3057 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3058 3059 // gpr_index 3060 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3061 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3062 InChain = GprIndex.getValue(1); 3063 3064 if (VT == MVT::i64) { 3065 // Check if GprIndex is even 3066 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3067 DAG.getConstant(1, dl, MVT::i32)); 3068 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3069 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3070 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3071 DAG.getConstant(1, dl, MVT::i32)); 3072 // Align GprIndex to be even if it isn't 3073 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3074 GprIndex); 3075 } 3076 3077 // fpr index is 1 byte after gpr 3078 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3079 DAG.getConstant(1, dl, MVT::i32)); 3080 3081 // fpr 3082 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3083 FprPtr, MachinePointerInfo(SV), MVT::i8); 3084 InChain = FprIndex.getValue(1); 3085 3086 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3087 DAG.getConstant(8, dl, MVT::i32)); 3088 3089 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3090 DAG.getConstant(4, dl, MVT::i32)); 3091 3092 // areas 3093 SDValue OverflowArea = 3094 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3095 InChain = OverflowArea.getValue(1); 3096 3097 SDValue RegSaveArea = 3098 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3099 InChain = RegSaveArea.getValue(1); 3100 3101 // select overflow_area if index > 8 3102 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3103 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3104 3105 // adjustment constant gpr_index * 4/8 3106 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3107 VT.isInteger() ? GprIndex : FprIndex, 3108 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3109 MVT::i32)); 3110 3111 // OurReg = RegSaveArea + RegConstant 3112 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3113 RegConstant); 3114 3115 // Floating types are 32 bytes into RegSaveArea 3116 if (VT.isFloatingPoint()) 3117 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3118 DAG.getConstant(32, dl, MVT::i32)); 3119 3120 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3121 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3122 VT.isInteger() ? GprIndex : FprIndex, 3123 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3124 MVT::i32)); 3125 3126 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3127 VT.isInteger() ? VAListPtr : FprPtr, 3128 MachinePointerInfo(SV), MVT::i8); 3129 3130 // determine if we should load from reg_save_area or overflow_area 3131 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3132 3133 // increase overflow_area by 4/8 if gpr/fpr > 8 3134 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3135 DAG.getConstant(VT.isInteger() ? 4 : 8, 3136 dl, MVT::i32)); 3137 3138 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3139 OverflowAreaPlusN); 3140 3141 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3142 MachinePointerInfo(), MVT::i32); 3143 3144 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3145 } 3146 3147 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3148 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3149 3150 // We have to copy the entire va_list struct: 3151 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3152 return DAG.getMemcpy(Op.getOperand(0), Op, 3153 Op.getOperand(1), Op.getOperand(2), 3154 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3155 false, MachinePointerInfo(), MachinePointerInfo()); 3156 } 3157 3158 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3159 SelectionDAG &DAG) const { 3160 if (Subtarget.isAIXABI()) 3161 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3162 3163 return Op.getOperand(0); 3164 } 3165 3166 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3167 SelectionDAG &DAG) const { 3168 if (Subtarget.isAIXABI()) 3169 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3170 3171 SDValue Chain = Op.getOperand(0); 3172 SDValue Trmp = Op.getOperand(1); // trampoline 3173 SDValue FPtr = Op.getOperand(2); // nested function 3174 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3175 SDLoc dl(Op); 3176 3177 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3178 bool isPPC64 = (PtrVT == MVT::i64); 3179 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3180 3181 TargetLowering::ArgListTy Args; 3182 TargetLowering::ArgListEntry Entry; 3183 3184 Entry.Ty = IntPtrTy; 3185 Entry.Node = Trmp; Args.push_back(Entry); 3186 3187 // TrampSize == (isPPC64 ? 48 : 40); 3188 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3189 isPPC64 ? MVT::i64 : MVT::i32); 3190 Args.push_back(Entry); 3191 3192 Entry.Node = FPtr; Args.push_back(Entry); 3193 Entry.Node = Nest; Args.push_back(Entry); 3194 3195 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3196 TargetLowering::CallLoweringInfo CLI(DAG); 3197 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3198 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3199 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3200 3201 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3202 return CallResult.second; 3203 } 3204 3205 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3206 MachineFunction &MF = DAG.getMachineFunction(); 3207 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3208 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3209 3210 SDLoc dl(Op); 3211 3212 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3213 // vastart just stores the address of the VarArgsFrameIndex slot into the 3214 // memory location argument. 3215 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3216 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3217 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3218 MachinePointerInfo(SV)); 3219 } 3220 3221 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3222 // We suppose the given va_list is already allocated. 3223 // 3224 // typedef struct { 3225 // char gpr; /* index into the array of 8 GPRs 3226 // * stored in the register save area 3227 // * gpr=0 corresponds to r3, 3228 // * gpr=1 to r4, etc. 3229 // */ 3230 // char fpr; /* index into the array of 8 FPRs 3231 // * stored in the register save area 3232 // * fpr=0 corresponds to f1, 3233 // * fpr=1 to f2, etc. 3234 // */ 3235 // char *overflow_arg_area; 3236 // /* location on stack that holds 3237 // * the next overflow argument 3238 // */ 3239 // char *reg_save_area; 3240 // /* where r3:r10 and f1:f8 (if saved) 3241 // * are stored 3242 // */ 3243 // } va_list[1]; 3244 3245 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3246 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3247 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3248 PtrVT); 3249 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3250 PtrVT); 3251 3252 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3253 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3254 3255 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3256 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3257 3258 uint64_t FPROffset = 1; 3259 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3260 3261 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3262 3263 // Store first byte : number of int regs 3264 SDValue firstStore = 3265 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3266 MachinePointerInfo(SV), MVT::i8); 3267 uint64_t nextOffset = FPROffset; 3268 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3269 ConstFPROffset); 3270 3271 // Store second byte : number of float regs 3272 SDValue secondStore = 3273 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3274 MachinePointerInfo(SV, nextOffset), MVT::i8); 3275 nextOffset += StackOffset; 3276 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3277 3278 // Store second word : arguments given on stack 3279 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3280 MachinePointerInfo(SV, nextOffset)); 3281 nextOffset += FrameOffset; 3282 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3283 3284 // Store third word : arguments given in registers 3285 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3286 MachinePointerInfo(SV, nextOffset)); 3287 } 3288 3289 /// FPR - The set of FP registers that should be allocated for arguments 3290 /// on Darwin and AIX. 3291 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3292 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3293 PPC::F11, PPC::F12, PPC::F13}; 3294 3295 /// QFPR - The set of QPX registers that should be allocated for arguments. 3296 static const MCPhysReg QFPR[] = { 3297 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3298 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3299 3300 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3301 /// the stack. 3302 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3303 unsigned PtrByteSize) { 3304 unsigned ArgSize = ArgVT.getStoreSize(); 3305 if (Flags.isByVal()) 3306 ArgSize = Flags.getByValSize(); 3307 3308 // Round up to multiples of the pointer size, except for array members, 3309 // which are always packed. 3310 if (!Flags.isInConsecutiveRegs()) 3311 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3312 3313 return ArgSize; 3314 } 3315 3316 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3317 /// on the stack. 3318 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3319 ISD::ArgFlagsTy Flags, 3320 unsigned PtrByteSize) { 3321 unsigned Align = PtrByteSize; 3322 3323 // Altivec parameters are padded to a 16 byte boundary. 3324 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3325 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3326 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3327 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3328 Align = 16; 3329 // QPX vector types stored in double-precision are padded to a 32 byte 3330 // boundary. 3331 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3332 Align = 32; 3333 3334 // ByVal parameters are aligned as requested. 3335 if (Flags.isByVal()) { 3336 unsigned BVAlign = Flags.getByValAlign(); 3337 if (BVAlign > PtrByteSize) { 3338 if (BVAlign % PtrByteSize != 0) 3339 llvm_unreachable( 3340 "ByVal alignment is not a multiple of the pointer size"); 3341 3342 Align = BVAlign; 3343 } 3344 } 3345 3346 // Array members are always packed to their original alignment. 3347 if (Flags.isInConsecutiveRegs()) { 3348 // If the array member was split into multiple registers, the first 3349 // needs to be aligned to the size of the full type. (Except for 3350 // ppcf128, which is only aligned as its f64 components.) 3351 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3352 Align = OrigVT.getStoreSize(); 3353 else 3354 Align = ArgVT.getStoreSize(); 3355 } 3356 3357 return Align; 3358 } 3359 3360 /// CalculateStackSlotUsed - Return whether this argument will use its 3361 /// stack slot (instead of being passed in registers). ArgOffset, 3362 /// AvailableFPRs, and AvailableVRs must hold the current argument 3363 /// position, and will be updated to account for this argument. 3364 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3365 ISD::ArgFlagsTy Flags, 3366 unsigned PtrByteSize, 3367 unsigned LinkageSize, 3368 unsigned ParamAreaSize, 3369 unsigned &ArgOffset, 3370 unsigned &AvailableFPRs, 3371 unsigned &AvailableVRs, bool HasQPX) { 3372 bool UseMemory = false; 3373 3374 // Respect alignment of argument on the stack. 3375 unsigned Align = 3376 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3377 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3378 // If there's no space left in the argument save area, we must 3379 // use memory (this check also catches zero-sized arguments). 3380 if (ArgOffset >= LinkageSize + ParamAreaSize) 3381 UseMemory = true; 3382 3383 // Allocate argument on the stack. 3384 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3385 if (Flags.isInConsecutiveRegsLast()) 3386 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3387 // If we overran the argument save area, we must use memory 3388 // (this check catches arguments passed partially in memory) 3389 if (ArgOffset > LinkageSize + ParamAreaSize) 3390 UseMemory = true; 3391 3392 // However, if the argument is actually passed in an FPR or a VR, 3393 // we don't use memory after all. 3394 if (!Flags.isByVal()) { 3395 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3396 // QPX registers overlap with the scalar FP registers. 3397 (HasQPX && (ArgVT == MVT::v4f32 || 3398 ArgVT == MVT::v4f64 || 3399 ArgVT == MVT::v4i1))) 3400 if (AvailableFPRs > 0) { 3401 --AvailableFPRs; 3402 return false; 3403 } 3404 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3405 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3406 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3407 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3408 if (AvailableVRs > 0) { 3409 --AvailableVRs; 3410 return false; 3411 } 3412 } 3413 3414 return UseMemory; 3415 } 3416 3417 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3418 /// ensure minimum alignment required for target. 3419 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3420 unsigned NumBytes) { 3421 unsigned TargetAlign = Lowering->getStackAlignment(); 3422 unsigned AlignMask = TargetAlign - 1; 3423 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3424 return NumBytes; 3425 } 3426 3427 SDValue PPCTargetLowering::LowerFormalArguments( 3428 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3429 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3430 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3431 if (Subtarget.isAIXABI()) 3432 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3433 InVals); 3434 if (Subtarget.is64BitELFABI()) 3435 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3436 InVals); 3437 if (Subtarget.is32BitELFABI()) 3438 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3439 InVals); 3440 3441 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3442 InVals); 3443 } 3444 3445 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3446 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3447 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3448 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3449 3450 // 32-bit SVR4 ABI Stack Frame Layout: 3451 // +-----------------------------------+ 3452 // +--> | Back chain | 3453 // | +-----------------------------------+ 3454 // | | Floating-point register save area | 3455 // | +-----------------------------------+ 3456 // | | General register save area | 3457 // | +-----------------------------------+ 3458 // | | CR save word | 3459 // | +-----------------------------------+ 3460 // | | VRSAVE save word | 3461 // | +-----------------------------------+ 3462 // | | Alignment padding | 3463 // | +-----------------------------------+ 3464 // | | Vector register save area | 3465 // | +-----------------------------------+ 3466 // | | Local variable space | 3467 // | +-----------------------------------+ 3468 // | | Parameter list area | 3469 // | +-----------------------------------+ 3470 // | | LR save word | 3471 // | +-----------------------------------+ 3472 // SP--> +--- | Back chain | 3473 // +-----------------------------------+ 3474 // 3475 // Specifications: 3476 // System V Application Binary Interface PowerPC Processor Supplement 3477 // AltiVec Technology Programming Interface Manual 3478 3479 MachineFunction &MF = DAG.getMachineFunction(); 3480 MachineFrameInfo &MFI = MF.getFrameInfo(); 3481 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3482 3483 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3484 // Potential tail calls could cause overwriting of argument stack slots. 3485 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3486 (CallConv == CallingConv::Fast)); 3487 unsigned PtrByteSize = 4; 3488 3489 // Assign locations to all of the incoming arguments. 3490 SmallVector<CCValAssign, 16> ArgLocs; 3491 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3492 *DAG.getContext()); 3493 3494 // Reserve space for the linkage area on the stack. 3495 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3496 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3497 if (useSoftFloat()) 3498 CCInfo.PreAnalyzeFormalArguments(Ins); 3499 3500 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3501 CCInfo.clearWasPPCF128(); 3502 3503 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3504 CCValAssign &VA = ArgLocs[i]; 3505 3506 // Arguments stored in registers. 3507 if (VA.isRegLoc()) { 3508 const TargetRegisterClass *RC; 3509 EVT ValVT = VA.getValVT(); 3510 3511 switch (ValVT.getSimpleVT().SimpleTy) { 3512 default: 3513 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3514 case MVT::i1: 3515 case MVT::i32: 3516 RC = &PPC::GPRCRegClass; 3517 break; 3518 case MVT::f32: 3519 if (Subtarget.hasP8Vector()) 3520 RC = &PPC::VSSRCRegClass; 3521 else if (Subtarget.hasSPE()) 3522 RC = &PPC::GPRCRegClass; 3523 else 3524 RC = &PPC::F4RCRegClass; 3525 break; 3526 case MVT::f64: 3527 if (Subtarget.hasVSX()) 3528 RC = &PPC::VSFRCRegClass; 3529 else if (Subtarget.hasSPE()) 3530 // SPE passes doubles in GPR pairs. 3531 RC = &PPC::GPRCRegClass; 3532 else 3533 RC = &PPC::F8RCRegClass; 3534 break; 3535 case MVT::v16i8: 3536 case MVT::v8i16: 3537 case MVT::v4i32: 3538 RC = &PPC::VRRCRegClass; 3539 break; 3540 case MVT::v4f32: 3541 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3542 break; 3543 case MVT::v2f64: 3544 case MVT::v2i64: 3545 RC = &PPC::VRRCRegClass; 3546 break; 3547 case MVT::v4f64: 3548 RC = &PPC::QFRCRegClass; 3549 break; 3550 case MVT::v4i1: 3551 RC = &PPC::QBRCRegClass; 3552 break; 3553 } 3554 3555 SDValue ArgValue; 3556 // Transform the arguments stored in physical registers into 3557 // virtual ones. 3558 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3559 assert(i + 1 < e && "No second half of double precision argument"); 3560 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3561 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3562 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3563 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3564 if (!Subtarget.isLittleEndian()) 3565 std::swap (ArgValueLo, ArgValueHi); 3566 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3567 ArgValueHi); 3568 } else { 3569 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3570 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3571 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3572 if (ValVT == MVT::i1) 3573 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3574 } 3575 3576 InVals.push_back(ArgValue); 3577 } else { 3578 // Argument stored in memory. 3579 assert(VA.isMemLoc()); 3580 3581 // Get the extended size of the argument type in stack 3582 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3583 // Get the actual size of the argument type 3584 unsigned ObjSize = VA.getValVT().getStoreSize(); 3585 unsigned ArgOffset = VA.getLocMemOffset(); 3586 // Stack objects in PPC32 are right justified. 3587 ArgOffset += ArgSize - ObjSize; 3588 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3589 3590 // Create load nodes to retrieve arguments from the stack. 3591 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3592 InVals.push_back( 3593 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3594 } 3595 } 3596 3597 // Assign locations to all of the incoming aggregate by value arguments. 3598 // Aggregates passed by value are stored in the local variable space of the 3599 // caller's stack frame, right above the parameter list area. 3600 SmallVector<CCValAssign, 16> ByValArgLocs; 3601 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3602 ByValArgLocs, *DAG.getContext()); 3603 3604 // Reserve stack space for the allocations in CCInfo. 3605 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3606 3607 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3608 3609 // Area that is at least reserved in the caller of this function. 3610 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3611 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3612 3613 // Set the size that is at least reserved in caller of this function. Tail 3614 // call optimized function's reserved stack space needs to be aligned so that 3615 // taking the difference between two stack areas will result in an aligned 3616 // stack. 3617 MinReservedArea = 3618 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3619 FuncInfo->setMinReservedArea(MinReservedArea); 3620 3621 SmallVector<SDValue, 8> MemOps; 3622 3623 // If the function takes variable number of arguments, make a frame index for 3624 // the start of the first vararg value... for expansion of llvm.va_start. 3625 if (isVarArg) { 3626 static const MCPhysReg GPArgRegs[] = { 3627 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3628 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3629 }; 3630 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3631 3632 static const MCPhysReg FPArgRegs[] = { 3633 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3634 PPC::F8 3635 }; 3636 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3637 3638 if (useSoftFloat() || hasSPE()) 3639 NumFPArgRegs = 0; 3640 3641 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3642 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3643 3644 // Make room for NumGPArgRegs and NumFPArgRegs. 3645 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3646 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3647 3648 FuncInfo->setVarArgsStackOffset( 3649 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3650 CCInfo.getNextStackOffset(), true)); 3651 3652 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3653 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3654 3655 // The fixed integer arguments of a variadic function are stored to the 3656 // VarArgsFrameIndex on the stack so that they may be loaded by 3657 // dereferencing the result of va_next. 3658 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3659 // Get an existing live-in vreg, or add a new one. 3660 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3661 if (!VReg) 3662 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3663 3664 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3665 SDValue Store = 3666 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3667 MemOps.push_back(Store); 3668 // Increment the address by four for the next argument to store 3669 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3670 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3671 } 3672 3673 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3674 // is set. 3675 // The double arguments are stored to the VarArgsFrameIndex 3676 // on the stack. 3677 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3678 // Get an existing live-in vreg, or add a new one. 3679 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3680 if (!VReg) 3681 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3682 3683 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3684 SDValue Store = 3685 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3686 MemOps.push_back(Store); 3687 // Increment the address by eight for the next argument to store 3688 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3689 PtrVT); 3690 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3691 } 3692 } 3693 3694 if (!MemOps.empty()) 3695 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3696 3697 return Chain; 3698 } 3699 3700 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3701 // value to MVT::i64 and then truncate to the correct register size. 3702 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3703 EVT ObjectVT, SelectionDAG &DAG, 3704 SDValue ArgVal, 3705 const SDLoc &dl) const { 3706 if (Flags.isSExt()) 3707 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3708 DAG.getValueType(ObjectVT)); 3709 else if (Flags.isZExt()) 3710 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3711 DAG.getValueType(ObjectVT)); 3712 3713 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3714 } 3715 3716 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3717 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3718 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3719 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3720 // TODO: add description of PPC stack frame format, or at least some docs. 3721 // 3722 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3723 bool isLittleEndian = Subtarget.isLittleEndian(); 3724 MachineFunction &MF = DAG.getMachineFunction(); 3725 MachineFrameInfo &MFI = MF.getFrameInfo(); 3726 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3727 3728 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3729 "fastcc not supported on varargs functions"); 3730 3731 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3732 // Potential tail calls could cause overwriting of argument stack slots. 3733 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3734 (CallConv == CallingConv::Fast)); 3735 unsigned PtrByteSize = 8; 3736 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3737 3738 static const MCPhysReg GPR[] = { 3739 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3740 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3741 }; 3742 static const MCPhysReg VR[] = { 3743 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3744 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3745 }; 3746 3747 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3748 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3749 const unsigned Num_VR_Regs = array_lengthof(VR); 3750 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3751 3752 // Do a first pass over the arguments to determine whether the ABI 3753 // guarantees that our caller has allocated the parameter save area 3754 // on its stack frame. In the ELFv1 ABI, this is always the case; 3755 // in the ELFv2 ABI, it is true if this is a vararg function or if 3756 // any parameter is located in a stack slot. 3757 3758 bool HasParameterArea = !isELFv2ABI || isVarArg; 3759 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3760 unsigned NumBytes = LinkageSize; 3761 unsigned AvailableFPRs = Num_FPR_Regs; 3762 unsigned AvailableVRs = Num_VR_Regs; 3763 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3764 if (Ins[i].Flags.isNest()) 3765 continue; 3766 3767 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3768 PtrByteSize, LinkageSize, ParamAreaSize, 3769 NumBytes, AvailableFPRs, AvailableVRs, 3770 Subtarget.hasQPX())) 3771 HasParameterArea = true; 3772 } 3773 3774 // Add DAG nodes to load the arguments or copy them out of registers. On 3775 // entry to a function on PPC, the arguments start after the linkage area, 3776 // although the first ones are often in registers. 3777 3778 unsigned ArgOffset = LinkageSize; 3779 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3780 unsigned &QFPR_idx = FPR_idx; 3781 SmallVector<SDValue, 8> MemOps; 3782 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3783 unsigned CurArgIdx = 0; 3784 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3785 SDValue ArgVal; 3786 bool needsLoad = false; 3787 EVT ObjectVT = Ins[ArgNo].VT; 3788 EVT OrigVT = Ins[ArgNo].ArgVT; 3789 unsigned ObjSize = ObjectVT.getStoreSize(); 3790 unsigned ArgSize = ObjSize; 3791 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3792 if (Ins[ArgNo].isOrigArg()) { 3793 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3794 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3795 } 3796 // We re-align the argument offset for each argument, except when using the 3797 // fast calling convention, when we need to make sure we do that only when 3798 // we'll actually use a stack slot. 3799 unsigned CurArgOffset, Align; 3800 auto ComputeArgOffset = [&]() { 3801 /* Respect alignment of argument on the stack. */ 3802 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3803 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3804 CurArgOffset = ArgOffset; 3805 }; 3806 3807 if (CallConv != CallingConv::Fast) { 3808 ComputeArgOffset(); 3809 3810 /* Compute GPR index associated with argument offset. */ 3811 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3812 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3813 } 3814 3815 // FIXME the codegen can be much improved in some cases. 3816 // We do not have to keep everything in memory. 3817 if (Flags.isByVal()) { 3818 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3819 3820 if (CallConv == CallingConv::Fast) 3821 ComputeArgOffset(); 3822 3823 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3824 ObjSize = Flags.getByValSize(); 3825 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3826 // Empty aggregate parameters do not take up registers. Examples: 3827 // struct { } a; 3828 // union { } b; 3829 // int c[0]; 3830 // etc. However, we have to provide a place-holder in InVals, so 3831 // pretend we have an 8-byte item at the current address for that 3832 // purpose. 3833 if (!ObjSize) { 3834 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3835 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3836 InVals.push_back(FIN); 3837 continue; 3838 } 3839 3840 // Create a stack object covering all stack doublewords occupied 3841 // by the argument. If the argument is (fully or partially) on 3842 // the stack, or if the argument is fully in registers but the 3843 // caller has allocated the parameter save anyway, we can refer 3844 // directly to the caller's stack frame. Otherwise, create a 3845 // local copy in our own frame. 3846 int FI; 3847 if (HasParameterArea || 3848 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3849 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3850 else 3851 FI = MFI.CreateStackObject(ArgSize, Align, false); 3852 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3853 3854 // Handle aggregates smaller than 8 bytes. 3855 if (ObjSize < PtrByteSize) { 3856 // The value of the object is its address, which differs from the 3857 // address of the enclosing doubleword on big-endian systems. 3858 SDValue Arg = FIN; 3859 if (!isLittleEndian) { 3860 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3861 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3862 } 3863 InVals.push_back(Arg); 3864 3865 if (GPR_idx != Num_GPR_Regs) { 3866 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3867 FuncInfo->addLiveInAttr(VReg, Flags); 3868 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3869 SDValue Store; 3870 3871 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3872 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3873 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3874 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3875 MachinePointerInfo(&*FuncArg), ObjType); 3876 } else { 3877 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3878 // store the whole register as-is to the parameter save area 3879 // slot. 3880 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3881 MachinePointerInfo(&*FuncArg)); 3882 } 3883 3884 MemOps.push_back(Store); 3885 } 3886 // Whether we copied from a register or not, advance the offset 3887 // into the parameter save area by a full doubleword. 3888 ArgOffset += PtrByteSize; 3889 continue; 3890 } 3891 3892 // The value of the object is its address, which is the address of 3893 // its first stack doubleword. 3894 InVals.push_back(FIN); 3895 3896 // Store whatever pieces of the object are in registers to memory. 3897 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3898 if (GPR_idx == Num_GPR_Regs) 3899 break; 3900 3901 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3902 FuncInfo->addLiveInAttr(VReg, Flags); 3903 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3904 SDValue Addr = FIN; 3905 if (j) { 3906 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3907 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3908 } 3909 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3910 MachinePointerInfo(&*FuncArg, j)); 3911 MemOps.push_back(Store); 3912 ++GPR_idx; 3913 } 3914 ArgOffset += ArgSize; 3915 continue; 3916 } 3917 3918 switch (ObjectVT.getSimpleVT().SimpleTy) { 3919 default: llvm_unreachable("Unhandled argument type!"); 3920 case MVT::i1: 3921 case MVT::i32: 3922 case MVT::i64: 3923 if (Flags.isNest()) { 3924 // The 'nest' parameter, if any, is passed in R11. 3925 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3926 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3927 3928 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3929 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3930 3931 break; 3932 } 3933 3934 // These can be scalar arguments or elements of an integer array type 3935 // passed directly. Clang may use those instead of "byval" aggregate 3936 // types to avoid forcing arguments to memory unnecessarily. 3937 if (GPR_idx != Num_GPR_Regs) { 3938 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3939 FuncInfo->addLiveInAttr(VReg, Flags); 3940 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3941 3942 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3943 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3944 // value to MVT::i64 and then truncate to the correct register size. 3945 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3946 } else { 3947 if (CallConv == CallingConv::Fast) 3948 ComputeArgOffset(); 3949 3950 needsLoad = true; 3951 ArgSize = PtrByteSize; 3952 } 3953 if (CallConv != CallingConv::Fast || needsLoad) 3954 ArgOffset += 8; 3955 break; 3956 3957 case MVT::f32: 3958 case MVT::f64: 3959 // These can be scalar arguments or elements of a float array type 3960 // passed directly. The latter are used to implement ELFv2 homogenous 3961 // float aggregates. 3962 if (FPR_idx != Num_FPR_Regs) { 3963 unsigned VReg; 3964 3965 if (ObjectVT == MVT::f32) 3966 VReg = MF.addLiveIn(FPR[FPR_idx], 3967 Subtarget.hasP8Vector() 3968 ? &PPC::VSSRCRegClass 3969 : &PPC::F4RCRegClass); 3970 else 3971 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3972 ? &PPC::VSFRCRegClass 3973 : &PPC::F8RCRegClass); 3974 3975 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3976 ++FPR_idx; 3977 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3978 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3979 // once we support fp <-> gpr moves. 3980 3981 // This can only ever happen in the presence of f32 array types, 3982 // since otherwise we never run out of FPRs before running out 3983 // of GPRs. 3984 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3985 FuncInfo->addLiveInAttr(VReg, Flags); 3986 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3987 3988 if (ObjectVT == MVT::f32) { 3989 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3990 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3991 DAG.getConstant(32, dl, MVT::i32)); 3992 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3993 } 3994 3995 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3996 } else { 3997 if (CallConv == CallingConv::Fast) 3998 ComputeArgOffset(); 3999 4000 needsLoad = true; 4001 } 4002 4003 // When passing an array of floats, the array occupies consecutive 4004 // space in the argument area; only round up to the next doubleword 4005 // at the end of the array. Otherwise, each float takes 8 bytes. 4006 if (CallConv != CallingConv::Fast || needsLoad) { 4007 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4008 ArgOffset += ArgSize; 4009 if (Flags.isInConsecutiveRegsLast()) 4010 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4011 } 4012 break; 4013 case MVT::v4f32: 4014 case MVT::v4i32: 4015 case MVT::v8i16: 4016 case MVT::v16i8: 4017 case MVT::v2f64: 4018 case MVT::v2i64: 4019 case MVT::v1i128: 4020 case MVT::f128: 4021 if (!Subtarget.hasQPX()) { 4022 // These can be scalar arguments or elements of a vector array type 4023 // passed directly. The latter are used to implement ELFv2 homogenous 4024 // vector aggregates. 4025 if (VR_idx != Num_VR_Regs) { 4026 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4027 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4028 ++VR_idx; 4029 } else { 4030 if (CallConv == CallingConv::Fast) 4031 ComputeArgOffset(); 4032 needsLoad = true; 4033 } 4034 if (CallConv != CallingConv::Fast || needsLoad) 4035 ArgOffset += 16; 4036 break; 4037 } // not QPX 4038 4039 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4040 "Invalid QPX parameter type"); 4041 LLVM_FALLTHROUGH; 4042 4043 case MVT::v4f64: 4044 case MVT::v4i1: 4045 // QPX vectors are treated like their scalar floating-point subregisters 4046 // (except that they're larger). 4047 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4048 if (QFPR_idx != Num_QFPR_Regs) { 4049 const TargetRegisterClass *RC; 4050 switch (ObjectVT.getSimpleVT().SimpleTy) { 4051 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4052 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4053 default: RC = &PPC::QBRCRegClass; break; 4054 } 4055 4056 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4057 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4058 ++QFPR_idx; 4059 } else { 4060 if (CallConv == CallingConv::Fast) 4061 ComputeArgOffset(); 4062 needsLoad = true; 4063 } 4064 if (CallConv != CallingConv::Fast || needsLoad) 4065 ArgOffset += Sz; 4066 break; 4067 } 4068 4069 // We need to load the argument to a virtual register if we determined 4070 // above that we ran out of physical registers of the appropriate type. 4071 if (needsLoad) { 4072 if (ObjSize < ArgSize && !isLittleEndian) 4073 CurArgOffset += ArgSize - ObjSize; 4074 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4075 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4076 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4077 } 4078 4079 InVals.push_back(ArgVal); 4080 } 4081 4082 // Area that is at least reserved in the caller of this function. 4083 unsigned MinReservedArea; 4084 if (HasParameterArea) 4085 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4086 else 4087 MinReservedArea = LinkageSize; 4088 4089 // Set the size that is at least reserved in caller of this function. Tail 4090 // call optimized functions' reserved stack space needs to be aligned so that 4091 // taking the difference between two stack areas will result in an aligned 4092 // stack. 4093 MinReservedArea = 4094 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4095 FuncInfo->setMinReservedArea(MinReservedArea); 4096 4097 // If the function takes variable number of arguments, make a frame index for 4098 // the start of the first vararg value... for expansion of llvm.va_start. 4099 if (isVarArg) { 4100 int Depth = ArgOffset; 4101 4102 FuncInfo->setVarArgsFrameIndex( 4103 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4104 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4105 4106 // If this function is vararg, store any remaining integer argument regs 4107 // to their spots on the stack so that they may be loaded by dereferencing 4108 // the result of va_next. 4109 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4110 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4111 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4112 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4113 SDValue Store = 4114 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4115 MemOps.push_back(Store); 4116 // Increment the address by four for the next argument to store 4117 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4118 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4119 } 4120 } 4121 4122 if (!MemOps.empty()) 4123 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4124 4125 return Chain; 4126 } 4127 4128 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4129 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4130 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4131 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4132 // TODO: add description of PPC stack frame format, or at least some docs. 4133 // 4134 MachineFunction &MF = DAG.getMachineFunction(); 4135 MachineFrameInfo &MFI = MF.getFrameInfo(); 4136 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4137 4138 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4139 bool isPPC64 = PtrVT == MVT::i64; 4140 // Potential tail calls could cause overwriting of argument stack slots. 4141 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4142 (CallConv == CallingConv::Fast)); 4143 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4144 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4145 unsigned ArgOffset = LinkageSize; 4146 // Area that is at least reserved in caller of this function. 4147 unsigned MinReservedArea = ArgOffset; 4148 4149 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4150 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4151 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4152 }; 4153 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4154 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4155 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4156 }; 4157 static const MCPhysReg VR[] = { 4158 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4159 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4160 }; 4161 4162 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4163 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4164 const unsigned Num_VR_Regs = array_lengthof( VR); 4165 4166 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4167 4168 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4169 4170 // In 32-bit non-varargs functions, the stack space for vectors is after the 4171 // stack space for non-vectors. We do not use this space unless we have 4172 // too many vectors to fit in registers, something that only occurs in 4173 // constructed examples:), but we have to walk the arglist to figure 4174 // that out...for the pathological case, compute VecArgOffset as the 4175 // start of the vector parameter area. Computing VecArgOffset is the 4176 // entire point of the following loop. 4177 unsigned VecArgOffset = ArgOffset; 4178 if (!isVarArg && !isPPC64) { 4179 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4180 ++ArgNo) { 4181 EVT ObjectVT = Ins[ArgNo].VT; 4182 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4183 4184 if (Flags.isByVal()) { 4185 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4186 unsigned ObjSize = Flags.getByValSize(); 4187 unsigned ArgSize = 4188 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4189 VecArgOffset += ArgSize; 4190 continue; 4191 } 4192 4193 switch(ObjectVT.getSimpleVT().SimpleTy) { 4194 default: llvm_unreachable("Unhandled argument type!"); 4195 case MVT::i1: 4196 case MVT::i32: 4197 case MVT::f32: 4198 VecArgOffset += 4; 4199 break; 4200 case MVT::i64: // PPC64 4201 case MVT::f64: 4202 // FIXME: We are guaranteed to be !isPPC64 at this point. 4203 // Does MVT::i64 apply? 4204 VecArgOffset += 8; 4205 break; 4206 case MVT::v4f32: 4207 case MVT::v4i32: 4208 case MVT::v8i16: 4209 case MVT::v16i8: 4210 // Nothing to do, we're only looking at Nonvector args here. 4211 break; 4212 } 4213 } 4214 } 4215 // We've found where the vector parameter area in memory is. Skip the 4216 // first 12 parameters; these don't use that memory. 4217 VecArgOffset = ((VecArgOffset+15)/16)*16; 4218 VecArgOffset += 12*16; 4219 4220 // Add DAG nodes to load the arguments or copy them out of registers. On 4221 // entry to a function on PPC, the arguments start after the linkage area, 4222 // although the first ones are often in registers. 4223 4224 SmallVector<SDValue, 8> MemOps; 4225 unsigned nAltivecParamsAtEnd = 0; 4226 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4227 unsigned CurArgIdx = 0; 4228 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4229 SDValue ArgVal; 4230 bool needsLoad = false; 4231 EVT ObjectVT = Ins[ArgNo].VT; 4232 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4233 unsigned ArgSize = ObjSize; 4234 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4235 if (Ins[ArgNo].isOrigArg()) { 4236 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4237 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4238 } 4239 unsigned CurArgOffset = ArgOffset; 4240 4241 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4242 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4243 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4244 if (isVarArg || isPPC64) { 4245 MinReservedArea = ((MinReservedArea+15)/16)*16; 4246 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4247 Flags, 4248 PtrByteSize); 4249 } else nAltivecParamsAtEnd++; 4250 } else 4251 // Calculate min reserved area. 4252 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4253 Flags, 4254 PtrByteSize); 4255 4256 // FIXME the codegen can be much improved in some cases. 4257 // We do not have to keep everything in memory. 4258 if (Flags.isByVal()) { 4259 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4260 4261 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4262 ObjSize = Flags.getByValSize(); 4263 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4264 // Objects of size 1 and 2 are right justified, everything else is 4265 // left justified. This means the memory address is adjusted forwards. 4266 if (ObjSize==1 || ObjSize==2) { 4267 CurArgOffset = CurArgOffset + (4 - ObjSize); 4268 } 4269 // The value of the object is its address. 4270 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4271 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4272 InVals.push_back(FIN); 4273 if (ObjSize==1 || ObjSize==2) { 4274 if (GPR_idx != Num_GPR_Regs) { 4275 unsigned VReg; 4276 if (isPPC64) 4277 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4278 else 4279 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4280 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4281 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4282 SDValue Store = 4283 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4284 MachinePointerInfo(&*FuncArg), ObjType); 4285 MemOps.push_back(Store); 4286 ++GPR_idx; 4287 } 4288 4289 ArgOffset += PtrByteSize; 4290 4291 continue; 4292 } 4293 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4294 // Store whatever pieces of the object are in registers 4295 // to memory. ArgOffset will be the address of the beginning 4296 // of the object. 4297 if (GPR_idx != Num_GPR_Regs) { 4298 unsigned VReg; 4299 if (isPPC64) 4300 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4301 else 4302 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4303 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4304 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4305 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4306 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4307 MachinePointerInfo(&*FuncArg, j)); 4308 MemOps.push_back(Store); 4309 ++GPR_idx; 4310 ArgOffset += PtrByteSize; 4311 } else { 4312 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4313 break; 4314 } 4315 } 4316 continue; 4317 } 4318 4319 switch (ObjectVT.getSimpleVT().SimpleTy) { 4320 default: llvm_unreachable("Unhandled argument type!"); 4321 case MVT::i1: 4322 case MVT::i32: 4323 if (!isPPC64) { 4324 if (GPR_idx != Num_GPR_Regs) { 4325 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4326 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4327 4328 if (ObjectVT == MVT::i1) 4329 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4330 4331 ++GPR_idx; 4332 } else { 4333 needsLoad = true; 4334 ArgSize = PtrByteSize; 4335 } 4336 // All int arguments reserve stack space in the Darwin ABI. 4337 ArgOffset += PtrByteSize; 4338 break; 4339 } 4340 LLVM_FALLTHROUGH; 4341 case MVT::i64: // PPC64 4342 if (GPR_idx != Num_GPR_Regs) { 4343 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4344 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4345 4346 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4347 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4348 // value to MVT::i64 and then truncate to the correct register size. 4349 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4350 4351 ++GPR_idx; 4352 } else { 4353 needsLoad = true; 4354 ArgSize = PtrByteSize; 4355 } 4356 // All int arguments reserve stack space in the Darwin ABI. 4357 ArgOffset += 8; 4358 break; 4359 4360 case MVT::f32: 4361 case MVT::f64: 4362 // Every 4 bytes of argument space consumes one of the GPRs available for 4363 // argument passing. 4364 if (GPR_idx != Num_GPR_Regs) { 4365 ++GPR_idx; 4366 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4367 ++GPR_idx; 4368 } 4369 if (FPR_idx != Num_FPR_Regs) { 4370 unsigned VReg; 4371 4372 if (ObjectVT == MVT::f32) 4373 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4374 else 4375 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4376 4377 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4378 ++FPR_idx; 4379 } else { 4380 needsLoad = true; 4381 } 4382 4383 // All FP arguments reserve stack space in the Darwin ABI. 4384 ArgOffset += isPPC64 ? 8 : ObjSize; 4385 break; 4386 case MVT::v4f32: 4387 case MVT::v4i32: 4388 case MVT::v8i16: 4389 case MVT::v16i8: 4390 // Note that vector arguments in registers don't reserve stack space, 4391 // except in varargs functions. 4392 if (VR_idx != Num_VR_Regs) { 4393 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4394 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4395 if (isVarArg) { 4396 while ((ArgOffset % 16) != 0) { 4397 ArgOffset += PtrByteSize; 4398 if (GPR_idx != Num_GPR_Regs) 4399 GPR_idx++; 4400 } 4401 ArgOffset += 16; 4402 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4403 } 4404 ++VR_idx; 4405 } else { 4406 if (!isVarArg && !isPPC64) { 4407 // Vectors go after all the nonvectors. 4408 CurArgOffset = VecArgOffset; 4409 VecArgOffset += 16; 4410 } else { 4411 // Vectors are aligned. 4412 ArgOffset = ((ArgOffset+15)/16)*16; 4413 CurArgOffset = ArgOffset; 4414 ArgOffset += 16; 4415 } 4416 needsLoad = true; 4417 } 4418 break; 4419 } 4420 4421 // We need to load the argument to a virtual register if we determined above 4422 // that we ran out of physical registers of the appropriate type. 4423 if (needsLoad) { 4424 int FI = MFI.CreateFixedObject(ObjSize, 4425 CurArgOffset + (ArgSize - ObjSize), 4426 isImmutable); 4427 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4428 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4429 } 4430 4431 InVals.push_back(ArgVal); 4432 } 4433 4434 // Allow for Altivec parameters at the end, if needed. 4435 if (nAltivecParamsAtEnd) { 4436 MinReservedArea = ((MinReservedArea+15)/16)*16; 4437 MinReservedArea += 16*nAltivecParamsAtEnd; 4438 } 4439 4440 // Area that is at least reserved in the caller of this function. 4441 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4442 4443 // Set the size that is at least reserved in caller of this function. Tail 4444 // call optimized functions' reserved stack space needs to be aligned so that 4445 // taking the difference between two stack areas will result in an aligned 4446 // stack. 4447 MinReservedArea = 4448 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4449 FuncInfo->setMinReservedArea(MinReservedArea); 4450 4451 // If the function takes variable number of arguments, make a frame index for 4452 // the start of the first vararg value... for expansion of llvm.va_start. 4453 if (isVarArg) { 4454 int Depth = ArgOffset; 4455 4456 FuncInfo->setVarArgsFrameIndex( 4457 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4458 Depth, true)); 4459 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4460 4461 // If this function is vararg, store any remaining integer argument regs 4462 // to their spots on the stack so that they may be loaded by dereferencing 4463 // the result of va_next. 4464 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4465 unsigned VReg; 4466 4467 if (isPPC64) 4468 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4469 else 4470 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4471 4472 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4473 SDValue Store = 4474 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4475 MemOps.push_back(Store); 4476 // Increment the address by four for the next argument to store 4477 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4478 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4479 } 4480 } 4481 4482 if (!MemOps.empty()) 4483 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4484 4485 return Chain; 4486 } 4487 4488 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4489 /// adjusted to accommodate the arguments for the tailcall. 4490 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4491 unsigned ParamSize) { 4492 4493 if (!isTailCall) return 0; 4494 4495 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4496 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4497 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4498 // Remember only if the new adjustment is bigger. 4499 if (SPDiff < FI->getTailCallSPDelta()) 4500 FI->setTailCallSPDelta(SPDiff); 4501 4502 return SPDiff; 4503 } 4504 4505 static bool isFunctionGlobalAddress(SDValue Callee); 4506 4507 static bool 4508 callsShareTOCBase(const Function *Caller, SDValue Callee, 4509 const TargetMachine &TM) { 4510 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4511 // don't have enough information to determine if the caller and calle share 4512 // the same TOC base, so we have to pessimistically assume they don't for 4513 // correctness. 4514 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4515 if (!G) 4516 return false; 4517 4518 const GlobalValue *GV = G->getGlobal(); 4519 // The medium and large code models are expected to provide a sufficiently 4520 // large TOC to provide all data addressing needs of a module with a 4521 // single TOC. Since each module will be addressed with a single TOC then we 4522 // only need to check that caller and callee don't cross dso boundaries. 4523 if (CodeModel::Medium == TM.getCodeModel() || 4524 CodeModel::Large == TM.getCodeModel()) 4525 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4526 4527 // Otherwise we need to ensure callee and caller are in the same section, 4528 // since the linker may allocate multiple TOCs, and we don't know which 4529 // sections will belong to the same TOC base. 4530 4531 if (!GV->isStrongDefinitionForLinker()) 4532 return false; 4533 4534 // Any explicitly-specified sections and section prefixes must also match. 4535 // Also, if we're using -ffunction-sections, then each function is always in 4536 // a different section (the same is true for COMDAT functions). 4537 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4538 GV->getSection() != Caller->getSection()) 4539 return false; 4540 if (const auto *F = dyn_cast<Function>(GV)) { 4541 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4542 return false; 4543 } 4544 4545 // If the callee might be interposed, then we can't assume the ultimate call 4546 // target will be in the same section. Even in cases where we can assume that 4547 // interposition won't happen, in any case where the linker might insert a 4548 // stub to allow for interposition, we must generate code as though 4549 // interposition might occur. To understand why this matters, consider a 4550 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4551 // in the same section, but a is in a different module (i.e. has a different 4552 // TOC base pointer). If the linker allows for interposition between b and c, 4553 // then it will generate a stub for the call edge between b and c which will 4554 // save the TOC pointer into the designated stack slot allocated by b. If we 4555 // return true here, and therefore allow a tail call between b and c, that 4556 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4557 // pointer into the stack slot allocated by a (where the a -> b stub saved 4558 // a's TOC base pointer). If we're not considering a tail call, but rather, 4559 // whether a nop is needed after the call instruction in b, because the linker 4560 // will insert a stub, it might complain about a missing nop if we omit it 4561 // (although many don't complain in this case). 4562 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4563 return false; 4564 4565 return true; 4566 } 4567 4568 static bool 4569 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4570 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4571 assert(Subtarget.is64BitELFABI()); 4572 4573 const unsigned PtrByteSize = 8; 4574 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4575 4576 static const MCPhysReg GPR[] = { 4577 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4578 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4579 }; 4580 static const MCPhysReg VR[] = { 4581 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4582 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4583 }; 4584 4585 const unsigned NumGPRs = array_lengthof(GPR); 4586 const unsigned NumFPRs = 13; 4587 const unsigned NumVRs = array_lengthof(VR); 4588 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4589 4590 unsigned NumBytes = LinkageSize; 4591 unsigned AvailableFPRs = NumFPRs; 4592 unsigned AvailableVRs = NumVRs; 4593 4594 for (const ISD::OutputArg& Param : Outs) { 4595 if (Param.Flags.isNest()) continue; 4596 4597 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4598 PtrByteSize, LinkageSize, ParamAreaSize, 4599 NumBytes, AvailableFPRs, AvailableVRs, 4600 Subtarget.hasQPX())) 4601 return true; 4602 } 4603 return false; 4604 } 4605 4606 static bool 4607 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4608 if (CS.arg_size() != CallerFn->arg_size()) 4609 return false; 4610 4611 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4612 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4613 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4614 4615 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4616 const Value* CalleeArg = *CalleeArgIter; 4617 const Value* CallerArg = &(*CallerArgIter); 4618 if (CalleeArg == CallerArg) 4619 continue; 4620 4621 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4622 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4623 // } 4624 // 1st argument of callee is undef and has the same type as caller. 4625 if (CalleeArg->getType() == CallerArg->getType() && 4626 isa<UndefValue>(CalleeArg)) 4627 continue; 4628 4629 return false; 4630 } 4631 4632 return true; 4633 } 4634 4635 // Returns true if TCO is possible between the callers and callees 4636 // calling conventions. 4637 static bool 4638 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4639 CallingConv::ID CalleeCC) { 4640 // Tail calls are possible with fastcc and ccc. 4641 auto isTailCallableCC = [] (CallingConv::ID CC){ 4642 return CC == CallingConv::C || CC == CallingConv::Fast; 4643 }; 4644 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4645 return false; 4646 4647 // We can safely tail call both fastcc and ccc callees from a c calling 4648 // convention caller. If the caller is fastcc, we may have less stack space 4649 // than a non-fastcc caller with the same signature so disable tail-calls in 4650 // that case. 4651 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4652 } 4653 4654 bool 4655 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4656 SDValue Callee, 4657 CallingConv::ID CalleeCC, 4658 ImmutableCallSite CS, 4659 bool isVarArg, 4660 const SmallVectorImpl<ISD::OutputArg> &Outs, 4661 const SmallVectorImpl<ISD::InputArg> &Ins, 4662 SelectionDAG& DAG) const { 4663 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4664 4665 if (DisableSCO && !TailCallOpt) return false; 4666 4667 // Variadic argument functions are not supported. 4668 if (isVarArg) return false; 4669 4670 auto &Caller = DAG.getMachineFunction().getFunction(); 4671 // Check that the calling conventions are compatible for tco. 4672 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4673 return false; 4674 4675 // Caller contains any byval parameter is not supported. 4676 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4677 return false; 4678 4679 // Callee contains any byval parameter is not supported, too. 4680 // Note: This is a quick work around, because in some cases, e.g. 4681 // caller's stack size > callee's stack size, we are still able to apply 4682 // sibling call optimization. For example, gcc is able to do SCO for caller1 4683 // in the following example, but not for caller2. 4684 // struct test { 4685 // long int a; 4686 // char ary[56]; 4687 // } gTest; 4688 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4689 // b->a = v.a; 4690 // return 0; 4691 // } 4692 // void caller1(struct test a, struct test c, struct test *b) { 4693 // callee(gTest, b); } 4694 // void caller2(struct test *b) { callee(gTest, b); } 4695 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4696 return false; 4697 4698 // If callee and caller use different calling conventions, we cannot pass 4699 // parameters on stack since offsets for the parameter area may be different. 4700 if (Caller.getCallingConv() != CalleeCC && 4701 needStackSlotPassParameters(Subtarget, Outs)) 4702 return false; 4703 4704 // No TCO/SCO on indirect call because Caller have to restore its TOC 4705 if (!isFunctionGlobalAddress(Callee) && 4706 !isa<ExternalSymbolSDNode>(Callee)) 4707 return false; 4708 4709 // If the caller and callee potentially have different TOC bases then we 4710 // cannot tail call since we need to restore the TOC pointer after the call. 4711 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4712 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4713 return false; 4714 4715 // TCO allows altering callee ABI, so we don't have to check further. 4716 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4717 return true; 4718 4719 if (DisableSCO) return false; 4720 4721 // If callee use the same argument list that caller is using, then we can 4722 // apply SCO on this case. If it is not, then we need to check if callee needs 4723 // stack for passing arguments. 4724 if (!hasSameArgumentList(&Caller, CS) && 4725 needStackSlotPassParameters(Subtarget, Outs)) { 4726 return false; 4727 } 4728 4729 return true; 4730 } 4731 4732 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4733 /// for tail call optimization. Targets which want to do tail call 4734 /// optimization should implement this function. 4735 bool 4736 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4737 CallingConv::ID CalleeCC, 4738 bool isVarArg, 4739 const SmallVectorImpl<ISD::InputArg> &Ins, 4740 SelectionDAG& DAG) const { 4741 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4742 return false; 4743 4744 // Variable argument functions are not supported. 4745 if (isVarArg) 4746 return false; 4747 4748 MachineFunction &MF = DAG.getMachineFunction(); 4749 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4750 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4751 // Functions containing by val parameters are not supported. 4752 for (unsigned i = 0; i != Ins.size(); i++) { 4753 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4754 if (Flags.isByVal()) return false; 4755 } 4756 4757 // Non-PIC/GOT tail calls are supported. 4758 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4759 return true; 4760 4761 // At the moment we can only do local tail calls (in same module, hidden 4762 // or protected) if we are generating PIC. 4763 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4764 return G->getGlobal()->hasHiddenVisibility() 4765 || G->getGlobal()->hasProtectedVisibility(); 4766 } 4767 4768 return false; 4769 } 4770 4771 /// isCallCompatibleAddress - Return the immediate to use if the specified 4772 /// 32-bit value is representable in the immediate field of a BxA instruction. 4773 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4774 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4775 if (!C) return nullptr; 4776 4777 int Addr = C->getZExtValue(); 4778 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4779 SignExtend32<26>(Addr) != Addr) 4780 return nullptr; // Top 6 bits have to be sext of immediate. 4781 4782 return DAG 4783 .getConstant( 4784 (int)C->getZExtValue() >> 2, SDLoc(Op), 4785 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4786 .getNode(); 4787 } 4788 4789 namespace { 4790 4791 struct TailCallArgumentInfo { 4792 SDValue Arg; 4793 SDValue FrameIdxOp; 4794 int FrameIdx = 0; 4795 4796 TailCallArgumentInfo() = default; 4797 }; 4798 4799 } // end anonymous namespace 4800 4801 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4802 static void StoreTailCallArgumentsToStackSlot( 4803 SelectionDAG &DAG, SDValue Chain, 4804 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4805 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4806 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4807 SDValue Arg = TailCallArgs[i].Arg; 4808 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4809 int FI = TailCallArgs[i].FrameIdx; 4810 // Store relative to framepointer. 4811 MemOpChains.push_back(DAG.getStore( 4812 Chain, dl, Arg, FIN, 4813 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4814 } 4815 } 4816 4817 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4818 /// the appropriate stack slot for the tail call optimized function call. 4819 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4820 SDValue OldRetAddr, SDValue OldFP, 4821 int SPDiff, const SDLoc &dl) { 4822 if (SPDiff) { 4823 // Calculate the new stack slot for the return address. 4824 MachineFunction &MF = DAG.getMachineFunction(); 4825 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4826 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4827 bool isPPC64 = Subtarget.isPPC64(); 4828 int SlotSize = isPPC64 ? 8 : 4; 4829 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4830 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4831 NewRetAddrLoc, true); 4832 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4833 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4834 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4835 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4836 4837 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4838 // slot as the FP is never overwritten. 4839 if (Subtarget.isDarwinABI()) { 4840 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4841 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4842 true); 4843 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4844 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4845 MachinePointerInfo::getFixedStack( 4846 DAG.getMachineFunction(), NewFPIdx)); 4847 } 4848 } 4849 return Chain; 4850 } 4851 4852 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4853 /// the position of the argument. 4854 static void 4855 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4856 SDValue Arg, int SPDiff, unsigned ArgOffset, 4857 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4858 int Offset = ArgOffset + SPDiff; 4859 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4860 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4861 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4862 SDValue FIN = DAG.getFrameIndex(FI, VT); 4863 TailCallArgumentInfo Info; 4864 Info.Arg = Arg; 4865 Info.FrameIdxOp = FIN; 4866 Info.FrameIdx = FI; 4867 TailCallArguments.push_back(Info); 4868 } 4869 4870 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4871 /// stack slot. Returns the chain as result and the loaded frame pointers in 4872 /// LROpOut/FPOpout. Used when tail calling. 4873 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4874 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4875 SDValue &FPOpOut, const SDLoc &dl) const { 4876 if (SPDiff) { 4877 // Load the LR and FP stack slot for later adjusting. 4878 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4879 LROpOut = getReturnAddrFrameIndex(DAG); 4880 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4881 Chain = SDValue(LROpOut.getNode(), 1); 4882 4883 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4884 // slot as the FP is never overwritten. 4885 if (Subtarget.isDarwinABI()) { 4886 FPOpOut = getFramePointerFrameIndex(DAG); 4887 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4888 Chain = SDValue(FPOpOut.getNode(), 1); 4889 } 4890 } 4891 return Chain; 4892 } 4893 4894 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4895 /// by "Src" to address "Dst" of size "Size". Alignment information is 4896 /// specified by the specific parameter attribute. The copy will be passed as 4897 /// a byval function parameter. 4898 /// Sometimes what we are copying is the end of a larger object, the part that 4899 /// does not fit in registers. 4900 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4901 SDValue Chain, ISD::ArgFlagsTy Flags, 4902 SelectionDAG &DAG, const SDLoc &dl) { 4903 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4904 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4905 false, false, false, MachinePointerInfo(), 4906 MachinePointerInfo()); 4907 } 4908 4909 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4910 /// tail calls. 4911 static void LowerMemOpCallTo( 4912 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4913 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4914 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4915 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4916 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4917 if (!isTailCall) { 4918 if (isVector) { 4919 SDValue StackPtr; 4920 if (isPPC64) 4921 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4922 else 4923 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4924 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4925 DAG.getConstant(ArgOffset, dl, PtrVT)); 4926 } 4927 MemOpChains.push_back( 4928 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4929 // Calculate and remember argument location. 4930 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4931 TailCallArguments); 4932 } 4933 4934 static void 4935 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4936 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4937 SDValue FPOp, 4938 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4939 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4940 // might overwrite each other in case of tail call optimization. 4941 SmallVector<SDValue, 8> MemOpChains2; 4942 // Do not flag preceding copytoreg stuff together with the following stuff. 4943 InFlag = SDValue(); 4944 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4945 MemOpChains2, dl); 4946 if (!MemOpChains2.empty()) 4947 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4948 4949 // Store the return address to the appropriate stack slot. 4950 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4951 4952 // Emit callseq_end just before tailcall node. 4953 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4954 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4955 InFlag = Chain.getValue(1); 4956 } 4957 4958 // Is this global address that of a function that can be called by name? (as 4959 // opposed to something that must hold a descriptor for an indirect call). 4960 static bool isFunctionGlobalAddress(SDValue Callee) { 4961 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4962 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4963 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4964 return false; 4965 4966 return G->getGlobal()->getValueType()->isFunctionTy(); 4967 } 4968 4969 return false; 4970 } 4971 4972 SDValue PPCTargetLowering::LowerCallResult( 4973 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4974 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4975 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4976 SmallVector<CCValAssign, 16> RVLocs; 4977 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4978 *DAG.getContext()); 4979 4980 CCRetInfo.AnalyzeCallResult( 4981 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 4982 ? RetCC_PPC_Cold 4983 : RetCC_PPC); 4984 4985 // Copy all of the result registers out of their specified physreg. 4986 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4987 CCValAssign &VA = RVLocs[i]; 4988 assert(VA.isRegLoc() && "Can only return in registers!"); 4989 4990 SDValue Val; 4991 4992 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 4993 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4994 InFlag); 4995 Chain = Lo.getValue(1); 4996 InFlag = Lo.getValue(2); 4997 VA = RVLocs[++i]; // skip ahead to next loc 4998 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4999 InFlag); 5000 Chain = Hi.getValue(1); 5001 InFlag = Hi.getValue(2); 5002 if (!Subtarget.isLittleEndian()) 5003 std::swap (Lo, Hi); 5004 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5005 } else { 5006 Val = DAG.getCopyFromReg(Chain, dl, 5007 VA.getLocReg(), VA.getLocVT(), InFlag); 5008 Chain = Val.getValue(1); 5009 InFlag = Val.getValue(2); 5010 } 5011 5012 switch (VA.getLocInfo()) { 5013 default: llvm_unreachable("Unknown loc info!"); 5014 case CCValAssign::Full: break; 5015 case CCValAssign::AExt: 5016 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5017 break; 5018 case CCValAssign::ZExt: 5019 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5020 DAG.getValueType(VA.getValVT())); 5021 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5022 break; 5023 case CCValAssign::SExt: 5024 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5025 DAG.getValueType(VA.getValVT())); 5026 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5027 break; 5028 } 5029 5030 InVals.push_back(Val); 5031 } 5032 5033 return Chain; 5034 } 5035 5036 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5037 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5038 // PatchPoint calls are not indirect. 5039 if (isPatchPoint) 5040 return false; 5041 5042 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5043 return false; 5044 5045 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5046 // becuase the immediate function pointer points to a descriptor instead of 5047 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5048 // pointer immediate points to the global entry point, while the BLA would 5049 // need to jump to the local entry point (see rL211174). 5050 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5051 isBLACompatibleAddress(Callee, DAG)) 5052 return false; 5053 5054 return true; 5055 } 5056 5057 static unsigned getCallOpcode(bool isIndirectCall, bool isPatchPoint, 5058 bool isTailCall, const Function &Caller, 5059 const SDValue &Callee, 5060 const PPCSubtarget &Subtarget, 5061 const TargetMachine &TM) { 5062 if (isTailCall) 5063 return PPCISD::TC_RETURN; 5064 5065 // This is a call through a function pointer. 5066 if (isIndirectCall) { 5067 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5068 // indirect calls. The save of the caller's TOC pointer to the stack will be 5069 // inserted into the DAG as part of call lowering. The restore of the TOC 5070 // pointer is modeled by using a pseudo instruction for the call opcode that 5071 // represents the 2 instruction sequence of an indirect branch and link, 5072 // immediately followed by a load of the TOC pointer from the the stack save 5073 // slot into gpr2. 5074 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5075 return PPCISD::BCTRL_LOAD_TOC; 5076 5077 // An indirect call that does not need a TOC restore. 5078 return PPCISD::BCTRL; 5079 } 5080 5081 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5082 // immediately following the call instruction if the caller and callee may 5083 // have different TOC bases. At link time if the linker determines the calls 5084 // may not share a TOC base, the call is redirected to a trampoline inserted 5085 // by the linker. The trampoline will (among other things) save the callers 5086 // TOC pointer at an ABI designated offset in the linkage area and the linker 5087 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5088 // into gpr2. 5089 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5090 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5091 : PPCISD::CALL_NOP; 5092 5093 return PPCISD::CALL; 5094 } 5095 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5096 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5097 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5098 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5099 return SDValue(Dest, 0); 5100 5101 // Returns true if the callee is local, and false otherwise. 5102 auto isLocalCallee = [&]() { 5103 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5104 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5105 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5106 5107 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5108 !dyn_cast_or_null<GlobalIFunc>(GV); 5109 }; 5110 5111 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5112 // a static relocation model causes some versions of GNU LD (2.17.50, at 5113 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5114 // built with secure-PLT. 5115 bool UsePlt = 5116 Subtarget.is32BitELFABI() && !isLocalCallee() && 5117 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5118 5119 if (isFunctionGlobalAddress(Callee)) { 5120 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5121 if (!Subtarget.isAIXABI()) 5122 return DAG.getTargetGlobalAddress(G->getGlobal(), dl, 5123 Callee.getValueType(), 0, 5124 UsePlt ? PPCII::MO_PLT : 0); 5125 5126 // On AIX, direct function calls reference the symbol for the function's 5127 // entry point, which is named by prepending a "." before the function's 5128 // C-linkage name. 5129 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5130 5131 const GlobalObject *GO = cast<GlobalObject>(G->getGlobal()); 5132 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5133 Context.getOrCreateSymbol(Twine(".") + Twine(GO->getName()))); 5134 5135 if (GO && GO->isDeclaration() && !S->hasContainingCsect()) { 5136 // On AIX, an undefined symbol needs to be associated with a 5137 // MCSectionXCOFF to get the correct storage mapping class. 5138 // In this case, XCOFF::XMC_PR. 5139 const XCOFF::StorageClass SC = 5140 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5141 MCSectionXCOFF *Sec = 5142 Context.getXCOFFSection(S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, 5143 SC, SectionKind::getMetadata()); 5144 S->setContainingCsect(Sec); 5145 } 5146 5147 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5148 return DAG.getMCSymbol(S, PtrVT); 5149 } 5150 5151 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) 5152 return DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 5153 UsePlt ? PPCII::MO_PLT : 0); 5154 5155 // No transformation needed. 5156 assert(Callee.getNode() && "What no callee?"); 5157 return Callee; 5158 } 5159 5160 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5161 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5162 "Expected a CALLSEQ_STARTSDNode."); 5163 5164 // The last operand is the chain, except when the node has glue. If the node 5165 // has glue, then the last operand is the glue, and the chain is the second 5166 // last operand. 5167 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5168 if (LastValue.getValueType() != MVT::Glue) 5169 return LastValue; 5170 5171 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5172 } 5173 5174 // Creates the node that moves a functions address into the count register 5175 // to prepare for an indirect call instruction. 5176 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5177 SDValue &Glue, SDValue &Chain, 5178 const SDLoc &dl) { 5179 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5180 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5181 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5182 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5183 // The glue is the second value produced. 5184 Glue = Chain.getValue(1); 5185 } 5186 5187 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5188 SDValue &Glue, SDValue &Chain, 5189 SDValue CallSeqStart, 5190 ImmutableCallSite CS, const SDLoc &dl, 5191 bool hasNest, 5192 const PPCSubtarget &Subtarget) { 5193 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5194 // entry point, but to the function descriptor (the function entry point 5195 // address is part of the function descriptor though). 5196 // The function descriptor is a three doubleword structure with the 5197 // following fields: function entry point, TOC base address and 5198 // environment pointer. 5199 // Thus for a call through a function pointer, the following actions need 5200 // to be performed: 5201 // 1. Save the TOC of the caller in the TOC save area of its stack 5202 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5203 // 2. Load the address of the function entry point from the function 5204 // descriptor. 5205 // 3. Load the TOC of the callee from the function descriptor into r2. 5206 // 4. Load the environment pointer from the function descriptor into 5207 // r11. 5208 // 5. Branch to the function entry point address. 5209 // 6. On return of the callee, the TOC of the caller needs to be 5210 // restored (this is done in FinishCall()). 5211 // 5212 // The loads are scheduled at the beginning of the call sequence, and the 5213 // register copies are flagged together to ensure that no other 5214 // operations can be scheduled in between. E.g. without flagging the 5215 // copies together, a TOC access in the caller could be scheduled between 5216 // the assignment of the callee TOC and the branch to the callee, which leads 5217 // to incorrect code. 5218 5219 // Start by loading the function address from the descriptor. 5220 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5221 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5222 ? (MachineMemOperand::MODereferenceable | 5223 MachineMemOperand::MOInvariant) 5224 : MachineMemOperand::MONone; 5225 5226 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5227 5228 // Registers used in building the DAG. 5229 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5230 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5231 5232 // Offsets of descriptor members. 5233 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5234 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5235 5236 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5237 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5238 5239 // One load for the functions entry point address. 5240 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5241 Alignment, MMOFlags); 5242 5243 // One for loading the TOC anchor for the module that contains the called 5244 // function. 5245 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5246 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5247 SDValue TOCPtr = 5248 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5249 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5250 5251 // One for loading the environment pointer. 5252 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5253 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5254 SDValue LoadEnvPtr = 5255 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5256 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5257 5258 5259 // Then copy the newly loaded TOC anchor to the TOC pointer. 5260 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5261 Chain = TOCVal.getValue(0); 5262 Glue = TOCVal.getValue(1); 5263 5264 // If the function call has an explicit 'nest' parameter, it takes the 5265 // place of the environment pointer. 5266 assert((!hasNest || !Subtarget.isAIXABI()) && 5267 "Nest parameter is not supported on AIX."); 5268 if (!hasNest) { 5269 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5270 Chain = EnvVal.getValue(0); 5271 Glue = EnvVal.getValue(1); 5272 } 5273 5274 // The rest of the indirect call sequence is the same as the non-descriptor 5275 // DAG. 5276 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5277 } 5278 5279 static void 5280 buildCallOperands(SmallVectorImpl<SDValue> &Ops, CallingConv::ID CallConv, 5281 const SDLoc &dl, bool isTailCall, bool isVarArg, 5282 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5283 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5284 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5285 const PPCSubtarget &Subtarget, bool isIndirect) { 5286 const bool IsPPC64 = Subtarget.isPPC64(); 5287 // MVT for a general purpose register. 5288 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5289 5290 // First operand is always the chain. 5291 Ops.push_back(Chain); 5292 5293 // If it's a direct call pass the callee as the second operand. 5294 if (!isIndirect) 5295 Ops.push_back(Callee); 5296 else { 5297 assert(!isPatchPoint && "Patch point call are not indirect."); 5298 5299 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5300 // on the stack (this would have been done in `LowerCall_64SVR4` or 5301 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5302 // represents both the indirect branch and a load that restores the TOC 5303 // pointer from the linkage area. The operand for the TOC restore is an add 5304 // of the TOC save offset to the stack pointer. This must be the second 5305 // operand: after the chain input but before any other variadic arguments. 5306 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 5307 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5308 5309 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5310 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5311 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5312 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5313 Ops.push_back(AddTOC); 5314 } 5315 5316 // Add the register used for the environment pointer. 5317 if (Subtarget.usesFunctionDescriptors() && !hasNest) 5318 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5319 RegVT)); 5320 5321 5322 // Add CTR register as callee so a bctr can be emitted later. 5323 if (isTailCall) 5324 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5325 } 5326 5327 // If this is a tail call add stack pointer delta. 5328 if (isTailCall) 5329 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5330 5331 // Add argument registers to the end of the list so that they are known live 5332 // into the call. 5333 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5334 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5335 RegsToPass[i].second.getValueType())); 5336 5337 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5338 // no way to mark dependencies as implicit here. 5339 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5340 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && !isPatchPoint) 5341 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5342 5343 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5344 if (isVarArg && Subtarget.is32BitELFABI()) 5345 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5346 5347 // Add a register mask operand representing the call-preserved registers. 5348 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5349 const uint32_t *Mask = 5350 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5351 assert(Mask && "Missing call preserved mask for calling convention"); 5352 Ops.push_back(DAG.getRegisterMask(Mask)); 5353 5354 // If the glue is valid, it is the last operand. 5355 if (Glue.getNode()) 5356 Ops.push_back(Glue); 5357 } 5358 5359 SDValue PPCTargetLowering::FinishCall( 5360 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5361 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5362 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5363 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5364 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5365 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5366 5367 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) 5368 setUsesTOCBasePtr(DAG); 5369 5370 const bool isIndirect = isIndirectCall(Callee, DAG, Subtarget, isPatchPoint); 5371 unsigned CallOpc = getCallOpcode(isIndirect, isPatchPoint, isTailCall, 5372 DAG.getMachineFunction().getFunction(), 5373 Callee, Subtarget, DAG.getTarget()); 5374 5375 if (!isIndirect) 5376 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5377 else if (Subtarget.usesFunctionDescriptors()) 5378 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS, 5379 dl, hasNest, Subtarget); 5380 else 5381 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5382 5383 // Build the operand list for the call instruction. 5384 SmallVector<SDValue, 8> Ops; 5385 buildCallOperands(Ops, CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5386 hasNest, DAG, RegsToPass, Glue, Chain, Callee, SPDiff, 5387 Subtarget, isIndirect); 5388 5389 // Emit tail call. 5390 if (isTailCall) { 5391 assert(((Callee.getOpcode() == ISD::Register && 5392 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5393 Callee.getOpcode() == ISD::TargetExternalSymbol || 5394 Callee.getOpcode() == ISD::TargetGlobalAddress || 5395 isa<ConstantSDNode>(Callee)) && 5396 "Expecting a global address, external symbol, absolute value or " 5397 "register"); 5398 assert(CallOpc == PPCISD::TC_RETURN && 5399 "Unexpected call opcode for a tail call."); 5400 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5401 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5402 } 5403 5404 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5405 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5406 Glue = Chain.getValue(1); 5407 5408 // When performing tail call optimization the callee pops its arguments off 5409 // the stack. Account for this here so these bytes can be pushed back on in 5410 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5411 int BytesCalleePops = (CallConv == CallingConv::Fast && 5412 getTargetMachine().Options.GuaranteedTailCallOpt) 5413 ? NumBytes 5414 : 0; 5415 5416 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5417 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5418 Glue, dl); 5419 Glue = Chain.getValue(1); 5420 5421 return LowerCallResult(Chain, Glue, CallConv, isVarArg, Ins, dl, DAG, InVals); 5422 } 5423 5424 SDValue 5425 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5426 SmallVectorImpl<SDValue> &InVals) const { 5427 SelectionDAG &DAG = CLI.DAG; 5428 SDLoc &dl = CLI.DL; 5429 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5430 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5431 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5432 SDValue Chain = CLI.Chain; 5433 SDValue Callee = CLI.Callee; 5434 bool &isTailCall = CLI.IsTailCall; 5435 CallingConv::ID CallConv = CLI.CallConv; 5436 bool isVarArg = CLI.IsVarArg; 5437 bool isPatchPoint = CLI.IsPatchPoint; 5438 ImmutableCallSite CS = CLI.CS; 5439 5440 if (isTailCall) { 5441 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5442 isTailCall = false; 5443 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5444 isTailCall = 5445 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5446 isVarArg, Outs, Ins, DAG); 5447 else 5448 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5449 Ins, DAG); 5450 if (isTailCall) { 5451 ++NumTailCalls; 5452 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5453 ++NumSiblingCalls; 5454 5455 assert(isa<GlobalAddressSDNode>(Callee) && 5456 "Callee should be an llvm::Function object."); 5457 LLVM_DEBUG( 5458 const GlobalValue *GV = 5459 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5460 const unsigned Width = 5461 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5462 dbgs() << "TCO caller: " 5463 << left_justify(DAG.getMachineFunction().getName(), Width) 5464 << ", callee linkage: " << GV->getVisibility() << ", " 5465 << GV->getLinkage() << "\n"); 5466 } 5467 } 5468 5469 if (!isTailCall && CS && CS.isMustTailCall()) 5470 report_fatal_error("failed to perform tail call elimination on a call " 5471 "site marked musttail"); 5472 5473 // When long calls (i.e. indirect calls) are always used, calls are always 5474 // made via function pointer. If we have a function name, first translate it 5475 // into a pointer. 5476 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5477 !isTailCall) 5478 Callee = LowerGlobalAddress(Callee, DAG); 5479 5480 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5481 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5482 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5483 dl, DAG, InVals, CS); 5484 5485 if (Subtarget.isSVR4ABI()) 5486 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5487 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5488 dl, DAG, InVals, CS); 5489 5490 if (Subtarget.isAIXABI()) 5491 return LowerCall_AIX(Chain, Callee, CallConv, isVarArg, 5492 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5493 dl, DAG, InVals, CS); 5494 5495 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5496 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5497 dl, DAG, InVals, CS); 5498 } 5499 5500 SDValue PPCTargetLowering::LowerCall_32SVR4( 5501 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5502 bool isTailCall, bool isPatchPoint, 5503 const SmallVectorImpl<ISD::OutputArg> &Outs, 5504 const SmallVectorImpl<SDValue> &OutVals, 5505 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5506 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5507 ImmutableCallSite CS) const { 5508 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5509 // of the 32-bit SVR4 ABI stack frame layout. 5510 5511 assert((CallConv == CallingConv::C || 5512 CallConv == CallingConv::Cold || 5513 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5514 5515 unsigned PtrByteSize = 4; 5516 5517 MachineFunction &MF = DAG.getMachineFunction(); 5518 5519 // Mark this function as potentially containing a function that contains a 5520 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5521 // and restoring the callers stack pointer in this functions epilog. This is 5522 // done because by tail calling the called function might overwrite the value 5523 // in this function's (MF) stack pointer stack slot 0(SP). 5524 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5525 CallConv == CallingConv::Fast) 5526 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5527 5528 // Count how many bytes are to be pushed on the stack, including the linkage 5529 // area, parameter list area and the part of the local variable space which 5530 // contains copies of aggregates which are passed by value. 5531 5532 // Assign locations to all of the outgoing arguments. 5533 SmallVector<CCValAssign, 16> ArgLocs; 5534 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5535 5536 // Reserve space for the linkage area on the stack. 5537 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5538 PtrByteSize); 5539 if (useSoftFloat()) 5540 CCInfo.PreAnalyzeCallOperands(Outs); 5541 5542 if (isVarArg) { 5543 // Handle fixed and variable vector arguments differently. 5544 // Fixed vector arguments go into registers as long as registers are 5545 // available. Variable vector arguments always go into memory. 5546 unsigned NumArgs = Outs.size(); 5547 5548 for (unsigned i = 0; i != NumArgs; ++i) { 5549 MVT ArgVT = Outs[i].VT; 5550 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5551 bool Result; 5552 5553 if (Outs[i].IsFixed) { 5554 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5555 CCInfo); 5556 } else { 5557 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5558 ArgFlags, CCInfo); 5559 } 5560 5561 if (Result) { 5562 #ifndef NDEBUG 5563 errs() << "Call operand #" << i << " has unhandled type " 5564 << EVT(ArgVT).getEVTString() << "\n"; 5565 #endif 5566 llvm_unreachable(nullptr); 5567 } 5568 } 5569 } else { 5570 // All arguments are treated the same. 5571 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5572 } 5573 CCInfo.clearWasPPCF128(); 5574 5575 // Assign locations to all of the outgoing aggregate by value arguments. 5576 SmallVector<CCValAssign, 16> ByValArgLocs; 5577 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5578 5579 // Reserve stack space for the allocations in CCInfo. 5580 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5581 5582 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5583 5584 // Size of the linkage area, parameter list area and the part of the local 5585 // space variable where copies of aggregates which are passed by value are 5586 // stored. 5587 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5588 5589 // Calculate by how many bytes the stack has to be adjusted in case of tail 5590 // call optimization. 5591 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5592 5593 // Adjust the stack pointer for the new arguments... 5594 // These operations are automatically eliminated by the prolog/epilog pass 5595 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5596 SDValue CallSeqStart = Chain; 5597 5598 // Load the return address and frame pointer so it can be moved somewhere else 5599 // later. 5600 SDValue LROp, FPOp; 5601 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5602 5603 // Set up a copy of the stack pointer for use loading and storing any 5604 // arguments that may not fit in the registers available for argument 5605 // passing. 5606 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5607 5608 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5609 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5610 SmallVector<SDValue, 8> MemOpChains; 5611 5612 bool seenFloatArg = false; 5613 // Walk the register/memloc assignments, inserting copies/loads. 5614 // i - Tracks the index into the list of registers allocated for the call 5615 // RealArgIdx - Tracks the index into the list of actual function arguments 5616 // j - Tracks the index into the list of byval arguments 5617 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5618 i != e; 5619 ++i, ++RealArgIdx) { 5620 CCValAssign &VA = ArgLocs[i]; 5621 SDValue Arg = OutVals[RealArgIdx]; 5622 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5623 5624 if (Flags.isByVal()) { 5625 // Argument is an aggregate which is passed by value, thus we need to 5626 // create a copy of it in the local variable space of the current stack 5627 // frame (which is the stack frame of the caller) and pass the address of 5628 // this copy to the callee. 5629 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5630 CCValAssign &ByValVA = ByValArgLocs[j++]; 5631 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5632 5633 // Memory reserved in the local variable space of the callers stack frame. 5634 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5635 5636 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5637 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5638 StackPtr, PtrOff); 5639 5640 // Create a copy of the argument in the local area of the current 5641 // stack frame. 5642 SDValue MemcpyCall = 5643 CreateCopyOfByValArgument(Arg, PtrOff, 5644 CallSeqStart.getNode()->getOperand(0), 5645 Flags, DAG, dl); 5646 5647 // This must go outside the CALLSEQ_START..END. 5648 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5649 SDLoc(MemcpyCall)); 5650 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5651 NewCallSeqStart.getNode()); 5652 Chain = CallSeqStart = NewCallSeqStart; 5653 5654 // Pass the address of the aggregate copy on the stack either in a 5655 // physical register or in the parameter list area of the current stack 5656 // frame to the callee. 5657 Arg = PtrOff; 5658 } 5659 5660 // When useCRBits() is true, there can be i1 arguments. 5661 // It is because getRegisterType(MVT::i1) => MVT::i1, 5662 // and for other integer types getRegisterType() => MVT::i32. 5663 // Extend i1 and ensure callee will get i32. 5664 if (Arg.getValueType() == MVT::i1) 5665 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5666 dl, MVT::i32, Arg); 5667 5668 if (VA.isRegLoc()) { 5669 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5670 // Put argument in a physical register. 5671 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5672 bool IsLE = Subtarget.isLittleEndian(); 5673 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5674 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5675 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5676 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5677 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5678 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5679 SVal.getValue(0))); 5680 } else 5681 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5682 } else { 5683 // Put argument in the parameter list area of the current stack frame. 5684 assert(VA.isMemLoc()); 5685 unsigned LocMemOffset = VA.getLocMemOffset(); 5686 5687 if (!isTailCall) { 5688 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5689 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5690 StackPtr, PtrOff); 5691 5692 MemOpChains.push_back( 5693 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5694 } else { 5695 // Calculate and remember argument location. 5696 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5697 TailCallArguments); 5698 } 5699 } 5700 } 5701 5702 if (!MemOpChains.empty()) 5703 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5704 5705 // Build a sequence of copy-to-reg nodes chained together with token chain 5706 // and flag operands which copy the outgoing args into the appropriate regs. 5707 SDValue InFlag; 5708 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5709 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5710 RegsToPass[i].second, InFlag); 5711 InFlag = Chain.getValue(1); 5712 } 5713 5714 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5715 // registers. 5716 if (isVarArg) { 5717 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5718 SDValue Ops[] = { Chain, InFlag }; 5719 5720 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5721 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5722 5723 InFlag = Chain.getValue(1); 5724 } 5725 5726 if (isTailCall) 5727 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5728 TailCallArguments); 5729 5730 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5731 /* unused except on PPC64 ELFv1 */ false, DAG, 5732 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5733 NumBytes, Ins, InVals, CS); 5734 } 5735 5736 // Copy an argument into memory, being careful to do this outside the 5737 // call sequence for the call to which the argument belongs. 5738 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5739 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5740 SelectionDAG &DAG, const SDLoc &dl) const { 5741 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5742 CallSeqStart.getNode()->getOperand(0), 5743 Flags, DAG, dl); 5744 // The MEMCPY must go outside the CALLSEQ_START..END. 5745 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5746 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5747 SDLoc(MemcpyCall)); 5748 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5749 NewCallSeqStart.getNode()); 5750 return NewCallSeqStart; 5751 } 5752 5753 SDValue PPCTargetLowering::LowerCall_64SVR4( 5754 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5755 bool isTailCall, bool isPatchPoint, 5756 const SmallVectorImpl<ISD::OutputArg> &Outs, 5757 const SmallVectorImpl<SDValue> &OutVals, 5758 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5759 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5760 ImmutableCallSite CS) const { 5761 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5762 bool isLittleEndian = Subtarget.isLittleEndian(); 5763 unsigned NumOps = Outs.size(); 5764 bool hasNest = false; 5765 bool IsSibCall = false; 5766 5767 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5768 unsigned PtrByteSize = 8; 5769 5770 MachineFunction &MF = DAG.getMachineFunction(); 5771 5772 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5773 IsSibCall = true; 5774 5775 // Mark this function as potentially containing a function that contains a 5776 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5777 // and restoring the callers stack pointer in this functions epilog. This is 5778 // done because by tail calling the called function might overwrite the value 5779 // in this function's (MF) stack pointer stack slot 0(SP). 5780 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5781 CallConv == CallingConv::Fast) 5782 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5783 5784 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5785 "fastcc not supported on varargs functions"); 5786 5787 // Count how many bytes are to be pushed on the stack, including the linkage 5788 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5789 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5790 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5791 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5792 unsigned NumBytes = LinkageSize; 5793 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5794 unsigned &QFPR_idx = FPR_idx; 5795 5796 static const MCPhysReg GPR[] = { 5797 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5798 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5799 }; 5800 static const MCPhysReg VR[] = { 5801 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5802 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5803 }; 5804 5805 const unsigned NumGPRs = array_lengthof(GPR); 5806 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5807 const unsigned NumVRs = array_lengthof(VR); 5808 const unsigned NumQFPRs = NumFPRs; 5809 5810 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5811 // can be passed to the callee in registers. 5812 // For the fast calling convention, there is another check below. 5813 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5814 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5815 if (!HasParameterArea) { 5816 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5817 unsigned AvailableFPRs = NumFPRs; 5818 unsigned AvailableVRs = NumVRs; 5819 unsigned NumBytesTmp = NumBytes; 5820 for (unsigned i = 0; i != NumOps; ++i) { 5821 if (Outs[i].Flags.isNest()) continue; 5822 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5823 PtrByteSize, LinkageSize, ParamAreaSize, 5824 NumBytesTmp, AvailableFPRs, AvailableVRs, 5825 Subtarget.hasQPX())) 5826 HasParameterArea = true; 5827 } 5828 } 5829 5830 // When using the fast calling convention, we don't provide backing for 5831 // arguments that will be in registers. 5832 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5833 5834 // Avoid allocating parameter area for fastcc functions if all the arguments 5835 // can be passed in the registers. 5836 if (CallConv == CallingConv::Fast) 5837 HasParameterArea = false; 5838 5839 // Add up all the space actually used. 5840 for (unsigned i = 0; i != NumOps; ++i) { 5841 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5842 EVT ArgVT = Outs[i].VT; 5843 EVT OrigVT = Outs[i].ArgVT; 5844 5845 if (Flags.isNest()) 5846 continue; 5847 5848 if (CallConv == CallingConv::Fast) { 5849 if (Flags.isByVal()) { 5850 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5851 if (NumGPRsUsed > NumGPRs) 5852 HasParameterArea = true; 5853 } else { 5854 switch (ArgVT.getSimpleVT().SimpleTy) { 5855 default: llvm_unreachable("Unexpected ValueType for argument!"); 5856 case MVT::i1: 5857 case MVT::i32: 5858 case MVT::i64: 5859 if (++NumGPRsUsed <= NumGPRs) 5860 continue; 5861 break; 5862 case MVT::v4i32: 5863 case MVT::v8i16: 5864 case MVT::v16i8: 5865 case MVT::v2f64: 5866 case MVT::v2i64: 5867 case MVT::v1i128: 5868 case MVT::f128: 5869 if (++NumVRsUsed <= NumVRs) 5870 continue; 5871 break; 5872 case MVT::v4f32: 5873 // When using QPX, this is handled like a FP register, otherwise, it 5874 // is an Altivec register. 5875 if (Subtarget.hasQPX()) { 5876 if (++NumFPRsUsed <= NumFPRs) 5877 continue; 5878 } else { 5879 if (++NumVRsUsed <= NumVRs) 5880 continue; 5881 } 5882 break; 5883 case MVT::f32: 5884 case MVT::f64: 5885 case MVT::v4f64: // QPX 5886 case MVT::v4i1: // QPX 5887 if (++NumFPRsUsed <= NumFPRs) 5888 continue; 5889 break; 5890 } 5891 HasParameterArea = true; 5892 } 5893 } 5894 5895 /* Respect alignment of argument on the stack. */ 5896 unsigned Align = 5897 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5898 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5899 5900 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5901 if (Flags.isInConsecutiveRegsLast()) 5902 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5903 } 5904 5905 unsigned NumBytesActuallyUsed = NumBytes; 5906 5907 // In the old ELFv1 ABI, 5908 // the prolog code of the callee may store up to 8 GPR argument registers to 5909 // the stack, allowing va_start to index over them in memory if its varargs. 5910 // Because we cannot tell if this is needed on the caller side, we have to 5911 // conservatively assume that it is needed. As such, make sure we have at 5912 // least enough stack space for the caller to store the 8 GPRs. 5913 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5914 // really requires memory operands, e.g. a vararg function. 5915 if (HasParameterArea) 5916 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5917 else 5918 NumBytes = LinkageSize; 5919 5920 // Tail call needs the stack to be aligned. 5921 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5922 CallConv == CallingConv::Fast) 5923 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5924 5925 int SPDiff = 0; 5926 5927 // Calculate by how many bytes the stack has to be adjusted in case of tail 5928 // call optimization. 5929 if (!IsSibCall) 5930 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5931 5932 // To protect arguments on the stack from being clobbered in a tail call, 5933 // force all the loads to happen before doing any other lowering. 5934 if (isTailCall) 5935 Chain = DAG.getStackArgumentTokenFactor(Chain); 5936 5937 // Adjust the stack pointer for the new arguments... 5938 // These operations are automatically eliminated by the prolog/epilog pass 5939 if (!IsSibCall) 5940 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5941 SDValue CallSeqStart = Chain; 5942 5943 // Load the return address and frame pointer so it can be move somewhere else 5944 // later. 5945 SDValue LROp, FPOp; 5946 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5947 5948 // Set up a copy of the stack pointer for use loading and storing any 5949 // arguments that may not fit in the registers available for argument 5950 // passing. 5951 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5952 5953 // Figure out which arguments are going to go in registers, and which in 5954 // memory. Also, if this is a vararg function, floating point operations 5955 // must be stored to our stack, and loaded into integer regs as well, if 5956 // any integer regs are available for argument passing. 5957 unsigned ArgOffset = LinkageSize; 5958 5959 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5960 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5961 5962 SmallVector<SDValue, 8> MemOpChains; 5963 for (unsigned i = 0; i != NumOps; ++i) { 5964 SDValue Arg = OutVals[i]; 5965 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5966 EVT ArgVT = Outs[i].VT; 5967 EVT OrigVT = Outs[i].ArgVT; 5968 5969 // PtrOff will be used to store the current argument to the stack if a 5970 // register cannot be found for it. 5971 SDValue PtrOff; 5972 5973 // We re-align the argument offset for each argument, except when using the 5974 // fast calling convention, when we need to make sure we do that only when 5975 // we'll actually use a stack slot. 5976 auto ComputePtrOff = [&]() { 5977 /* Respect alignment of argument on the stack. */ 5978 unsigned Align = 5979 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5980 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5981 5982 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5983 5984 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5985 }; 5986 5987 if (CallConv != CallingConv::Fast) { 5988 ComputePtrOff(); 5989 5990 /* Compute GPR index associated with argument offset. */ 5991 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5992 GPR_idx = std::min(GPR_idx, NumGPRs); 5993 } 5994 5995 // Promote integers to 64-bit values. 5996 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5997 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5998 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5999 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6000 } 6001 6002 // FIXME memcpy is used way more than necessary. Correctness first. 6003 // Note: "by value" is code for passing a structure by value, not 6004 // basic types. 6005 if (Flags.isByVal()) { 6006 // Note: Size includes alignment padding, so 6007 // struct x { short a; char b; } 6008 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6009 // These are the proper values we need for right-justifying the 6010 // aggregate in a parameter register. 6011 unsigned Size = Flags.getByValSize(); 6012 6013 // An empty aggregate parameter takes up no storage and no 6014 // registers. 6015 if (Size == 0) 6016 continue; 6017 6018 if (CallConv == CallingConv::Fast) 6019 ComputePtrOff(); 6020 6021 // All aggregates smaller than 8 bytes must be passed right-justified. 6022 if (Size==1 || Size==2 || Size==4) { 6023 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6024 if (GPR_idx != NumGPRs) { 6025 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6026 MachinePointerInfo(), VT); 6027 MemOpChains.push_back(Load.getValue(1)); 6028 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6029 6030 ArgOffset += PtrByteSize; 6031 continue; 6032 } 6033 } 6034 6035 if (GPR_idx == NumGPRs && Size < 8) { 6036 SDValue AddPtr = PtrOff; 6037 if (!isLittleEndian) { 6038 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6039 PtrOff.getValueType()); 6040 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6041 } 6042 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6043 CallSeqStart, 6044 Flags, DAG, dl); 6045 ArgOffset += PtrByteSize; 6046 continue; 6047 } 6048 // Copy entire object into memory. There are cases where gcc-generated 6049 // code assumes it is there, even if it could be put entirely into 6050 // registers. (This is not what the doc says.) 6051 6052 // FIXME: The above statement is likely due to a misunderstanding of the 6053 // documents. All arguments must be copied into the parameter area BY 6054 // THE CALLEE in the event that the callee takes the address of any 6055 // formal argument. That has not yet been implemented. However, it is 6056 // reasonable to use the stack area as a staging area for the register 6057 // load. 6058 6059 // Skip this for small aggregates, as we will use the same slot for a 6060 // right-justified copy, below. 6061 if (Size >= 8) 6062 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6063 CallSeqStart, 6064 Flags, DAG, dl); 6065 6066 // When a register is available, pass a small aggregate right-justified. 6067 if (Size < 8 && GPR_idx != NumGPRs) { 6068 // The easiest way to get this right-justified in a register 6069 // is to copy the structure into the rightmost portion of a 6070 // local variable slot, then load the whole slot into the 6071 // register. 6072 // FIXME: The memcpy seems to produce pretty awful code for 6073 // small aggregates, particularly for packed ones. 6074 // FIXME: It would be preferable to use the slot in the 6075 // parameter save area instead of a new local variable. 6076 SDValue AddPtr = PtrOff; 6077 if (!isLittleEndian) { 6078 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6079 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6080 } 6081 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6082 CallSeqStart, 6083 Flags, DAG, dl); 6084 6085 // Load the slot into the register. 6086 SDValue Load = 6087 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6088 MemOpChains.push_back(Load.getValue(1)); 6089 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6090 6091 // Done with this argument. 6092 ArgOffset += PtrByteSize; 6093 continue; 6094 } 6095 6096 // For aggregates larger than PtrByteSize, copy the pieces of the 6097 // object that fit into registers from the parameter save area. 6098 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6099 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6100 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6101 if (GPR_idx != NumGPRs) { 6102 SDValue Load = 6103 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6104 MemOpChains.push_back(Load.getValue(1)); 6105 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6106 ArgOffset += PtrByteSize; 6107 } else { 6108 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6109 break; 6110 } 6111 } 6112 continue; 6113 } 6114 6115 switch (Arg.getSimpleValueType().SimpleTy) { 6116 default: llvm_unreachable("Unexpected ValueType for argument!"); 6117 case MVT::i1: 6118 case MVT::i32: 6119 case MVT::i64: 6120 if (Flags.isNest()) { 6121 // The 'nest' parameter, if any, is passed in R11. 6122 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6123 hasNest = true; 6124 break; 6125 } 6126 6127 // These can be scalar arguments or elements of an integer array type 6128 // passed directly. Clang may use those instead of "byval" aggregate 6129 // types to avoid forcing arguments to memory unnecessarily. 6130 if (GPR_idx != NumGPRs) { 6131 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6132 } else { 6133 if (CallConv == CallingConv::Fast) 6134 ComputePtrOff(); 6135 6136 assert(HasParameterArea && 6137 "Parameter area must exist to pass an argument in memory."); 6138 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6139 true, isTailCall, false, MemOpChains, 6140 TailCallArguments, dl); 6141 if (CallConv == CallingConv::Fast) 6142 ArgOffset += PtrByteSize; 6143 } 6144 if (CallConv != CallingConv::Fast) 6145 ArgOffset += PtrByteSize; 6146 break; 6147 case MVT::f32: 6148 case MVT::f64: { 6149 // These can be scalar arguments or elements of a float array type 6150 // passed directly. The latter are used to implement ELFv2 homogenous 6151 // float aggregates. 6152 6153 // Named arguments go into FPRs first, and once they overflow, the 6154 // remaining arguments go into GPRs and then the parameter save area. 6155 // Unnamed arguments for vararg functions always go to GPRs and 6156 // then the parameter save area. For now, put all arguments to vararg 6157 // routines always in both locations (FPR *and* GPR or stack slot). 6158 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 6159 bool NeededLoad = false; 6160 6161 // First load the argument into the next available FPR. 6162 if (FPR_idx != NumFPRs) 6163 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6164 6165 // Next, load the argument into GPR or stack slot if needed. 6166 if (!NeedGPROrStack) 6167 ; 6168 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 6169 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6170 // once we support fp <-> gpr moves. 6171 6172 // In the non-vararg case, this can only ever happen in the 6173 // presence of f32 array types, since otherwise we never run 6174 // out of FPRs before running out of GPRs. 6175 SDValue ArgVal; 6176 6177 // Double values are always passed in a single GPR. 6178 if (Arg.getValueType() != MVT::f32) { 6179 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6180 6181 // Non-array float values are extended and passed in a GPR. 6182 } else if (!Flags.isInConsecutiveRegs()) { 6183 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6184 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6185 6186 // If we have an array of floats, we collect every odd element 6187 // together with its predecessor into one GPR. 6188 } else if (ArgOffset % PtrByteSize != 0) { 6189 SDValue Lo, Hi; 6190 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6191 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6192 if (!isLittleEndian) 6193 std::swap(Lo, Hi); 6194 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6195 6196 // The final element, if even, goes into the first half of a GPR. 6197 } else if (Flags.isInConsecutiveRegsLast()) { 6198 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6199 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6200 if (!isLittleEndian) 6201 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6202 DAG.getConstant(32, dl, MVT::i32)); 6203 6204 // Non-final even elements are skipped; they will be handled 6205 // together the with subsequent argument on the next go-around. 6206 } else 6207 ArgVal = SDValue(); 6208 6209 if (ArgVal.getNode()) 6210 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6211 } else { 6212 if (CallConv == CallingConv::Fast) 6213 ComputePtrOff(); 6214 6215 // Single-precision floating-point values are mapped to the 6216 // second (rightmost) word of the stack doubleword. 6217 if (Arg.getValueType() == MVT::f32 && 6218 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6219 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6220 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6221 } 6222 6223 assert(HasParameterArea && 6224 "Parameter area must exist to pass an argument in memory."); 6225 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6226 true, isTailCall, false, MemOpChains, 6227 TailCallArguments, dl); 6228 6229 NeededLoad = true; 6230 } 6231 // When passing an array of floats, the array occupies consecutive 6232 // space in the argument area; only round up to the next doubleword 6233 // at the end of the array. Otherwise, each float takes 8 bytes. 6234 if (CallConv != CallingConv::Fast || NeededLoad) { 6235 ArgOffset += (Arg.getValueType() == MVT::f32 && 6236 Flags.isInConsecutiveRegs()) ? 4 : 8; 6237 if (Flags.isInConsecutiveRegsLast()) 6238 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6239 } 6240 break; 6241 } 6242 case MVT::v4f32: 6243 case MVT::v4i32: 6244 case MVT::v8i16: 6245 case MVT::v16i8: 6246 case MVT::v2f64: 6247 case MVT::v2i64: 6248 case MVT::v1i128: 6249 case MVT::f128: 6250 if (!Subtarget.hasQPX()) { 6251 // These can be scalar arguments or elements of a vector array type 6252 // passed directly. The latter are used to implement ELFv2 homogenous 6253 // vector aggregates. 6254 6255 // For a varargs call, named arguments go into VRs or on the stack as 6256 // usual; unnamed arguments always go to the stack or the corresponding 6257 // GPRs when within range. For now, we always put the value in both 6258 // locations (or even all three). 6259 if (isVarArg) { 6260 assert(HasParameterArea && 6261 "Parameter area must exist if we have a varargs call."); 6262 // We could elide this store in the case where the object fits 6263 // entirely in R registers. Maybe later. 6264 SDValue Store = 6265 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6266 MemOpChains.push_back(Store); 6267 if (VR_idx != NumVRs) { 6268 SDValue Load = 6269 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6270 MemOpChains.push_back(Load.getValue(1)); 6271 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6272 } 6273 ArgOffset += 16; 6274 for (unsigned i=0; i<16; i+=PtrByteSize) { 6275 if (GPR_idx == NumGPRs) 6276 break; 6277 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6278 DAG.getConstant(i, dl, PtrVT)); 6279 SDValue Load = 6280 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6281 MemOpChains.push_back(Load.getValue(1)); 6282 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6283 } 6284 break; 6285 } 6286 6287 // Non-varargs Altivec params go into VRs or on the stack. 6288 if (VR_idx != NumVRs) { 6289 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6290 } else { 6291 if (CallConv == CallingConv::Fast) 6292 ComputePtrOff(); 6293 6294 assert(HasParameterArea && 6295 "Parameter area must exist to pass an argument in memory."); 6296 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6297 true, isTailCall, true, MemOpChains, 6298 TailCallArguments, dl); 6299 if (CallConv == CallingConv::Fast) 6300 ArgOffset += 16; 6301 } 6302 6303 if (CallConv != CallingConv::Fast) 6304 ArgOffset += 16; 6305 break; 6306 } // not QPX 6307 6308 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6309 "Invalid QPX parameter type"); 6310 6311 LLVM_FALLTHROUGH; 6312 case MVT::v4f64: 6313 case MVT::v4i1: { 6314 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6315 if (isVarArg) { 6316 assert(HasParameterArea && 6317 "Parameter area must exist if we have a varargs call."); 6318 // We could elide this store in the case where the object fits 6319 // entirely in R registers. Maybe later. 6320 SDValue Store = 6321 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6322 MemOpChains.push_back(Store); 6323 if (QFPR_idx != NumQFPRs) { 6324 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6325 PtrOff, MachinePointerInfo()); 6326 MemOpChains.push_back(Load.getValue(1)); 6327 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6328 } 6329 ArgOffset += (IsF32 ? 16 : 32); 6330 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6331 if (GPR_idx == NumGPRs) 6332 break; 6333 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6334 DAG.getConstant(i, dl, PtrVT)); 6335 SDValue Load = 6336 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6337 MemOpChains.push_back(Load.getValue(1)); 6338 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6339 } 6340 break; 6341 } 6342 6343 // Non-varargs QPX params go into registers or on the stack. 6344 if (QFPR_idx != NumQFPRs) { 6345 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6346 } else { 6347 if (CallConv == CallingConv::Fast) 6348 ComputePtrOff(); 6349 6350 assert(HasParameterArea && 6351 "Parameter area must exist to pass an argument in memory."); 6352 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6353 true, isTailCall, true, MemOpChains, 6354 TailCallArguments, dl); 6355 if (CallConv == CallingConv::Fast) 6356 ArgOffset += (IsF32 ? 16 : 32); 6357 } 6358 6359 if (CallConv != CallingConv::Fast) 6360 ArgOffset += (IsF32 ? 16 : 32); 6361 break; 6362 } 6363 } 6364 } 6365 6366 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6367 "mismatch in size of parameter area"); 6368 (void)NumBytesActuallyUsed; 6369 6370 if (!MemOpChains.empty()) 6371 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6372 6373 // Check if this is an indirect call (MTCTR/BCTRL). 6374 // See prepareDescriptorIndirectCall and buildCallOperands for more 6375 // information about calls through function pointers in the 64-bit SVR4 ABI. 6376 if (!isTailCall && !isPatchPoint && 6377 !isFunctionGlobalAddress(Callee) && 6378 !isa<ExternalSymbolSDNode>(Callee)) { 6379 // Load r2 into a virtual register and store it to the TOC save area. 6380 setUsesTOCBasePtr(DAG); 6381 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6382 // TOC save area offset. 6383 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6384 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6385 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6386 Chain = DAG.getStore( 6387 Val.getValue(1), dl, Val, AddPtr, 6388 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6389 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6390 // This does not mean the MTCTR instruction must use R12; it's easier 6391 // to model this as an extra parameter, so do that. 6392 if (isELFv2ABI && !isPatchPoint) 6393 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6394 } 6395 6396 // Build a sequence of copy-to-reg nodes chained together with token chain 6397 // and flag operands which copy the outgoing args into the appropriate regs. 6398 SDValue InFlag; 6399 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6400 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6401 RegsToPass[i].second, InFlag); 6402 InFlag = Chain.getValue(1); 6403 } 6404 6405 if (isTailCall && !IsSibCall) 6406 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6407 TailCallArguments); 6408 6409 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6410 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6411 SPDiff, NumBytes, Ins, InVals, CS); 6412 } 6413 6414 SDValue PPCTargetLowering::LowerCall_Darwin( 6415 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6416 bool isTailCall, bool isPatchPoint, 6417 const SmallVectorImpl<ISD::OutputArg> &Outs, 6418 const SmallVectorImpl<SDValue> &OutVals, 6419 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6420 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6421 ImmutableCallSite CS) const { 6422 unsigned NumOps = Outs.size(); 6423 6424 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6425 bool isPPC64 = PtrVT == MVT::i64; 6426 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6427 6428 MachineFunction &MF = DAG.getMachineFunction(); 6429 6430 // Mark this function as potentially containing a function that contains a 6431 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6432 // and restoring the callers stack pointer in this functions epilog. This is 6433 // done because by tail calling the called function might overwrite the value 6434 // in this function's (MF) stack pointer stack slot 0(SP). 6435 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6436 CallConv == CallingConv::Fast) 6437 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6438 6439 // Count how many bytes are to be pushed on the stack, including the linkage 6440 // area, and parameter passing area. We start with 24/48 bytes, which is 6441 // prereserved space for [SP][CR][LR][3 x unused]. 6442 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6443 unsigned NumBytes = LinkageSize; 6444 6445 // Add up all the space actually used. 6446 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6447 // they all go in registers, but we must reserve stack space for them for 6448 // possible use by the caller. In varargs or 64-bit calls, parameters are 6449 // assigned stack space in order, with padding so Altivec parameters are 6450 // 16-byte aligned. 6451 unsigned nAltivecParamsAtEnd = 0; 6452 for (unsigned i = 0; i != NumOps; ++i) { 6453 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6454 EVT ArgVT = Outs[i].VT; 6455 // Varargs Altivec parameters are padded to a 16 byte boundary. 6456 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6457 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6458 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6459 if (!isVarArg && !isPPC64) { 6460 // Non-varargs Altivec parameters go after all the non-Altivec 6461 // parameters; handle those later so we know how much padding we need. 6462 nAltivecParamsAtEnd++; 6463 continue; 6464 } 6465 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6466 NumBytes = ((NumBytes+15)/16)*16; 6467 } 6468 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6469 } 6470 6471 // Allow for Altivec parameters at the end, if needed. 6472 if (nAltivecParamsAtEnd) { 6473 NumBytes = ((NumBytes+15)/16)*16; 6474 NumBytes += 16*nAltivecParamsAtEnd; 6475 } 6476 6477 // The prolog code of the callee may store up to 8 GPR argument registers to 6478 // the stack, allowing va_start to index over them in memory if its varargs. 6479 // Because we cannot tell if this is needed on the caller side, we have to 6480 // conservatively assume that it is needed. As such, make sure we have at 6481 // least enough stack space for the caller to store the 8 GPRs. 6482 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6483 6484 // Tail call needs the stack to be aligned. 6485 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6486 CallConv == CallingConv::Fast) 6487 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6488 6489 // Calculate by how many bytes the stack has to be adjusted in case of tail 6490 // call optimization. 6491 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6492 6493 // To protect arguments on the stack from being clobbered in a tail call, 6494 // force all the loads to happen before doing any other lowering. 6495 if (isTailCall) 6496 Chain = DAG.getStackArgumentTokenFactor(Chain); 6497 6498 // Adjust the stack pointer for the new arguments... 6499 // These operations are automatically eliminated by the prolog/epilog pass 6500 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6501 SDValue CallSeqStart = Chain; 6502 6503 // Load the return address and frame pointer so it can be move somewhere else 6504 // later. 6505 SDValue LROp, FPOp; 6506 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6507 6508 // Set up a copy of the stack pointer for use loading and storing any 6509 // arguments that may not fit in the registers available for argument 6510 // passing. 6511 SDValue StackPtr; 6512 if (isPPC64) 6513 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6514 else 6515 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6516 6517 // Figure out which arguments are going to go in registers, and which in 6518 // memory. Also, if this is a vararg function, floating point operations 6519 // must be stored to our stack, and loaded into integer regs as well, if 6520 // any integer regs are available for argument passing. 6521 unsigned ArgOffset = LinkageSize; 6522 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6523 6524 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6525 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6526 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6527 }; 6528 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6529 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6530 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6531 }; 6532 static const MCPhysReg VR[] = { 6533 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6534 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6535 }; 6536 const unsigned NumGPRs = array_lengthof(GPR_32); 6537 const unsigned NumFPRs = 13; 6538 const unsigned NumVRs = array_lengthof(VR); 6539 6540 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6541 6542 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6543 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6544 6545 SmallVector<SDValue, 8> MemOpChains; 6546 for (unsigned i = 0; i != NumOps; ++i) { 6547 SDValue Arg = OutVals[i]; 6548 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6549 6550 // PtrOff will be used to store the current argument to the stack if a 6551 // register cannot be found for it. 6552 SDValue PtrOff; 6553 6554 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6555 6556 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6557 6558 // On PPC64, promote integers to 64-bit values. 6559 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6560 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6561 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6562 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6563 } 6564 6565 // FIXME memcpy is used way more than necessary. Correctness first. 6566 // Note: "by value" is code for passing a structure by value, not 6567 // basic types. 6568 if (Flags.isByVal()) { 6569 unsigned Size = Flags.getByValSize(); 6570 // Very small objects are passed right-justified. Everything else is 6571 // passed left-justified. 6572 if (Size==1 || Size==2) { 6573 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6574 if (GPR_idx != NumGPRs) { 6575 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6576 MachinePointerInfo(), VT); 6577 MemOpChains.push_back(Load.getValue(1)); 6578 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6579 6580 ArgOffset += PtrByteSize; 6581 } else { 6582 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6583 PtrOff.getValueType()); 6584 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6585 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6586 CallSeqStart, 6587 Flags, DAG, dl); 6588 ArgOffset += PtrByteSize; 6589 } 6590 continue; 6591 } 6592 // Copy entire object into memory. There are cases where gcc-generated 6593 // code assumes it is there, even if it could be put entirely into 6594 // registers. (This is not what the doc says.) 6595 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6596 CallSeqStart, 6597 Flags, DAG, dl); 6598 6599 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6600 // copy the pieces of the object that fit into registers from the 6601 // parameter save area. 6602 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6603 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6604 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6605 if (GPR_idx != NumGPRs) { 6606 SDValue Load = 6607 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6608 MemOpChains.push_back(Load.getValue(1)); 6609 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6610 ArgOffset += PtrByteSize; 6611 } else { 6612 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6613 break; 6614 } 6615 } 6616 continue; 6617 } 6618 6619 switch (Arg.getSimpleValueType().SimpleTy) { 6620 default: llvm_unreachable("Unexpected ValueType for argument!"); 6621 case MVT::i1: 6622 case MVT::i32: 6623 case MVT::i64: 6624 if (GPR_idx != NumGPRs) { 6625 if (Arg.getValueType() == MVT::i1) 6626 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6627 6628 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6629 } else { 6630 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6631 isPPC64, isTailCall, false, MemOpChains, 6632 TailCallArguments, dl); 6633 } 6634 ArgOffset += PtrByteSize; 6635 break; 6636 case MVT::f32: 6637 case MVT::f64: 6638 if (FPR_idx != NumFPRs) { 6639 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6640 6641 if (isVarArg) { 6642 SDValue Store = 6643 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6644 MemOpChains.push_back(Store); 6645 6646 // Float varargs are always shadowed in available integer registers 6647 if (GPR_idx != NumGPRs) { 6648 SDValue Load = 6649 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6650 MemOpChains.push_back(Load.getValue(1)); 6651 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6652 } 6653 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6654 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6655 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6656 SDValue Load = 6657 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6658 MemOpChains.push_back(Load.getValue(1)); 6659 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6660 } 6661 } else { 6662 // If we have any FPRs remaining, we may also have GPRs remaining. 6663 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6664 // GPRs. 6665 if (GPR_idx != NumGPRs) 6666 ++GPR_idx; 6667 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6668 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6669 ++GPR_idx; 6670 } 6671 } else 6672 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6673 isPPC64, isTailCall, false, MemOpChains, 6674 TailCallArguments, dl); 6675 if (isPPC64) 6676 ArgOffset += 8; 6677 else 6678 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6679 break; 6680 case MVT::v4f32: 6681 case MVT::v4i32: 6682 case MVT::v8i16: 6683 case MVT::v16i8: 6684 if (isVarArg) { 6685 // These go aligned on the stack, or in the corresponding R registers 6686 // when within range. The Darwin PPC ABI doc claims they also go in 6687 // V registers; in fact gcc does this only for arguments that are 6688 // prototyped, not for those that match the ... We do it for all 6689 // arguments, seems to work. 6690 while (ArgOffset % 16 !=0) { 6691 ArgOffset += PtrByteSize; 6692 if (GPR_idx != NumGPRs) 6693 GPR_idx++; 6694 } 6695 // We could elide this store in the case where the object fits 6696 // entirely in R registers. Maybe later. 6697 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6698 DAG.getConstant(ArgOffset, dl, PtrVT)); 6699 SDValue Store = 6700 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6701 MemOpChains.push_back(Store); 6702 if (VR_idx != NumVRs) { 6703 SDValue Load = 6704 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6705 MemOpChains.push_back(Load.getValue(1)); 6706 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6707 } 6708 ArgOffset += 16; 6709 for (unsigned i=0; i<16; i+=PtrByteSize) { 6710 if (GPR_idx == NumGPRs) 6711 break; 6712 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6713 DAG.getConstant(i, dl, PtrVT)); 6714 SDValue Load = 6715 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6716 MemOpChains.push_back(Load.getValue(1)); 6717 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6718 } 6719 break; 6720 } 6721 6722 // Non-varargs Altivec params generally go in registers, but have 6723 // stack space allocated at the end. 6724 if (VR_idx != NumVRs) { 6725 // Doesn't have GPR space allocated. 6726 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6727 } else if (nAltivecParamsAtEnd==0) { 6728 // We are emitting Altivec params in order. 6729 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6730 isPPC64, isTailCall, true, MemOpChains, 6731 TailCallArguments, dl); 6732 ArgOffset += 16; 6733 } 6734 break; 6735 } 6736 } 6737 // If all Altivec parameters fit in registers, as they usually do, 6738 // they get stack space following the non-Altivec parameters. We 6739 // don't track this here because nobody below needs it. 6740 // If there are more Altivec parameters than fit in registers emit 6741 // the stores here. 6742 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6743 unsigned j = 0; 6744 // Offset is aligned; skip 1st 12 params which go in V registers. 6745 ArgOffset = ((ArgOffset+15)/16)*16; 6746 ArgOffset += 12*16; 6747 for (unsigned i = 0; i != NumOps; ++i) { 6748 SDValue Arg = OutVals[i]; 6749 EVT ArgType = Outs[i].VT; 6750 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6751 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6752 if (++j > NumVRs) { 6753 SDValue PtrOff; 6754 // We are emitting Altivec params in order. 6755 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6756 isPPC64, isTailCall, true, MemOpChains, 6757 TailCallArguments, dl); 6758 ArgOffset += 16; 6759 } 6760 } 6761 } 6762 } 6763 6764 if (!MemOpChains.empty()) 6765 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6766 6767 // On Darwin, R12 must contain the address of an indirect callee. This does 6768 // not mean the MTCTR instruction must use R12; it's easier to model this as 6769 // an extra parameter, so do that. 6770 if (!isTailCall && 6771 !isFunctionGlobalAddress(Callee) && 6772 !isa<ExternalSymbolSDNode>(Callee) && 6773 !isBLACompatibleAddress(Callee, DAG)) 6774 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6775 PPC::R12), Callee)); 6776 6777 // Build a sequence of copy-to-reg nodes chained together with token chain 6778 // and flag operands which copy the outgoing args into the appropriate regs. 6779 SDValue InFlag; 6780 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6781 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6782 RegsToPass[i].second, InFlag); 6783 InFlag = Chain.getValue(1); 6784 } 6785 6786 if (isTailCall) 6787 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6788 TailCallArguments); 6789 6790 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6791 /* unused except on PPC64 ELFv1 */ false, DAG, 6792 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6793 NumBytes, Ins, InVals, CS); 6794 } 6795 6796 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6797 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6798 CCState &State) { 6799 6800 if (ValVT == MVT::f128) 6801 report_fatal_error("f128 is unimplemented on AIX."); 6802 6803 if (ArgFlags.isByVal()) 6804 report_fatal_error("Passing structure by value is unimplemented."); 6805 6806 if (ArgFlags.isSRet()) 6807 report_fatal_error("Struct return arguments are unimplemented."); 6808 6809 if (ArgFlags.isNest()) 6810 report_fatal_error("Nest arguments are unimplemented."); 6811 6812 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6813 State.getMachineFunction().getSubtarget()); 6814 const bool IsPPC64 = Subtarget.isPPC64(); 6815 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6816 6817 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6818 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6819 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6820 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6821 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6822 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6823 6824 // Arguments always reserve parameter save area. 6825 switch (ValVT.SimpleTy) { 6826 default: 6827 report_fatal_error("Unhandled value type for argument."); 6828 case MVT::i64: 6829 // i64 arguments should have been split to i32 for PPC32. 6830 assert(IsPPC64 && "PPC32 should have split i64 values."); 6831 LLVM_FALLTHROUGH; 6832 case MVT::i1: 6833 case MVT::i32: 6834 State.AllocateStack(PtrByteSize, PtrByteSize); 6835 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6836 MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6837 // Promote integers if needed. 6838 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6839 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6840 : CCValAssign::LocInfo::ZExt; 6841 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6842 } 6843 else 6844 report_fatal_error("Handling of placing parameters on the stack is " 6845 "unimplemented!"); 6846 return false; 6847 6848 case MVT::f32: 6849 case MVT::f64: { 6850 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6851 const unsigned StoreSize = LocVT.getStoreSize(); 6852 // Floats are always 4-byte aligned in the PSA on AIX. 6853 // This includes f64 in 64-bit mode for ABI compatibility. 6854 State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 6855 if (unsigned Reg = State.AllocateReg(FPR)) 6856 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::f64, LocInfo)); 6857 else 6858 report_fatal_error("Handling of placing parameters on the stack is " 6859 "unimplemented!"); 6860 6861 // f32 reserves 1 GPR in both PPC32 and PPC64. 6862 // f64 reserves 2 GPRs in PPC32 and 1 GPR in PPC64. 6863 for (unsigned i = 0; i < StoreSize; i += PtrByteSize) 6864 State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32); 6865 return false; 6866 } 6867 } 6868 } 6869 6870 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6871 bool IsPPC64) { 6872 assert((IsPPC64 || SVT != MVT::i64) && 6873 "i64 should have been split for 32-bit codegen."); 6874 6875 switch (SVT) { 6876 default: 6877 report_fatal_error("Unexpected value type for formal argument"); 6878 case MVT::i1: 6879 case MVT::i32: 6880 case MVT::i64: 6881 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6882 case MVT::f32: 6883 return &PPC::F4RCRegClass; 6884 case MVT::f64: 6885 return &PPC::F8RCRegClass; 6886 } 6887 } 6888 6889 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6890 SelectionDAG &DAG, SDValue ArgValue, 6891 MVT LocVT, const SDLoc &dl) { 6892 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6893 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 6894 6895 if (Flags.isSExt()) 6896 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6897 DAG.getValueType(ValVT)); 6898 else if (Flags.isZExt()) 6899 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6900 DAG.getValueType(ValVT)); 6901 6902 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6903 } 6904 6905 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6906 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6907 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6908 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6909 6910 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6911 CallConv == CallingConv::Fast) && 6912 "Unexpected calling convention!"); 6913 6914 if (isVarArg) 6915 report_fatal_error("This call type is unimplemented on AIX."); 6916 6917 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6918 report_fatal_error("Tail call support is unimplemented on AIX."); 6919 6920 if (useSoftFloat()) 6921 report_fatal_error("Soft float support is unimplemented on AIX."); 6922 6923 const PPCSubtarget &Subtarget = 6924 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 6925 if (Subtarget.hasQPX()) 6926 report_fatal_error("QPX support is not supported on AIX."); 6927 6928 const bool IsPPC64 = Subtarget.isPPC64(); 6929 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6930 6931 // Assign locations to all of the incoming arguments. 6932 SmallVector<CCValAssign, 16> ArgLocs; 6933 MachineFunction &MF = DAG.getMachineFunction(); 6934 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6935 6936 // Reserve space for the linkage area on the stack. 6937 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6938 // On AIX a minimum of 8 words is saved to the parameter save area. 6939 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 6940 CCInfo.AllocateStack(LinkageSize + MinParameterSaveArea, PtrByteSize); 6941 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6942 6943 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 6944 CCValAssign &VA = ArgLocs[i]; 6945 SDValue ArgValue; 6946 ISD::ArgFlagsTy Flags = Ins[i].Flags; 6947 if (VA.isRegLoc()) { 6948 EVT ValVT = VA.getValVT(); 6949 MVT LocVT = VA.getLocVT(); 6950 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 6951 unsigned VReg = 6952 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 6953 ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 6954 if (ValVT.isScalarInteger() && 6955 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 6956 ArgValue = 6957 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 6958 } 6959 InVals.push_back(ArgValue); 6960 } else { 6961 report_fatal_error("Handling of formal arguments on the stack is " 6962 "unimplemented!"); 6963 } 6964 } 6965 6966 // Area that is at least reserved in the caller of this function. 6967 unsigned MinReservedArea = CCInfo.getNextStackOffset(); 6968 6969 // Set the size that is at least reserved in caller of this function. Tail 6970 // call optimized function's reserved stack space needs to be aligned so 6971 // that taking the difference between two stack areas will result in an 6972 // aligned stack. 6973 MinReservedArea = 6974 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 6975 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 6976 FuncInfo->setMinReservedArea(MinReservedArea); 6977 6978 return Chain; 6979 } 6980 6981 SDValue PPCTargetLowering::LowerCall_AIX( 6982 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6983 bool isTailCall, bool isPatchPoint, 6984 const SmallVectorImpl<ISD::OutputArg> &Outs, 6985 const SmallVectorImpl<SDValue> &OutVals, 6986 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6987 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6988 ImmutableCallSite CS) const { 6989 6990 assert((CallConv == CallingConv::C || 6991 CallConv == CallingConv::Cold || 6992 CallConv == CallingConv::Fast) && "Unexpected calling convention!"); 6993 6994 if (isVarArg || isPatchPoint) 6995 report_fatal_error("This call type is unimplemented on AIX."); 6996 6997 const PPCSubtarget& Subtarget = 6998 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 6999 if (Subtarget.hasQPX()) 7000 report_fatal_error("QPX is not supported on AIX."); 7001 if (Subtarget.hasAltivec()) 7002 report_fatal_error("Altivec support is unimplemented on AIX."); 7003 7004 MachineFunction &MF = DAG.getMachineFunction(); 7005 SmallVector<CCValAssign, 16> ArgLocs; 7006 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7007 7008 // Reserve space for the linkage save area (LSA) on the stack. 7009 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7010 // [SP][CR][LR][2 x reserved][TOC]. 7011 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7012 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7013 const unsigned PtrByteSize = Subtarget.isPPC64() ? 8 : 4; 7014 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7015 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7016 7017 // The prolog code of the callee may store up to 8 GPR argument registers to 7018 // the stack, allowing va_start to index over them in memory if the callee 7019 // is variadic. 7020 // Because we cannot tell if this is needed on the caller side, we have to 7021 // conservatively assume that it is needed. As such, make sure we have at 7022 // least enough stack space for the caller to store the 8 GPRs. 7023 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7024 const unsigned NumBytes = LinkageSize + MinParameterSaveAreaSize; 7025 7026 // Adjust the stack pointer for the new arguments... 7027 // These operations are automatically eliminated by the prolog/epilog pass. 7028 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7029 SDValue CallSeqStart = Chain; 7030 7031 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7032 7033 for (CCValAssign &VA : ArgLocs) { 7034 SDValue Arg = OutVals[VA.getValNo()]; 7035 7036 switch (VA.getLocInfo()) { 7037 default: report_fatal_error("Unexpected argument extension type."); 7038 case CCValAssign::Full: break; 7039 case CCValAssign::ZExt: 7040 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7041 break; 7042 case CCValAssign::SExt: 7043 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7044 break; 7045 } 7046 7047 if (VA.isRegLoc()) 7048 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7049 7050 if (VA.isMemLoc()) 7051 report_fatal_error("Handling of placing parameters on the stack is " 7052 "unimplemented!"); 7053 } 7054 7055 // For indirect calls, we need to save the TOC base to the stack for 7056 // restoration after the call. 7057 if (!isTailCall && !isPatchPoint && 7058 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) { 7059 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7060 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7061 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7062 const unsigned TOCSaveOffset = 7063 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7064 7065 setUsesTOCBasePtr(DAG); 7066 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7067 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7068 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7069 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7070 Chain = DAG.getStore( 7071 Val.getValue(1), dl, Val, AddPtr, 7072 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7073 } 7074 7075 // Build a sequence of copy-to-reg nodes chained together with token chain 7076 // and flag operands which copy the outgoing args into the appropriate regs. 7077 SDValue InFlag; 7078 for (auto Reg : RegsToPass) { 7079 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7080 InFlag = Chain.getValue(1); 7081 } 7082 7083 const int SPDiff = 0; 7084 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 7085 /* unused except on PPC64 ELFv1 */ false, DAG, RegsToPass, 7086 InFlag, Chain, CallSeqStart, Callee, SPDiff, NumBytes, Ins, 7087 InVals, CS); 7088 } 7089 7090 bool 7091 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7092 MachineFunction &MF, bool isVarArg, 7093 const SmallVectorImpl<ISD::OutputArg> &Outs, 7094 LLVMContext &Context) const { 7095 SmallVector<CCValAssign, 16> RVLocs; 7096 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7097 return CCInfo.CheckReturn( 7098 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7099 ? RetCC_PPC_Cold 7100 : RetCC_PPC); 7101 } 7102 7103 SDValue 7104 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7105 bool isVarArg, 7106 const SmallVectorImpl<ISD::OutputArg> &Outs, 7107 const SmallVectorImpl<SDValue> &OutVals, 7108 const SDLoc &dl, SelectionDAG &DAG) const { 7109 SmallVector<CCValAssign, 16> RVLocs; 7110 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7111 *DAG.getContext()); 7112 CCInfo.AnalyzeReturn(Outs, 7113 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7114 ? RetCC_PPC_Cold 7115 : RetCC_PPC); 7116 7117 SDValue Flag; 7118 SmallVector<SDValue, 4> RetOps(1, Chain); 7119 7120 // Copy the result values into the output registers. 7121 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7122 CCValAssign &VA = RVLocs[i]; 7123 assert(VA.isRegLoc() && "Can only return in registers!"); 7124 7125 SDValue Arg = OutVals[RealResIdx]; 7126 7127 switch (VA.getLocInfo()) { 7128 default: llvm_unreachable("Unknown loc info!"); 7129 case CCValAssign::Full: break; 7130 case CCValAssign::AExt: 7131 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7132 break; 7133 case CCValAssign::ZExt: 7134 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7135 break; 7136 case CCValAssign::SExt: 7137 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7138 break; 7139 } 7140 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7141 bool isLittleEndian = Subtarget.isLittleEndian(); 7142 // Legalize ret f64 -> ret 2 x i32. 7143 SDValue SVal = 7144 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7145 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7146 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7147 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7148 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7149 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7150 Flag = Chain.getValue(1); 7151 VA = RVLocs[++i]; // skip ahead to next loc 7152 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7153 } else 7154 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7155 Flag = Chain.getValue(1); 7156 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7157 } 7158 7159 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 7160 const MCPhysReg *I = 7161 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 7162 if (I) { 7163 for (; *I; ++I) { 7164 7165 if (PPC::G8RCRegClass.contains(*I)) 7166 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 7167 else if (PPC::F8RCRegClass.contains(*I)) 7168 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 7169 else if (PPC::CRRCRegClass.contains(*I)) 7170 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 7171 else if (PPC::VRRCRegClass.contains(*I)) 7172 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 7173 else 7174 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 7175 } 7176 } 7177 7178 RetOps[0] = Chain; // Update chain. 7179 7180 // Add the flag if we have it. 7181 if (Flag.getNode()) 7182 RetOps.push_back(Flag); 7183 7184 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7185 } 7186 7187 SDValue 7188 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7189 SelectionDAG &DAG) const { 7190 SDLoc dl(Op); 7191 7192 // Get the correct type for integers. 7193 EVT IntVT = Op.getValueType(); 7194 7195 // Get the inputs. 7196 SDValue Chain = Op.getOperand(0); 7197 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7198 // Build a DYNAREAOFFSET node. 7199 SDValue Ops[2] = {Chain, FPSIdx}; 7200 SDVTList VTs = DAG.getVTList(IntVT); 7201 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7202 } 7203 7204 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7205 SelectionDAG &DAG) const { 7206 // When we pop the dynamic allocation we need to restore the SP link. 7207 SDLoc dl(Op); 7208 7209 // Get the correct type for pointers. 7210 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7211 7212 // Construct the stack pointer operand. 7213 bool isPPC64 = Subtarget.isPPC64(); 7214 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7215 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7216 7217 // Get the operands for the STACKRESTORE. 7218 SDValue Chain = Op.getOperand(0); 7219 SDValue SaveSP = Op.getOperand(1); 7220 7221 // Load the old link SP. 7222 SDValue LoadLinkSP = 7223 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7224 7225 // Restore the stack pointer. 7226 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7227 7228 // Store the old link SP. 7229 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7230 } 7231 7232 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7233 MachineFunction &MF = DAG.getMachineFunction(); 7234 bool isPPC64 = Subtarget.isPPC64(); 7235 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7236 7237 // Get current frame pointer save index. The users of this index will be 7238 // primarily DYNALLOC instructions. 7239 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7240 int RASI = FI->getReturnAddrSaveIndex(); 7241 7242 // If the frame pointer save index hasn't been defined yet. 7243 if (!RASI) { 7244 // Find out what the fix offset of the frame pointer save area. 7245 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7246 // Allocate the frame index for frame pointer save area. 7247 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7248 // Save the result. 7249 FI->setReturnAddrSaveIndex(RASI); 7250 } 7251 return DAG.getFrameIndex(RASI, PtrVT); 7252 } 7253 7254 SDValue 7255 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7256 MachineFunction &MF = DAG.getMachineFunction(); 7257 bool isPPC64 = Subtarget.isPPC64(); 7258 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7259 7260 // Get current frame pointer save index. The users of this index will be 7261 // primarily DYNALLOC instructions. 7262 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7263 int FPSI = FI->getFramePointerSaveIndex(); 7264 7265 // If the frame pointer save index hasn't been defined yet. 7266 if (!FPSI) { 7267 // Find out what the fix offset of the frame pointer save area. 7268 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7269 // Allocate the frame index for frame pointer save area. 7270 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7271 // Save the result. 7272 FI->setFramePointerSaveIndex(FPSI); 7273 } 7274 return DAG.getFrameIndex(FPSI, PtrVT); 7275 } 7276 7277 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7278 SelectionDAG &DAG) const { 7279 // Get the inputs. 7280 SDValue Chain = Op.getOperand(0); 7281 SDValue Size = Op.getOperand(1); 7282 SDLoc dl(Op); 7283 7284 // Get the correct type for pointers. 7285 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7286 // Negate the size. 7287 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7288 DAG.getConstant(0, dl, PtrVT), Size); 7289 // Construct a node for the frame pointer save index. 7290 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7291 // Build a DYNALLOC node. 7292 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7293 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7294 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7295 } 7296 7297 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7298 SelectionDAG &DAG) const { 7299 MachineFunction &MF = DAG.getMachineFunction(); 7300 7301 bool isPPC64 = Subtarget.isPPC64(); 7302 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7303 7304 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7305 return DAG.getFrameIndex(FI, PtrVT); 7306 } 7307 7308 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7309 SelectionDAG &DAG) const { 7310 SDLoc DL(Op); 7311 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7312 DAG.getVTList(MVT::i32, MVT::Other), 7313 Op.getOperand(0), Op.getOperand(1)); 7314 } 7315 7316 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7317 SelectionDAG &DAG) const { 7318 SDLoc DL(Op); 7319 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7320 Op.getOperand(0), Op.getOperand(1)); 7321 } 7322 7323 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7324 if (Op.getValueType().isVector()) 7325 return LowerVectorLoad(Op, DAG); 7326 7327 assert(Op.getValueType() == MVT::i1 && 7328 "Custom lowering only for i1 loads"); 7329 7330 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7331 7332 SDLoc dl(Op); 7333 LoadSDNode *LD = cast<LoadSDNode>(Op); 7334 7335 SDValue Chain = LD->getChain(); 7336 SDValue BasePtr = LD->getBasePtr(); 7337 MachineMemOperand *MMO = LD->getMemOperand(); 7338 7339 SDValue NewLD = 7340 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7341 BasePtr, MVT::i8, MMO); 7342 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7343 7344 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7345 return DAG.getMergeValues(Ops, dl); 7346 } 7347 7348 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7349 if (Op.getOperand(1).getValueType().isVector()) 7350 return LowerVectorStore(Op, DAG); 7351 7352 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7353 "Custom lowering only for i1 stores"); 7354 7355 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7356 7357 SDLoc dl(Op); 7358 StoreSDNode *ST = cast<StoreSDNode>(Op); 7359 7360 SDValue Chain = ST->getChain(); 7361 SDValue BasePtr = ST->getBasePtr(); 7362 SDValue Value = ST->getValue(); 7363 MachineMemOperand *MMO = ST->getMemOperand(); 7364 7365 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7366 Value); 7367 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7368 } 7369 7370 // FIXME: Remove this once the ANDI glue bug is fixed: 7371 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7372 assert(Op.getValueType() == MVT::i1 && 7373 "Custom lowering only for i1 results"); 7374 7375 SDLoc DL(Op); 7376 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 7377 Op.getOperand(0)); 7378 } 7379 7380 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7381 SelectionDAG &DAG) const { 7382 7383 // Implements a vector truncate that fits in a vector register as a shuffle. 7384 // We want to legalize vector truncates down to where the source fits in 7385 // a vector register (and target is therefore smaller than vector register 7386 // size). At that point legalization will try to custom lower the sub-legal 7387 // result and get here - where we can contain the truncate as a single target 7388 // operation. 7389 7390 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7391 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7392 // 7393 // We will implement it for big-endian ordering as this (where x denotes 7394 // undefined): 7395 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7396 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7397 // 7398 // The same operation in little-endian ordering will be: 7399 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7400 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7401 7402 assert(Op.getValueType().isVector() && "Vector type expected."); 7403 7404 SDLoc DL(Op); 7405 SDValue N1 = Op.getOperand(0); 7406 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7407 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7408 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7409 7410 EVT TrgVT = Op.getValueType(); 7411 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7412 EVT EltVT = TrgVT.getVectorElementType(); 7413 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7414 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7415 7416 // First list the elements we want to keep. 7417 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7418 SmallVector<int, 16> ShuffV; 7419 if (Subtarget.isLittleEndian()) 7420 for (unsigned i = 0; i < TrgNumElts; ++i) 7421 ShuffV.push_back(i * SizeMult); 7422 else 7423 for (unsigned i = 1; i <= TrgNumElts; ++i) 7424 ShuffV.push_back(i * SizeMult - 1); 7425 7426 // Populate the remaining elements with undefs. 7427 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7428 // ShuffV.push_back(i + WideNumElts); 7429 ShuffV.push_back(WideNumElts + 1); 7430 7431 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7432 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7433 } 7434 7435 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7436 /// possible. 7437 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7438 // Not FP? Not a fsel. 7439 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7440 !Op.getOperand(2).getValueType().isFloatingPoint()) 7441 return Op; 7442 7443 bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath; 7444 bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath; 7445 // We might be able to do better than this under some circumstances, but in 7446 // general, fsel-based lowering of select is a finite-math-only optimization. 7447 // For more information, see section F.3 of the 2.06 ISA specification. 7448 // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the 7449 // presence of infinities. 7450 if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs)) 7451 return Op; 7452 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7453 7454 EVT ResVT = Op.getValueType(); 7455 EVT CmpVT = Op.getOperand(0).getValueType(); 7456 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7457 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7458 SDLoc dl(Op); 7459 7460 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7461 switch (CC) { 7462 default: 7463 // Not a min/max but with finite math, we may still be able to use fsel. 7464 if (HasNoInfs && HasNoNaNs) 7465 break; 7466 return Op; 7467 case ISD::SETOGT: 7468 case ISD::SETGT: 7469 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7470 case ISD::SETOLT: 7471 case ISD::SETLT: 7472 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7473 } 7474 } 7475 7476 // TODO: Propagate flags from the select rather than global settings. 7477 SDNodeFlags Flags; 7478 Flags.setNoInfs(true); 7479 Flags.setNoNaNs(true); 7480 7481 // If the RHS of the comparison is a 0.0, we don't need to do the 7482 // subtraction at all. 7483 SDValue Sel1; 7484 if (isFloatingPointZero(RHS)) 7485 switch (CC) { 7486 default: break; // SETUO etc aren't handled by fsel. 7487 case ISD::SETNE: 7488 std::swap(TV, FV); 7489 LLVM_FALLTHROUGH; 7490 case ISD::SETEQ: 7491 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7492 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7493 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7494 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7495 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7496 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7497 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7498 case ISD::SETULT: 7499 case ISD::SETLT: 7500 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7501 LLVM_FALLTHROUGH; 7502 case ISD::SETOGE: 7503 case ISD::SETGE: 7504 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7505 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7506 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7507 case ISD::SETUGT: 7508 case ISD::SETGT: 7509 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7510 LLVM_FALLTHROUGH; 7511 case ISD::SETOLE: 7512 case ISD::SETLE: 7513 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7514 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7515 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7516 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7517 } 7518 7519 SDValue Cmp; 7520 switch (CC) { 7521 default: break; // SETUO etc aren't handled by fsel. 7522 case ISD::SETNE: 7523 std::swap(TV, FV); 7524 LLVM_FALLTHROUGH; 7525 case ISD::SETEQ: 7526 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7527 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7528 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7529 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7530 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7531 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7532 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7533 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7534 case ISD::SETULT: 7535 case ISD::SETLT: 7536 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7537 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7538 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7539 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7540 case ISD::SETOGE: 7541 case ISD::SETGE: 7542 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7543 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7544 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7545 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7546 case ISD::SETUGT: 7547 case ISD::SETGT: 7548 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7549 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7550 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7551 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7552 case ISD::SETOLE: 7553 case ISD::SETLE: 7554 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7555 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7556 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7557 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7558 } 7559 return Op; 7560 } 7561 7562 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7563 SelectionDAG &DAG, 7564 const SDLoc &dl) const { 7565 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7566 SDValue Src = Op.getOperand(0); 7567 if (Src.getValueType() == MVT::f32) 7568 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7569 7570 SDValue Tmp; 7571 switch (Op.getSimpleValueType().SimpleTy) { 7572 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7573 case MVT::i32: 7574 Tmp = DAG.getNode( 7575 Op.getOpcode() == ISD::FP_TO_SINT 7576 ? PPCISD::FCTIWZ 7577 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7578 dl, MVT::f64, Src); 7579 break; 7580 case MVT::i64: 7581 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7582 "i64 FP_TO_UINT is supported only with FPCVT"); 7583 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7584 PPCISD::FCTIDUZ, 7585 dl, MVT::f64, Src); 7586 break; 7587 } 7588 7589 // Convert the FP value to an int value through memory. 7590 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7591 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7592 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7593 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7594 MachinePointerInfo MPI = 7595 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7596 7597 // Emit a store to the stack slot. 7598 SDValue Chain; 7599 if (i32Stack) { 7600 MachineFunction &MF = DAG.getMachineFunction(); 7601 MachineMemOperand *MMO = 7602 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7603 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7604 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7605 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7606 } else 7607 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7608 7609 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7610 // add in a bias on big endian. 7611 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7612 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7613 DAG.getConstant(4, dl, FIPtr.getValueType())); 7614 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7615 } 7616 7617 RLI.Chain = Chain; 7618 RLI.Ptr = FIPtr; 7619 RLI.MPI = MPI; 7620 } 7621 7622 /// Custom lowers floating point to integer conversions to use 7623 /// the direct move instructions available in ISA 2.07 to avoid the 7624 /// need for load/store combinations. 7625 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7626 SelectionDAG &DAG, 7627 const SDLoc &dl) const { 7628 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7629 SDValue Src = Op.getOperand(0); 7630 7631 if (Src.getValueType() == MVT::f32) 7632 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7633 7634 SDValue Tmp; 7635 switch (Op.getSimpleValueType().SimpleTy) { 7636 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7637 case MVT::i32: 7638 Tmp = DAG.getNode( 7639 Op.getOpcode() == ISD::FP_TO_SINT 7640 ? PPCISD::FCTIWZ 7641 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7642 dl, MVT::f64, Src); 7643 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7644 break; 7645 case MVT::i64: 7646 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7647 "i64 FP_TO_UINT is supported only with FPCVT"); 7648 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7649 PPCISD::FCTIDUZ, 7650 dl, MVT::f64, Src); 7651 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7652 break; 7653 } 7654 return Tmp; 7655 } 7656 7657 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7658 const SDLoc &dl) const { 7659 7660 // FP to INT conversions are legal for f128. 7661 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7662 return Op; 7663 7664 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7665 // PPC (the libcall is not available). 7666 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7667 if (Op.getValueType() == MVT::i32) { 7668 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7669 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7670 MVT::f64, Op.getOperand(0), 7671 DAG.getIntPtrConstant(0, dl)); 7672 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7673 MVT::f64, Op.getOperand(0), 7674 DAG.getIntPtrConstant(1, dl)); 7675 7676 // Add the two halves of the long double in round-to-zero mode. 7677 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7678 7679 // Now use a smaller FP_TO_SINT. 7680 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7681 } 7682 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7683 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7684 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7685 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7686 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7687 // FIXME: generated code sucks. 7688 // TODO: Are there fast-math-flags to propagate to this FSUB? 7689 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7690 Op.getOperand(0), Tmp); 7691 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7692 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7693 DAG.getConstant(0x80000000, dl, MVT::i32)); 7694 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7695 Op.getOperand(0)); 7696 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7697 ISD::SETGE); 7698 } 7699 } 7700 7701 return SDValue(); 7702 } 7703 7704 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7705 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7706 7707 ReuseLoadInfo RLI; 7708 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7709 7710 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7711 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7712 } 7713 7714 // We're trying to insert a regular store, S, and then a load, L. If the 7715 // incoming value, O, is a load, we might just be able to have our load use the 7716 // address used by O. However, we don't know if anything else will store to 7717 // that address before we can load from it. To prevent this situation, we need 7718 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7719 // the same chain operand as O, we create a token factor from the chain results 7720 // of O and L, and we replace all uses of O's chain result with that token 7721 // factor (see spliceIntoChain below for this last part). 7722 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7723 ReuseLoadInfo &RLI, 7724 SelectionDAG &DAG, 7725 ISD::LoadExtType ET) const { 7726 SDLoc dl(Op); 7727 if (ET == ISD::NON_EXTLOAD && 7728 (Op.getOpcode() == ISD::FP_TO_UINT || 7729 Op.getOpcode() == ISD::FP_TO_SINT) && 7730 isOperationLegalOrCustom(Op.getOpcode(), 7731 Op.getOperand(0).getValueType())) { 7732 7733 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7734 return true; 7735 } 7736 7737 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7738 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7739 LD->isNonTemporal()) 7740 return false; 7741 if (LD->getMemoryVT() != MemVT) 7742 return false; 7743 7744 RLI.Ptr = LD->getBasePtr(); 7745 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7746 assert(LD->getAddressingMode() == ISD::PRE_INC && 7747 "Non-pre-inc AM on PPC?"); 7748 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7749 LD->getOffset()); 7750 } 7751 7752 RLI.Chain = LD->getChain(); 7753 RLI.MPI = LD->getPointerInfo(); 7754 RLI.IsDereferenceable = LD->isDereferenceable(); 7755 RLI.IsInvariant = LD->isInvariant(); 7756 RLI.Alignment = LD->getAlignment(); 7757 RLI.AAInfo = LD->getAAInfo(); 7758 RLI.Ranges = LD->getRanges(); 7759 7760 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7761 return true; 7762 } 7763 7764 // Given the head of the old chain, ResChain, insert a token factor containing 7765 // it and NewResChain, and make users of ResChain now be users of that token 7766 // factor. 7767 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7768 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7769 SDValue NewResChain, 7770 SelectionDAG &DAG) const { 7771 if (!ResChain) 7772 return; 7773 7774 SDLoc dl(NewResChain); 7775 7776 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7777 NewResChain, DAG.getUNDEF(MVT::Other)); 7778 assert(TF.getNode() != NewResChain.getNode() && 7779 "A new TF really is required here"); 7780 7781 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7782 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7783 } 7784 7785 /// Analyze profitability of direct move 7786 /// prefer float load to int load plus direct move 7787 /// when there is no integer use of int load 7788 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7789 SDNode *Origin = Op.getOperand(0).getNode(); 7790 if (Origin->getOpcode() != ISD::LOAD) 7791 return true; 7792 7793 // If there is no LXSIBZX/LXSIHZX, like Power8, 7794 // prefer direct move if the memory size is 1 or 2 bytes. 7795 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7796 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7797 return true; 7798 7799 for (SDNode::use_iterator UI = Origin->use_begin(), 7800 UE = Origin->use_end(); 7801 UI != UE; ++UI) { 7802 7803 // Only look at the users of the loaded value. 7804 if (UI.getUse().get().getResNo() != 0) 7805 continue; 7806 7807 if (UI->getOpcode() != ISD::SINT_TO_FP && 7808 UI->getOpcode() != ISD::UINT_TO_FP) 7809 return true; 7810 } 7811 7812 return false; 7813 } 7814 7815 /// Custom lowers integer to floating point conversions to use 7816 /// the direct move instructions available in ISA 2.07 to avoid the 7817 /// need for load/store combinations. 7818 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7819 SelectionDAG &DAG, 7820 const SDLoc &dl) const { 7821 assert((Op.getValueType() == MVT::f32 || 7822 Op.getValueType() == MVT::f64) && 7823 "Invalid floating point type as target of conversion"); 7824 assert(Subtarget.hasFPCVT() && 7825 "Int to FP conversions with direct moves require FPCVT"); 7826 SDValue FP; 7827 SDValue Src = Op.getOperand(0); 7828 bool SinglePrec = Op.getValueType() == MVT::f32; 7829 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7830 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7831 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7832 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7833 7834 if (WordInt) { 7835 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7836 dl, MVT::f64, Src); 7837 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7838 } 7839 else { 7840 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7841 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7842 } 7843 7844 return FP; 7845 } 7846 7847 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7848 7849 EVT VecVT = Vec.getValueType(); 7850 assert(VecVT.isVector() && "Expected a vector type."); 7851 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7852 7853 EVT EltVT = VecVT.getVectorElementType(); 7854 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7855 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7856 7857 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7858 SmallVector<SDValue, 16> Ops(NumConcat); 7859 Ops[0] = Vec; 7860 SDValue UndefVec = DAG.getUNDEF(VecVT); 7861 for (unsigned i = 1; i < NumConcat; ++i) 7862 Ops[i] = UndefVec; 7863 7864 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7865 } 7866 7867 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7868 const SDLoc &dl) const { 7869 7870 unsigned Opc = Op.getOpcode(); 7871 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7872 "Unexpected conversion type"); 7873 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7874 "Supports conversions to v2f64/v4f32 only."); 7875 7876 bool SignedConv = Opc == ISD::SINT_TO_FP; 7877 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7878 7879 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7880 EVT WideVT = Wide.getValueType(); 7881 unsigned WideNumElts = WideVT.getVectorNumElements(); 7882 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7883 7884 SmallVector<int, 16> ShuffV; 7885 for (unsigned i = 0; i < WideNumElts; ++i) 7886 ShuffV.push_back(i + WideNumElts); 7887 7888 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7889 int SaveElts = FourEltRes ? 4 : 2; 7890 if (Subtarget.isLittleEndian()) 7891 for (int i = 0; i < SaveElts; i++) 7892 ShuffV[i * Stride] = i; 7893 else 7894 for (int i = 1; i <= SaveElts; i++) 7895 ShuffV[i * Stride - 1] = i - 1; 7896 7897 SDValue ShuffleSrc2 = 7898 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 7899 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7900 unsigned ExtendOp = 7901 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 7902 7903 SDValue Extend; 7904 if (!Subtarget.hasP9Altivec() && SignedConv) { 7905 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 7906 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 7907 DAG.getValueType(Op.getOperand(0).getValueType())); 7908 } else 7909 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 7910 7911 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7912 } 7913 7914 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7915 SelectionDAG &DAG) const { 7916 SDLoc dl(Op); 7917 7918 EVT InVT = Op.getOperand(0).getValueType(); 7919 EVT OutVT = Op.getValueType(); 7920 if (OutVT.isVector() && OutVT.isFloatingPoint() && 7921 isOperationCustom(Op.getOpcode(), InVT)) 7922 return LowerINT_TO_FPVector(Op, DAG, dl); 7923 7924 // Conversions to f128 are legal. 7925 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7926 return Op; 7927 7928 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7929 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7930 return SDValue(); 7931 7932 SDValue Value = Op.getOperand(0); 7933 // The values are now known to be -1 (false) or 1 (true). To convert this 7934 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7935 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7936 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7937 7938 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7939 7940 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7941 7942 if (Op.getValueType() != MVT::v4f64) 7943 Value = DAG.getNode(ISD::FP_ROUND, dl, 7944 Op.getValueType(), Value, 7945 DAG.getIntPtrConstant(1, dl)); 7946 return Value; 7947 } 7948 7949 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7950 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7951 return SDValue(); 7952 7953 if (Op.getOperand(0).getValueType() == MVT::i1) 7954 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7955 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7956 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7957 7958 // If we have direct moves, we can do all the conversion, skip the store/load 7959 // however, without FPCVT we can't do most conversions. 7960 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7961 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7962 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7963 7964 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7965 "UINT_TO_FP is supported only with FPCVT"); 7966 7967 // If we have FCFIDS, then use it when converting to single-precision. 7968 // Otherwise, convert to double-precision and then round. 7969 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7970 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7971 : PPCISD::FCFIDS) 7972 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7973 : PPCISD::FCFID); 7974 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7975 ? MVT::f32 7976 : MVT::f64; 7977 7978 if (Op.getOperand(0).getValueType() == MVT::i64) { 7979 SDValue SINT = Op.getOperand(0); 7980 // When converting to single-precision, we actually need to convert 7981 // to double-precision first and then round to single-precision. 7982 // To avoid double-rounding effects during that operation, we have 7983 // to prepare the input operand. Bits that might be truncated when 7984 // converting to double-precision are replaced by a bit that won't 7985 // be lost at this stage, but is below the single-precision rounding 7986 // position. 7987 // 7988 // However, if -enable-unsafe-fp-math is in effect, accept double 7989 // rounding to avoid the extra overhead. 7990 if (Op.getValueType() == MVT::f32 && 7991 !Subtarget.hasFPCVT() && 7992 !DAG.getTarget().Options.UnsafeFPMath) { 7993 7994 // Twiddle input to make sure the low 11 bits are zero. (If this 7995 // is the case, we are guaranteed the value will fit into the 53 bit 7996 // mantissa of an IEEE double-precision value without rounding.) 7997 // If any of those low 11 bits were not zero originally, make sure 7998 // bit 12 (value 2048) is set instead, so that the final rounding 7999 // to single-precision gets the correct result. 8000 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8001 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8002 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8003 Round, DAG.getConstant(2047, dl, MVT::i64)); 8004 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8005 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8006 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8007 8008 // However, we cannot use that value unconditionally: if the magnitude 8009 // of the input value is small, the bit-twiddling we did above might 8010 // end up visibly changing the output. Fortunately, in that case, we 8011 // don't need to twiddle bits since the original input will convert 8012 // exactly to double-precision floating-point already. Therefore, 8013 // construct a conditional to use the original value if the top 11 8014 // bits are all sign-bit copies, and use the rounded value computed 8015 // above otherwise. 8016 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8017 SINT, DAG.getConstant(53, dl, MVT::i32)); 8018 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8019 Cond, DAG.getConstant(1, dl, MVT::i64)); 8020 Cond = DAG.getSetCC(dl, MVT::i32, 8021 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8022 8023 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8024 } 8025 8026 ReuseLoadInfo RLI; 8027 SDValue Bits; 8028 8029 MachineFunction &MF = DAG.getMachineFunction(); 8030 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8031 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8032 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8033 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8034 } else if (Subtarget.hasLFIWAX() && 8035 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8036 MachineMemOperand *MMO = 8037 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8038 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8039 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8040 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8041 DAG.getVTList(MVT::f64, MVT::Other), 8042 Ops, MVT::i32, MMO); 8043 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8044 } else if (Subtarget.hasFPCVT() && 8045 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8046 MachineMemOperand *MMO = 8047 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8048 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8049 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8050 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8051 DAG.getVTList(MVT::f64, MVT::Other), 8052 Ops, MVT::i32, MMO); 8053 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8054 } else if (((Subtarget.hasLFIWAX() && 8055 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8056 (Subtarget.hasFPCVT() && 8057 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8058 SINT.getOperand(0).getValueType() == MVT::i32) { 8059 MachineFrameInfo &MFI = MF.getFrameInfo(); 8060 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8061 8062 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8063 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8064 8065 SDValue Store = 8066 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8067 MachinePointerInfo::getFixedStack( 8068 DAG.getMachineFunction(), FrameIdx)); 8069 8070 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8071 "Expected an i32 store"); 8072 8073 RLI.Ptr = FIdx; 8074 RLI.Chain = Store; 8075 RLI.MPI = 8076 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8077 RLI.Alignment = 4; 8078 8079 MachineMemOperand *MMO = 8080 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8081 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8082 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8083 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8084 PPCISD::LFIWZX : PPCISD::LFIWAX, 8085 dl, DAG.getVTList(MVT::f64, MVT::Other), 8086 Ops, MVT::i32, MMO); 8087 } else 8088 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8089 8090 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8091 8092 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8093 FP = DAG.getNode(ISD::FP_ROUND, dl, 8094 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8095 return FP; 8096 } 8097 8098 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8099 "Unhandled INT_TO_FP type in custom expander!"); 8100 // Since we only generate this in 64-bit mode, we can take advantage of 8101 // 64-bit registers. In particular, sign extend the input value into the 8102 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8103 // then lfd it and fcfid it. 8104 MachineFunction &MF = DAG.getMachineFunction(); 8105 MachineFrameInfo &MFI = MF.getFrameInfo(); 8106 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8107 8108 SDValue Ld; 8109 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8110 ReuseLoadInfo RLI; 8111 bool ReusingLoad; 8112 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8113 DAG))) { 8114 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8115 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8116 8117 SDValue Store = 8118 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8119 MachinePointerInfo::getFixedStack( 8120 DAG.getMachineFunction(), FrameIdx)); 8121 8122 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8123 "Expected an i32 store"); 8124 8125 RLI.Ptr = FIdx; 8126 RLI.Chain = Store; 8127 RLI.MPI = 8128 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8129 RLI.Alignment = 4; 8130 } 8131 8132 MachineMemOperand *MMO = 8133 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8134 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8135 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8136 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8137 PPCISD::LFIWZX : PPCISD::LFIWAX, 8138 dl, DAG.getVTList(MVT::f64, MVT::Other), 8139 Ops, MVT::i32, MMO); 8140 if (ReusingLoad) 8141 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8142 } else { 8143 assert(Subtarget.isPPC64() && 8144 "i32->FP without LFIWAX supported only on PPC64"); 8145 8146 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8147 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8148 8149 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8150 Op.getOperand(0)); 8151 8152 // STD the extended value into the stack slot. 8153 SDValue Store = DAG.getStore( 8154 DAG.getEntryNode(), dl, Ext64, FIdx, 8155 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8156 8157 // Load the value as a double. 8158 Ld = DAG.getLoad( 8159 MVT::f64, dl, Store, FIdx, 8160 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8161 } 8162 8163 // FCFID it and return it. 8164 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8165 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8166 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8167 DAG.getIntPtrConstant(0, dl)); 8168 return FP; 8169 } 8170 8171 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8172 SelectionDAG &DAG) const { 8173 SDLoc dl(Op); 8174 /* 8175 The rounding mode is in bits 30:31 of FPSR, and has the following 8176 settings: 8177 00 Round to nearest 8178 01 Round to 0 8179 10 Round to +inf 8180 11 Round to -inf 8181 8182 FLT_ROUNDS, on the other hand, expects the following: 8183 -1 Undefined 8184 0 Round to 0 8185 1 Round to nearest 8186 2 Round to +inf 8187 3 Round to -inf 8188 8189 To perform the conversion, we do: 8190 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8191 */ 8192 8193 MachineFunction &MF = DAG.getMachineFunction(); 8194 EVT VT = Op.getValueType(); 8195 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8196 8197 // Save FP Control Word to register 8198 EVT NodeTys[] = { 8199 MVT::f64, // return register 8200 MVT::Glue // unused in this context 8201 }; 8202 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 8203 8204 // Save FP register to stack slot 8205 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8206 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8207 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 8208 MachinePointerInfo()); 8209 8210 // Load FP Control Word from low 32 bits of stack slot. 8211 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8212 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8213 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 8214 8215 // Transform as necessary 8216 SDValue CWD1 = 8217 DAG.getNode(ISD::AND, dl, MVT::i32, 8218 CWD, DAG.getConstant(3, dl, MVT::i32)); 8219 SDValue CWD2 = 8220 DAG.getNode(ISD::SRL, dl, MVT::i32, 8221 DAG.getNode(ISD::AND, dl, MVT::i32, 8222 DAG.getNode(ISD::XOR, dl, MVT::i32, 8223 CWD, DAG.getConstant(3, dl, MVT::i32)), 8224 DAG.getConstant(3, dl, MVT::i32)), 8225 DAG.getConstant(1, dl, MVT::i32)); 8226 8227 SDValue RetVal = 8228 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8229 8230 return DAG.getNode((VT.getSizeInBits() < 16 ? 8231 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 8232 } 8233 8234 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8235 EVT VT = Op.getValueType(); 8236 unsigned BitWidth = VT.getSizeInBits(); 8237 SDLoc dl(Op); 8238 assert(Op.getNumOperands() == 3 && 8239 VT == Op.getOperand(1).getValueType() && 8240 "Unexpected SHL!"); 8241 8242 // Expand into a bunch of logical ops. Note that these ops 8243 // depend on the PPC behavior for oversized shift amounts. 8244 SDValue Lo = Op.getOperand(0); 8245 SDValue Hi = Op.getOperand(1); 8246 SDValue Amt = Op.getOperand(2); 8247 EVT AmtVT = Amt.getValueType(); 8248 8249 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8250 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8251 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8252 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8253 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8254 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8255 DAG.getConstant(-BitWidth, dl, AmtVT)); 8256 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8257 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8258 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8259 SDValue OutOps[] = { OutLo, OutHi }; 8260 return DAG.getMergeValues(OutOps, dl); 8261 } 8262 8263 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8264 EVT VT = Op.getValueType(); 8265 SDLoc dl(Op); 8266 unsigned BitWidth = VT.getSizeInBits(); 8267 assert(Op.getNumOperands() == 3 && 8268 VT == Op.getOperand(1).getValueType() && 8269 "Unexpected SRL!"); 8270 8271 // Expand into a bunch of logical ops. Note that these ops 8272 // depend on the PPC behavior for oversized shift amounts. 8273 SDValue Lo = Op.getOperand(0); 8274 SDValue Hi = Op.getOperand(1); 8275 SDValue Amt = Op.getOperand(2); 8276 EVT AmtVT = Amt.getValueType(); 8277 8278 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8279 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8280 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8281 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8282 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8283 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8284 DAG.getConstant(-BitWidth, dl, AmtVT)); 8285 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8286 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8287 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8288 SDValue OutOps[] = { OutLo, OutHi }; 8289 return DAG.getMergeValues(OutOps, dl); 8290 } 8291 8292 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8293 SDLoc dl(Op); 8294 EVT VT = Op.getValueType(); 8295 unsigned BitWidth = VT.getSizeInBits(); 8296 assert(Op.getNumOperands() == 3 && 8297 VT == Op.getOperand(1).getValueType() && 8298 "Unexpected SRA!"); 8299 8300 // Expand into a bunch of logical ops, followed by a select_cc. 8301 SDValue Lo = Op.getOperand(0); 8302 SDValue Hi = Op.getOperand(1); 8303 SDValue Amt = Op.getOperand(2); 8304 EVT AmtVT = Amt.getValueType(); 8305 8306 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8307 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8308 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8309 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8310 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8311 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8312 DAG.getConstant(-BitWidth, dl, AmtVT)); 8313 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8314 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8315 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8316 Tmp4, Tmp6, ISD::SETLE); 8317 SDValue OutOps[] = { OutLo, OutHi }; 8318 return DAG.getMergeValues(OutOps, dl); 8319 } 8320 8321 //===----------------------------------------------------------------------===// 8322 // Vector related lowering. 8323 // 8324 8325 /// BuildSplatI - Build a canonical splati of Val with an element size of 8326 /// SplatSize. Cast the result to VT. 8327 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8328 SelectionDAG &DAG, const SDLoc &dl) { 8329 static const MVT VTys[] = { // canonical VT to use for each size. 8330 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8331 }; 8332 8333 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8334 8335 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8336 if (Val == -1) 8337 SplatSize = 1; 8338 8339 EVT CanonicalVT = VTys[SplatSize-1]; 8340 8341 // Build a canonical splat for this value. 8342 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8343 } 8344 8345 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8346 /// specified intrinsic ID. 8347 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8348 const SDLoc &dl, EVT DestVT = MVT::Other) { 8349 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8350 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8351 DAG.getConstant(IID, dl, MVT::i32), Op); 8352 } 8353 8354 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8355 /// specified intrinsic ID. 8356 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8357 SelectionDAG &DAG, const SDLoc &dl, 8358 EVT DestVT = MVT::Other) { 8359 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8360 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8361 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8362 } 8363 8364 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8365 /// specified intrinsic ID. 8366 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8367 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8368 EVT DestVT = MVT::Other) { 8369 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8370 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8371 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8372 } 8373 8374 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8375 /// amount. The result has the specified value type. 8376 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8377 SelectionDAG &DAG, const SDLoc &dl) { 8378 // Force LHS/RHS to be the right type. 8379 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8380 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8381 8382 int Ops[16]; 8383 for (unsigned i = 0; i != 16; ++i) 8384 Ops[i] = i + Amt; 8385 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8386 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8387 } 8388 8389 /// Do we have an efficient pattern in a .td file for this node? 8390 /// 8391 /// \param V - pointer to the BuildVectorSDNode being matched 8392 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8393 /// 8394 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8395 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8396 /// the opposite is true (expansion is beneficial) are: 8397 /// - The node builds a vector out of integers that are not 32 or 64-bits 8398 /// - The node builds a vector out of constants 8399 /// - The node is a "load-and-splat" 8400 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8401 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8402 bool HasDirectMove, 8403 bool HasP8Vector) { 8404 EVT VecVT = V->getValueType(0); 8405 bool RightType = VecVT == MVT::v2f64 || 8406 (HasP8Vector && VecVT == MVT::v4f32) || 8407 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8408 if (!RightType) 8409 return false; 8410 8411 bool IsSplat = true; 8412 bool IsLoad = false; 8413 SDValue Op0 = V->getOperand(0); 8414 8415 // This function is called in a block that confirms the node is not a constant 8416 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8417 // different constants. 8418 if (V->isConstant()) 8419 return false; 8420 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8421 if (V->getOperand(i).isUndef()) 8422 return false; 8423 // We want to expand nodes that represent load-and-splat even if the 8424 // loaded value is a floating point truncation or conversion to int. 8425 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8426 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8427 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8428 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8429 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8430 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8431 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8432 IsLoad = true; 8433 // If the operands are different or the input is not a load and has more 8434 // uses than just this BV node, then it isn't a splat. 8435 if (V->getOperand(i) != Op0 || 8436 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8437 IsSplat = false; 8438 } 8439 return !(IsSplat && IsLoad); 8440 } 8441 8442 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8443 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8444 8445 SDLoc dl(Op); 8446 SDValue Op0 = Op->getOperand(0); 8447 8448 if (!EnableQuadPrecision || 8449 (Op.getValueType() != MVT::f128 ) || 8450 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8451 (Op0.getOperand(0).getValueType() != MVT::i64) || 8452 (Op0.getOperand(1).getValueType() != MVT::i64)) 8453 return SDValue(); 8454 8455 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8456 Op0.getOperand(1)); 8457 } 8458 8459 static const SDValue *getNormalLoadInput(const SDValue &Op) { 8460 const SDValue *InputLoad = &Op; 8461 if (InputLoad->getOpcode() == ISD::BITCAST) 8462 InputLoad = &InputLoad->getOperand(0); 8463 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 8464 InputLoad = &InputLoad->getOperand(0); 8465 if (InputLoad->getOpcode() != ISD::LOAD) 8466 return nullptr; 8467 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8468 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8469 } 8470 8471 // If this is a case we can't handle, return null and let the default 8472 // expansion code take care of it. If we CAN select this case, and if it 8473 // selects to a single instruction, return Op. Otherwise, if we can codegen 8474 // this case more efficiently than a constant pool load, lower it to the 8475 // sequence of ops that should be used. 8476 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8477 SelectionDAG &DAG) const { 8478 SDLoc dl(Op); 8479 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8480 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8481 8482 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 8483 // We first build an i32 vector, load it into a QPX register, 8484 // then convert it to a floating-point vector and compare it 8485 // to a zero vector to get the boolean result. 8486 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8487 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8488 MachinePointerInfo PtrInfo = 8489 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8490 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8491 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8492 8493 assert(BVN->getNumOperands() == 4 && 8494 "BUILD_VECTOR for v4i1 does not have 4 operands"); 8495 8496 bool IsConst = true; 8497 for (unsigned i = 0; i < 4; ++i) { 8498 if (BVN->getOperand(i).isUndef()) continue; 8499 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 8500 IsConst = false; 8501 break; 8502 } 8503 } 8504 8505 if (IsConst) { 8506 Constant *One = 8507 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 8508 Constant *NegOne = 8509 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 8510 8511 Constant *CV[4]; 8512 for (unsigned i = 0; i < 4; ++i) { 8513 if (BVN->getOperand(i).isUndef()) 8514 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 8515 else if (isNullConstant(BVN->getOperand(i))) 8516 CV[i] = NegOne; 8517 else 8518 CV[i] = One; 8519 } 8520 8521 Constant *CP = ConstantVector::get(CV); 8522 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 8523 16 /* alignment */); 8524 8525 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 8526 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 8527 return DAG.getMemIntrinsicNode( 8528 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 8529 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 8530 } 8531 8532 SmallVector<SDValue, 4> Stores; 8533 for (unsigned i = 0; i < 4; ++i) { 8534 if (BVN->getOperand(i).isUndef()) continue; 8535 8536 unsigned Offset = 4*i; 8537 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8538 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8539 8540 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 8541 if (StoreSize > 4) { 8542 Stores.push_back( 8543 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 8544 PtrInfo.getWithOffset(Offset), MVT::i32)); 8545 } else { 8546 SDValue StoreValue = BVN->getOperand(i); 8547 if (StoreSize < 4) 8548 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 8549 8550 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 8551 PtrInfo.getWithOffset(Offset))); 8552 } 8553 } 8554 8555 SDValue StoreChain; 8556 if (!Stores.empty()) 8557 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8558 else 8559 StoreChain = DAG.getEntryNode(); 8560 8561 // Now load from v4i32 into the QPX register; this will extend it to 8562 // v4i64 but not yet convert it to a floating point. Nevertheless, this 8563 // is typed as v4f64 because the QPX register integer states are not 8564 // explicitly represented. 8565 8566 SDValue Ops[] = {StoreChain, 8567 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 8568 FIdx}; 8569 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 8570 8571 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 8572 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8573 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8574 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 8575 LoadedVect); 8576 8577 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 8578 8579 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 8580 } 8581 8582 // All other QPX vectors are handled by generic code. 8583 if (Subtarget.hasQPX()) 8584 return SDValue(); 8585 8586 // Check if this is a splat of a constant value. 8587 APInt APSplatBits, APSplatUndef; 8588 unsigned SplatBitSize; 8589 bool HasAnyUndefs; 8590 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8591 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8592 SplatBitSize > 32) { 8593 8594 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 8595 // Handle load-and-splat patterns as we have instructions that will do this 8596 // in one go. 8597 if (InputLoad && DAG.isSplatValue(Op, true)) { 8598 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8599 8600 // We have handling for 4 and 8 byte elements. 8601 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 8602 8603 // Checking for a single use of this load, we have to check for vector 8604 // width (128 bits) / ElementSize uses (since each operand of the 8605 // BUILD_VECTOR is a separate use of the value. 8606 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 8607 ((Subtarget.hasVSX() && ElementSize == 64) || 8608 (Subtarget.hasP9Vector() && ElementSize == 32))) { 8609 SDValue Ops[] = { 8610 LD->getChain(), // Chain 8611 LD->getBasePtr(), // Ptr 8612 DAG.getValueType(Op.getValueType()) // VT 8613 }; 8614 return 8615 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 8616 DAG.getVTList(Op.getValueType(), MVT::Other), 8617 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8618 } 8619 } 8620 8621 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8622 // lowered to VSX instructions under certain conditions. 8623 // Without VSX, there is no pattern more efficient than expanding the node. 8624 if (Subtarget.hasVSX() && 8625 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8626 Subtarget.hasP8Vector())) 8627 return Op; 8628 return SDValue(); 8629 } 8630 8631 unsigned SplatBits = APSplatBits.getZExtValue(); 8632 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8633 unsigned SplatSize = SplatBitSize / 8; 8634 8635 // First, handle single instruction cases. 8636 8637 // All zeros? 8638 if (SplatBits == 0) { 8639 // Canonicalize all zero vectors to be v4i32. 8640 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8641 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8642 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8643 } 8644 return Op; 8645 } 8646 8647 // We have XXSPLTIB for constant splats one byte wide 8648 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 8649 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 8650 if (Subtarget.hasP9Vector() && SplatSize == 1) 8651 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 8652 8653 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8654 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8655 (32-SplatBitSize)); 8656 if (SextVal >= -16 && SextVal <= 15) 8657 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8658 8659 // Two instruction sequences. 8660 8661 // If this value is in the range [-32,30] and is even, use: 8662 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8663 // If this value is in the range [17,31] and is odd, use: 8664 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8665 // If this value is in the range [-31,-17] and is odd, use: 8666 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8667 // Note the last two are three-instruction sequences. 8668 if (SextVal >= -32 && SextVal <= 31) { 8669 // To avoid having these optimizations undone by constant folding, 8670 // we convert to a pseudo that will be expanded later into one of 8671 // the above forms. 8672 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8673 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8674 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8675 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8676 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8677 if (VT == Op.getValueType()) 8678 return RetVal; 8679 else 8680 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8681 } 8682 8683 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8684 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8685 // for fneg/fabs. 8686 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8687 // Make -1 and vspltisw -1: 8688 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8689 8690 // Make the VSLW intrinsic, computing 0x8000_0000. 8691 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8692 OnesV, DAG, dl); 8693 8694 // xor by OnesV to invert it. 8695 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8696 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8697 } 8698 8699 // Check to see if this is a wide variety of vsplti*, binop self cases. 8700 static const signed char SplatCsts[] = { 8701 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8702 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8703 }; 8704 8705 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8706 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8707 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8708 int i = SplatCsts[idx]; 8709 8710 // Figure out what shift amount will be used by altivec if shifted by i in 8711 // this splat size. 8712 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8713 8714 // vsplti + shl self. 8715 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8716 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8717 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8718 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8719 Intrinsic::ppc_altivec_vslw 8720 }; 8721 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8722 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8723 } 8724 8725 // vsplti + srl self. 8726 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8727 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8728 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8729 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8730 Intrinsic::ppc_altivec_vsrw 8731 }; 8732 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8733 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8734 } 8735 8736 // vsplti + sra self. 8737 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8738 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8739 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8740 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8741 Intrinsic::ppc_altivec_vsraw 8742 }; 8743 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8744 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8745 } 8746 8747 // vsplti + rol self. 8748 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8749 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8750 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8751 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8752 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8753 Intrinsic::ppc_altivec_vrlw 8754 }; 8755 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8756 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8757 } 8758 8759 // t = vsplti c, result = vsldoi t, t, 1 8760 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8761 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8762 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8763 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8764 } 8765 // t = vsplti c, result = vsldoi t, t, 2 8766 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8767 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8768 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8769 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8770 } 8771 // t = vsplti c, result = vsldoi t, t, 3 8772 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8773 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8774 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8775 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8776 } 8777 } 8778 8779 return SDValue(); 8780 } 8781 8782 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8783 /// the specified operations to build the shuffle. 8784 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8785 SDValue RHS, SelectionDAG &DAG, 8786 const SDLoc &dl) { 8787 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8788 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8789 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8790 8791 enum { 8792 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8793 OP_VMRGHW, 8794 OP_VMRGLW, 8795 OP_VSPLTISW0, 8796 OP_VSPLTISW1, 8797 OP_VSPLTISW2, 8798 OP_VSPLTISW3, 8799 OP_VSLDOI4, 8800 OP_VSLDOI8, 8801 OP_VSLDOI12 8802 }; 8803 8804 if (OpNum == OP_COPY) { 8805 if (LHSID == (1*9+2)*9+3) return LHS; 8806 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8807 return RHS; 8808 } 8809 8810 SDValue OpLHS, OpRHS; 8811 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8812 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8813 8814 int ShufIdxs[16]; 8815 switch (OpNum) { 8816 default: llvm_unreachable("Unknown i32 permute!"); 8817 case OP_VMRGHW: 8818 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8819 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8820 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8821 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8822 break; 8823 case OP_VMRGLW: 8824 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8825 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8826 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8827 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8828 break; 8829 case OP_VSPLTISW0: 8830 for (unsigned i = 0; i != 16; ++i) 8831 ShufIdxs[i] = (i&3)+0; 8832 break; 8833 case OP_VSPLTISW1: 8834 for (unsigned i = 0; i != 16; ++i) 8835 ShufIdxs[i] = (i&3)+4; 8836 break; 8837 case OP_VSPLTISW2: 8838 for (unsigned i = 0; i != 16; ++i) 8839 ShufIdxs[i] = (i&3)+8; 8840 break; 8841 case OP_VSPLTISW3: 8842 for (unsigned i = 0; i != 16; ++i) 8843 ShufIdxs[i] = (i&3)+12; 8844 break; 8845 case OP_VSLDOI4: 8846 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8847 case OP_VSLDOI8: 8848 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8849 case OP_VSLDOI12: 8850 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8851 } 8852 EVT VT = OpLHS.getValueType(); 8853 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8854 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8855 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8856 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8857 } 8858 8859 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8860 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8861 /// SDValue. 8862 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8863 SelectionDAG &DAG) const { 8864 const unsigned BytesInVector = 16; 8865 bool IsLE = Subtarget.isLittleEndian(); 8866 SDLoc dl(N); 8867 SDValue V1 = N->getOperand(0); 8868 SDValue V2 = N->getOperand(1); 8869 unsigned ShiftElts = 0, InsertAtByte = 0; 8870 bool Swap = false; 8871 8872 // Shifts required to get the byte we want at element 7. 8873 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8874 0, 15, 14, 13, 12, 11, 10, 9}; 8875 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8876 1, 2, 3, 4, 5, 6, 7, 8}; 8877 8878 ArrayRef<int> Mask = N->getMask(); 8879 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8880 8881 // For each mask element, find out if we're just inserting something 8882 // from V2 into V1 or vice versa. 8883 // Possible permutations inserting an element from V2 into V1: 8884 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8885 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8886 // ... 8887 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8888 // Inserting from V1 into V2 will be similar, except mask range will be 8889 // [16,31]. 8890 8891 bool FoundCandidate = false; 8892 // If both vector operands for the shuffle are the same vector, the mask 8893 // will contain only elements from the first one and the second one will be 8894 // undef. 8895 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8896 // Go through the mask of half-words to find an element that's being moved 8897 // from one vector to the other. 8898 for (unsigned i = 0; i < BytesInVector; ++i) { 8899 unsigned CurrentElement = Mask[i]; 8900 // If 2nd operand is undefined, we should only look for element 7 in the 8901 // Mask. 8902 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8903 continue; 8904 8905 bool OtherElementsInOrder = true; 8906 // Examine the other elements in the Mask to see if they're in original 8907 // order. 8908 for (unsigned j = 0; j < BytesInVector; ++j) { 8909 if (j == i) 8910 continue; 8911 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8912 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8913 // in which we always assume we're always picking from the 1st operand. 8914 int MaskOffset = 8915 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8916 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8917 OtherElementsInOrder = false; 8918 break; 8919 } 8920 } 8921 // If other elements are in original order, we record the number of shifts 8922 // we need to get the element we want into element 7. Also record which byte 8923 // in the vector we should insert into. 8924 if (OtherElementsInOrder) { 8925 // If 2nd operand is undefined, we assume no shifts and no swapping. 8926 if (V2.isUndef()) { 8927 ShiftElts = 0; 8928 Swap = false; 8929 } else { 8930 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8931 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8932 : BigEndianShifts[CurrentElement & 0xF]; 8933 Swap = CurrentElement < BytesInVector; 8934 } 8935 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8936 FoundCandidate = true; 8937 break; 8938 } 8939 } 8940 8941 if (!FoundCandidate) 8942 return SDValue(); 8943 8944 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8945 // optionally with VECSHL if shift is required. 8946 if (Swap) 8947 std::swap(V1, V2); 8948 if (V2.isUndef()) 8949 V2 = V1; 8950 if (ShiftElts) { 8951 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8952 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8953 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8954 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8955 } 8956 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8957 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8958 } 8959 8960 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8961 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8962 /// SDValue. 8963 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8964 SelectionDAG &DAG) const { 8965 const unsigned NumHalfWords = 8; 8966 const unsigned BytesInVector = NumHalfWords * 2; 8967 // Check that the shuffle is on half-words. 8968 if (!isNByteElemShuffleMask(N, 2, 1)) 8969 return SDValue(); 8970 8971 bool IsLE = Subtarget.isLittleEndian(); 8972 SDLoc dl(N); 8973 SDValue V1 = N->getOperand(0); 8974 SDValue V2 = N->getOperand(1); 8975 unsigned ShiftElts = 0, InsertAtByte = 0; 8976 bool Swap = false; 8977 8978 // Shifts required to get the half-word we want at element 3. 8979 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8980 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8981 8982 uint32_t Mask = 0; 8983 uint32_t OriginalOrderLow = 0x1234567; 8984 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8985 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8986 // 32-bit space, only need 4-bit nibbles per element. 8987 for (unsigned i = 0; i < NumHalfWords; ++i) { 8988 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8989 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8990 } 8991 8992 // For each mask element, find out if we're just inserting something 8993 // from V2 into V1 or vice versa. Possible permutations inserting an element 8994 // from V2 into V1: 8995 // X, 1, 2, 3, 4, 5, 6, 7 8996 // 0, X, 2, 3, 4, 5, 6, 7 8997 // 0, 1, X, 3, 4, 5, 6, 7 8998 // 0, 1, 2, X, 4, 5, 6, 7 8999 // 0, 1, 2, 3, X, 5, 6, 7 9000 // 0, 1, 2, 3, 4, X, 6, 7 9001 // 0, 1, 2, 3, 4, 5, X, 7 9002 // 0, 1, 2, 3, 4, 5, 6, X 9003 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9004 9005 bool FoundCandidate = false; 9006 // Go through the mask of half-words to find an element that's being moved 9007 // from one vector to the other. 9008 for (unsigned i = 0; i < NumHalfWords; ++i) { 9009 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9010 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9011 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9012 uint32_t TargetOrder = 0x0; 9013 9014 // If both vector operands for the shuffle are the same vector, the mask 9015 // will contain only elements from the first one and the second one will be 9016 // undef. 9017 if (V2.isUndef()) { 9018 ShiftElts = 0; 9019 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9020 TargetOrder = OriginalOrderLow; 9021 Swap = false; 9022 // Skip if not the correct element or mask of other elements don't equal 9023 // to our expected order. 9024 if (MaskOneElt == VINSERTHSrcElem && 9025 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9026 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9027 FoundCandidate = true; 9028 break; 9029 } 9030 } else { // If both operands are defined. 9031 // Target order is [8,15] if the current mask is between [0,7]. 9032 TargetOrder = 9033 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9034 // Skip if mask of other elements don't equal our expected order. 9035 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9036 // We only need the last 3 bits for the number of shifts. 9037 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9038 : BigEndianShifts[MaskOneElt & 0x7]; 9039 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9040 Swap = MaskOneElt < NumHalfWords; 9041 FoundCandidate = true; 9042 break; 9043 } 9044 } 9045 } 9046 9047 if (!FoundCandidate) 9048 return SDValue(); 9049 9050 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9051 // optionally with VECSHL if shift is required. 9052 if (Swap) 9053 std::swap(V1, V2); 9054 if (V2.isUndef()) 9055 V2 = V1; 9056 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9057 if (ShiftElts) { 9058 // Double ShiftElts because we're left shifting on v16i8 type. 9059 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9060 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9061 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9062 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9063 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9064 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9065 } 9066 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9067 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9068 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9069 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9070 } 9071 9072 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9073 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9074 /// return the code it can be lowered into. Worst case, it can always be 9075 /// lowered into a vperm. 9076 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9077 SelectionDAG &DAG) const { 9078 SDLoc dl(Op); 9079 SDValue V1 = Op.getOperand(0); 9080 SDValue V2 = Op.getOperand(1); 9081 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9082 EVT VT = Op.getValueType(); 9083 bool isLittleEndian = Subtarget.isLittleEndian(); 9084 9085 unsigned ShiftElts, InsertAtByte; 9086 bool Swap = false; 9087 9088 // If this is a load-and-splat, we can do that with a single instruction 9089 // in some cases. However if the load has multiple uses, we don't want to 9090 // combine it because that will just produce multiple loads. 9091 const SDValue *InputLoad = getNormalLoadInput(V1); 9092 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9093 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9094 InputLoad->hasOneUse()) { 9095 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9096 int SplatIdx = 9097 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9098 9099 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9100 // For 4-byte load-and-splat, we need Power9. 9101 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9102 uint64_t Offset = 0; 9103 if (IsFourByte) 9104 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9105 else 9106 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9107 SDValue BasePtr = LD->getBasePtr(); 9108 if (Offset != 0) 9109 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9110 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9111 SDValue Ops[] = { 9112 LD->getChain(), // Chain 9113 BasePtr, // BasePtr 9114 DAG.getValueType(Op.getValueType()) // VT 9115 }; 9116 SDVTList VTL = 9117 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9118 SDValue LdSplt = 9119 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9120 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9121 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9122 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9123 return LdSplt; 9124 } 9125 } 9126 if (Subtarget.hasP9Vector() && 9127 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9128 isLittleEndian)) { 9129 if (Swap) 9130 std::swap(V1, V2); 9131 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9132 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9133 if (ShiftElts) { 9134 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9135 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9136 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9137 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9138 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9139 } 9140 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9141 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9142 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9143 } 9144 9145 if (Subtarget.hasP9Altivec()) { 9146 SDValue NewISDNode; 9147 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9148 return NewISDNode; 9149 9150 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9151 return NewISDNode; 9152 } 9153 9154 if (Subtarget.hasVSX() && 9155 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9156 if (Swap) 9157 std::swap(V1, V2); 9158 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9159 SDValue Conv2 = 9160 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9161 9162 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9163 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9164 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9165 } 9166 9167 if (Subtarget.hasVSX() && 9168 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9169 if (Swap) 9170 std::swap(V1, V2); 9171 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9172 SDValue Conv2 = 9173 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9174 9175 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9176 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9177 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9178 } 9179 9180 if (Subtarget.hasP9Vector()) { 9181 if (PPC::isXXBRHShuffleMask(SVOp)) { 9182 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9183 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 9184 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9185 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9186 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9187 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 9188 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9189 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9190 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9191 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 9192 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9193 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9194 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9195 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 9196 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9197 } 9198 } 9199 9200 if (Subtarget.hasVSX()) { 9201 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9202 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9203 9204 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9205 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9206 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9207 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9208 } 9209 9210 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9211 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9212 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9213 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9214 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9215 } 9216 } 9217 9218 if (Subtarget.hasQPX()) { 9219 if (VT.getVectorNumElements() != 4) 9220 return SDValue(); 9221 9222 if (V2.isUndef()) V2 = V1; 9223 9224 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9225 if (AlignIdx != -1) { 9226 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9227 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9228 } else if (SVOp->isSplat()) { 9229 int SplatIdx = SVOp->getSplatIndex(); 9230 if (SplatIdx >= 4) { 9231 std::swap(V1, V2); 9232 SplatIdx -= 4; 9233 } 9234 9235 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9236 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9237 } 9238 9239 // Lower this into a qvgpci/qvfperm pair. 9240 9241 // Compute the qvgpci literal 9242 unsigned idx = 0; 9243 for (unsigned i = 0; i < 4; ++i) { 9244 int m = SVOp->getMaskElt(i); 9245 unsigned mm = m >= 0 ? (unsigned) m : i; 9246 idx |= mm << (3-i)*3; 9247 } 9248 9249 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9250 DAG.getConstant(idx, dl, MVT::i32)); 9251 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9252 } 9253 9254 // Cases that are handled by instructions that take permute immediates 9255 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9256 // selected by the instruction selector. 9257 if (V2.isUndef()) { 9258 if (PPC::isSplatShuffleMask(SVOp, 1) || 9259 PPC::isSplatShuffleMask(SVOp, 2) || 9260 PPC::isSplatShuffleMask(SVOp, 4) || 9261 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9262 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9263 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9264 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9265 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9266 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9267 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9268 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9269 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9270 (Subtarget.hasP8Altivec() && ( 9271 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9272 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9273 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9274 return Op; 9275 } 9276 } 9277 9278 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9279 // and produce a fixed permutation. If any of these match, do not lower to 9280 // VPERM. 9281 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9282 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9283 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9284 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9285 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9286 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9287 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9288 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9289 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9290 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9291 (Subtarget.hasP8Altivec() && ( 9292 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9293 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9294 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9295 return Op; 9296 9297 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9298 // perfect shuffle table to emit an optimal matching sequence. 9299 ArrayRef<int> PermMask = SVOp->getMask(); 9300 9301 unsigned PFIndexes[4]; 9302 bool isFourElementShuffle = true; 9303 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9304 unsigned EltNo = 8; // Start out undef. 9305 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9306 if (PermMask[i*4+j] < 0) 9307 continue; // Undef, ignore it. 9308 9309 unsigned ByteSource = PermMask[i*4+j]; 9310 if ((ByteSource & 3) != j) { 9311 isFourElementShuffle = false; 9312 break; 9313 } 9314 9315 if (EltNo == 8) { 9316 EltNo = ByteSource/4; 9317 } else if (EltNo != ByteSource/4) { 9318 isFourElementShuffle = false; 9319 break; 9320 } 9321 } 9322 PFIndexes[i] = EltNo; 9323 } 9324 9325 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9326 // perfect shuffle vector to determine if it is cost effective to do this as 9327 // discrete instructions, or whether we should use a vperm. 9328 // For now, we skip this for little endian until such time as we have a 9329 // little-endian perfect shuffle table. 9330 if (isFourElementShuffle && !isLittleEndian) { 9331 // Compute the index in the perfect shuffle table. 9332 unsigned PFTableIndex = 9333 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9334 9335 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9336 unsigned Cost = (PFEntry >> 30); 9337 9338 // Determining when to avoid vperm is tricky. Many things affect the cost 9339 // of vperm, particularly how many times the perm mask needs to be computed. 9340 // For example, if the perm mask can be hoisted out of a loop or is already 9341 // used (perhaps because there are multiple permutes with the same shuffle 9342 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9343 // the loop requires an extra register. 9344 // 9345 // As a compromise, we only emit discrete instructions if the shuffle can be 9346 // generated in 3 or fewer operations. When we have loop information 9347 // available, if this block is within a loop, we should avoid using vperm 9348 // for 3-operation perms and use a constant pool load instead. 9349 if (Cost < 3) 9350 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9351 } 9352 9353 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9354 // vector that will get spilled to the constant pool. 9355 if (V2.isUndef()) V2 = V1; 9356 9357 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9358 // that it is in input element units, not in bytes. Convert now. 9359 9360 // For little endian, the order of the input vectors is reversed, and 9361 // the permutation mask is complemented with respect to 31. This is 9362 // necessary to produce proper semantics with the big-endian-biased vperm 9363 // instruction. 9364 EVT EltVT = V1.getValueType().getVectorElementType(); 9365 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9366 9367 SmallVector<SDValue, 16> ResultMask; 9368 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9369 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9370 9371 for (unsigned j = 0; j != BytesPerElement; ++j) 9372 if (isLittleEndian) 9373 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9374 dl, MVT::i32)); 9375 else 9376 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9377 MVT::i32)); 9378 } 9379 9380 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9381 if (isLittleEndian) 9382 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9383 V2, V1, VPermMask); 9384 else 9385 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9386 V1, V2, VPermMask); 9387 } 9388 9389 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9390 /// vector comparison. If it is, return true and fill in Opc/isDot with 9391 /// information about the intrinsic. 9392 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9393 bool &isDot, const PPCSubtarget &Subtarget) { 9394 unsigned IntrinsicID = 9395 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9396 CompareOpc = -1; 9397 isDot = false; 9398 switch (IntrinsicID) { 9399 default: 9400 return false; 9401 // Comparison predicates. 9402 case Intrinsic::ppc_altivec_vcmpbfp_p: 9403 CompareOpc = 966; 9404 isDot = true; 9405 break; 9406 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9407 CompareOpc = 198; 9408 isDot = true; 9409 break; 9410 case Intrinsic::ppc_altivec_vcmpequb_p: 9411 CompareOpc = 6; 9412 isDot = true; 9413 break; 9414 case Intrinsic::ppc_altivec_vcmpequh_p: 9415 CompareOpc = 70; 9416 isDot = true; 9417 break; 9418 case Intrinsic::ppc_altivec_vcmpequw_p: 9419 CompareOpc = 134; 9420 isDot = true; 9421 break; 9422 case Intrinsic::ppc_altivec_vcmpequd_p: 9423 if (Subtarget.hasP8Altivec()) { 9424 CompareOpc = 199; 9425 isDot = true; 9426 } else 9427 return false; 9428 break; 9429 case Intrinsic::ppc_altivec_vcmpneb_p: 9430 case Intrinsic::ppc_altivec_vcmpneh_p: 9431 case Intrinsic::ppc_altivec_vcmpnew_p: 9432 case Intrinsic::ppc_altivec_vcmpnezb_p: 9433 case Intrinsic::ppc_altivec_vcmpnezh_p: 9434 case Intrinsic::ppc_altivec_vcmpnezw_p: 9435 if (Subtarget.hasP9Altivec()) { 9436 switch (IntrinsicID) { 9437 default: 9438 llvm_unreachable("Unknown comparison intrinsic."); 9439 case Intrinsic::ppc_altivec_vcmpneb_p: 9440 CompareOpc = 7; 9441 break; 9442 case Intrinsic::ppc_altivec_vcmpneh_p: 9443 CompareOpc = 71; 9444 break; 9445 case Intrinsic::ppc_altivec_vcmpnew_p: 9446 CompareOpc = 135; 9447 break; 9448 case Intrinsic::ppc_altivec_vcmpnezb_p: 9449 CompareOpc = 263; 9450 break; 9451 case Intrinsic::ppc_altivec_vcmpnezh_p: 9452 CompareOpc = 327; 9453 break; 9454 case Intrinsic::ppc_altivec_vcmpnezw_p: 9455 CompareOpc = 391; 9456 break; 9457 } 9458 isDot = true; 9459 } else 9460 return false; 9461 break; 9462 case Intrinsic::ppc_altivec_vcmpgefp_p: 9463 CompareOpc = 454; 9464 isDot = true; 9465 break; 9466 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9467 CompareOpc = 710; 9468 isDot = true; 9469 break; 9470 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9471 CompareOpc = 774; 9472 isDot = true; 9473 break; 9474 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9475 CompareOpc = 838; 9476 isDot = true; 9477 break; 9478 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9479 CompareOpc = 902; 9480 isDot = true; 9481 break; 9482 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9483 if (Subtarget.hasP8Altivec()) { 9484 CompareOpc = 967; 9485 isDot = true; 9486 } else 9487 return false; 9488 break; 9489 case Intrinsic::ppc_altivec_vcmpgtub_p: 9490 CompareOpc = 518; 9491 isDot = true; 9492 break; 9493 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9494 CompareOpc = 582; 9495 isDot = true; 9496 break; 9497 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9498 CompareOpc = 646; 9499 isDot = true; 9500 break; 9501 case Intrinsic::ppc_altivec_vcmpgtud_p: 9502 if (Subtarget.hasP8Altivec()) { 9503 CompareOpc = 711; 9504 isDot = true; 9505 } else 9506 return false; 9507 break; 9508 9509 // VSX predicate comparisons use the same infrastructure 9510 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9511 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9512 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9513 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9514 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9515 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9516 if (Subtarget.hasVSX()) { 9517 switch (IntrinsicID) { 9518 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9519 CompareOpc = 99; 9520 break; 9521 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9522 CompareOpc = 115; 9523 break; 9524 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9525 CompareOpc = 107; 9526 break; 9527 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9528 CompareOpc = 67; 9529 break; 9530 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9531 CompareOpc = 83; 9532 break; 9533 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9534 CompareOpc = 75; 9535 break; 9536 } 9537 isDot = true; 9538 } else 9539 return false; 9540 break; 9541 9542 // Normal Comparisons. 9543 case Intrinsic::ppc_altivec_vcmpbfp: 9544 CompareOpc = 966; 9545 break; 9546 case Intrinsic::ppc_altivec_vcmpeqfp: 9547 CompareOpc = 198; 9548 break; 9549 case Intrinsic::ppc_altivec_vcmpequb: 9550 CompareOpc = 6; 9551 break; 9552 case Intrinsic::ppc_altivec_vcmpequh: 9553 CompareOpc = 70; 9554 break; 9555 case Intrinsic::ppc_altivec_vcmpequw: 9556 CompareOpc = 134; 9557 break; 9558 case Intrinsic::ppc_altivec_vcmpequd: 9559 if (Subtarget.hasP8Altivec()) 9560 CompareOpc = 199; 9561 else 9562 return false; 9563 break; 9564 case Intrinsic::ppc_altivec_vcmpneb: 9565 case Intrinsic::ppc_altivec_vcmpneh: 9566 case Intrinsic::ppc_altivec_vcmpnew: 9567 case Intrinsic::ppc_altivec_vcmpnezb: 9568 case Intrinsic::ppc_altivec_vcmpnezh: 9569 case Intrinsic::ppc_altivec_vcmpnezw: 9570 if (Subtarget.hasP9Altivec()) 9571 switch (IntrinsicID) { 9572 default: 9573 llvm_unreachable("Unknown comparison intrinsic."); 9574 case Intrinsic::ppc_altivec_vcmpneb: 9575 CompareOpc = 7; 9576 break; 9577 case Intrinsic::ppc_altivec_vcmpneh: 9578 CompareOpc = 71; 9579 break; 9580 case Intrinsic::ppc_altivec_vcmpnew: 9581 CompareOpc = 135; 9582 break; 9583 case Intrinsic::ppc_altivec_vcmpnezb: 9584 CompareOpc = 263; 9585 break; 9586 case Intrinsic::ppc_altivec_vcmpnezh: 9587 CompareOpc = 327; 9588 break; 9589 case Intrinsic::ppc_altivec_vcmpnezw: 9590 CompareOpc = 391; 9591 break; 9592 } 9593 else 9594 return false; 9595 break; 9596 case Intrinsic::ppc_altivec_vcmpgefp: 9597 CompareOpc = 454; 9598 break; 9599 case Intrinsic::ppc_altivec_vcmpgtfp: 9600 CompareOpc = 710; 9601 break; 9602 case Intrinsic::ppc_altivec_vcmpgtsb: 9603 CompareOpc = 774; 9604 break; 9605 case Intrinsic::ppc_altivec_vcmpgtsh: 9606 CompareOpc = 838; 9607 break; 9608 case Intrinsic::ppc_altivec_vcmpgtsw: 9609 CompareOpc = 902; 9610 break; 9611 case Intrinsic::ppc_altivec_vcmpgtsd: 9612 if (Subtarget.hasP8Altivec()) 9613 CompareOpc = 967; 9614 else 9615 return false; 9616 break; 9617 case Intrinsic::ppc_altivec_vcmpgtub: 9618 CompareOpc = 518; 9619 break; 9620 case Intrinsic::ppc_altivec_vcmpgtuh: 9621 CompareOpc = 582; 9622 break; 9623 case Intrinsic::ppc_altivec_vcmpgtuw: 9624 CompareOpc = 646; 9625 break; 9626 case Intrinsic::ppc_altivec_vcmpgtud: 9627 if (Subtarget.hasP8Altivec()) 9628 CompareOpc = 711; 9629 else 9630 return false; 9631 break; 9632 } 9633 return true; 9634 } 9635 9636 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 9637 /// lower, do it, otherwise return null. 9638 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 9639 SelectionDAG &DAG) const { 9640 unsigned IntrinsicID = 9641 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9642 9643 SDLoc dl(Op); 9644 9645 if (IntrinsicID == Intrinsic::thread_pointer) { 9646 // Reads the thread pointer register, used for __builtin_thread_pointer. 9647 if (Subtarget.isPPC64()) 9648 return DAG.getRegister(PPC::X13, MVT::i64); 9649 return DAG.getRegister(PPC::R2, MVT::i32); 9650 } 9651 9652 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9653 // opcode number of the comparison. 9654 int CompareOpc; 9655 bool isDot; 9656 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9657 return SDValue(); // Don't custom lower most intrinsics. 9658 9659 // If this is a non-dot comparison, make the VCMP node and we are done. 9660 if (!isDot) { 9661 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9662 Op.getOperand(1), Op.getOperand(2), 9663 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9664 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9665 } 9666 9667 // Create the PPCISD altivec 'dot' comparison node. 9668 SDValue Ops[] = { 9669 Op.getOperand(2), // LHS 9670 Op.getOperand(3), // RHS 9671 DAG.getConstant(CompareOpc, dl, MVT::i32) 9672 }; 9673 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9674 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9675 9676 // Now that we have the comparison, emit a copy from the CR to a GPR. 9677 // This is flagged to the above dot comparison. 9678 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9679 DAG.getRegister(PPC::CR6, MVT::i32), 9680 CompNode.getValue(1)); 9681 9682 // Unpack the result based on how the target uses it. 9683 unsigned BitNo; // Bit # of CR6. 9684 bool InvertBit; // Invert result? 9685 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9686 default: // Can't happen, don't crash on invalid number though. 9687 case 0: // Return the value of the EQ bit of CR6. 9688 BitNo = 0; InvertBit = false; 9689 break; 9690 case 1: // Return the inverted value of the EQ bit of CR6. 9691 BitNo = 0; InvertBit = true; 9692 break; 9693 case 2: // Return the value of the LT bit of CR6. 9694 BitNo = 2; InvertBit = false; 9695 break; 9696 case 3: // Return the inverted value of the LT bit of CR6. 9697 BitNo = 2; InvertBit = true; 9698 break; 9699 } 9700 9701 // Shift the bit into the low position. 9702 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9703 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9704 // Isolate the bit. 9705 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9706 DAG.getConstant(1, dl, MVT::i32)); 9707 9708 // If we are supposed to, toggle the bit. 9709 if (InvertBit) 9710 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9711 DAG.getConstant(1, dl, MVT::i32)); 9712 return Flags; 9713 } 9714 9715 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9716 SelectionDAG &DAG) const { 9717 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9718 // the beginning of the argument list. 9719 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9720 SDLoc DL(Op); 9721 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9722 case Intrinsic::ppc_cfence: { 9723 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9724 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9725 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9726 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9727 Op.getOperand(ArgStart + 1)), 9728 Op.getOperand(0)), 9729 0); 9730 } 9731 default: 9732 break; 9733 } 9734 return SDValue(); 9735 } 9736 9737 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9738 // Check for a DIV with the same operands as this REM. 9739 for (auto UI : Op.getOperand(1)->uses()) { 9740 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9741 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9742 if (UI->getOperand(0) == Op.getOperand(0) && 9743 UI->getOperand(1) == Op.getOperand(1)) 9744 return SDValue(); 9745 } 9746 return Op; 9747 } 9748 9749 // Lower scalar BSWAP64 to xxbrd. 9750 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9751 SDLoc dl(Op); 9752 // MTVSRDD 9753 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9754 Op.getOperand(0)); 9755 // XXBRD 9756 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9757 // MFVSRD 9758 int VectorIndex = 0; 9759 if (Subtarget.isLittleEndian()) 9760 VectorIndex = 1; 9761 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9762 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9763 return Op; 9764 } 9765 9766 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9767 // compared to a value that is atomically loaded (atomic loads zero-extend). 9768 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9769 SelectionDAG &DAG) const { 9770 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9771 "Expecting an atomic compare-and-swap here."); 9772 SDLoc dl(Op); 9773 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9774 EVT MemVT = AtomicNode->getMemoryVT(); 9775 if (MemVT.getSizeInBits() >= 32) 9776 return Op; 9777 9778 SDValue CmpOp = Op.getOperand(2); 9779 // If this is already correctly zero-extended, leave it alone. 9780 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9781 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9782 return Op; 9783 9784 // Clear the high bits of the compare operand. 9785 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9786 SDValue NewCmpOp = 9787 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9788 DAG.getConstant(MaskVal, dl, MVT::i32)); 9789 9790 // Replace the existing compare operand with the properly zero-extended one. 9791 SmallVector<SDValue, 4> Ops; 9792 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9793 Ops.push_back(AtomicNode->getOperand(i)); 9794 Ops[2] = NewCmpOp; 9795 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9796 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9797 auto NodeTy = 9798 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9799 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9800 } 9801 9802 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9803 SelectionDAG &DAG) const { 9804 SDLoc dl(Op); 9805 // Create a stack slot that is 16-byte aligned. 9806 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9807 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9808 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9809 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9810 9811 // Store the input value into Value#0 of the stack slot. 9812 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9813 MachinePointerInfo()); 9814 // Load it out. 9815 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9816 } 9817 9818 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9819 SelectionDAG &DAG) const { 9820 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9821 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9822 9823 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9824 // We have legal lowering for constant indices but not for variable ones. 9825 if (!C) 9826 return SDValue(); 9827 9828 EVT VT = Op.getValueType(); 9829 SDLoc dl(Op); 9830 SDValue V1 = Op.getOperand(0); 9831 SDValue V2 = Op.getOperand(1); 9832 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9833 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9834 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9835 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9836 unsigned InsertAtElement = C->getZExtValue(); 9837 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9838 if (Subtarget.isLittleEndian()) { 9839 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9840 } 9841 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9842 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9843 } 9844 return Op; 9845 } 9846 9847 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9848 SelectionDAG &DAG) const { 9849 SDLoc dl(Op); 9850 SDNode *N = Op.getNode(); 9851 9852 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9853 "Unknown extract_vector_elt type"); 9854 9855 SDValue Value = N->getOperand(0); 9856 9857 // The first part of this is like the store lowering except that we don't 9858 // need to track the chain. 9859 9860 // The values are now known to be -1 (false) or 1 (true). To convert this 9861 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9862 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9863 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9864 9865 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9866 // understand how to form the extending load. 9867 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9868 9869 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9870 9871 // Now convert to an integer and store. 9872 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9873 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9874 Value); 9875 9876 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9877 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9878 MachinePointerInfo PtrInfo = 9879 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9880 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9881 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9882 9883 SDValue StoreChain = DAG.getEntryNode(); 9884 SDValue Ops[] = {StoreChain, 9885 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9886 Value, FIdx}; 9887 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9888 9889 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9890 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9891 9892 // Extract the value requested. 9893 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9894 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9895 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9896 9897 SDValue IntVal = 9898 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9899 9900 if (!Subtarget.useCRBits()) 9901 return IntVal; 9902 9903 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9904 } 9905 9906 /// Lowering for QPX v4i1 loads 9907 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9908 SelectionDAG &DAG) const { 9909 SDLoc dl(Op); 9910 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9911 SDValue LoadChain = LN->getChain(); 9912 SDValue BasePtr = LN->getBasePtr(); 9913 9914 if (Op.getValueType() == MVT::v4f64 || 9915 Op.getValueType() == MVT::v4f32) { 9916 EVT MemVT = LN->getMemoryVT(); 9917 unsigned Alignment = LN->getAlignment(); 9918 9919 // If this load is properly aligned, then it is legal. 9920 if (Alignment >= MemVT.getStoreSize()) 9921 return Op; 9922 9923 EVT ScalarVT = Op.getValueType().getScalarType(), 9924 ScalarMemVT = MemVT.getScalarType(); 9925 unsigned Stride = ScalarMemVT.getStoreSize(); 9926 9927 SDValue Vals[4], LoadChains[4]; 9928 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9929 SDValue Load; 9930 if (ScalarVT != ScalarMemVT) 9931 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9932 BasePtr, 9933 LN->getPointerInfo().getWithOffset(Idx * Stride), 9934 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9935 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9936 else 9937 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9938 LN->getPointerInfo().getWithOffset(Idx * Stride), 9939 MinAlign(Alignment, Idx * Stride), 9940 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9941 9942 if (Idx == 0 && LN->isIndexed()) { 9943 assert(LN->getAddressingMode() == ISD::PRE_INC && 9944 "Unknown addressing mode on vector load"); 9945 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9946 LN->getAddressingMode()); 9947 } 9948 9949 Vals[Idx] = Load; 9950 LoadChains[Idx] = Load.getValue(1); 9951 9952 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9953 DAG.getConstant(Stride, dl, 9954 BasePtr.getValueType())); 9955 } 9956 9957 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9958 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9959 9960 if (LN->isIndexed()) { 9961 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9962 return DAG.getMergeValues(RetOps, dl); 9963 } 9964 9965 SDValue RetOps[] = { Value, TF }; 9966 return DAG.getMergeValues(RetOps, dl); 9967 } 9968 9969 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9970 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9971 9972 // To lower v4i1 from a byte array, we load the byte elements of the 9973 // vector and then reuse the BUILD_VECTOR logic. 9974 9975 SDValue VectElmts[4], VectElmtChains[4]; 9976 for (unsigned i = 0; i < 4; ++i) { 9977 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9978 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9979 9980 VectElmts[i] = DAG.getExtLoad( 9981 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9982 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9983 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9984 VectElmtChains[i] = VectElmts[i].getValue(1); 9985 } 9986 9987 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9988 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9989 9990 SDValue RVals[] = { Value, LoadChain }; 9991 return DAG.getMergeValues(RVals, dl); 9992 } 9993 9994 /// Lowering for QPX v4i1 stores 9995 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9996 SelectionDAG &DAG) const { 9997 SDLoc dl(Op); 9998 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9999 SDValue StoreChain = SN->getChain(); 10000 SDValue BasePtr = SN->getBasePtr(); 10001 SDValue Value = SN->getValue(); 10002 10003 if (Value.getValueType() == MVT::v4f64 || 10004 Value.getValueType() == MVT::v4f32) { 10005 EVT MemVT = SN->getMemoryVT(); 10006 unsigned Alignment = SN->getAlignment(); 10007 10008 // If this store is properly aligned, then it is legal. 10009 if (Alignment >= MemVT.getStoreSize()) 10010 return Op; 10011 10012 EVT ScalarVT = Value.getValueType().getScalarType(), 10013 ScalarMemVT = MemVT.getScalarType(); 10014 unsigned Stride = ScalarMemVT.getStoreSize(); 10015 10016 SDValue Stores[4]; 10017 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10018 SDValue Ex = DAG.getNode( 10019 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10020 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 10021 SDValue Store; 10022 if (ScalarVT != ScalarMemVT) 10023 Store = 10024 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10025 SN->getPointerInfo().getWithOffset(Idx * Stride), 10026 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10027 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10028 else 10029 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10030 SN->getPointerInfo().getWithOffset(Idx * Stride), 10031 MinAlign(Alignment, Idx * Stride), 10032 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10033 10034 if (Idx == 0 && SN->isIndexed()) { 10035 assert(SN->getAddressingMode() == ISD::PRE_INC && 10036 "Unknown addressing mode on vector store"); 10037 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10038 SN->getAddressingMode()); 10039 } 10040 10041 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10042 DAG.getConstant(Stride, dl, 10043 BasePtr.getValueType())); 10044 Stores[Idx] = Store; 10045 } 10046 10047 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10048 10049 if (SN->isIndexed()) { 10050 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10051 return DAG.getMergeValues(RetOps, dl); 10052 } 10053 10054 return TF; 10055 } 10056 10057 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10058 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10059 10060 // The values are now known to be -1 (false) or 1 (true). To convert this 10061 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10062 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10063 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10064 10065 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10066 // understand how to form the extending load. 10067 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10068 10069 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10070 10071 // Now convert to an integer and store. 10072 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10073 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10074 Value); 10075 10076 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10077 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10078 MachinePointerInfo PtrInfo = 10079 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10080 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10081 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10082 10083 SDValue Ops[] = {StoreChain, 10084 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10085 Value, FIdx}; 10086 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10087 10088 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10089 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10090 10091 // Move data into the byte array. 10092 SDValue Loads[4], LoadChains[4]; 10093 for (unsigned i = 0; i < 4; ++i) { 10094 unsigned Offset = 4*i; 10095 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10096 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10097 10098 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10099 PtrInfo.getWithOffset(Offset)); 10100 LoadChains[i] = Loads[i].getValue(1); 10101 } 10102 10103 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10104 10105 SDValue Stores[4]; 10106 for (unsigned i = 0; i < 4; ++i) { 10107 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10108 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10109 10110 Stores[i] = DAG.getTruncStore( 10111 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10112 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10113 SN->getAAInfo()); 10114 } 10115 10116 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10117 10118 return StoreChain; 10119 } 10120 10121 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10122 SDLoc dl(Op); 10123 if (Op.getValueType() == MVT::v4i32) { 10124 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10125 10126 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10127 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10128 10129 SDValue RHSSwap = // = vrlw RHS, 16 10130 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10131 10132 // Shrinkify inputs to v8i16. 10133 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10134 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10135 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10136 10137 // Low parts multiplied together, generating 32-bit results (we ignore the 10138 // top parts). 10139 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10140 LHS, RHS, DAG, dl, MVT::v4i32); 10141 10142 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10143 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10144 // Shift the high parts up 16 bits. 10145 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10146 Neg16, DAG, dl); 10147 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10148 } else if (Op.getValueType() == MVT::v8i16) { 10149 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10150 10151 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 10152 10153 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 10154 LHS, RHS, Zero, DAG, dl); 10155 } else if (Op.getValueType() == MVT::v16i8) { 10156 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10157 bool isLittleEndian = Subtarget.isLittleEndian(); 10158 10159 // Multiply the even 8-bit parts, producing 16-bit sums. 10160 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10161 LHS, RHS, DAG, dl, MVT::v8i16); 10162 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10163 10164 // Multiply the odd 8-bit parts, producing 16-bit sums. 10165 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10166 LHS, RHS, DAG, dl, MVT::v8i16); 10167 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10168 10169 // Merge the results together. Because vmuleub and vmuloub are 10170 // instructions with a big-endian bias, we must reverse the 10171 // element numbering and reverse the meaning of "odd" and "even" 10172 // when generating little endian code. 10173 int Ops[16]; 10174 for (unsigned i = 0; i != 8; ++i) { 10175 if (isLittleEndian) { 10176 Ops[i*2 ] = 2*i; 10177 Ops[i*2+1] = 2*i+16; 10178 } else { 10179 Ops[i*2 ] = 2*i+1; 10180 Ops[i*2+1] = 2*i+1+16; 10181 } 10182 } 10183 if (isLittleEndian) 10184 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10185 else 10186 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10187 } else { 10188 llvm_unreachable("Unknown mul to lower!"); 10189 } 10190 } 10191 10192 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10193 10194 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10195 10196 EVT VT = Op.getValueType(); 10197 assert(VT.isVector() && 10198 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10199 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10200 VT == MVT::v16i8) && 10201 "Unexpected vector element type!"); 10202 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10203 "Current subtarget doesn't support smax v2i64!"); 10204 10205 // For vector abs, it can be lowered to: 10206 // abs x 10207 // ==> 10208 // y = -x 10209 // smax(x, y) 10210 10211 SDLoc dl(Op); 10212 SDValue X = Op.getOperand(0); 10213 SDValue Zero = DAG.getConstant(0, dl, VT); 10214 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10215 10216 // SMAX patch https://reviews.llvm.org/D47332 10217 // hasn't landed yet, so use intrinsic first here. 10218 // TODO: Should use SMAX directly once SMAX patch landed 10219 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10220 if (VT == MVT::v2i64) 10221 BifID = Intrinsic::ppc_altivec_vmaxsd; 10222 else if (VT == MVT::v8i16) 10223 BifID = Intrinsic::ppc_altivec_vmaxsh; 10224 else if (VT == MVT::v16i8) 10225 BifID = Intrinsic::ppc_altivec_vmaxsb; 10226 10227 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10228 } 10229 10230 // Custom lowering for fpext vf32 to v2f64 10231 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10232 10233 assert(Op.getOpcode() == ISD::FP_EXTEND && 10234 "Should only be called for ISD::FP_EXTEND"); 10235 10236 // We only want to custom lower an extend from v2f32 to v2f64. 10237 if (Op.getValueType() != MVT::v2f64 || 10238 Op.getOperand(0).getValueType() != MVT::v2f32) 10239 return SDValue(); 10240 10241 SDLoc dl(Op); 10242 SDValue Op0 = Op.getOperand(0); 10243 10244 switch (Op0.getOpcode()) { 10245 default: 10246 return SDValue(); 10247 case ISD::EXTRACT_SUBVECTOR: { 10248 assert(Op0.getNumOperands() == 2 && 10249 isa<ConstantSDNode>(Op0->getOperand(1)) && 10250 "Node should have 2 operands with second one being a constant!"); 10251 10252 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10253 return SDValue(); 10254 10255 // Custom lower is only done for high or low doubleword. 10256 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10257 if (Idx % 2 != 0) 10258 return SDValue(); 10259 10260 // Since input is v4f32, at this point Idx is either 0 or 2. 10261 // Shift to get the doubleword position we want. 10262 int DWord = Idx >> 1; 10263 10264 // High and low word positions are different on little endian. 10265 if (Subtarget.isLittleEndian()) 10266 DWord ^= 0x1; 10267 10268 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10269 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10270 } 10271 case ISD::FADD: 10272 case ISD::FMUL: 10273 case ISD::FSUB: { 10274 SDValue NewLoad[2]; 10275 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10276 // Ensure both input are loads. 10277 SDValue LdOp = Op0.getOperand(i); 10278 if (LdOp.getOpcode() != ISD::LOAD) 10279 return SDValue(); 10280 // Generate new load node. 10281 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10282 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10283 NewLoad[i] = DAG.getMemIntrinsicNode( 10284 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10285 LD->getMemoryVT(), LD->getMemOperand()); 10286 } 10287 SDValue NewOp = 10288 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10289 NewLoad[1], Op0.getNode()->getFlags()); 10290 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10291 DAG.getConstant(0, dl, MVT::i32)); 10292 } 10293 case ISD::LOAD: { 10294 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10295 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10296 SDValue NewLd = DAG.getMemIntrinsicNode( 10297 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10298 LD->getMemoryVT(), LD->getMemOperand()); 10299 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10300 DAG.getConstant(0, dl, MVT::i32)); 10301 } 10302 } 10303 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10304 } 10305 10306 /// LowerOperation - Provide custom lowering hooks for some operations. 10307 /// 10308 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10309 switch (Op.getOpcode()) { 10310 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10311 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10312 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10313 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10314 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10315 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10316 case ISD::SETCC: return LowerSETCC(Op, DAG); 10317 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10318 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10319 10320 // Variable argument lowering. 10321 case ISD::VASTART: return LowerVASTART(Op, DAG); 10322 case ISD::VAARG: return LowerVAARG(Op, DAG); 10323 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10324 10325 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10326 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10327 case ISD::GET_DYNAMIC_AREA_OFFSET: 10328 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10329 10330 // Exception handling lowering. 10331 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10332 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10333 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10334 10335 case ISD::LOAD: return LowerLOAD(Op, DAG); 10336 case ISD::STORE: return LowerSTORE(Op, DAG); 10337 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10338 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10339 case ISD::FP_TO_UINT: 10340 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10341 case ISD::UINT_TO_FP: 10342 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10343 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10344 10345 // Lower 64-bit shifts. 10346 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10347 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10348 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10349 10350 // Vector-related lowering. 10351 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10352 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10353 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10354 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10355 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10356 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10357 case ISD::MUL: return LowerMUL(Op, DAG); 10358 case ISD::ABS: return LowerABS(Op, DAG); 10359 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10360 10361 // For counter-based loop handling. 10362 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10363 10364 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10365 10366 // Frame & Return address. 10367 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10368 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10369 10370 case ISD::INTRINSIC_VOID: 10371 return LowerINTRINSIC_VOID(Op, DAG); 10372 case ISD::SREM: 10373 case ISD::UREM: 10374 return LowerREM(Op, DAG); 10375 case ISD::BSWAP: 10376 return LowerBSWAP(Op, DAG); 10377 case ISD::ATOMIC_CMP_SWAP: 10378 return LowerATOMIC_CMP_SWAP(Op, DAG); 10379 } 10380 } 10381 10382 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10383 SmallVectorImpl<SDValue>&Results, 10384 SelectionDAG &DAG) const { 10385 SDLoc dl(N); 10386 switch (N->getOpcode()) { 10387 default: 10388 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10389 case ISD::READCYCLECOUNTER: { 10390 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10391 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10392 10393 Results.push_back(RTB); 10394 Results.push_back(RTB.getValue(1)); 10395 Results.push_back(RTB.getValue(2)); 10396 break; 10397 } 10398 case ISD::INTRINSIC_W_CHAIN: { 10399 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10400 Intrinsic::loop_decrement) 10401 break; 10402 10403 assert(N->getValueType(0) == MVT::i1 && 10404 "Unexpected result type for CTR decrement intrinsic"); 10405 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10406 N->getValueType(0)); 10407 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10408 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10409 N->getOperand(1)); 10410 10411 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10412 Results.push_back(NewInt.getValue(1)); 10413 break; 10414 } 10415 case ISD::VAARG: { 10416 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10417 return; 10418 10419 EVT VT = N->getValueType(0); 10420 10421 if (VT == MVT::i64) { 10422 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10423 10424 Results.push_back(NewNode); 10425 Results.push_back(NewNode.getValue(1)); 10426 } 10427 return; 10428 } 10429 case ISD::FP_TO_SINT: 10430 case ISD::FP_TO_UINT: 10431 // LowerFP_TO_INT() can only handle f32 and f64. 10432 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10433 return; 10434 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10435 return; 10436 case ISD::TRUNCATE: { 10437 EVT TrgVT = N->getValueType(0); 10438 EVT OpVT = N->getOperand(0).getValueType(); 10439 if (TrgVT.isVector() && 10440 isOperationCustom(N->getOpcode(), TrgVT) && 10441 OpVT.getSizeInBits() <= 128 && 10442 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10443 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10444 return; 10445 } 10446 case ISD::BITCAST: 10447 // Don't handle bitcast here. 10448 return; 10449 } 10450 } 10451 10452 //===----------------------------------------------------------------------===// 10453 // Other Lowering Code 10454 //===----------------------------------------------------------------------===// 10455 10456 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10457 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10458 Function *Func = Intrinsic::getDeclaration(M, Id); 10459 return Builder.CreateCall(Func, {}); 10460 } 10461 10462 // The mappings for emitLeading/TrailingFence is taken from 10463 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10464 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10465 Instruction *Inst, 10466 AtomicOrdering Ord) const { 10467 if (Ord == AtomicOrdering::SequentiallyConsistent) 10468 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10469 if (isReleaseOrStronger(Ord)) 10470 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10471 return nullptr; 10472 } 10473 10474 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10475 Instruction *Inst, 10476 AtomicOrdering Ord) const { 10477 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10478 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10479 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10480 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10481 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10482 return Builder.CreateCall( 10483 Intrinsic::getDeclaration( 10484 Builder.GetInsertBlock()->getParent()->getParent(), 10485 Intrinsic::ppc_cfence, {Inst->getType()}), 10486 {Inst}); 10487 // FIXME: Can use isync for rmw operation. 10488 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10489 } 10490 return nullptr; 10491 } 10492 10493 MachineBasicBlock * 10494 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10495 unsigned AtomicSize, 10496 unsigned BinOpcode, 10497 unsigned CmpOpcode, 10498 unsigned CmpPred) const { 10499 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10500 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10501 10502 auto LoadMnemonic = PPC::LDARX; 10503 auto StoreMnemonic = PPC::STDCX; 10504 switch (AtomicSize) { 10505 default: 10506 llvm_unreachable("Unexpected size of atomic entity"); 10507 case 1: 10508 LoadMnemonic = PPC::LBARX; 10509 StoreMnemonic = PPC::STBCX; 10510 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10511 break; 10512 case 2: 10513 LoadMnemonic = PPC::LHARX; 10514 StoreMnemonic = PPC::STHCX; 10515 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10516 break; 10517 case 4: 10518 LoadMnemonic = PPC::LWARX; 10519 StoreMnemonic = PPC::STWCX; 10520 break; 10521 case 8: 10522 LoadMnemonic = PPC::LDARX; 10523 StoreMnemonic = PPC::STDCX; 10524 break; 10525 } 10526 10527 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10528 MachineFunction *F = BB->getParent(); 10529 MachineFunction::iterator It = ++BB->getIterator(); 10530 10531 Register dest = MI.getOperand(0).getReg(); 10532 Register ptrA = MI.getOperand(1).getReg(); 10533 Register ptrB = MI.getOperand(2).getReg(); 10534 Register incr = MI.getOperand(3).getReg(); 10535 DebugLoc dl = MI.getDebugLoc(); 10536 10537 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10538 MachineBasicBlock *loop2MBB = 10539 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10540 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10541 F->insert(It, loopMBB); 10542 if (CmpOpcode) 10543 F->insert(It, loop2MBB); 10544 F->insert(It, exitMBB); 10545 exitMBB->splice(exitMBB->begin(), BB, 10546 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10547 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10548 10549 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10550 Register TmpReg = (!BinOpcode) ? incr : 10551 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10552 : &PPC::GPRCRegClass); 10553 10554 // thisMBB: 10555 // ... 10556 // fallthrough --> loopMBB 10557 BB->addSuccessor(loopMBB); 10558 10559 // loopMBB: 10560 // l[wd]arx dest, ptr 10561 // add r0, dest, incr 10562 // st[wd]cx. r0, ptr 10563 // bne- loopMBB 10564 // fallthrough --> exitMBB 10565 10566 // For max/min... 10567 // loopMBB: 10568 // l[wd]arx dest, ptr 10569 // cmpl?[wd] incr, dest 10570 // bgt exitMBB 10571 // loop2MBB: 10572 // st[wd]cx. dest, ptr 10573 // bne- loopMBB 10574 // fallthrough --> exitMBB 10575 10576 BB = loopMBB; 10577 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10578 .addReg(ptrA).addReg(ptrB); 10579 if (BinOpcode) 10580 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10581 if (CmpOpcode) { 10582 // Signed comparisons of byte or halfword values must be sign-extended. 10583 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10584 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10585 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10586 ExtReg).addReg(dest); 10587 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10588 .addReg(incr).addReg(ExtReg); 10589 } else 10590 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10591 .addReg(incr).addReg(dest); 10592 10593 BuildMI(BB, dl, TII->get(PPC::BCC)) 10594 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10595 BB->addSuccessor(loop2MBB); 10596 BB->addSuccessor(exitMBB); 10597 BB = loop2MBB; 10598 } 10599 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10600 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10601 BuildMI(BB, dl, TII->get(PPC::BCC)) 10602 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10603 BB->addSuccessor(loopMBB); 10604 BB->addSuccessor(exitMBB); 10605 10606 // exitMBB: 10607 // ... 10608 BB = exitMBB; 10609 return BB; 10610 } 10611 10612 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10613 MachineInstr &MI, MachineBasicBlock *BB, 10614 bool is8bit, // operation 10615 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10616 // If we support part-word atomic mnemonics, just use them 10617 if (Subtarget.hasPartwordAtomics()) 10618 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10619 CmpPred); 10620 10621 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10622 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10623 // In 64 bit mode we have to use 64 bits for addresses, even though the 10624 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10625 // registers without caring whether they're 32 or 64, but here we're 10626 // doing actual arithmetic on the addresses. 10627 bool is64bit = Subtarget.isPPC64(); 10628 bool isLittleEndian = Subtarget.isLittleEndian(); 10629 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10630 10631 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10632 MachineFunction *F = BB->getParent(); 10633 MachineFunction::iterator It = ++BB->getIterator(); 10634 10635 Register dest = MI.getOperand(0).getReg(); 10636 Register ptrA = MI.getOperand(1).getReg(); 10637 Register ptrB = MI.getOperand(2).getReg(); 10638 Register incr = MI.getOperand(3).getReg(); 10639 DebugLoc dl = MI.getDebugLoc(); 10640 10641 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10642 MachineBasicBlock *loop2MBB = 10643 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10644 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10645 F->insert(It, loopMBB); 10646 if (CmpOpcode) 10647 F->insert(It, loop2MBB); 10648 F->insert(It, exitMBB); 10649 exitMBB->splice(exitMBB->begin(), BB, 10650 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10651 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10652 10653 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10654 const TargetRegisterClass *RC = 10655 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10656 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10657 10658 Register PtrReg = RegInfo.createVirtualRegister(RC); 10659 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10660 Register ShiftReg = 10661 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10662 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10663 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10664 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10665 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10666 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10667 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10668 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10669 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10670 Register Ptr1Reg; 10671 Register TmpReg = 10672 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10673 10674 // thisMBB: 10675 // ... 10676 // fallthrough --> loopMBB 10677 BB->addSuccessor(loopMBB); 10678 10679 // The 4-byte load must be aligned, while a char or short may be 10680 // anywhere in the word. Hence all this nasty bookkeeping code. 10681 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10682 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10683 // xori shift, shift1, 24 [16] 10684 // rlwinm ptr, ptr1, 0, 0, 29 10685 // slw incr2, incr, shift 10686 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10687 // slw mask, mask2, shift 10688 // loopMBB: 10689 // lwarx tmpDest, ptr 10690 // add tmp, tmpDest, incr2 10691 // andc tmp2, tmpDest, mask 10692 // and tmp3, tmp, mask 10693 // or tmp4, tmp3, tmp2 10694 // stwcx. tmp4, ptr 10695 // bne- loopMBB 10696 // fallthrough --> exitMBB 10697 // srw dest, tmpDest, shift 10698 if (ptrA != ZeroReg) { 10699 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10700 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10701 .addReg(ptrA) 10702 .addReg(ptrB); 10703 } else { 10704 Ptr1Reg = ptrB; 10705 } 10706 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10707 // mode. 10708 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10709 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10710 .addImm(3) 10711 .addImm(27) 10712 .addImm(is8bit ? 28 : 27); 10713 if (!isLittleEndian) 10714 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10715 .addReg(Shift1Reg) 10716 .addImm(is8bit ? 24 : 16); 10717 if (is64bit) 10718 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10719 .addReg(Ptr1Reg) 10720 .addImm(0) 10721 .addImm(61); 10722 else 10723 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10724 .addReg(Ptr1Reg) 10725 .addImm(0) 10726 .addImm(0) 10727 .addImm(29); 10728 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10729 if (is8bit) 10730 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10731 else { 10732 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10733 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10734 .addReg(Mask3Reg) 10735 .addImm(65535); 10736 } 10737 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10738 .addReg(Mask2Reg) 10739 .addReg(ShiftReg); 10740 10741 BB = loopMBB; 10742 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10743 .addReg(ZeroReg) 10744 .addReg(PtrReg); 10745 if (BinOpcode) 10746 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10747 .addReg(Incr2Reg) 10748 .addReg(TmpDestReg); 10749 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10750 .addReg(TmpDestReg) 10751 .addReg(MaskReg); 10752 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10753 if (CmpOpcode) { 10754 // For unsigned comparisons, we can directly compare the shifted values. 10755 // For signed comparisons we shift and sign extend. 10756 Register SReg = RegInfo.createVirtualRegister(GPRC); 10757 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10758 .addReg(TmpDestReg) 10759 .addReg(MaskReg); 10760 unsigned ValueReg = SReg; 10761 unsigned CmpReg = Incr2Reg; 10762 if (CmpOpcode == PPC::CMPW) { 10763 ValueReg = RegInfo.createVirtualRegister(GPRC); 10764 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10765 .addReg(SReg) 10766 .addReg(ShiftReg); 10767 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 10768 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10769 .addReg(ValueReg); 10770 ValueReg = ValueSReg; 10771 CmpReg = incr; 10772 } 10773 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10774 .addReg(CmpReg) 10775 .addReg(ValueReg); 10776 BuildMI(BB, dl, TII->get(PPC::BCC)) 10777 .addImm(CmpPred) 10778 .addReg(PPC::CR0) 10779 .addMBB(exitMBB); 10780 BB->addSuccessor(loop2MBB); 10781 BB->addSuccessor(exitMBB); 10782 BB = loop2MBB; 10783 } 10784 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10785 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10786 .addReg(Tmp4Reg) 10787 .addReg(ZeroReg) 10788 .addReg(PtrReg); 10789 BuildMI(BB, dl, TII->get(PPC::BCC)) 10790 .addImm(PPC::PRED_NE) 10791 .addReg(PPC::CR0) 10792 .addMBB(loopMBB); 10793 BB->addSuccessor(loopMBB); 10794 BB->addSuccessor(exitMBB); 10795 10796 // exitMBB: 10797 // ... 10798 BB = exitMBB; 10799 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10800 .addReg(TmpDestReg) 10801 .addReg(ShiftReg); 10802 return BB; 10803 } 10804 10805 llvm::MachineBasicBlock * 10806 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10807 MachineBasicBlock *MBB) const { 10808 DebugLoc DL = MI.getDebugLoc(); 10809 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10810 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10811 10812 MachineFunction *MF = MBB->getParent(); 10813 MachineRegisterInfo &MRI = MF->getRegInfo(); 10814 10815 const BasicBlock *BB = MBB->getBasicBlock(); 10816 MachineFunction::iterator I = ++MBB->getIterator(); 10817 10818 Register DstReg = MI.getOperand(0).getReg(); 10819 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10820 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10821 Register mainDstReg = MRI.createVirtualRegister(RC); 10822 Register restoreDstReg = MRI.createVirtualRegister(RC); 10823 10824 MVT PVT = getPointerTy(MF->getDataLayout()); 10825 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10826 "Invalid Pointer Size!"); 10827 // For v = setjmp(buf), we generate 10828 // 10829 // thisMBB: 10830 // SjLjSetup mainMBB 10831 // bl mainMBB 10832 // v_restore = 1 10833 // b sinkMBB 10834 // 10835 // mainMBB: 10836 // buf[LabelOffset] = LR 10837 // v_main = 0 10838 // 10839 // sinkMBB: 10840 // v = phi(main, restore) 10841 // 10842 10843 MachineBasicBlock *thisMBB = MBB; 10844 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10845 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10846 MF->insert(I, mainMBB); 10847 MF->insert(I, sinkMBB); 10848 10849 MachineInstrBuilder MIB; 10850 10851 // Transfer the remainder of BB and its successor edges to sinkMBB. 10852 sinkMBB->splice(sinkMBB->begin(), MBB, 10853 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10854 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10855 10856 // Note that the structure of the jmp_buf used here is not compatible 10857 // with that used by libc, and is not designed to be. Specifically, it 10858 // stores only those 'reserved' registers that LLVM does not otherwise 10859 // understand how to spill. Also, by convention, by the time this 10860 // intrinsic is called, Clang has already stored the frame address in the 10861 // first slot of the buffer and stack address in the third. Following the 10862 // X86 target code, we'll store the jump address in the second slot. We also 10863 // need to save the TOC pointer (R2) to handle jumps between shared 10864 // libraries, and that will be stored in the fourth slot. The thread 10865 // identifier (R13) is not affected. 10866 10867 // thisMBB: 10868 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10869 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10870 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10871 10872 // Prepare IP either in reg. 10873 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10874 Register LabelReg = MRI.createVirtualRegister(PtrRC); 10875 Register BufReg = MI.getOperand(1).getReg(); 10876 10877 if (Subtarget.is64BitELFABI()) { 10878 setUsesTOCBasePtr(*MBB->getParent()); 10879 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10880 .addReg(PPC::X2) 10881 .addImm(TOCOffset) 10882 .addReg(BufReg) 10883 .cloneMemRefs(MI); 10884 } 10885 10886 // Naked functions never have a base pointer, and so we use r1. For all 10887 // other functions, this decision must be delayed until during PEI. 10888 unsigned BaseReg; 10889 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10890 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10891 else 10892 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10893 10894 MIB = BuildMI(*thisMBB, MI, DL, 10895 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10896 .addReg(BaseReg) 10897 .addImm(BPOffset) 10898 .addReg(BufReg) 10899 .cloneMemRefs(MI); 10900 10901 // Setup 10902 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10903 MIB.addRegMask(TRI->getNoPreservedMask()); 10904 10905 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10906 10907 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10908 .addMBB(mainMBB); 10909 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10910 10911 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10912 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10913 10914 // mainMBB: 10915 // mainDstReg = 0 10916 MIB = 10917 BuildMI(mainMBB, DL, 10918 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10919 10920 // Store IP 10921 if (Subtarget.isPPC64()) { 10922 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10923 .addReg(LabelReg) 10924 .addImm(LabelOffset) 10925 .addReg(BufReg); 10926 } else { 10927 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10928 .addReg(LabelReg) 10929 .addImm(LabelOffset) 10930 .addReg(BufReg); 10931 } 10932 MIB.cloneMemRefs(MI); 10933 10934 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10935 mainMBB->addSuccessor(sinkMBB); 10936 10937 // sinkMBB: 10938 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10939 TII->get(PPC::PHI), DstReg) 10940 .addReg(mainDstReg).addMBB(mainMBB) 10941 .addReg(restoreDstReg).addMBB(thisMBB); 10942 10943 MI.eraseFromParent(); 10944 return sinkMBB; 10945 } 10946 10947 MachineBasicBlock * 10948 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10949 MachineBasicBlock *MBB) const { 10950 DebugLoc DL = MI.getDebugLoc(); 10951 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10952 10953 MachineFunction *MF = MBB->getParent(); 10954 MachineRegisterInfo &MRI = MF->getRegInfo(); 10955 10956 MVT PVT = getPointerTy(MF->getDataLayout()); 10957 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10958 "Invalid Pointer Size!"); 10959 10960 const TargetRegisterClass *RC = 10961 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10962 Register Tmp = MRI.createVirtualRegister(RC); 10963 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10964 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10965 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10966 unsigned BP = 10967 (PVT == MVT::i64) 10968 ? PPC::X30 10969 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10970 : PPC::R30); 10971 10972 MachineInstrBuilder MIB; 10973 10974 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10975 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10976 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10977 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10978 10979 Register BufReg = MI.getOperand(0).getReg(); 10980 10981 // Reload FP (the jumped-to function may not have had a 10982 // frame pointer, and if so, then its r31 will be restored 10983 // as necessary). 10984 if (PVT == MVT::i64) { 10985 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10986 .addImm(0) 10987 .addReg(BufReg); 10988 } else { 10989 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10990 .addImm(0) 10991 .addReg(BufReg); 10992 } 10993 MIB.cloneMemRefs(MI); 10994 10995 // Reload IP 10996 if (PVT == MVT::i64) { 10997 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10998 .addImm(LabelOffset) 10999 .addReg(BufReg); 11000 } else { 11001 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11002 .addImm(LabelOffset) 11003 .addReg(BufReg); 11004 } 11005 MIB.cloneMemRefs(MI); 11006 11007 // Reload SP 11008 if (PVT == MVT::i64) { 11009 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11010 .addImm(SPOffset) 11011 .addReg(BufReg); 11012 } else { 11013 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11014 .addImm(SPOffset) 11015 .addReg(BufReg); 11016 } 11017 MIB.cloneMemRefs(MI); 11018 11019 // Reload BP 11020 if (PVT == MVT::i64) { 11021 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11022 .addImm(BPOffset) 11023 .addReg(BufReg); 11024 } else { 11025 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11026 .addImm(BPOffset) 11027 .addReg(BufReg); 11028 } 11029 MIB.cloneMemRefs(MI); 11030 11031 // Reload TOC 11032 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11033 setUsesTOCBasePtr(*MBB->getParent()); 11034 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11035 .addImm(TOCOffset) 11036 .addReg(BufReg) 11037 .cloneMemRefs(MI); 11038 } 11039 11040 // Jump 11041 BuildMI(*MBB, MI, DL, 11042 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11043 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11044 11045 MI.eraseFromParent(); 11046 return MBB; 11047 } 11048 11049 MachineBasicBlock * 11050 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11051 MachineBasicBlock *BB) const { 11052 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11053 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11054 if (Subtarget.is64BitELFABI() && 11055 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11056 // Call lowering should have added an r2 operand to indicate a dependence 11057 // on the TOC base pointer value. It can't however, because there is no 11058 // way to mark the dependence as implicit there, and so the stackmap code 11059 // will confuse it with a regular operand. Instead, add the dependence 11060 // here. 11061 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11062 } 11063 11064 return emitPatchPoint(MI, BB); 11065 } 11066 11067 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11068 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11069 return emitEHSjLjSetJmp(MI, BB); 11070 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11071 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11072 return emitEHSjLjLongJmp(MI, BB); 11073 } 11074 11075 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11076 11077 // To "insert" these instructions we actually have to insert their 11078 // control-flow patterns. 11079 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11080 MachineFunction::iterator It = ++BB->getIterator(); 11081 11082 MachineFunction *F = BB->getParent(); 11083 11084 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11085 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11086 MI.getOpcode() == PPC::SELECT_I8) { 11087 SmallVector<MachineOperand, 2> Cond; 11088 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11089 MI.getOpcode() == PPC::SELECT_CC_I8) 11090 Cond.push_back(MI.getOperand(4)); 11091 else 11092 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11093 Cond.push_back(MI.getOperand(1)); 11094 11095 DebugLoc dl = MI.getDebugLoc(); 11096 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11097 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11098 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11099 MI.getOpcode() == PPC::SELECT_CC_F8 || 11100 MI.getOpcode() == PPC::SELECT_CC_F16 || 11101 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11102 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11103 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11104 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11105 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11106 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11107 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11108 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11109 MI.getOpcode() == PPC::SELECT_CC_SPE || 11110 MI.getOpcode() == PPC::SELECT_F4 || 11111 MI.getOpcode() == PPC::SELECT_F8 || 11112 MI.getOpcode() == PPC::SELECT_F16 || 11113 MI.getOpcode() == PPC::SELECT_QFRC || 11114 MI.getOpcode() == PPC::SELECT_QSRC || 11115 MI.getOpcode() == PPC::SELECT_QBRC || 11116 MI.getOpcode() == PPC::SELECT_SPE || 11117 MI.getOpcode() == PPC::SELECT_SPE4 || 11118 MI.getOpcode() == PPC::SELECT_VRRC || 11119 MI.getOpcode() == PPC::SELECT_VSFRC || 11120 MI.getOpcode() == PPC::SELECT_VSSRC || 11121 MI.getOpcode() == PPC::SELECT_VSRC) { 11122 // The incoming instruction knows the destination vreg to set, the 11123 // condition code register to branch on, the true/false values to 11124 // select between, and a branch opcode to use. 11125 11126 // thisMBB: 11127 // ... 11128 // TrueVal = ... 11129 // cmpTY ccX, r1, r2 11130 // bCC copy1MBB 11131 // fallthrough --> copy0MBB 11132 MachineBasicBlock *thisMBB = BB; 11133 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11134 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11135 DebugLoc dl = MI.getDebugLoc(); 11136 F->insert(It, copy0MBB); 11137 F->insert(It, sinkMBB); 11138 11139 // Transfer the remainder of BB and its successor edges to sinkMBB. 11140 sinkMBB->splice(sinkMBB->begin(), BB, 11141 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11142 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11143 11144 // Next, add the true and fallthrough blocks as its successors. 11145 BB->addSuccessor(copy0MBB); 11146 BB->addSuccessor(sinkMBB); 11147 11148 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11149 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11150 MI.getOpcode() == PPC::SELECT_F16 || 11151 MI.getOpcode() == PPC::SELECT_SPE4 || 11152 MI.getOpcode() == PPC::SELECT_SPE || 11153 MI.getOpcode() == PPC::SELECT_QFRC || 11154 MI.getOpcode() == PPC::SELECT_QSRC || 11155 MI.getOpcode() == PPC::SELECT_QBRC || 11156 MI.getOpcode() == PPC::SELECT_VRRC || 11157 MI.getOpcode() == PPC::SELECT_VSFRC || 11158 MI.getOpcode() == PPC::SELECT_VSSRC || 11159 MI.getOpcode() == PPC::SELECT_VSRC) { 11160 BuildMI(BB, dl, TII->get(PPC::BC)) 11161 .addReg(MI.getOperand(1).getReg()) 11162 .addMBB(sinkMBB); 11163 } else { 11164 unsigned SelectPred = MI.getOperand(4).getImm(); 11165 BuildMI(BB, dl, TII->get(PPC::BCC)) 11166 .addImm(SelectPred) 11167 .addReg(MI.getOperand(1).getReg()) 11168 .addMBB(sinkMBB); 11169 } 11170 11171 // copy0MBB: 11172 // %FalseValue = ... 11173 // # fallthrough to sinkMBB 11174 BB = copy0MBB; 11175 11176 // Update machine-CFG edges 11177 BB->addSuccessor(sinkMBB); 11178 11179 // sinkMBB: 11180 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11181 // ... 11182 BB = sinkMBB; 11183 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11184 .addReg(MI.getOperand(3).getReg()) 11185 .addMBB(copy0MBB) 11186 .addReg(MI.getOperand(2).getReg()) 11187 .addMBB(thisMBB); 11188 } else if (MI.getOpcode() == PPC::ReadTB) { 11189 // To read the 64-bit time-base register on a 32-bit target, we read the 11190 // two halves. Should the counter have wrapped while it was being read, we 11191 // need to try again. 11192 // ... 11193 // readLoop: 11194 // mfspr Rx,TBU # load from TBU 11195 // mfspr Ry,TB # load from TB 11196 // mfspr Rz,TBU # load from TBU 11197 // cmpw crX,Rx,Rz # check if 'old'='new' 11198 // bne readLoop # branch if they're not equal 11199 // ... 11200 11201 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11202 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11203 DebugLoc dl = MI.getDebugLoc(); 11204 F->insert(It, readMBB); 11205 F->insert(It, sinkMBB); 11206 11207 // Transfer the remainder of BB and its successor edges to sinkMBB. 11208 sinkMBB->splice(sinkMBB->begin(), BB, 11209 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11210 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11211 11212 BB->addSuccessor(readMBB); 11213 BB = readMBB; 11214 11215 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11216 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11217 Register LoReg = MI.getOperand(0).getReg(); 11218 Register HiReg = MI.getOperand(1).getReg(); 11219 11220 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11221 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11222 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11223 11224 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11225 11226 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11227 .addReg(HiReg) 11228 .addReg(ReadAgainReg); 11229 BuildMI(BB, dl, TII->get(PPC::BCC)) 11230 .addImm(PPC::PRED_NE) 11231 .addReg(CmpReg) 11232 .addMBB(readMBB); 11233 11234 BB->addSuccessor(readMBB); 11235 BB->addSuccessor(sinkMBB); 11236 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11237 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11238 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11239 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11240 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11241 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11242 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11243 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11244 11245 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11246 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11247 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11248 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11249 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11250 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11251 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11252 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11253 11254 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11255 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11256 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11257 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11258 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11259 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11260 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11261 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11262 11263 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11264 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11265 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11266 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11267 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11268 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11269 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11270 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11271 11272 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11273 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11274 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11275 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11276 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11277 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11278 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11279 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11280 11281 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11282 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11283 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11284 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11285 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11286 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11287 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11288 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11289 11290 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11291 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11292 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11293 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11294 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11295 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11296 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11297 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11298 11299 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11300 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11301 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11302 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11303 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11304 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11305 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11306 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11307 11308 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11309 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11310 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11311 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11312 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11313 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11314 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11315 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11316 11317 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11318 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11319 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11320 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11321 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11322 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11323 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11324 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11325 11326 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11327 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11328 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11329 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11330 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11331 BB = EmitAtomicBinary(MI, BB, 4, 0); 11332 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11333 BB = EmitAtomicBinary(MI, BB, 8, 0); 11334 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11335 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11336 (Subtarget.hasPartwordAtomics() && 11337 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11338 (Subtarget.hasPartwordAtomics() && 11339 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11340 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11341 11342 auto LoadMnemonic = PPC::LDARX; 11343 auto StoreMnemonic = PPC::STDCX; 11344 switch (MI.getOpcode()) { 11345 default: 11346 llvm_unreachable("Compare and swap of unknown size"); 11347 case PPC::ATOMIC_CMP_SWAP_I8: 11348 LoadMnemonic = PPC::LBARX; 11349 StoreMnemonic = PPC::STBCX; 11350 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11351 break; 11352 case PPC::ATOMIC_CMP_SWAP_I16: 11353 LoadMnemonic = PPC::LHARX; 11354 StoreMnemonic = PPC::STHCX; 11355 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11356 break; 11357 case PPC::ATOMIC_CMP_SWAP_I32: 11358 LoadMnemonic = PPC::LWARX; 11359 StoreMnemonic = PPC::STWCX; 11360 break; 11361 case PPC::ATOMIC_CMP_SWAP_I64: 11362 LoadMnemonic = PPC::LDARX; 11363 StoreMnemonic = PPC::STDCX; 11364 break; 11365 } 11366 Register dest = MI.getOperand(0).getReg(); 11367 Register ptrA = MI.getOperand(1).getReg(); 11368 Register ptrB = MI.getOperand(2).getReg(); 11369 Register oldval = MI.getOperand(3).getReg(); 11370 Register newval = MI.getOperand(4).getReg(); 11371 DebugLoc dl = MI.getDebugLoc(); 11372 11373 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11374 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11375 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11376 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11377 F->insert(It, loop1MBB); 11378 F->insert(It, loop2MBB); 11379 F->insert(It, midMBB); 11380 F->insert(It, exitMBB); 11381 exitMBB->splice(exitMBB->begin(), BB, 11382 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11383 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11384 11385 // thisMBB: 11386 // ... 11387 // fallthrough --> loopMBB 11388 BB->addSuccessor(loop1MBB); 11389 11390 // loop1MBB: 11391 // l[bhwd]arx dest, ptr 11392 // cmp[wd] dest, oldval 11393 // bne- midMBB 11394 // loop2MBB: 11395 // st[bhwd]cx. newval, ptr 11396 // bne- loopMBB 11397 // b exitBB 11398 // midMBB: 11399 // st[bhwd]cx. dest, ptr 11400 // exitBB: 11401 BB = loop1MBB; 11402 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11403 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11404 .addReg(oldval) 11405 .addReg(dest); 11406 BuildMI(BB, dl, TII->get(PPC::BCC)) 11407 .addImm(PPC::PRED_NE) 11408 .addReg(PPC::CR0) 11409 .addMBB(midMBB); 11410 BB->addSuccessor(loop2MBB); 11411 BB->addSuccessor(midMBB); 11412 11413 BB = loop2MBB; 11414 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11415 .addReg(newval) 11416 .addReg(ptrA) 11417 .addReg(ptrB); 11418 BuildMI(BB, dl, TII->get(PPC::BCC)) 11419 .addImm(PPC::PRED_NE) 11420 .addReg(PPC::CR0) 11421 .addMBB(loop1MBB); 11422 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11423 BB->addSuccessor(loop1MBB); 11424 BB->addSuccessor(exitMBB); 11425 11426 BB = midMBB; 11427 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11428 .addReg(dest) 11429 .addReg(ptrA) 11430 .addReg(ptrB); 11431 BB->addSuccessor(exitMBB); 11432 11433 // exitMBB: 11434 // ... 11435 BB = exitMBB; 11436 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11437 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11438 // We must use 64-bit registers for addresses when targeting 64-bit, 11439 // since we're actually doing arithmetic on them. Other registers 11440 // can be 32-bit. 11441 bool is64bit = Subtarget.isPPC64(); 11442 bool isLittleEndian = Subtarget.isLittleEndian(); 11443 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11444 11445 Register dest = MI.getOperand(0).getReg(); 11446 Register ptrA = MI.getOperand(1).getReg(); 11447 Register ptrB = MI.getOperand(2).getReg(); 11448 Register oldval = MI.getOperand(3).getReg(); 11449 Register newval = MI.getOperand(4).getReg(); 11450 DebugLoc dl = MI.getDebugLoc(); 11451 11452 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11453 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11454 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11455 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11456 F->insert(It, loop1MBB); 11457 F->insert(It, loop2MBB); 11458 F->insert(It, midMBB); 11459 F->insert(It, exitMBB); 11460 exitMBB->splice(exitMBB->begin(), BB, 11461 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11462 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11463 11464 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11465 const TargetRegisterClass *RC = 11466 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11467 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11468 11469 Register PtrReg = RegInfo.createVirtualRegister(RC); 11470 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11471 Register ShiftReg = 11472 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11473 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11474 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11475 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11476 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11477 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11478 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11479 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11480 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11481 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11482 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11483 Register Ptr1Reg; 11484 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11485 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11486 // thisMBB: 11487 // ... 11488 // fallthrough --> loopMBB 11489 BB->addSuccessor(loop1MBB); 11490 11491 // The 4-byte load must be aligned, while a char or short may be 11492 // anywhere in the word. Hence all this nasty bookkeeping code. 11493 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11494 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11495 // xori shift, shift1, 24 [16] 11496 // rlwinm ptr, ptr1, 0, 0, 29 11497 // slw newval2, newval, shift 11498 // slw oldval2, oldval,shift 11499 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11500 // slw mask, mask2, shift 11501 // and newval3, newval2, mask 11502 // and oldval3, oldval2, mask 11503 // loop1MBB: 11504 // lwarx tmpDest, ptr 11505 // and tmp, tmpDest, mask 11506 // cmpw tmp, oldval3 11507 // bne- midMBB 11508 // loop2MBB: 11509 // andc tmp2, tmpDest, mask 11510 // or tmp4, tmp2, newval3 11511 // stwcx. tmp4, ptr 11512 // bne- loop1MBB 11513 // b exitBB 11514 // midMBB: 11515 // stwcx. tmpDest, ptr 11516 // exitBB: 11517 // srw dest, tmpDest, shift 11518 if (ptrA != ZeroReg) { 11519 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11520 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11521 .addReg(ptrA) 11522 .addReg(ptrB); 11523 } else { 11524 Ptr1Reg = ptrB; 11525 } 11526 11527 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11528 // mode. 11529 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11530 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11531 .addImm(3) 11532 .addImm(27) 11533 .addImm(is8bit ? 28 : 27); 11534 if (!isLittleEndian) 11535 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11536 .addReg(Shift1Reg) 11537 .addImm(is8bit ? 24 : 16); 11538 if (is64bit) 11539 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11540 .addReg(Ptr1Reg) 11541 .addImm(0) 11542 .addImm(61); 11543 else 11544 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11545 .addReg(Ptr1Reg) 11546 .addImm(0) 11547 .addImm(0) 11548 .addImm(29); 11549 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11550 .addReg(newval) 11551 .addReg(ShiftReg); 11552 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11553 .addReg(oldval) 11554 .addReg(ShiftReg); 11555 if (is8bit) 11556 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11557 else { 11558 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11559 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11560 .addReg(Mask3Reg) 11561 .addImm(65535); 11562 } 11563 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11564 .addReg(Mask2Reg) 11565 .addReg(ShiftReg); 11566 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11567 .addReg(NewVal2Reg) 11568 .addReg(MaskReg); 11569 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11570 .addReg(OldVal2Reg) 11571 .addReg(MaskReg); 11572 11573 BB = loop1MBB; 11574 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11575 .addReg(ZeroReg) 11576 .addReg(PtrReg); 11577 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11578 .addReg(TmpDestReg) 11579 .addReg(MaskReg); 11580 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11581 .addReg(TmpReg) 11582 .addReg(OldVal3Reg); 11583 BuildMI(BB, dl, TII->get(PPC::BCC)) 11584 .addImm(PPC::PRED_NE) 11585 .addReg(PPC::CR0) 11586 .addMBB(midMBB); 11587 BB->addSuccessor(loop2MBB); 11588 BB->addSuccessor(midMBB); 11589 11590 BB = loop2MBB; 11591 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11592 .addReg(TmpDestReg) 11593 .addReg(MaskReg); 11594 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11595 .addReg(Tmp2Reg) 11596 .addReg(NewVal3Reg); 11597 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11598 .addReg(Tmp4Reg) 11599 .addReg(ZeroReg) 11600 .addReg(PtrReg); 11601 BuildMI(BB, dl, TII->get(PPC::BCC)) 11602 .addImm(PPC::PRED_NE) 11603 .addReg(PPC::CR0) 11604 .addMBB(loop1MBB); 11605 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11606 BB->addSuccessor(loop1MBB); 11607 BB->addSuccessor(exitMBB); 11608 11609 BB = midMBB; 11610 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11611 .addReg(TmpDestReg) 11612 .addReg(ZeroReg) 11613 .addReg(PtrReg); 11614 BB->addSuccessor(exitMBB); 11615 11616 // exitMBB: 11617 // ... 11618 BB = exitMBB; 11619 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11620 .addReg(TmpReg) 11621 .addReg(ShiftReg); 11622 } else if (MI.getOpcode() == PPC::FADDrtz) { 11623 // This pseudo performs an FADD with rounding mode temporarily forced 11624 // to round-to-zero. We emit this via custom inserter since the FPSCR 11625 // is not modeled at the SelectionDAG level. 11626 Register Dest = MI.getOperand(0).getReg(); 11627 Register Src1 = MI.getOperand(1).getReg(); 11628 Register Src2 = MI.getOperand(2).getReg(); 11629 DebugLoc dl = MI.getDebugLoc(); 11630 11631 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11632 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11633 11634 // Save FPSCR value. 11635 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11636 11637 // Set rounding mode to round-to-zero. 11638 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 11639 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 11640 11641 // Perform addition. 11642 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11643 11644 // Restore FPSCR value. 11645 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11646 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11647 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 11648 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11649 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 11650 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11651 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 11652 ? PPC::ANDI8o 11653 : PPC::ANDIo; 11654 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11655 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 11656 11657 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11658 Register Dest = RegInfo.createVirtualRegister( 11659 Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11660 11661 DebugLoc dl = MI.getDebugLoc(); 11662 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 11663 .addReg(MI.getOperand(1).getReg()) 11664 .addImm(1); 11665 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 11666 MI.getOperand(0).getReg()) 11667 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 11668 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11669 DebugLoc Dl = MI.getDebugLoc(); 11670 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11671 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11672 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11673 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11674 MI.getOperand(0).getReg()) 11675 .addReg(CRReg); 11676 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 11677 DebugLoc Dl = MI.getDebugLoc(); 11678 unsigned Imm = MI.getOperand(1).getImm(); 11679 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 11680 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11681 MI.getOperand(0).getReg()) 11682 .addReg(PPC::CR0EQ); 11683 } else if (MI.getOpcode() == PPC::SETRNDi) { 11684 DebugLoc dl = MI.getDebugLoc(); 11685 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11686 11687 // Save FPSCR value. 11688 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11689 11690 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 11691 // the following settings: 11692 // 00 Round to nearest 11693 // 01 Round to 0 11694 // 10 Round to +inf 11695 // 11 Round to -inf 11696 11697 // When the operand is immediate, using the two least significant bits of 11698 // the immediate to set the bits 62:63 of FPSCR. 11699 unsigned Mode = MI.getOperand(1).getImm(); 11700 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 11701 .addImm(31); 11702 11703 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 11704 .addImm(30); 11705 } else if (MI.getOpcode() == PPC::SETRND) { 11706 DebugLoc dl = MI.getDebugLoc(); 11707 11708 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 11709 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 11710 // If the target doesn't have DirectMove, we should use stack to do the 11711 // conversion, because the target doesn't have the instructions like mtvsrd 11712 // or mfvsrd to do this conversion directly. 11713 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 11714 if (Subtarget.hasDirectMove()) { 11715 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 11716 .addReg(SrcReg); 11717 } else { 11718 // Use stack to do the register copy. 11719 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 11720 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11721 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 11722 if (RC == &PPC::F8RCRegClass) { 11723 // Copy register from F8RCRegClass to G8RCRegclass. 11724 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11725 "Unsupported RegClass."); 11726 11727 StoreOp = PPC::STFD; 11728 LoadOp = PPC::LD; 11729 } else { 11730 // Copy register from G8RCRegClass to F8RCRegclass. 11731 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11732 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11733 "Unsupported RegClass."); 11734 } 11735 11736 MachineFrameInfo &MFI = F->getFrameInfo(); 11737 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11738 11739 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11740 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11741 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11742 MFI.getObjectAlignment(FrameIdx)); 11743 11744 // Store the SrcReg into the stack. 11745 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11746 .addReg(SrcReg) 11747 .addImm(0) 11748 .addFrameIndex(FrameIdx) 11749 .addMemOperand(MMOStore); 11750 11751 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11752 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11753 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11754 MFI.getObjectAlignment(FrameIdx)); 11755 11756 // Load from the stack where SrcReg is stored, and save to DestReg, 11757 // so we have done the RegClass conversion from RegClass::SrcReg to 11758 // RegClass::DestReg. 11759 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11760 .addImm(0) 11761 .addFrameIndex(FrameIdx) 11762 .addMemOperand(MMOLoad); 11763 } 11764 }; 11765 11766 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11767 11768 // Save FPSCR value. 11769 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11770 11771 // When the operand is gprc register, use two least significant bits of the 11772 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11773 // 11774 // copy OldFPSCRTmpReg, OldFPSCRReg 11775 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11776 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11777 // copy NewFPSCRReg, NewFPSCRTmpReg 11778 // mtfsf 255, NewFPSCRReg 11779 MachineOperand SrcOp = MI.getOperand(1); 11780 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11781 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11782 11783 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11784 11785 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11786 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11787 11788 // The first operand of INSERT_SUBREG should be a register which has 11789 // subregisters, we only care about its RegClass, so we should use an 11790 // IMPLICIT_DEF register. 11791 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11792 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11793 .addReg(ImDefReg) 11794 .add(SrcOp) 11795 .addImm(1); 11796 11797 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11798 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11799 .addReg(OldFPSCRTmpReg) 11800 .addReg(ExtSrcReg) 11801 .addImm(0) 11802 .addImm(62); 11803 11804 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11805 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11806 11807 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11808 // bits of FPSCR. 11809 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11810 .addImm(255) 11811 .addReg(NewFPSCRReg) 11812 .addImm(0) 11813 .addImm(0); 11814 } else { 11815 llvm_unreachable("Unexpected instr type to insert"); 11816 } 11817 11818 MI.eraseFromParent(); // The pseudo instruction is gone now. 11819 return BB; 11820 } 11821 11822 //===----------------------------------------------------------------------===// 11823 // Target Optimization Hooks 11824 //===----------------------------------------------------------------------===// 11825 11826 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11827 // For the estimates, convergence is quadratic, so we essentially double the 11828 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11829 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11830 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11831 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11832 if (VT.getScalarType() == MVT::f64) 11833 RefinementSteps++; 11834 return RefinementSteps; 11835 } 11836 11837 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11838 int Enabled, int &RefinementSteps, 11839 bool &UseOneConstNR, 11840 bool Reciprocal) const { 11841 EVT VT = Operand.getValueType(); 11842 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11843 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11844 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11845 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11846 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11847 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11848 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11849 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11850 11851 // The Newton-Raphson computation with a single constant does not provide 11852 // enough accuracy on some CPUs. 11853 UseOneConstNR = !Subtarget.needsTwoConstNR(); 11854 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11855 } 11856 return SDValue(); 11857 } 11858 11859 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11860 int Enabled, 11861 int &RefinementSteps) const { 11862 EVT VT = Operand.getValueType(); 11863 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11864 (VT == MVT::f64 && Subtarget.hasFRE()) || 11865 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11866 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11867 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11868 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11869 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11870 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11871 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11872 } 11873 return SDValue(); 11874 } 11875 11876 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11877 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11878 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11879 // enabled for division), this functionality is redundant with the default 11880 // combiner logic (once the division -> reciprocal/multiply transformation 11881 // has taken place). As a result, this matters more for older cores than for 11882 // newer ones. 11883 11884 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11885 // reciprocal if there are two or more FDIVs (for embedded cores with only 11886 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11887 switch (Subtarget.getCPUDirective()) { 11888 default: 11889 return 3; 11890 case PPC::DIR_440: 11891 case PPC::DIR_A2: 11892 case PPC::DIR_E500: 11893 case PPC::DIR_E500mc: 11894 case PPC::DIR_E5500: 11895 return 2; 11896 } 11897 } 11898 11899 // isConsecutiveLSLoc needs to work even if all adds have not yet been 11900 // collapsed, and so we need to look through chains of them. 11901 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 11902 int64_t& Offset, SelectionDAG &DAG) { 11903 if (DAG.isBaseWithConstantOffset(Loc)) { 11904 Base = Loc.getOperand(0); 11905 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 11906 11907 // The base might itself be a base plus an offset, and if so, accumulate 11908 // that as well. 11909 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 11910 } 11911 } 11912 11913 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 11914 unsigned Bytes, int Dist, 11915 SelectionDAG &DAG) { 11916 if (VT.getSizeInBits() / 8 != Bytes) 11917 return false; 11918 11919 SDValue BaseLoc = Base->getBasePtr(); 11920 if (Loc.getOpcode() == ISD::FrameIndex) { 11921 if (BaseLoc.getOpcode() != ISD::FrameIndex) 11922 return false; 11923 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 11924 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 11925 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 11926 int FS = MFI.getObjectSize(FI); 11927 int BFS = MFI.getObjectSize(BFI); 11928 if (FS != BFS || FS != (int)Bytes) return false; 11929 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 11930 } 11931 11932 SDValue Base1 = Loc, Base2 = BaseLoc; 11933 int64_t Offset1 = 0, Offset2 = 0; 11934 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 11935 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 11936 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 11937 return true; 11938 11939 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11940 const GlobalValue *GV1 = nullptr; 11941 const GlobalValue *GV2 = nullptr; 11942 Offset1 = 0; 11943 Offset2 = 0; 11944 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 11945 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 11946 if (isGA1 && isGA2 && GV1 == GV2) 11947 return Offset1 == (Offset2 + Dist*Bytes); 11948 return false; 11949 } 11950 11951 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11952 // not enforce equality of the chain operands. 11953 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11954 unsigned Bytes, int Dist, 11955 SelectionDAG &DAG) { 11956 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11957 EVT VT = LS->getMemoryVT(); 11958 SDValue Loc = LS->getBasePtr(); 11959 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11960 } 11961 11962 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11963 EVT VT; 11964 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11965 default: return false; 11966 case Intrinsic::ppc_qpx_qvlfd: 11967 case Intrinsic::ppc_qpx_qvlfda: 11968 VT = MVT::v4f64; 11969 break; 11970 case Intrinsic::ppc_qpx_qvlfs: 11971 case Intrinsic::ppc_qpx_qvlfsa: 11972 VT = MVT::v4f32; 11973 break; 11974 case Intrinsic::ppc_qpx_qvlfcd: 11975 case Intrinsic::ppc_qpx_qvlfcda: 11976 VT = MVT::v2f64; 11977 break; 11978 case Intrinsic::ppc_qpx_qvlfcs: 11979 case Intrinsic::ppc_qpx_qvlfcsa: 11980 VT = MVT::v2f32; 11981 break; 11982 case Intrinsic::ppc_qpx_qvlfiwa: 11983 case Intrinsic::ppc_qpx_qvlfiwz: 11984 case Intrinsic::ppc_altivec_lvx: 11985 case Intrinsic::ppc_altivec_lvxl: 11986 case Intrinsic::ppc_vsx_lxvw4x: 11987 case Intrinsic::ppc_vsx_lxvw4x_be: 11988 VT = MVT::v4i32; 11989 break; 11990 case Intrinsic::ppc_vsx_lxvd2x: 11991 case Intrinsic::ppc_vsx_lxvd2x_be: 11992 VT = MVT::v2f64; 11993 break; 11994 case Intrinsic::ppc_altivec_lvebx: 11995 VT = MVT::i8; 11996 break; 11997 case Intrinsic::ppc_altivec_lvehx: 11998 VT = MVT::i16; 11999 break; 12000 case Intrinsic::ppc_altivec_lvewx: 12001 VT = MVT::i32; 12002 break; 12003 } 12004 12005 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12006 } 12007 12008 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12009 EVT VT; 12010 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12011 default: return false; 12012 case Intrinsic::ppc_qpx_qvstfd: 12013 case Intrinsic::ppc_qpx_qvstfda: 12014 VT = MVT::v4f64; 12015 break; 12016 case Intrinsic::ppc_qpx_qvstfs: 12017 case Intrinsic::ppc_qpx_qvstfsa: 12018 VT = MVT::v4f32; 12019 break; 12020 case Intrinsic::ppc_qpx_qvstfcd: 12021 case Intrinsic::ppc_qpx_qvstfcda: 12022 VT = MVT::v2f64; 12023 break; 12024 case Intrinsic::ppc_qpx_qvstfcs: 12025 case Intrinsic::ppc_qpx_qvstfcsa: 12026 VT = MVT::v2f32; 12027 break; 12028 case Intrinsic::ppc_qpx_qvstfiw: 12029 case Intrinsic::ppc_qpx_qvstfiwa: 12030 case Intrinsic::ppc_altivec_stvx: 12031 case Intrinsic::ppc_altivec_stvxl: 12032 case Intrinsic::ppc_vsx_stxvw4x: 12033 VT = MVT::v4i32; 12034 break; 12035 case Intrinsic::ppc_vsx_stxvd2x: 12036 VT = MVT::v2f64; 12037 break; 12038 case Intrinsic::ppc_vsx_stxvw4x_be: 12039 VT = MVT::v4i32; 12040 break; 12041 case Intrinsic::ppc_vsx_stxvd2x_be: 12042 VT = MVT::v2f64; 12043 break; 12044 case Intrinsic::ppc_altivec_stvebx: 12045 VT = MVT::i8; 12046 break; 12047 case Intrinsic::ppc_altivec_stvehx: 12048 VT = MVT::i16; 12049 break; 12050 case Intrinsic::ppc_altivec_stvewx: 12051 VT = MVT::i32; 12052 break; 12053 } 12054 12055 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12056 } 12057 12058 return false; 12059 } 12060 12061 // Return true is there is a nearyby consecutive load to the one provided 12062 // (regardless of alignment). We search up and down the chain, looking though 12063 // token factors and other loads (but nothing else). As a result, a true result 12064 // indicates that it is safe to create a new consecutive load adjacent to the 12065 // load provided. 12066 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12067 SDValue Chain = LD->getChain(); 12068 EVT VT = LD->getMemoryVT(); 12069 12070 SmallSet<SDNode *, 16> LoadRoots; 12071 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12072 SmallSet<SDNode *, 16> Visited; 12073 12074 // First, search up the chain, branching to follow all token-factor operands. 12075 // If we find a consecutive load, then we're done, otherwise, record all 12076 // nodes just above the top-level loads and token factors. 12077 while (!Queue.empty()) { 12078 SDNode *ChainNext = Queue.pop_back_val(); 12079 if (!Visited.insert(ChainNext).second) 12080 continue; 12081 12082 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12083 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12084 return true; 12085 12086 if (!Visited.count(ChainLD->getChain().getNode())) 12087 Queue.push_back(ChainLD->getChain().getNode()); 12088 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12089 for (const SDUse &O : ChainNext->ops()) 12090 if (!Visited.count(O.getNode())) 12091 Queue.push_back(O.getNode()); 12092 } else 12093 LoadRoots.insert(ChainNext); 12094 } 12095 12096 // Second, search down the chain, starting from the top-level nodes recorded 12097 // in the first phase. These top-level nodes are the nodes just above all 12098 // loads and token factors. Starting with their uses, recursively look though 12099 // all loads (just the chain uses) and token factors to find a consecutive 12100 // load. 12101 Visited.clear(); 12102 Queue.clear(); 12103 12104 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12105 IE = LoadRoots.end(); I != IE; ++I) { 12106 Queue.push_back(*I); 12107 12108 while (!Queue.empty()) { 12109 SDNode *LoadRoot = Queue.pop_back_val(); 12110 if (!Visited.insert(LoadRoot).second) 12111 continue; 12112 12113 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12114 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12115 return true; 12116 12117 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12118 UE = LoadRoot->use_end(); UI != UE; ++UI) 12119 if (((isa<MemSDNode>(*UI) && 12120 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12121 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12122 Queue.push_back(*UI); 12123 } 12124 } 12125 12126 return false; 12127 } 12128 12129 /// This function is called when we have proved that a SETCC node can be replaced 12130 /// by subtraction (and other supporting instructions) so that the result of 12131 /// comparison is kept in a GPR instead of CR. This function is purely for 12132 /// codegen purposes and has some flags to guide the codegen process. 12133 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12134 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12135 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12136 12137 // Zero extend the operands to the largest legal integer. Originally, they 12138 // must be of a strictly smaller size. 12139 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12140 DAG.getConstant(Size, DL, MVT::i32)); 12141 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12142 DAG.getConstant(Size, DL, MVT::i32)); 12143 12144 // Swap if needed. Depends on the condition code. 12145 if (Swap) 12146 std::swap(Op0, Op1); 12147 12148 // Subtract extended integers. 12149 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12150 12151 // Move the sign bit to the least significant position and zero out the rest. 12152 // Now the least significant bit carries the result of original comparison. 12153 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12154 DAG.getConstant(Size - 1, DL, MVT::i32)); 12155 auto Final = Shifted; 12156 12157 // Complement the result if needed. Based on the condition code. 12158 if (Complement) 12159 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12160 DAG.getConstant(1, DL, MVT::i64)); 12161 12162 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12163 } 12164 12165 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12166 DAGCombinerInfo &DCI) const { 12167 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12168 12169 SelectionDAG &DAG = DCI.DAG; 12170 SDLoc DL(N); 12171 12172 // Size of integers being compared has a critical role in the following 12173 // analysis, so we prefer to do this when all types are legal. 12174 if (!DCI.isAfterLegalizeDAG()) 12175 return SDValue(); 12176 12177 // If all users of SETCC extend its value to a legal integer type 12178 // then we replace SETCC with a subtraction 12179 for (SDNode::use_iterator UI = N->use_begin(), 12180 UE = N->use_end(); UI != UE; ++UI) { 12181 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12182 return SDValue(); 12183 } 12184 12185 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12186 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12187 12188 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12189 12190 if (OpSize < Size) { 12191 switch (CC) { 12192 default: break; 12193 case ISD::SETULT: 12194 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12195 case ISD::SETULE: 12196 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12197 case ISD::SETUGT: 12198 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12199 case ISD::SETUGE: 12200 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12201 } 12202 } 12203 12204 return SDValue(); 12205 } 12206 12207 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12208 DAGCombinerInfo &DCI) const { 12209 SelectionDAG &DAG = DCI.DAG; 12210 SDLoc dl(N); 12211 12212 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12213 // If we're tracking CR bits, we need to be careful that we don't have: 12214 // trunc(binary-ops(zext(x), zext(y))) 12215 // or 12216 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12217 // such that we're unnecessarily moving things into GPRs when it would be 12218 // better to keep them in CR bits. 12219 12220 // Note that trunc here can be an actual i1 trunc, or can be the effective 12221 // truncation that comes from a setcc or select_cc. 12222 if (N->getOpcode() == ISD::TRUNCATE && 12223 N->getValueType(0) != MVT::i1) 12224 return SDValue(); 12225 12226 if (N->getOperand(0).getValueType() != MVT::i32 && 12227 N->getOperand(0).getValueType() != MVT::i64) 12228 return SDValue(); 12229 12230 if (N->getOpcode() == ISD::SETCC || 12231 N->getOpcode() == ISD::SELECT_CC) { 12232 // If we're looking at a comparison, then we need to make sure that the 12233 // high bits (all except for the first) don't matter the result. 12234 ISD::CondCode CC = 12235 cast<CondCodeSDNode>(N->getOperand( 12236 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12237 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12238 12239 if (ISD::isSignedIntSetCC(CC)) { 12240 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12241 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12242 return SDValue(); 12243 } else if (ISD::isUnsignedIntSetCC(CC)) { 12244 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12245 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12246 !DAG.MaskedValueIsZero(N->getOperand(1), 12247 APInt::getHighBitsSet(OpBits, OpBits-1))) 12248 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12249 : SDValue()); 12250 } else { 12251 // This is neither a signed nor an unsigned comparison, just make sure 12252 // that the high bits are equal. 12253 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12254 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12255 12256 // We don't really care about what is known about the first bit (if 12257 // anything), so clear it in all masks prior to comparing them. 12258 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12259 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12260 12261 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12262 return SDValue(); 12263 } 12264 } 12265 12266 // We now know that the higher-order bits are irrelevant, we just need to 12267 // make sure that all of the intermediate operations are bit operations, and 12268 // all inputs are extensions. 12269 if (N->getOperand(0).getOpcode() != ISD::AND && 12270 N->getOperand(0).getOpcode() != ISD::OR && 12271 N->getOperand(0).getOpcode() != ISD::XOR && 12272 N->getOperand(0).getOpcode() != ISD::SELECT && 12273 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12274 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12275 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12276 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12277 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12278 return SDValue(); 12279 12280 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12281 N->getOperand(1).getOpcode() != ISD::AND && 12282 N->getOperand(1).getOpcode() != ISD::OR && 12283 N->getOperand(1).getOpcode() != ISD::XOR && 12284 N->getOperand(1).getOpcode() != ISD::SELECT && 12285 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12286 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12287 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12288 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12289 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12290 return SDValue(); 12291 12292 SmallVector<SDValue, 4> Inputs; 12293 SmallVector<SDValue, 8> BinOps, PromOps; 12294 SmallPtrSet<SDNode *, 16> Visited; 12295 12296 for (unsigned i = 0; i < 2; ++i) { 12297 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12298 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12299 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12300 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12301 isa<ConstantSDNode>(N->getOperand(i))) 12302 Inputs.push_back(N->getOperand(i)); 12303 else 12304 BinOps.push_back(N->getOperand(i)); 12305 12306 if (N->getOpcode() == ISD::TRUNCATE) 12307 break; 12308 } 12309 12310 // Visit all inputs, collect all binary operations (and, or, xor and 12311 // select) that are all fed by extensions. 12312 while (!BinOps.empty()) { 12313 SDValue BinOp = BinOps.back(); 12314 BinOps.pop_back(); 12315 12316 if (!Visited.insert(BinOp.getNode()).second) 12317 continue; 12318 12319 PromOps.push_back(BinOp); 12320 12321 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12322 // The condition of the select is not promoted. 12323 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12324 continue; 12325 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12326 continue; 12327 12328 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12329 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12330 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12331 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12332 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12333 Inputs.push_back(BinOp.getOperand(i)); 12334 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12335 BinOp.getOperand(i).getOpcode() == ISD::OR || 12336 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12337 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12338 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12339 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12340 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12341 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12342 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12343 BinOps.push_back(BinOp.getOperand(i)); 12344 } else { 12345 // We have an input that is not an extension or another binary 12346 // operation; we'll abort this transformation. 12347 return SDValue(); 12348 } 12349 } 12350 } 12351 12352 // Make sure that this is a self-contained cluster of operations (which 12353 // is not quite the same thing as saying that everything has only one 12354 // use). 12355 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12356 if (isa<ConstantSDNode>(Inputs[i])) 12357 continue; 12358 12359 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12360 UE = Inputs[i].getNode()->use_end(); 12361 UI != UE; ++UI) { 12362 SDNode *User = *UI; 12363 if (User != N && !Visited.count(User)) 12364 return SDValue(); 12365 12366 // Make sure that we're not going to promote the non-output-value 12367 // operand(s) or SELECT or SELECT_CC. 12368 // FIXME: Although we could sometimes handle this, and it does occur in 12369 // practice that one of the condition inputs to the select is also one of 12370 // the outputs, we currently can't deal with this. 12371 if (User->getOpcode() == ISD::SELECT) { 12372 if (User->getOperand(0) == Inputs[i]) 12373 return SDValue(); 12374 } else if (User->getOpcode() == ISD::SELECT_CC) { 12375 if (User->getOperand(0) == Inputs[i] || 12376 User->getOperand(1) == Inputs[i]) 12377 return SDValue(); 12378 } 12379 } 12380 } 12381 12382 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12383 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12384 UE = PromOps[i].getNode()->use_end(); 12385 UI != UE; ++UI) { 12386 SDNode *User = *UI; 12387 if (User != N && !Visited.count(User)) 12388 return SDValue(); 12389 12390 // Make sure that we're not going to promote the non-output-value 12391 // operand(s) or SELECT or SELECT_CC. 12392 // FIXME: Although we could sometimes handle this, and it does occur in 12393 // practice that one of the condition inputs to the select is also one of 12394 // the outputs, we currently can't deal with this. 12395 if (User->getOpcode() == ISD::SELECT) { 12396 if (User->getOperand(0) == PromOps[i]) 12397 return SDValue(); 12398 } else if (User->getOpcode() == ISD::SELECT_CC) { 12399 if (User->getOperand(0) == PromOps[i] || 12400 User->getOperand(1) == PromOps[i]) 12401 return SDValue(); 12402 } 12403 } 12404 } 12405 12406 // Replace all inputs with the extension operand. 12407 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12408 // Constants may have users outside the cluster of to-be-promoted nodes, 12409 // and so we need to replace those as we do the promotions. 12410 if (isa<ConstantSDNode>(Inputs[i])) 12411 continue; 12412 else 12413 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12414 } 12415 12416 std::list<HandleSDNode> PromOpHandles; 12417 for (auto &PromOp : PromOps) 12418 PromOpHandles.emplace_back(PromOp); 12419 12420 // Replace all operations (these are all the same, but have a different 12421 // (i1) return type). DAG.getNode will validate that the types of 12422 // a binary operator match, so go through the list in reverse so that 12423 // we've likely promoted both operands first. Any intermediate truncations or 12424 // extensions disappear. 12425 while (!PromOpHandles.empty()) { 12426 SDValue PromOp = PromOpHandles.back().getValue(); 12427 PromOpHandles.pop_back(); 12428 12429 if (PromOp.getOpcode() == ISD::TRUNCATE || 12430 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12431 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12432 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12433 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12434 PromOp.getOperand(0).getValueType() != MVT::i1) { 12435 // The operand is not yet ready (see comment below). 12436 PromOpHandles.emplace_front(PromOp); 12437 continue; 12438 } 12439 12440 SDValue RepValue = PromOp.getOperand(0); 12441 if (isa<ConstantSDNode>(RepValue)) 12442 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12443 12444 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12445 continue; 12446 } 12447 12448 unsigned C; 12449 switch (PromOp.getOpcode()) { 12450 default: C = 0; break; 12451 case ISD::SELECT: C = 1; break; 12452 case ISD::SELECT_CC: C = 2; break; 12453 } 12454 12455 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12456 PromOp.getOperand(C).getValueType() != MVT::i1) || 12457 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12458 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12459 // The to-be-promoted operands of this node have not yet been 12460 // promoted (this should be rare because we're going through the 12461 // list backward, but if one of the operands has several users in 12462 // this cluster of to-be-promoted nodes, it is possible). 12463 PromOpHandles.emplace_front(PromOp); 12464 continue; 12465 } 12466 12467 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12468 PromOp.getNode()->op_end()); 12469 12470 // If there are any constant inputs, make sure they're replaced now. 12471 for (unsigned i = 0; i < 2; ++i) 12472 if (isa<ConstantSDNode>(Ops[C+i])) 12473 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12474 12475 DAG.ReplaceAllUsesOfValueWith(PromOp, 12476 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12477 } 12478 12479 // Now we're left with the initial truncation itself. 12480 if (N->getOpcode() == ISD::TRUNCATE) 12481 return N->getOperand(0); 12482 12483 // Otherwise, this is a comparison. The operands to be compared have just 12484 // changed type (to i1), but everything else is the same. 12485 return SDValue(N, 0); 12486 } 12487 12488 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12489 DAGCombinerInfo &DCI) const { 12490 SelectionDAG &DAG = DCI.DAG; 12491 SDLoc dl(N); 12492 12493 // If we're tracking CR bits, we need to be careful that we don't have: 12494 // zext(binary-ops(trunc(x), trunc(y))) 12495 // or 12496 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12497 // such that we're unnecessarily moving things into CR bits that can more 12498 // efficiently stay in GPRs. Note that if we're not certain that the high 12499 // bits are set as required by the final extension, we still may need to do 12500 // some masking to get the proper behavior. 12501 12502 // This same functionality is important on PPC64 when dealing with 12503 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12504 // the return values of functions. Because it is so similar, it is handled 12505 // here as well. 12506 12507 if (N->getValueType(0) != MVT::i32 && 12508 N->getValueType(0) != MVT::i64) 12509 return SDValue(); 12510 12511 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12512 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12513 return SDValue(); 12514 12515 if (N->getOperand(0).getOpcode() != ISD::AND && 12516 N->getOperand(0).getOpcode() != ISD::OR && 12517 N->getOperand(0).getOpcode() != ISD::XOR && 12518 N->getOperand(0).getOpcode() != ISD::SELECT && 12519 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12520 return SDValue(); 12521 12522 SmallVector<SDValue, 4> Inputs; 12523 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12524 SmallPtrSet<SDNode *, 16> Visited; 12525 12526 // Visit all inputs, collect all binary operations (and, or, xor and 12527 // select) that are all fed by truncations. 12528 while (!BinOps.empty()) { 12529 SDValue BinOp = BinOps.back(); 12530 BinOps.pop_back(); 12531 12532 if (!Visited.insert(BinOp.getNode()).second) 12533 continue; 12534 12535 PromOps.push_back(BinOp); 12536 12537 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12538 // The condition of the select is not promoted. 12539 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12540 continue; 12541 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12542 continue; 12543 12544 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12545 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12546 Inputs.push_back(BinOp.getOperand(i)); 12547 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12548 BinOp.getOperand(i).getOpcode() == ISD::OR || 12549 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12550 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12551 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12552 BinOps.push_back(BinOp.getOperand(i)); 12553 } else { 12554 // We have an input that is not a truncation or another binary 12555 // operation; we'll abort this transformation. 12556 return SDValue(); 12557 } 12558 } 12559 } 12560 12561 // The operands of a select that must be truncated when the select is 12562 // promoted because the operand is actually part of the to-be-promoted set. 12563 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12564 12565 // Make sure that this is a self-contained cluster of operations (which 12566 // is not quite the same thing as saying that everything has only one 12567 // use). 12568 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12569 if (isa<ConstantSDNode>(Inputs[i])) 12570 continue; 12571 12572 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12573 UE = Inputs[i].getNode()->use_end(); 12574 UI != UE; ++UI) { 12575 SDNode *User = *UI; 12576 if (User != N && !Visited.count(User)) 12577 return SDValue(); 12578 12579 // If we're going to promote the non-output-value operand(s) or SELECT or 12580 // SELECT_CC, record them for truncation. 12581 if (User->getOpcode() == ISD::SELECT) { 12582 if (User->getOperand(0) == Inputs[i]) 12583 SelectTruncOp[0].insert(std::make_pair(User, 12584 User->getOperand(0).getValueType())); 12585 } else if (User->getOpcode() == ISD::SELECT_CC) { 12586 if (User->getOperand(0) == Inputs[i]) 12587 SelectTruncOp[0].insert(std::make_pair(User, 12588 User->getOperand(0).getValueType())); 12589 if (User->getOperand(1) == Inputs[i]) 12590 SelectTruncOp[1].insert(std::make_pair(User, 12591 User->getOperand(1).getValueType())); 12592 } 12593 } 12594 } 12595 12596 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12597 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12598 UE = PromOps[i].getNode()->use_end(); 12599 UI != UE; ++UI) { 12600 SDNode *User = *UI; 12601 if (User != N && !Visited.count(User)) 12602 return SDValue(); 12603 12604 // If we're going to promote the non-output-value operand(s) or SELECT or 12605 // SELECT_CC, record them for truncation. 12606 if (User->getOpcode() == ISD::SELECT) { 12607 if (User->getOperand(0) == PromOps[i]) 12608 SelectTruncOp[0].insert(std::make_pair(User, 12609 User->getOperand(0).getValueType())); 12610 } else if (User->getOpcode() == ISD::SELECT_CC) { 12611 if (User->getOperand(0) == PromOps[i]) 12612 SelectTruncOp[0].insert(std::make_pair(User, 12613 User->getOperand(0).getValueType())); 12614 if (User->getOperand(1) == PromOps[i]) 12615 SelectTruncOp[1].insert(std::make_pair(User, 12616 User->getOperand(1).getValueType())); 12617 } 12618 } 12619 } 12620 12621 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12622 bool ReallyNeedsExt = false; 12623 if (N->getOpcode() != ISD::ANY_EXTEND) { 12624 // If all of the inputs are not already sign/zero extended, then 12625 // we'll still need to do that at the end. 12626 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12627 if (isa<ConstantSDNode>(Inputs[i])) 12628 continue; 12629 12630 unsigned OpBits = 12631 Inputs[i].getOperand(0).getValueSizeInBits(); 12632 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12633 12634 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12635 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12636 APInt::getHighBitsSet(OpBits, 12637 OpBits-PromBits))) || 12638 (N->getOpcode() == ISD::SIGN_EXTEND && 12639 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12640 (OpBits-(PromBits-1)))) { 12641 ReallyNeedsExt = true; 12642 break; 12643 } 12644 } 12645 } 12646 12647 // Replace all inputs, either with the truncation operand, or a 12648 // truncation or extension to the final output type. 12649 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12650 // Constant inputs need to be replaced with the to-be-promoted nodes that 12651 // use them because they might have users outside of the cluster of 12652 // promoted nodes. 12653 if (isa<ConstantSDNode>(Inputs[i])) 12654 continue; 12655 12656 SDValue InSrc = Inputs[i].getOperand(0); 12657 if (Inputs[i].getValueType() == N->getValueType(0)) 12658 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12659 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12660 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12661 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12662 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12663 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12664 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12665 else 12666 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12667 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12668 } 12669 12670 std::list<HandleSDNode> PromOpHandles; 12671 for (auto &PromOp : PromOps) 12672 PromOpHandles.emplace_back(PromOp); 12673 12674 // Replace all operations (these are all the same, but have a different 12675 // (promoted) return type). DAG.getNode will validate that the types of 12676 // a binary operator match, so go through the list in reverse so that 12677 // we've likely promoted both operands first. 12678 while (!PromOpHandles.empty()) { 12679 SDValue PromOp = PromOpHandles.back().getValue(); 12680 PromOpHandles.pop_back(); 12681 12682 unsigned C; 12683 switch (PromOp.getOpcode()) { 12684 default: C = 0; break; 12685 case ISD::SELECT: C = 1; break; 12686 case ISD::SELECT_CC: C = 2; break; 12687 } 12688 12689 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12690 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12691 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12692 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12693 // The to-be-promoted operands of this node have not yet been 12694 // promoted (this should be rare because we're going through the 12695 // list backward, but if one of the operands has several users in 12696 // this cluster of to-be-promoted nodes, it is possible). 12697 PromOpHandles.emplace_front(PromOp); 12698 continue; 12699 } 12700 12701 // For SELECT and SELECT_CC nodes, we do a similar check for any 12702 // to-be-promoted comparison inputs. 12703 if (PromOp.getOpcode() == ISD::SELECT || 12704 PromOp.getOpcode() == ISD::SELECT_CC) { 12705 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12706 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12707 (SelectTruncOp[1].count(PromOp.getNode()) && 12708 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12709 PromOpHandles.emplace_front(PromOp); 12710 continue; 12711 } 12712 } 12713 12714 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12715 PromOp.getNode()->op_end()); 12716 12717 // If this node has constant inputs, then they'll need to be promoted here. 12718 for (unsigned i = 0; i < 2; ++i) { 12719 if (!isa<ConstantSDNode>(Ops[C+i])) 12720 continue; 12721 if (Ops[C+i].getValueType() == N->getValueType(0)) 12722 continue; 12723 12724 if (N->getOpcode() == ISD::SIGN_EXTEND) 12725 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12726 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12727 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12728 else 12729 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12730 } 12731 12732 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12733 // truncate them again to the original value type. 12734 if (PromOp.getOpcode() == ISD::SELECT || 12735 PromOp.getOpcode() == ISD::SELECT_CC) { 12736 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12737 if (SI0 != SelectTruncOp[0].end()) 12738 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12739 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12740 if (SI1 != SelectTruncOp[1].end()) 12741 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12742 } 12743 12744 DAG.ReplaceAllUsesOfValueWith(PromOp, 12745 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12746 } 12747 12748 // Now we're left with the initial extension itself. 12749 if (!ReallyNeedsExt) 12750 return N->getOperand(0); 12751 12752 // To zero extend, just mask off everything except for the first bit (in the 12753 // i1 case). 12754 if (N->getOpcode() == ISD::ZERO_EXTEND) 12755 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12756 DAG.getConstant(APInt::getLowBitsSet( 12757 N->getValueSizeInBits(0), PromBits), 12758 dl, N->getValueType(0))); 12759 12760 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12761 "Invalid extension type"); 12762 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12763 SDValue ShiftCst = 12764 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12765 return DAG.getNode( 12766 ISD::SRA, dl, N->getValueType(0), 12767 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12768 ShiftCst); 12769 } 12770 12771 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12772 DAGCombinerInfo &DCI) const { 12773 assert(N->getOpcode() == ISD::SETCC && 12774 "Should be called with a SETCC node"); 12775 12776 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12777 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12778 SDValue LHS = N->getOperand(0); 12779 SDValue RHS = N->getOperand(1); 12780 12781 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12782 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12783 LHS.hasOneUse()) 12784 std::swap(LHS, RHS); 12785 12786 // x == 0-y --> x+y == 0 12787 // x != 0-y --> x+y != 0 12788 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12789 RHS.hasOneUse()) { 12790 SDLoc DL(N); 12791 SelectionDAG &DAG = DCI.DAG; 12792 EVT VT = N->getValueType(0); 12793 EVT OpVT = LHS.getValueType(); 12794 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12795 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12796 } 12797 } 12798 12799 return DAGCombineTruncBoolExt(N, DCI); 12800 } 12801 12802 // Is this an extending load from an f32 to an f64? 12803 static bool isFPExtLoad(SDValue Op) { 12804 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12805 return LD->getExtensionType() == ISD::EXTLOAD && 12806 Op.getValueType() == MVT::f64; 12807 return false; 12808 } 12809 12810 /// Reduces the number of fp-to-int conversion when building a vector. 12811 /// 12812 /// If this vector is built out of floating to integer conversions, 12813 /// transform it to a vector built out of floating point values followed by a 12814 /// single floating to integer conversion of the vector. 12815 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12816 /// becomes (fptosi (build_vector ($A, $B, ...))) 12817 SDValue PPCTargetLowering:: 12818 combineElementTruncationToVectorTruncation(SDNode *N, 12819 DAGCombinerInfo &DCI) const { 12820 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12821 "Should be called with a BUILD_VECTOR node"); 12822 12823 SelectionDAG &DAG = DCI.DAG; 12824 SDLoc dl(N); 12825 12826 SDValue FirstInput = N->getOperand(0); 12827 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12828 "The input operand must be an fp-to-int conversion."); 12829 12830 // This combine happens after legalization so the fp_to_[su]i nodes are 12831 // already converted to PPCSISD nodes. 12832 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12833 if (FirstConversion == PPCISD::FCTIDZ || 12834 FirstConversion == PPCISD::FCTIDUZ || 12835 FirstConversion == PPCISD::FCTIWZ || 12836 FirstConversion == PPCISD::FCTIWUZ) { 12837 bool IsSplat = true; 12838 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12839 FirstConversion == PPCISD::FCTIWUZ; 12840 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12841 SmallVector<SDValue, 4> Ops; 12842 EVT TargetVT = N->getValueType(0); 12843 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12844 SDValue NextOp = N->getOperand(i); 12845 if (NextOp.getOpcode() != PPCISD::MFVSR) 12846 return SDValue(); 12847 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12848 if (NextConversion != FirstConversion) 12849 return SDValue(); 12850 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12851 // This is not valid if the input was originally double precision. It is 12852 // also not profitable to do unless this is an extending load in which 12853 // case doing this combine will allow us to combine consecutive loads. 12854 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12855 return SDValue(); 12856 if (N->getOperand(i) != FirstInput) 12857 IsSplat = false; 12858 } 12859 12860 // If this is a splat, we leave it as-is since there will be only a single 12861 // fp-to-int conversion followed by a splat of the integer. This is better 12862 // for 32-bit and smaller ints and neutral for 64-bit ints. 12863 if (IsSplat) 12864 return SDValue(); 12865 12866 // Now that we know we have the right type of node, get its operands 12867 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12868 SDValue In = N->getOperand(i).getOperand(0); 12869 if (Is32Bit) { 12870 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12871 // here, we know that all inputs are extending loads so this is safe). 12872 if (In.isUndef()) 12873 Ops.push_back(DAG.getUNDEF(SrcVT)); 12874 else { 12875 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12876 MVT::f32, In.getOperand(0), 12877 DAG.getIntPtrConstant(1, dl)); 12878 Ops.push_back(Trunc); 12879 } 12880 } else 12881 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12882 } 12883 12884 unsigned Opcode; 12885 if (FirstConversion == PPCISD::FCTIDZ || 12886 FirstConversion == PPCISD::FCTIWZ) 12887 Opcode = ISD::FP_TO_SINT; 12888 else 12889 Opcode = ISD::FP_TO_UINT; 12890 12891 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12892 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12893 return DAG.getNode(Opcode, dl, TargetVT, BV); 12894 } 12895 return SDValue(); 12896 } 12897 12898 /// Reduce the number of loads when building a vector. 12899 /// 12900 /// Building a vector out of multiple loads can be converted to a load 12901 /// of the vector type if the loads are consecutive. If the loads are 12902 /// consecutive but in descending order, a shuffle is added at the end 12903 /// to reorder the vector. 12904 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 12905 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12906 "Should be called with a BUILD_VECTOR node"); 12907 12908 SDLoc dl(N); 12909 12910 // Return early for non byte-sized type, as they can't be consecutive. 12911 if (!N->getValueType(0).getVectorElementType().isByteSized()) 12912 return SDValue(); 12913 12914 bool InputsAreConsecutiveLoads = true; 12915 bool InputsAreReverseConsecutive = true; 12916 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 12917 SDValue FirstInput = N->getOperand(0); 12918 bool IsRoundOfExtLoad = false; 12919 12920 if (FirstInput.getOpcode() == ISD::FP_ROUND && 12921 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 12922 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 12923 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 12924 } 12925 // Not a build vector of (possibly fp_rounded) loads. 12926 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 12927 N->getNumOperands() == 1) 12928 return SDValue(); 12929 12930 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 12931 // If any inputs are fp_round(extload), they all must be. 12932 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 12933 return SDValue(); 12934 12935 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 12936 N->getOperand(i); 12937 if (NextInput.getOpcode() != ISD::LOAD) 12938 return SDValue(); 12939 12940 SDValue PreviousInput = 12941 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 12942 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 12943 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 12944 12945 // If any inputs are fp_round(extload), they all must be. 12946 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 12947 return SDValue(); 12948 12949 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 12950 InputsAreConsecutiveLoads = false; 12951 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 12952 InputsAreReverseConsecutive = false; 12953 12954 // Exit early if the loads are neither consecutive nor reverse consecutive. 12955 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12956 return SDValue(); 12957 } 12958 12959 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12960 "The loads cannot be both consecutive and reverse consecutive."); 12961 12962 SDValue FirstLoadOp = 12963 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12964 SDValue LastLoadOp = 12965 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12966 N->getOperand(N->getNumOperands()-1); 12967 12968 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12969 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12970 if (InputsAreConsecutiveLoads) { 12971 assert(LD1 && "Input needs to be a LoadSDNode."); 12972 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12973 LD1->getBasePtr(), LD1->getPointerInfo(), 12974 LD1->getAlignment()); 12975 } 12976 if (InputsAreReverseConsecutive) { 12977 assert(LDL && "Input needs to be a LoadSDNode."); 12978 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12979 LDL->getBasePtr(), LDL->getPointerInfo(), 12980 LDL->getAlignment()); 12981 SmallVector<int, 16> Ops; 12982 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12983 Ops.push_back(i); 12984 12985 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12986 DAG.getUNDEF(N->getValueType(0)), Ops); 12987 } 12988 return SDValue(); 12989 } 12990 12991 // This function adds the required vector_shuffle needed to get 12992 // the elements of the vector extract in the correct position 12993 // as specified by the CorrectElems encoding. 12994 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12995 SDValue Input, uint64_t Elems, 12996 uint64_t CorrectElems) { 12997 SDLoc dl(N); 12998 12999 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13000 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13001 13002 // Knowing the element indices being extracted from the original 13003 // vector and the order in which they're being inserted, just put 13004 // them at element indices required for the instruction. 13005 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13006 if (DAG.getDataLayout().isLittleEndian()) 13007 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13008 else 13009 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13010 CorrectElems = CorrectElems >> 8; 13011 Elems = Elems >> 8; 13012 } 13013 13014 SDValue Shuffle = 13015 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13016 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13017 13018 EVT Ty = N->getValueType(0); 13019 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 13020 return BV; 13021 } 13022 13023 // Look for build vector patterns where input operands come from sign 13024 // extended vector_extract elements of specific indices. If the correct indices 13025 // aren't used, add a vector shuffle to fix up the indices and create a new 13026 // PPCISD:SExtVElems node which selects the vector sign extend instructions 13027 // during instruction selection. 13028 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13029 // This array encodes the indices that the vector sign extend instructions 13030 // extract from when extending from one type to another for both BE and LE. 13031 // The right nibble of each byte corresponds to the LE incides. 13032 // and the left nibble of each byte corresponds to the BE incides. 13033 // For example: 0x3074B8FC byte->word 13034 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13035 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13036 // For example: 0x000070F8 byte->double word 13037 // For LE: the allowed indices are: 0x0,0x8 13038 // For BE: the allowed indices are: 0x7,0xF 13039 uint64_t TargetElems[] = { 13040 0x3074B8FC, // b->w 13041 0x000070F8, // b->d 13042 0x10325476, // h->w 13043 0x00003074, // h->d 13044 0x00001032, // w->d 13045 }; 13046 13047 uint64_t Elems = 0; 13048 int Index; 13049 SDValue Input; 13050 13051 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13052 if (!Op) 13053 return false; 13054 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13055 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13056 return false; 13057 13058 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13059 // of the right width. 13060 SDValue Extract = Op.getOperand(0); 13061 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13062 Extract = Extract.getOperand(0); 13063 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13064 return false; 13065 13066 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13067 if (!ExtOp) 13068 return false; 13069 13070 Index = ExtOp->getZExtValue(); 13071 if (Input && Input != Extract.getOperand(0)) 13072 return false; 13073 13074 if (!Input) 13075 Input = Extract.getOperand(0); 13076 13077 Elems = Elems << 8; 13078 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13079 Elems |= Index; 13080 13081 return true; 13082 }; 13083 13084 // If the build vector operands aren't sign extended vector extracts, 13085 // of the same input vector, then return. 13086 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13087 if (!isSExtOfVecExtract(N->getOperand(i))) { 13088 return SDValue(); 13089 } 13090 } 13091 13092 // If the vector extract indicies are not correct, add the appropriate 13093 // vector_shuffle. 13094 int TgtElemArrayIdx; 13095 int InputSize = Input.getValueType().getScalarSizeInBits(); 13096 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13097 if (InputSize + OutputSize == 40) 13098 TgtElemArrayIdx = 0; 13099 else if (InputSize + OutputSize == 72) 13100 TgtElemArrayIdx = 1; 13101 else if (InputSize + OutputSize == 48) 13102 TgtElemArrayIdx = 2; 13103 else if (InputSize + OutputSize == 80) 13104 TgtElemArrayIdx = 3; 13105 else if (InputSize + OutputSize == 96) 13106 TgtElemArrayIdx = 4; 13107 else 13108 return SDValue(); 13109 13110 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13111 CorrectElems = DAG.getDataLayout().isLittleEndian() 13112 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13113 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13114 if (Elems != CorrectElems) { 13115 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13116 } 13117 13118 // Regular lowering will catch cases where a shuffle is not needed. 13119 return SDValue(); 13120 } 13121 13122 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13123 DAGCombinerInfo &DCI) const { 13124 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13125 "Should be called with a BUILD_VECTOR node"); 13126 13127 SelectionDAG &DAG = DCI.DAG; 13128 SDLoc dl(N); 13129 13130 if (!Subtarget.hasVSX()) 13131 return SDValue(); 13132 13133 // The target independent DAG combiner will leave a build_vector of 13134 // float-to-int conversions intact. We can generate MUCH better code for 13135 // a float-to-int conversion of a vector of floats. 13136 SDValue FirstInput = N->getOperand(0); 13137 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13138 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13139 if (Reduced) 13140 return Reduced; 13141 } 13142 13143 // If we're building a vector out of consecutive loads, just load that 13144 // vector type. 13145 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13146 if (Reduced) 13147 return Reduced; 13148 13149 // If we're building a vector out of extended elements from another vector 13150 // we have P9 vector integer extend instructions. The code assumes legal 13151 // input types (i.e. it can't handle things like v4i16) so do not run before 13152 // legalization. 13153 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13154 Reduced = combineBVOfVecSExt(N, DAG); 13155 if (Reduced) 13156 return Reduced; 13157 } 13158 13159 13160 if (N->getValueType(0) != MVT::v2f64) 13161 return SDValue(); 13162 13163 // Looking for: 13164 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13165 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13166 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13167 return SDValue(); 13168 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13169 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13170 return SDValue(); 13171 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13172 return SDValue(); 13173 13174 SDValue Ext1 = FirstInput.getOperand(0); 13175 SDValue Ext2 = N->getOperand(1).getOperand(0); 13176 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13177 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13178 return SDValue(); 13179 13180 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13181 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13182 if (!Ext1Op || !Ext2Op) 13183 return SDValue(); 13184 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13185 Ext1.getOperand(0) != Ext2.getOperand(0)) 13186 return SDValue(); 13187 13188 int FirstElem = Ext1Op->getZExtValue(); 13189 int SecondElem = Ext2Op->getZExtValue(); 13190 int SubvecIdx; 13191 if (FirstElem == 0 && SecondElem == 1) 13192 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13193 else if (FirstElem == 2 && SecondElem == 3) 13194 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13195 else 13196 return SDValue(); 13197 13198 SDValue SrcVec = Ext1.getOperand(0); 13199 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13200 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13201 return DAG.getNode(NodeType, dl, MVT::v2f64, 13202 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13203 } 13204 13205 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13206 DAGCombinerInfo &DCI) const { 13207 assert((N->getOpcode() == ISD::SINT_TO_FP || 13208 N->getOpcode() == ISD::UINT_TO_FP) && 13209 "Need an int -> FP conversion node here"); 13210 13211 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13212 return SDValue(); 13213 13214 SelectionDAG &DAG = DCI.DAG; 13215 SDLoc dl(N); 13216 SDValue Op(N, 0); 13217 13218 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13219 // from the hardware. 13220 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13221 return SDValue(); 13222 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13223 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13224 return SDValue(); 13225 13226 SDValue FirstOperand(Op.getOperand(0)); 13227 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13228 (FirstOperand.getValueType() == MVT::i8 || 13229 FirstOperand.getValueType() == MVT::i16); 13230 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13231 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13232 bool DstDouble = Op.getValueType() == MVT::f64; 13233 unsigned ConvOp = Signed ? 13234 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13235 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13236 SDValue WidthConst = 13237 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13238 dl, false); 13239 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13240 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13241 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13242 DAG.getVTList(MVT::f64, MVT::Other), 13243 Ops, MVT::i8, LDN->getMemOperand()); 13244 13245 // For signed conversion, we need to sign-extend the value in the VSR 13246 if (Signed) { 13247 SDValue ExtOps[] = { Ld, WidthConst }; 13248 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13249 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13250 } else 13251 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13252 } 13253 13254 13255 // For i32 intermediate values, unfortunately, the conversion functions 13256 // leave the upper 32 bits of the value are undefined. Within the set of 13257 // scalar instructions, we have no method for zero- or sign-extending the 13258 // value. Thus, we cannot handle i32 intermediate values here. 13259 if (Op.getOperand(0).getValueType() == MVT::i32) 13260 return SDValue(); 13261 13262 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13263 "UINT_TO_FP is supported only with FPCVT"); 13264 13265 // If we have FCFIDS, then use it when converting to single-precision. 13266 // Otherwise, convert to double-precision and then round. 13267 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13268 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13269 : PPCISD::FCFIDS) 13270 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13271 : PPCISD::FCFID); 13272 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13273 ? MVT::f32 13274 : MVT::f64; 13275 13276 // If we're converting from a float, to an int, and back to a float again, 13277 // then we don't need the store/load pair at all. 13278 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13279 Subtarget.hasFPCVT()) || 13280 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13281 SDValue Src = Op.getOperand(0).getOperand(0); 13282 if (Src.getValueType() == MVT::f32) { 13283 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13284 DCI.AddToWorklist(Src.getNode()); 13285 } else if (Src.getValueType() != MVT::f64) { 13286 // Make sure that we don't pick up a ppc_fp128 source value. 13287 return SDValue(); 13288 } 13289 13290 unsigned FCTOp = 13291 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13292 PPCISD::FCTIDUZ; 13293 13294 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13295 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13296 13297 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13298 FP = DAG.getNode(ISD::FP_ROUND, dl, 13299 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13300 DCI.AddToWorklist(FP.getNode()); 13301 } 13302 13303 return FP; 13304 } 13305 13306 return SDValue(); 13307 } 13308 13309 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13310 // builtins) into loads with swaps. 13311 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13312 DAGCombinerInfo &DCI) const { 13313 SelectionDAG &DAG = DCI.DAG; 13314 SDLoc dl(N); 13315 SDValue Chain; 13316 SDValue Base; 13317 MachineMemOperand *MMO; 13318 13319 switch (N->getOpcode()) { 13320 default: 13321 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13322 case ISD::LOAD: { 13323 LoadSDNode *LD = cast<LoadSDNode>(N); 13324 Chain = LD->getChain(); 13325 Base = LD->getBasePtr(); 13326 MMO = LD->getMemOperand(); 13327 // If the MMO suggests this isn't a load of a full vector, leave 13328 // things alone. For a built-in, we have to make the change for 13329 // correctness, so if there is a size problem that will be a bug. 13330 if (MMO->getSize() < 16) 13331 return SDValue(); 13332 break; 13333 } 13334 case ISD::INTRINSIC_W_CHAIN: { 13335 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13336 Chain = Intrin->getChain(); 13337 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13338 // us what we want. Get operand 2 instead. 13339 Base = Intrin->getOperand(2); 13340 MMO = Intrin->getMemOperand(); 13341 break; 13342 } 13343 } 13344 13345 MVT VecTy = N->getValueType(0).getSimpleVT(); 13346 13347 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13348 // aligned and the type is a vector with elements up to 4 bytes 13349 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13350 && VecTy.getScalarSizeInBits() <= 32 ) { 13351 return SDValue(); 13352 } 13353 13354 SDValue LoadOps[] = { Chain, Base }; 13355 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13356 DAG.getVTList(MVT::v2f64, MVT::Other), 13357 LoadOps, MVT::v2f64, MMO); 13358 13359 DCI.AddToWorklist(Load.getNode()); 13360 Chain = Load.getValue(1); 13361 SDValue Swap = DAG.getNode( 13362 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13363 DCI.AddToWorklist(Swap.getNode()); 13364 13365 // Add a bitcast if the resulting load type doesn't match v2f64. 13366 if (VecTy != MVT::v2f64) { 13367 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13368 DCI.AddToWorklist(N.getNode()); 13369 // Package {bitcast value, swap's chain} to match Load's shape. 13370 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13371 N, Swap.getValue(1)); 13372 } 13373 13374 return Swap; 13375 } 13376 13377 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13378 // builtins) into stores with swaps. 13379 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13380 DAGCombinerInfo &DCI) const { 13381 SelectionDAG &DAG = DCI.DAG; 13382 SDLoc dl(N); 13383 SDValue Chain; 13384 SDValue Base; 13385 unsigned SrcOpnd; 13386 MachineMemOperand *MMO; 13387 13388 switch (N->getOpcode()) { 13389 default: 13390 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13391 case ISD::STORE: { 13392 StoreSDNode *ST = cast<StoreSDNode>(N); 13393 Chain = ST->getChain(); 13394 Base = ST->getBasePtr(); 13395 MMO = ST->getMemOperand(); 13396 SrcOpnd = 1; 13397 // If the MMO suggests this isn't a store of a full vector, leave 13398 // things alone. For a built-in, we have to make the change for 13399 // correctness, so if there is a size problem that will be a bug. 13400 if (MMO->getSize() < 16) 13401 return SDValue(); 13402 break; 13403 } 13404 case ISD::INTRINSIC_VOID: { 13405 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13406 Chain = Intrin->getChain(); 13407 // Intrin->getBasePtr() oddly does not get what we want. 13408 Base = Intrin->getOperand(3); 13409 MMO = Intrin->getMemOperand(); 13410 SrcOpnd = 2; 13411 break; 13412 } 13413 } 13414 13415 SDValue Src = N->getOperand(SrcOpnd); 13416 MVT VecTy = Src.getValueType().getSimpleVT(); 13417 13418 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13419 // aligned and the type is a vector with elements up to 4 bytes 13420 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13421 && VecTy.getScalarSizeInBits() <= 32 ) { 13422 return SDValue(); 13423 } 13424 13425 // All stores are done as v2f64 and possible bit cast. 13426 if (VecTy != MVT::v2f64) { 13427 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13428 DCI.AddToWorklist(Src.getNode()); 13429 } 13430 13431 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13432 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13433 DCI.AddToWorklist(Swap.getNode()); 13434 Chain = Swap.getValue(1); 13435 SDValue StoreOps[] = { Chain, Swap, Base }; 13436 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13437 DAG.getVTList(MVT::Other), 13438 StoreOps, VecTy, MMO); 13439 DCI.AddToWorklist(Store.getNode()); 13440 return Store; 13441 } 13442 13443 // Handle DAG combine for STORE (FP_TO_INT F). 13444 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13445 DAGCombinerInfo &DCI) const { 13446 13447 SelectionDAG &DAG = DCI.DAG; 13448 SDLoc dl(N); 13449 unsigned Opcode = N->getOperand(1).getOpcode(); 13450 13451 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13452 && "Not a FP_TO_INT Instruction!"); 13453 13454 SDValue Val = N->getOperand(1).getOperand(0); 13455 EVT Op1VT = N->getOperand(1).getValueType(); 13456 EVT ResVT = Val.getValueType(); 13457 13458 // Floating point types smaller than 32 bits are not legal on Power. 13459 if (ResVT.getScalarSizeInBits() < 32) 13460 return SDValue(); 13461 13462 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13463 bool ValidTypeForStoreFltAsInt = 13464 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13465 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13466 13467 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 13468 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13469 return SDValue(); 13470 13471 // Extend f32 values to f64 13472 if (ResVT.getScalarSizeInBits() == 32) { 13473 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13474 DCI.AddToWorklist(Val.getNode()); 13475 } 13476 13477 // Set signed or unsigned conversion opcode. 13478 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13479 PPCISD::FP_TO_SINT_IN_VSR : 13480 PPCISD::FP_TO_UINT_IN_VSR; 13481 13482 Val = DAG.getNode(ConvOpcode, 13483 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13484 DCI.AddToWorklist(Val.getNode()); 13485 13486 // Set number of bytes being converted. 13487 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13488 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13489 DAG.getIntPtrConstant(ByteSize, dl, false), 13490 DAG.getValueType(Op1VT) }; 13491 13492 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13493 DAG.getVTList(MVT::Other), Ops, 13494 cast<StoreSDNode>(N)->getMemoryVT(), 13495 cast<StoreSDNode>(N)->getMemOperand()); 13496 13497 DCI.AddToWorklist(Val.getNode()); 13498 return Val; 13499 } 13500 13501 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 13502 LSBaseSDNode *LSBase, 13503 DAGCombinerInfo &DCI) const { 13504 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 13505 "Not a reverse memop pattern!"); 13506 13507 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 13508 auto Mask = SVN->getMask(); 13509 int i = 0; 13510 auto I = Mask.rbegin(); 13511 auto E = Mask.rend(); 13512 13513 for (; I != E; ++I) { 13514 if (*I != i) 13515 return false; 13516 i++; 13517 } 13518 return true; 13519 }; 13520 13521 SelectionDAG &DAG = DCI.DAG; 13522 EVT VT = SVN->getValueType(0); 13523 13524 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 13525 return SDValue(); 13526 13527 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 13528 // See comment in PPCVSXSwapRemoval.cpp. 13529 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 13530 if (!Subtarget.hasP9Vector()) 13531 return SDValue(); 13532 13533 if(!IsElementReverse(SVN)) 13534 return SDValue(); 13535 13536 if (LSBase->getOpcode() == ISD::LOAD) { 13537 SDLoc dl(SVN); 13538 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 13539 return DAG.getMemIntrinsicNode( 13540 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 13541 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13542 } 13543 13544 if (LSBase->getOpcode() == ISD::STORE) { 13545 SDLoc dl(LSBase); 13546 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 13547 LSBase->getBasePtr()}; 13548 return DAG.getMemIntrinsicNode( 13549 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 13550 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13551 } 13552 13553 llvm_unreachable("Expected a load or store node here"); 13554 } 13555 13556 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 13557 DAGCombinerInfo &DCI) const { 13558 SelectionDAG &DAG = DCI.DAG; 13559 SDLoc dl(N); 13560 switch (N->getOpcode()) { 13561 default: break; 13562 case ISD::ADD: 13563 return combineADD(N, DCI); 13564 case ISD::SHL: 13565 return combineSHL(N, DCI); 13566 case ISD::SRA: 13567 return combineSRA(N, DCI); 13568 case ISD::SRL: 13569 return combineSRL(N, DCI); 13570 case ISD::MUL: 13571 return combineMUL(N, DCI); 13572 case PPCISD::SHL: 13573 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 13574 return N->getOperand(0); 13575 break; 13576 case PPCISD::SRL: 13577 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 13578 return N->getOperand(0); 13579 break; 13580 case PPCISD::SRA: 13581 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 13582 if (C->isNullValue() || // 0 >>s V -> 0. 13583 C->isAllOnesValue()) // -1 >>s V -> -1. 13584 return N->getOperand(0); 13585 } 13586 break; 13587 case ISD::SIGN_EXTEND: 13588 case ISD::ZERO_EXTEND: 13589 case ISD::ANY_EXTEND: 13590 return DAGCombineExtBoolTrunc(N, DCI); 13591 case ISD::TRUNCATE: 13592 return combineTRUNCATE(N, DCI); 13593 case ISD::SETCC: 13594 if (SDValue CSCC = combineSetCC(N, DCI)) 13595 return CSCC; 13596 LLVM_FALLTHROUGH; 13597 case ISD::SELECT_CC: 13598 return DAGCombineTruncBoolExt(N, DCI); 13599 case ISD::SINT_TO_FP: 13600 case ISD::UINT_TO_FP: 13601 return combineFPToIntToFP(N, DCI); 13602 case ISD::VECTOR_SHUFFLE: 13603 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 13604 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 13605 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 13606 } 13607 break; 13608 case ISD::STORE: { 13609 13610 EVT Op1VT = N->getOperand(1).getValueType(); 13611 unsigned Opcode = N->getOperand(1).getOpcode(); 13612 13613 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 13614 SDValue Val= combineStoreFPToInt(N, DCI); 13615 if (Val) 13616 return Val; 13617 } 13618 13619 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 13620 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 13621 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 13622 if (Val) 13623 return Val; 13624 } 13625 13626 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 13627 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 13628 N->getOperand(1).getNode()->hasOneUse() && 13629 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 13630 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 13631 13632 // STBRX can only handle simple types and it makes no sense to store less 13633 // two bytes in byte-reversed order. 13634 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 13635 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 13636 break; 13637 13638 SDValue BSwapOp = N->getOperand(1).getOperand(0); 13639 // Do an any-extend to 32-bits if this is a half-word input. 13640 if (BSwapOp.getValueType() == MVT::i16) 13641 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 13642 13643 // If the type of BSWAP operand is wider than stored memory width 13644 // it need to be shifted to the right side before STBRX. 13645 if (Op1VT.bitsGT(mVT)) { 13646 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 13647 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 13648 DAG.getConstant(Shift, dl, MVT::i32)); 13649 // Need to truncate if this is a bswap of i64 stored as i32/i16. 13650 if (Op1VT == MVT::i64) 13651 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 13652 } 13653 13654 SDValue Ops[] = { 13655 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 13656 }; 13657 return 13658 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 13659 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 13660 cast<StoreSDNode>(N)->getMemOperand()); 13661 } 13662 13663 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 13664 // So it can increase the chance of CSE constant construction. 13665 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 13666 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 13667 // Need to sign-extended to 64-bits to handle negative values. 13668 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 13669 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 13670 MemVT.getSizeInBits()); 13671 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 13672 13673 // DAG.getTruncStore() can't be used here because it doesn't accept 13674 // the general (base + offset) addressing mode. 13675 // So we use UpdateNodeOperands and setTruncatingStore instead. 13676 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 13677 N->getOperand(3)); 13678 cast<StoreSDNode>(N)->setTruncatingStore(true); 13679 return SDValue(N, 0); 13680 } 13681 13682 // For little endian, VSX stores require generating xxswapd/lxvd2x. 13683 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13684 if (Op1VT.isSimple()) { 13685 MVT StoreVT = Op1VT.getSimpleVT(); 13686 if (Subtarget.needsSwapsForVSXMemOps() && 13687 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 13688 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 13689 return expandVSXStoreForLE(N, DCI); 13690 } 13691 break; 13692 } 13693 case ISD::LOAD: { 13694 LoadSDNode *LD = cast<LoadSDNode>(N); 13695 EVT VT = LD->getValueType(0); 13696 13697 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13698 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13699 if (VT.isSimple()) { 13700 MVT LoadVT = VT.getSimpleVT(); 13701 if (Subtarget.needsSwapsForVSXMemOps() && 13702 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 13703 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 13704 return expandVSXLoadForLE(N, DCI); 13705 } 13706 13707 // We sometimes end up with a 64-bit integer load, from which we extract 13708 // two single-precision floating-point numbers. This happens with 13709 // std::complex<float>, and other similar structures, because of the way we 13710 // canonicalize structure copies. However, if we lack direct moves, 13711 // then the final bitcasts from the extracted integer values to the 13712 // floating-point numbers turn into store/load pairs. Even with direct moves, 13713 // just loading the two floating-point numbers is likely better. 13714 auto ReplaceTwoFloatLoad = [&]() { 13715 if (VT != MVT::i64) 13716 return false; 13717 13718 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 13719 LD->isVolatile()) 13720 return false; 13721 13722 // We're looking for a sequence like this: 13723 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 13724 // t16: i64 = srl t13, Constant:i32<32> 13725 // t17: i32 = truncate t16 13726 // t18: f32 = bitcast t17 13727 // t19: i32 = truncate t13 13728 // t20: f32 = bitcast t19 13729 13730 if (!LD->hasNUsesOfValue(2, 0)) 13731 return false; 13732 13733 auto UI = LD->use_begin(); 13734 while (UI.getUse().getResNo() != 0) ++UI; 13735 SDNode *Trunc = *UI++; 13736 while (UI.getUse().getResNo() != 0) ++UI; 13737 SDNode *RightShift = *UI; 13738 if (Trunc->getOpcode() != ISD::TRUNCATE) 13739 std::swap(Trunc, RightShift); 13740 13741 if (Trunc->getOpcode() != ISD::TRUNCATE || 13742 Trunc->getValueType(0) != MVT::i32 || 13743 !Trunc->hasOneUse()) 13744 return false; 13745 if (RightShift->getOpcode() != ISD::SRL || 13746 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 13747 RightShift->getConstantOperandVal(1) != 32 || 13748 !RightShift->hasOneUse()) 13749 return false; 13750 13751 SDNode *Trunc2 = *RightShift->use_begin(); 13752 if (Trunc2->getOpcode() != ISD::TRUNCATE || 13753 Trunc2->getValueType(0) != MVT::i32 || 13754 !Trunc2->hasOneUse()) 13755 return false; 13756 13757 SDNode *Bitcast = *Trunc->use_begin(); 13758 SDNode *Bitcast2 = *Trunc2->use_begin(); 13759 13760 if (Bitcast->getOpcode() != ISD::BITCAST || 13761 Bitcast->getValueType(0) != MVT::f32) 13762 return false; 13763 if (Bitcast2->getOpcode() != ISD::BITCAST || 13764 Bitcast2->getValueType(0) != MVT::f32) 13765 return false; 13766 13767 if (Subtarget.isLittleEndian()) 13768 std::swap(Bitcast, Bitcast2); 13769 13770 // Bitcast has the second float (in memory-layout order) and Bitcast2 13771 // has the first one. 13772 13773 SDValue BasePtr = LD->getBasePtr(); 13774 if (LD->isIndexed()) { 13775 assert(LD->getAddressingMode() == ISD::PRE_INC && 13776 "Non-pre-inc AM on PPC?"); 13777 BasePtr = 13778 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 13779 LD->getOffset()); 13780 } 13781 13782 auto MMOFlags = 13783 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 13784 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 13785 LD->getPointerInfo(), LD->getAlignment(), 13786 MMOFlags, LD->getAAInfo()); 13787 SDValue AddPtr = 13788 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 13789 BasePtr, DAG.getIntPtrConstant(4, dl)); 13790 SDValue FloatLoad2 = DAG.getLoad( 13791 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 13792 LD->getPointerInfo().getWithOffset(4), 13793 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 13794 13795 if (LD->isIndexed()) { 13796 // Note that DAGCombine should re-form any pre-increment load(s) from 13797 // what is produced here if that makes sense. 13798 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13799 } 13800 13801 DCI.CombineTo(Bitcast2, FloatLoad); 13802 DCI.CombineTo(Bitcast, FloatLoad2); 13803 13804 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13805 SDValue(FloatLoad2.getNode(), 1)); 13806 return true; 13807 }; 13808 13809 if (ReplaceTwoFloatLoad()) 13810 return SDValue(N, 0); 13811 13812 EVT MemVT = LD->getMemoryVT(); 13813 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13814 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13815 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13816 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13817 if (LD->isUnindexed() && VT.isVector() && 13818 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13819 // P8 and later hardware should just use LOAD. 13820 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13821 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13822 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13823 LD->getAlignment() >= ScalarABIAlignment)) && 13824 LD->getAlignment() < ABIAlignment) { 13825 // This is a type-legal unaligned Altivec or QPX load. 13826 SDValue Chain = LD->getChain(); 13827 SDValue Ptr = LD->getBasePtr(); 13828 bool isLittleEndian = Subtarget.isLittleEndian(); 13829 13830 // This implements the loading of unaligned vectors as described in 13831 // the venerable Apple Velocity Engine overview. Specifically: 13832 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13833 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13834 // 13835 // The general idea is to expand a sequence of one or more unaligned 13836 // loads into an alignment-based permutation-control instruction (lvsl 13837 // or lvsr), a series of regular vector loads (which always truncate 13838 // their input address to an aligned address), and a series of 13839 // permutations. The results of these permutations are the requested 13840 // loaded values. The trick is that the last "extra" load is not taken 13841 // from the address you might suspect (sizeof(vector) bytes after the 13842 // last requested load), but rather sizeof(vector) - 1 bytes after the 13843 // last requested vector. The point of this is to avoid a page fault if 13844 // the base address happened to be aligned. This works because if the 13845 // base address is aligned, then adding less than a full vector length 13846 // will cause the last vector in the sequence to be (re)loaded. 13847 // Otherwise, the next vector will be fetched as you might suspect was 13848 // necessary. 13849 13850 // We might be able to reuse the permutation generation from 13851 // a different base address offset from this one by an aligned amount. 13852 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13853 // optimization later. 13854 Intrinsic::ID Intr, IntrLD, IntrPerm; 13855 MVT PermCntlTy, PermTy, LDTy; 13856 if (Subtarget.hasAltivec()) { 13857 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13858 Intrinsic::ppc_altivec_lvsl; 13859 IntrLD = Intrinsic::ppc_altivec_lvx; 13860 IntrPerm = Intrinsic::ppc_altivec_vperm; 13861 PermCntlTy = MVT::v16i8; 13862 PermTy = MVT::v4i32; 13863 LDTy = MVT::v4i32; 13864 } else { 13865 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13866 Intrinsic::ppc_qpx_qvlpcls; 13867 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13868 Intrinsic::ppc_qpx_qvlfs; 13869 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13870 PermCntlTy = MVT::v4f64; 13871 PermTy = MVT::v4f64; 13872 LDTy = MemVT.getSimpleVT(); 13873 } 13874 13875 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13876 13877 // Create the new MMO for the new base load. It is like the original MMO, 13878 // but represents an area in memory almost twice the vector size centered 13879 // on the original address. If the address is unaligned, we might start 13880 // reading up to (sizeof(vector)-1) bytes below the address of the 13881 // original unaligned load. 13882 MachineFunction &MF = DAG.getMachineFunction(); 13883 MachineMemOperand *BaseMMO = 13884 MF.getMachineMemOperand(LD->getMemOperand(), 13885 -(long)MemVT.getStoreSize()+1, 13886 2*MemVT.getStoreSize()-1); 13887 13888 // Create the new base load. 13889 SDValue LDXIntID = 13890 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13891 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13892 SDValue BaseLoad = 13893 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13894 DAG.getVTList(PermTy, MVT::Other), 13895 BaseLoadOps, LDTy, BaseMMO); 13896 13897 // Note that the value of IncOffset (which is provided to the next 13898 // load's pointer info offset value, and thus used to calculate the 13899 // alignment), and the value of IncValue (which is actually used to 13900 // increment the pointer value) are different! This is because we 13901 // require the next load to appear to be aligned, even though it 13902 // is actually offset from the base pointer by a lesser amount. 13903 int IncOffset = VT.getSizeInBits() / 8; 13904 int IncValue = IncOffset; 13905 13906 // Walk (both up and down) the chain looking for another load at the real 13907 // (aligned) offset (the alignment of the other load does not matter in 13908 // this case). If found, then do not use the offset reduction trick, as 13909 // that will prevent the loads from being later combined (as they would 13910 // otherwise be duplicates). 13911 if (!findConsecutiveLoad(LD, DAG)) 13912 --IncValue; 13913 13914 SDValue Increment = 13915 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 13916 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 13917 13918 MachineMemOperand *ExtraMMO = 13919 MF.getMachineMemOperand(LD->getMemOperand(), 13920 1, 2*MemVT.getStoreSize()-1); 13921 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 13922 SDValue ExtraLoad = 13923 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13924 DAG.getVTList(PermTy, MVT::Other), 13925 ExtraLoadOps, LDTy, ExtraMMO); 13926 13927 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13928 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 13929 13930 // Because vperm has a big-endian bias, we must reverse the order 13931 // of the input vectors and complement the permute control vector 13932 // when generating little endian code. We have already handled the 13933 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 13934 // and ExtraLoad here. 13935 SDValue Perm; 13936 if (isLittleEndian) 13937 Perm = BuildIntrinsicOp(IntrPerm, 13938 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 13939 else 13940 Perm = BuildIntrinsicOp(IntrPerm, 13941 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 13942 13943 if (VT != PermTy) 13944 Perm = Subtarget.hasAltivec() ? 13945 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 13946 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 13947 DAG.getTargetConstant(1, dl, MVT::i64)); 13948 // second argument is 1 because this rounding 13949 // is always exact. 13950 13951 // The output of the permutation is our loaded result, the TokenFactor is 13952 // our new chain. 13953 DCI.CombineTo(N, Perm, TF); 13954 return SDValue(N, 0); 13955 } 13956 } 13957 break; 13958 case ISD::INTRINSIC_WO_CHAIN: { 13959 bool isLittleEndian = Subtarget.isLittleEndian(); 13960 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13961 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 13962 : Intrinsic::ppc_altivec_lvsl); 13963 if ((IID == Intr || 13964 IID == Intrinsic::ppc_qpx_qvlpcld || 13965 IID == Intrinsic::ppc_qpx_qvlpcls) && 13966 N->getOperand(1)->getOpcode() == ISD::ADD) { 13967 SDValue Add = N->getOperand(1); 13968 13969 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 13970 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 13971 13972 if (DAG.MaskedValueIsZero(Add->getOperand(1), 13973 APInt::getAllOnesValue(Bits /* alignment */) 13974 .zext(Add.getScalarValueSizeInBits()))) { 13975 SDNode *BasePtr = Add->getOperand(0).getNode(); 13976 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13977 UE = BasePtr->use_end(); 13978 UI != UE; ++UI) { 13979 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13980 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 13981 // We've found another LVSL/LVSR, and this address is an aligned 13982 // multiple of that one. The results will be the same, so use the 13983 // one we've just found instead. 13984 13985 return SDValue(*UI, 0); 13986 } 13987 } 13988 } 13989 13990 if (isa<ConstantSDNode>(Add->getOperand(1))) { 13991 SDNode *BasePtr = Add->getOperand(0).getNode(); 13992 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13993 UE = BasePtr->use_end(); UI != UE; ++UI) { 13994 if (UI->getOpcode() == ISD::ADD && 13995 isa<ConstantSDNode>(UI->getOperand(1)) && 13996 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 13997 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 13998 (1ULL << Bits) == 0) { 13999 SDNode *OtherAdd = *UI; 14000 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14001 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14002 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14003 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14004 return SDValue(*VI, 0); 14005 } 14006 } 14007 } 14008 } 14009 } 14010 } 14011 14012 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14013 // Expose the vabsduw/h/b opportunity for down stream 14014 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14015 (IID == Intrinsic::ppc_altivec_vmaxsw || 14016 IID == Intrinsic::ppc_altivec_vmaxsh || 14017 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14018 SDValue V1 = N->getOperand(1); 14019 SDValue V2 = N->getOperand(2); 14020 if ((V1.getSimpleValueType() == MVT::v4i32 || 14021 V1.getSimpleValueType() == MVT::v8i16 || 14022 V1.getSimpleValueType() == MVT::v16i8) && 14023 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14024 // (0-a, a) 14025 if (V1.getOpcode() == ISD::SUB && 14026 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14027 V1.getOperand(1) == V2) { 14028 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14029 } 14030 // (a, 0-a) 14031 if (V2.getOpcode() == ISD::SUB && 14032 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14033 V2.getOperand(1) == V1) { 14034 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14035 } 14036 // (x-y, y-x) 14037 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14038 V1.getOperand(0) == V2.getOperand(1) && 14039 V1.getOperand(1) == V2.getOperand(0)) { 14040 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14041 } 14042 } 14043 } 14044 } 14045 14046 break; 14047 case ISD::INTRINSIC_W_CHAIN: 14048 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14049 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14050 if (Subtarget.needsSwapsForVSXMemOps()) { 14051 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14052 default: 14053 break; 14054 case Intrinsic::ppc_vsx_lxvw4x: 14055 case Intrinsic::ppc_vsx_lxvd2x: 14056 return expandVSXLoadForLE(N, DCI); 14057 } 14058 } 14059 break; 14060 case ISD::INTRINSIC_VOID: 14061 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14062 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14063 if (Subtarget.needsSwapsForVSXMemOps()) { 14064 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14065 default: 14066 break; 14067 case Intrinsic::ppc_vsx_stxvw4x: 14068 case Intrinsic::ppc_vsx_stxvd2x: 14069 return expandVSXStoreForLE(N, DCI); 14070 } 14071 } 14072 break; 14073 case ISD::BSWAP: 14074 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14075 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14076 N->getOperand(0).hasOneUse() && 14077 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14078 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14079 N->getValueType(0) == MVT::i64))) { 14080 SDValue Load = N->getOperand(0); 14081 LoadSDNode *LD = cast<LoadSDNode>(Load); 14082 // Create the byte-swapping load. 14083 SDValue Ops[] = { 14084 LD->getChain(), // Chain 14085 LD->getBasePtr(), // Ptr 14086 DAG.getValueType(N->getValueType(0)) // VT 14087 }; 14088 SDValue BSLoad = 14089 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14090 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14091 MVT::i64 : MVT::i32, MVT::Other), 14092 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14093 14094 // If this is an i16 load, insert the truncate. 14095 SDValue ResVal = BSLoad; 14096 if (N->getValueType(0) == MVT::i16) 14097 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14098 14099 // First, combine the bswap away. This makes the value produced by the 14100 // load dead. 14101 DCI.CombineTo(N, ResVal); 14102 14103 // Next, combine the load away, we give it a bogus result value but a real 14104 // chain result. The result value is dead because the bswap is dead. 14105 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14106 14107 // Return N so it doesn't get rechecked! 14108 return SDValue(N, 0); 14109 } 14110 break; 14111 case PPCISD::VCMP: 14112 // If a VCMPo node already exists with exactly the same operands as this 14113 // node, use its result instead of this node (VCMPo computes both a CR6 and 14114 // a normal output). 14115 // 14116 if (!N->getOperand(0).hasOneUse() && 14117 !N->getOperand(1).hasOneUse() && 14118 !N->getOperand(2).hasOneUse()) { 14119 14120 // Scan all of the users of the LHS, looking for VCMPo's that match. 14121 SDNode *VCMPoNode = nullptr; 14122 14123 SDNode *LHSN = N->getOperand(0).getNode(); 14124 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14125 UI != E; ++UI) 14126 if (UI->getOpcode() == PPCISD::VCMPo && 14127 UI->getOperand(1) == N->getOperand(1) && 14128 UI->getOperand(2) == N->getOperand(2) && 14129 UI->getOperand(0) == N->getOperand(0)) { 14130 VCMPoNode = *UI; 14131 break; 14132 } 14133 14134 // If there is no VCMPo node, or if the flag value has a single use, don't 14135 // transform this. 14136 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14137 break; 14138 14139 // Look at the (necessarily single) use of the flag value. If it has a 14140 // chain, this transformation is more complex. Note that multiple things 14141 // could use the value result, which we should ignore. 14142 SDNode *FlagUser = nullptr; 14143 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14144 FlagUser == nullptr; ++UI) { 14145 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14146 SDNode *User = *UI; 14147 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14148 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14149 FlagUser = User; 14150 break; 14151 } 14152 } 14153 } 14154 14155 // If the user is a MFOCRF instruction, we know this is safe. 14156 // Otherwise we give up for right now. 14157 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14158 return SDValue(VCMPoNode, 0); 14159 } 14160 break; 14161 case ISD::BRCOND: { 14162 SDValue Cond = N->getOperand(1); 14163 SDValue Target = N->getOperand(2); 14164 14165 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14166 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14167 Intrinsic::loop_decrement) { 14168 14169 // We now need to make the intrinsic dead (it cannot be instruction 14170 // selected). 14171 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14172 assert(Cond.getNode()->hasOneUse() && 14173 "Counter decrement has more than one use"); 14174 14175 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14176 N->getOperand(0), Target); 14177 } 14178 } 14179 break; 14180 case ISD::BR_CC: { 14181 // If this is a branch on an altivec predicate comparison, lower this so 14182 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14183 // lowering is done pre-legalize, because the legalizer lowers the predicate 14184 // compare down to code that is difficult to reassemble. 14185 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14186 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14187 14188 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14189 // value. If so, pass-through the AND to get to the intrinsic. 14190 if (LHS.getOpcode() == ISD::AND && 14191 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14192 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14193 Intrinsic::loop_decrement && 14194 isa<ConstantSDNode>(LHS.getOperand(1)) && 14195 !isNullConstant(LHS.getOperand(1))) 14196 LHS = LHS.getOperand(0); 14197 14198 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14199 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14200 Intrinsic::loop_decrement && 14201 isa<ConstantSDNode>(RHS)) { 14202 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14203 "Counter decrement comparison is not EQ or NE"); 14204 14205 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14206 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14207 (CC == ISD::SETNE && !Val); 14208 14209 // We now need to make the intrinsic dead (it cannot be instruction 14210 // selected). 14211 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14212 assert(LHS.getNode()->hasOneUse() && 14213 "Counter decrement has more than one use"); 14214 14215 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14216 N->getOperand(0), N->getOperand(4)); 14217 } 14218 14219 int CompareOpc; 14220 bool isDot; 14221 14222 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14223 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14224 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14225 assert(isDot && "Can't compare against a vector result!"); 14226 14227 // If this is a comparison against something other than 0/1, then we know 14228 // that the condition is never/always true. 14229 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14230 if (Val != 0 && Val != 1) { 14231 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14232 return N->getOperand(0); 14233 // Always !=, turn it into an unconditional branch. 14234 return DAG.getNode(ISD::BR, dl, MVT::Other, 14235 N->getOperand(0), N->getOperand(4)); 14236 } 14237 14238 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14239 14240 // Create the PPCISD altivec 'dot' comparison node. 14241 SDValue Ops[] = { 14242 LHS.getOperand(2), // LHS of compare 14243 LHS.getOperand(3), // RHS of compare 14244 DAG.getConstant(CompareOpc, dl, MVT::i32) 14245 }; 14246 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14247 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14248 14249 // Unpack the result based on how the target uses it. 14250 PPC::Predicate CompOpc; 14251 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14252 default: // Can't happen, don't crash on invalid number though. 14253 case 0: // Branch on the value of the EQ bit of CR6. 14254 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14255 break; 14256 case 1: // Branch on the inverted value of the EQ bit of CR6. 14257 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14258 break; 14259 case 2: // Branch on the value of the LT bit of CR6. 14260 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14261 break; 14262 case 3: // Branch on the inverted value of the LT bit of CR6. 14263 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14264 break; 14265 } 14266 14267 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14268 DAG.getConstant(CompOpc, dl, MVT::i32), 14269 DAG.getRegister(PPC::CR6, MVT::i32), 14270 N->getOperand(4), CompNode.getValue(1)); 14271 } 14272 break; 14273 } 14274 case ISD::BUILD_VECTOR: 14275 return DAGCombineBuildVector(N, DCI); 14276 case ISD::ABS: 14277 return combineABS(N, DCI); 14278 case ISD::VSELECT: 14279 return combineVSelect(N, DCI); 14280 } 14281 14282 return SDValue(); 14283 } 14284 14285 SDValue 14286 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14287 SelectionDAG &DAG, 14288 SmallVectorImpl<SDNode *> &Created) const { 14289 // fold (sdiv X, pow2) 14290 EVT VT = N->getValueType(0); 14291 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14292 return SDValue(); 14293 if ((VT != MVT::i32 && VT != MVT::i64) || 14294 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14295 return SDValue(); 14296 14297 SDLoc DL(N); 14298 SDValue N0 = N->getOperand(0); 14299 14300 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14301 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14302 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14303 14304 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14305 Created.push_back(Op.getNode()); 14306 14307 if (IsNegPow2) { 14308 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14309 Created.push_back(Op.getNode()); 14310 } 14311 14312 return Op; 14313 } 14314 14315 //===----------------------------------------------------------------------===// 14316 // Inline Assembly Support 14317 //===----------------------------------------------------------------------===// 14318 14319 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14320 KnownBits &Known, 14321 const APInt &DemandedElts, 14322 const SelectionDAG &DAG, 14323 unsigned Depth) const { 14324 Known.resetAll(); 14325 switch (Op.getOpcode()) { 14326 default: break; 14327 case PPCISD::LBRX: { 14328 // lhbrx is known to have the top bits cleared out. 14329 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14330 Known.Zero = 0xFFFF0000; 14331 break; 14332 } 14333 case ISD::INTRINSIC_WO_CHAIN: { 14334 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14335 default: break; 14336 case Intrinsic::ppc_altivec_vcmpbfp_p: 14337 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14338 case Intrinsic::ppc_altivec_vcmpequb_p: 14339 case Intrinsic::ppc_altivec_vcmpequh_p: 14340 case Intrinsic::ppc_altivec_vcmpequw_p: 14341 case Intrinsic::ppc_altivec_vcmpequd_p: 14342 case Intrinsic::ppc_altivec_vcmpgefp_p: 14343 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14344 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14345 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14346 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14347 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14348 case Intrinsic::ppc_altivec_vcmpgtub_p: 14349 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14350 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14351 case Intrinsic::ppc_altivec_vcmpgtud_p: 14352 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14353 break; 14354 } 14355 } 14356 } 14357 } 14358 14359 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14360 switch (Subtarget.getCPUDirective()) { 14361 default: break; 14362 case PPC::DIR_970: 14363 case PPC::DIR_PWR4: 14364 case PPC::DIR_PWR5: 14365 case PPC::DIR_PWR5X: 14366 case PPC::DIR_PWR6: 14367 case PPC::DIR_PWR6X: 14368 case PPC::DIR_PWR7: 14369 case PPC::DIR_PWR8: 14370 case PPC::DIR_PWR9: 14371 case PPC::DIR_PWR_FUTURE: { 14372 if (!ML) 14373 break; 14374 14375 if (!DisableInnermostLoopAlign32) { 14376 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14377 // so that we can decrease cache misses and branch-prediction misses. 14378 // Actual alignment of the loop will depend on the hotness check and other 14379 // logic in alignBlocks. 14380 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14381 return Align(32); 14382 } 14383 14384 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14385 14386 // For small loops (between 5 and 8 instructions), align to a 32-byte 14387 // boundary so that the entire loop fits in one instruction-cache line. 14388 uint64_t LoopSize = 0; 14389 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14390 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14391 LoopSize += TII->getInstSizeInBytes(*J); 14392 if (LoopSize > 32) 14393 break; 14394 } 14395 14396 if (LoopSize > 16 && LoopSize <= 32) 14397 return Align(32); 14398 14399 break; 14400 } 14401 } 14402 14403 return TargetLowering::getPrefLoopAlignment(ML); 14404 } 14405 14406 /// getConstraintType - Given a constraint, return the type of 14407 /// constraint it is for this target. 14408 PPCTargetLowering::ConstraintType 14409 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14410 if (Constraint.size() == 1) { 14411 switch (Constraint[0]) { 14412 default: break; 14413 case 'b': 14414 case 'r': 14415 case 'f': 14416 case 'd': 14417 case 'v': 14418 case 'y': 14419 return C_RegisterClass; 14420 case 'Z': 14421 // FIXME: While Z does indicate a memory constraint, it specifically 14422 // indicates an r+r address (used in conjunction with the 'y' modifier 14423 // in the replacement string). Currently, we're forcing the base 14424 // register to be r0 in the asm printer (which is interpreted as zero) 14425 // and forming the complete address in the second register. This is 14426 // suboptimal. 14427 return C_Memory; 14428 } 14429 } else if (Constraint == "wc") { // individual CR bits. 14430 return C_RegisterClass; 14431 } else if (Constraint == "wa" || Constraint == "wd" || 14432 Constraint == "wf" || Constraint == "ws" || 14433 Constraint == "wi" || Constraint == "ww") { 14434 return C_RegisterClass; // VSX registers. 14435 } 14436 return TargetLowering::getConstraintType(Constraint); 14437 } 14438 14439 /// Examine constraint type and operand type and determine a weight value. 14440 /// This object must already have been set up with the operand type 14441 /// and the current alternative constraint selected. 14442 TargetLowering::ConstraintWeight 14443 PPCTargetLowering::getSingleConstraintMatchWeight( 14444 AsmOperandInfo &info, const char *constraint) const { 14445 ConstraintWeight weight = CW_Invalid; 14446 Value *CallOperandVal = info.CallOperandVal; 14447 // If we don't have a value, we can't do a match, 14448 // but allow it at the lowest weight. 14449 if (!CallOperandVal) 14450 return CW_Default; 14451 Type *type = CallOperandVal->getType(); 14452 14453 // Look at the constraint type. 14454 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14455 return CW_Register; // an individual CR bit. 14456 else if ((StringRef(constraint) == "wa" || 14457 StringRef(constraint) == "wd" || 14458 StringRef(constraint) == "wf") && 14459 type->isVectorTy()) 14460 return CW_Register; 14461 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14462 return CW_Register; // just hold 64-bit integers data. 14463 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14464 return CW_Register; 14465 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14466 return CW_Register; 14467 14468 switch (*constraint) { 14469 default: 14470 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14471 break; 14472 case 'b': 14473 if (type->isIntegerTy()) 14474 weight = CW_Register; 14475 break; 14476 case 'f': 14477 if (type->isFloatTy()) 14478 weight = CW_Register; 14479 break; 14480 case 'd': 14481 if (type->isDoubleTy()) 14482 weight = CW_Register; 14483 break; 14484 case 'v': 14485 if (type->isVectorTy()) 14486 weight = CW_Register; 14487 break; 14488 case 'y': 14489 weight = CW_Register; 14490 break; 14491 case 'Z': 14492 weight = CW_Memory; 14493 break; 14494 } 14495 return weight; 14496 } 14497 14498 std::pair<unsigned, const TargetRegisterClass *> 14499 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14500 StringRef Constraint, 14501 MVT VT) const { 14502 if (Constraint.size() == 1) { 14503 // GCC RS6000 Constraint Letters 14504 switch (Constraint[0]) { 14505 case 'b': // R1-R31 14506 if (VT == MVT::i64 && Subtarget.isPPC64()) 14507 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 14508 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 14509 case 'r': // R0-R31 14510 if (VT == MVT::i64 && Subtarget.isPPC64()) 14511 return std::make_pair(0U, &PPC::G8RCRegClass); 14512 return std::make_pair(0U, &PPC::GPRCRegClass); 14513 // 'd' and 'f' constraints are both defined to be "the floating point 14514 // registers", where one is for 32-bit and the other for 64-bit. We don't 14515 // really care overly much here so just give them all the same reg classes. 14516 case 'd': 14517 case 'f': 14518 if (Subtarget.hasSPE()) { 14519 if (VT == MVT::f32 || VT == MVT::i32) 14520 return std::make_pair(0U, &PPC::GPRCRegClass); 14521 if (VT == MVT::f64 || VT == MVT::i64) 14522 return std::make_pair(0U, &PPC::SPERCRegClass); 14523 } else { 14524 if (VT == MVT::f32 || VT == MVT::i32) 14525 return std::make_pair(0U, &PPC::F4RCRegClass); 14526 if (VT == MVT::f64 || VT == MVT::i64) 14527 return std::make_pair(0U, &PPC::F8RCRegClass); 14528 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14529 return std::make_pair(0U, &PPC::QFRCRegClass); 14530 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14531 return std::make_pair(0U, &PPC::QSRCRegClass); 14532 } 14533 break; 14534 case 'v': 14535 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14536 return std::make_pair(0U, &PPC::QFRCRegClass); 14537 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14538 return std::make_pair(0U, &PPC::QSRCRegClass); 14539 if (Subtarget.hasAltivec()) 14540 return std::make_pair(0U, &PPC::VRRCRegClass); 14541 break; 14542 case 'y': // crrc 14543 return std::make_pair(0U, &PPC::CRRCRegClass); 14544 } 14545 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 14546 // An individual CR bit. 14547 return std::make_pair(0U, &PPC::CRBITRCRegClass); 14548 } else if ((Constraint == "wa" || Constraint == "wd" || 14549 Constraint == "wf" || Constraint == "wi") && 14550 Subtarget.hasVSX()) { 14551 return std::make_pair(0U, &PPC::VSRCRegClass); 14552 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 14553 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 14554 return std::make_pair(0U, &PPC::VSSRCRegClass); 14555 else 14556 return std::make_pair(0U, &PPC::VSFRCRegClass); 14557 } 14558 14559 // If we name a VSX register, we can't defer to the base class because it 14560 // will not recognize the correct register (their names will be VSL{0-31} 14561 // and V{0-31} so they won't match). So we match them here. 14562 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 14563 int VSNum = atoi(Constraint.data() + 3); 14564 assert(VSNum >= 0 && VSNum <= 63 && 14565 "Attempted to access a vsr out of range"); 14566 if (VSNum < 32) 14567 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 14568 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 14569 } 14570 std::pair<unsigned, const TargetRegisterClass *> R = 14571 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14572 14573 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 14574 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 14575 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 14576 // register. 14577 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 14578 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 14579 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 14580 PPC::GPRCRegClass.contains(R.first)) 14581 return std::make_pair(TRI->getMatchingSuperReg(R.first, 14582 PPC::sub_32, &PPC::G8RCRegClass), 14583 &PPC::G8RCRegClass); 14584 14585 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 14586 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 14587 R.first = PPC::CR0; 14588 R.second = &PPC::CRRCRegClass; 14589 } 14590 14591 return R; 14592 } 14593 14594 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14595 /// vector. If it is invalid, don't add anything to Ops. 14596 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14597 std::string &Constraint, 14598 std::vector<SDValue>&Ops, 14599 SelectionDAG &DAG) const { 14600 SDValue Result; 14601 14602 // Only support length 1 constraints. 14603 if (Constraint.length() > 1) return; 14604 14605 char Letter = Constraint[0]; 14606 switch (Letter) { 14607 default: break; 14608 case 'I': 14609 case 'J': 14610 case 'K': 14611 case 'L': 14612 case 'M': 14613 case 'N': 14614 case 'O': 14615 case 'P': { 14616 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 14617 if (!CST) return; // Must be an immediate to match. 14618 SDLoc dl(Op); 14619 int64_t Value = CST->getSExtValue(); 14620 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 14621 // numbers are printed as such. 14622 switch (Letter) { 14623 default: llvm_unreachable("Unknown constraint letter!"); 14624 case 'I': // "I" is a signed 16-bit constant. 14625 if (isInt<16>(Value)) 14626 Result = DAG.getTargetConstant(Value, dl, TCVT); 14627 break; 14628 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 14629 if (isShiftedUInt<16, 16>(Value)) 14630 Result = DAG.getTargetConstant(Value, dl, TCVT); 14631 break; 14632 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 14633 if (isShiftedInt<16, 16>(Value)) 14634 Result = DAG.getTargetConstant(Value, dl, TCVT); 14635 break; 14636 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 14637 if (isUInt<16>(Value)) 14638 Result = DAG.getTargetConstant(Value, dl, TCVT); 14639 break; 14640 case 'M': // "M" is a constant that is greater than 31. 14641 if (Value > 31) 14642 Result = DAG.getTargetConstant(Value, dl, TCVT); 14643 break; 14644 case 'N': // "N" is a positive constant that is an exact power of two. 14645 if (Value > 0 && isPowerOf2_64(Value)) 14646 Result = DAG.getTargetConstant(Value, dl, TCVT); 14647 break; 14648 case 'O': // "O" is the constant zero. 14649 if (Value == 0) 14650 Result = DAG.getTargetConstant(Value, dl, TCVT); 14651 break; 14652 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 14653 if (isInt<16>(-Value)) 14654 Result = DAG.getTargetConstant(Value, dl, TCVT); 14655 break; 14656 } 14657 break; 14658 } 14659 } 14660 14661 if (Result.getNode()) { 14662 Ops.push_back(Result); 14663 return; 14664 } 14665 14666 // Handle standard constraint letters. 14667 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14668 } 14669 14670 // isLegalAddressingMode - Return true if the addressing mode represented 14671 // by AM is legal for this target, for a load/store of the specified type. 14672 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14673 const AddrMode &AM, Type *Ty, 14674 unsigned AS, Instruction *I) const { 14675 // PPC does not allow r+i addressing modes for vectors! 14676 if (Ty->isVectorTy() && AM.BaseOffs != 0) 14677 return false; 14678 14679 // PPC allows a sign-extended 16-bit immediate field. 14680 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 14681 return false; 14682 14683 // No global is ever allowed as a base. 14684 if (AM.BaseGV) 14685 return false; 14686 14687 // PPC only support r+r, 14688 switch (AM.Scale) { 14689 case 0: // "r+i" or just "i", depending on HasBaseReg. 14690 break; 14691 case 1: 14692 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 14693 return false; 14694 // Otherwise we have r+r or r+i. 14695 break; 14696 case 2: 14697 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 14698 return false; 14699 // Allow 2*r as r+r. 14700 break; 14701 default: 14702 // No other scales are supported. 14703 return false; 14704 } 14705 14706 return true; 14707 } 14708 14709 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 14710 SelectionDAG &DAG) const { 14711 MachineFunction &MF = DAG.getMachineFunction(); 14712 MachineFrameInfo &MFI = MF.getFrameInfo(); 14713 MFI.setReturnAddressIsTaken(true); 14714 14715 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 14716 return SDValue(); 14717 14718 SDLoc dl(Op); 14719 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14720 14721 // Make sure the function does not optimize away the store of the RA to 14722 // the stack. 14723 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 14724 FuncInfo->setLRStoreRequired(); 14725 bool isPPC64 = Subtarget.isPPC64(); 14726 auto PtrVT = getPointerTy(MF.getDataLayout()); 14727 14728 if (Depth > 0) { 14729 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 14730 SDValue Offset = 14731 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 14732 isPPC64 ? MVT::i64 : MVT::i32); 14733 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 14734 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 14735 MachinePointerInfo()); 14736 } 14737 14738 // Just load the return address off the stack. 14739 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 14740 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 14741 MachinePointerInfo()); 14742 } 14743 14744 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 14745 SelectionDAG &DAG) const { 14746 SDLoc dl(Op); 14747 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14748 14749 MachineFunction &MF = DAG.getMachineFunction(); 14750 MachineFrameInfo &MFI = MF.getFrameInfo(); 14751 MFI.setFrameAddressIsTaken(true); 14752 14753 EVT PtrVT = getPointerTy(MF.getDataLayout()); 14754 bool isPPC64 = PtrVT == MVT::i64; 14755 14756 // Naked functions never have a frame pointer, and so we use r1. For all 14757 // other functions, this decision must be delayed until during PEI. 14758 unsigned FrameReg; 14759 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 14760 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 14761 else 14762 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 14763 14764 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 14765 PtrVT); 14766 while (Depth--) 14767 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 14768 FrameAddr, MachinePointerInfo()); 14769 return FrameAddr; 14770 } 14771 14772 // FIXME? Maybe this could be a TableGen attribute on some registers and 14773 // this table could be generated automatically from RegInfo. 14774 Register PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 14775 const MachineFunction &MF) const { 14776 bool isPPC64 = Subtarget.isPPC64(); 14777 bool IsDarwinABI = Subtarget.isDarwinABI(); 14778 14779 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 14780 (!isPPC64 && VT != MVT::i32)) 14781 report_fatal_error("Invalid register global variable type"); 14782 14783 bool is64Bit = isPPC64 && VT == MVT::i64; 14784 Register Reg = StringSwitch<Register>(RegName) 14785 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 14786 .Case("r2", (IsDarwinABI || isPPC64) ? Register() : PPC::R2) 14787 .Case("r13", (!isPPC64 && IsDarwinABI) ? Register() : 14788 (is64Bit ? PPC::X13 : PPC::R13)) 14789 .Default(Register()); 14790 14791 if (Reg) 14792 return Reg; 14793 report_fatal_error("Invalid register name global variable"); 14794 } 14795 14796 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 14797 // 32-bit SVR4 ABI access everything as got-indirect. 14798 if (Subtarget.is32BitELFABI()) 14799 return true; 14800 14801 // AIX accesses everything indirectly through the TOC, which is similar to 14802 // the GOT. 14803 if (Subtarget.isAIXABI()) 14804 return true; 14805 14806 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 14807 // If it is small or large code model, module locals are accessed 14808 // indirectly by loading their address from .toc/.got. 14809 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 14810 return true; 14811 14812 // JumpTable and BlockAddress are accessed as got-indirect. 14813 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 14814 return true; 14815 14816 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 14817 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 14818 14819 return false; 14820 } 14821 14822 bool 14823 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14824 // The PowerPC target isn't yet aware of offsets. 14825 return false; 14826 } 14827 14828 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14829 const CallInst &I, 14830 MachineFunction &MF, 14831 unsigned Intrinsic) const { 14832 switch (Intrinsic) { 14833 case Intrinsic::ppc_qpx_qvlfd: 14834 case Intrinsic::ppc_qpx_qvlfs: 14835 case Intrinsic::ppc_qpx_qvlfcd: 14836 case Intrinsic::ppc_qpx_qvlfcs: 14837 case Intrinsic::ppc_qpx_qvlfiwa: 14838 case Intrinsic::ppc_qpx_qvlfiwz: 14839 case Intrinsic::ppc_altivec_lvx: 14840 case Intrinsic::ppc_altivec_lvxl: 14841 case Intrinsic::ppc_altivec_lvebx: 14842 case Intrinsic::ppc_altivec_lvehx: 14843 case Intrinsic::ppc_altivec_lvewx: 14844 case Intrinsic::ppc_vsx_lxvd2x: 14845 case Intrinsic::ppc_vsx_lxvw4x: { 14846 EVT VT; 14847 switch (Intrinsic) { 14848 case Intrinsic::ppc_altivec_lvebx: 14849 VT = MVT::i8; 14850 break; 14851 case Intrinsic::ppc_altivec_lvehx: 14852 VT = MVT::i16; 14853 break; 14854 case Intrinsic::ppc_altivec_lvewx: 14855 VT = MVT::i32; 14856 break; 14857 case Intrinsic::ppc_vsx_lxvd2x: 14858 VT = MVT::v2f64; 14859 break; 14860 case Intrinsic::ppc_qpx_qvlfd: 14861 VT = MVT::v4f64; 14862 break; 14863 case Intrinsic::ppc_qpx_qvlfs: 14864 VT = MVT::v4f32; 14865 break; 14866 case Intrinsic::ppc_qpx_qvlfcd: 14867 VT = MVT::v2f64; 14868 break; 14869 case Intrinsic::ppc_qpx_qvlfcs: 14870 VT = MVT::v2f32; 14871 break; 14872 default: 14873 VT = MVT::v4i32; 14874 break; 14875 } 14876 14877 Info.opc = ISD::INTRINSIC_W_CHAIN; 14878 Info.memVT = VT; 14879 Info.ptrVal = I.getArgOperand(0); 14880 Info.offset = -VT.getStoreSize()+1; 14881 Info.size = 2*VT.getStoreSize()-1; 14882 Info.align = Align::None(); 14883 Info.flags = MachineMemOperand::MOLoad; 14884 return true; 14885 } 14886 case Intrinsic::ppc_qpx_qvlfda: 14887 case Intrinsic::ppc_qpx_qvlfsa: 14888 case Intrinsic::ppc_qpx_qvlfcda: 14889 case Intrinsic::ppc_qpx_qvlfcsa: 14890 case Intrinsic::ppc_qpx_qvlfiwaa: 14891 case Intrinsic::ppc_qpx_qvlfiwza: { 14892 EVT VT; 14893 switch (Intrinsic) { 14894 case Intrinsic::ppc_qpx_qvlfda: 14895 VT = MVT::v4f64; 14896 break; 14897 case Intrinsic::ppc_qpx_qvlfsa: 14898 VT = MVT::v4f32; 14899 break; 14900 case Intrinsic::ppc_qpx_qvlfcda: 14901 VT = MVT::v2f64; 14902 break; 14903 case Intrinsic::ppc_qpx_qvlfcsa: 14904 VT = MVT::v2f32; 14905 break; 14906 default: 14907 VT = MVT::v4i32; 14908 break; 14909 } 14910 14911 Info.opc = ISD::INTRINSIC_W_CHAIN; 14912 Info.memVT = VT; 14913 Info.ptrVal = I.getArgOperand(0); 14914 Info.offset = 0; 14915 Info.size = VT.getStoreSize(); 14916 Info.align = Align::None(); 14917 Info.flags = MachineMemOperand::MOLoad; 14918 return true; 14919 } 14920 case Intrinsic::ppc_qpx_qvstfd: 14921 case Intrinsic::ppc_qpx_qvstfs: 14922 case Intrinsic::ppc_qpx_qvstfcd: 14923 case Intrinsic::ppc_qpx_qvstfcs: 14924 case Intrinsic::ppc_qpx_qvstfiw: 14925 case Intrinsic::ppc_altivec_stvx: 14926 case Intrinsic::ppc_altivec_stvxl: 14927 case Intrinsic::ppc_altivec_stvebx: 14928 case Intrinsic::ppc_altivec_stvehx: 14929 case Intrinsic::ppc_altivec_stvewx: 14930 case Intrinsic::ppc_vsx_stxvd2x: 14931 case Intrinsic::ppc_vsx_stxvw4x: { 14932 EVT VT; 14933 switch (Intrinsic) { 14934 case Intrinsic::ppc_altivec_stvebx: 14935 VT = MVT::i8; 14936 break; 14937 case Intrinsic::ppc_altivec_stvehx: 14938 VT = MVT::i16; 14939 break; 14940 case Intrinsic::ppc_altivec_stvewx: 14941 VT = MVT::i32; 14942 break; 14943 case Intrinsic::ppc_vsx_stxvd2x: 14944 VT = MVT::v2f64; 14945 break; 14946 case Intrinsic::ppc_qpx_qvstfd: 14947 VT = MVT::v4f64; 14948 break; 14949 case Intrinsic::ppc_qpx_qvstfs: 14950 VT = MVT::v4f32; 14951 break; 14952 case Intrinsic::ppc_qpx_qvstfcd: 14953 VT = MVT::v2f64; 14954 break; 14955 case Intrinsic::ppc_qpx_qvstfcs: 14956 VT = MVT::v2f32; 14957 break; 14958 default: 14959 VT = MVT::v4i32; 14960 break; 14961 } 14962 14963 Info.opc = ISD::INTRINSIC_VOID; 14964 Info.memVT = VT; 14965 Info.ptrVal = I.getArgOperand(1); 14966 Info.offset = -VT.getStoreSize()+1; 14967 Info.size = 2*VT.getStoreSize()-1; 14968 Info.align = Align::None(); 14969 Info.flags = MachineMemOperand::MOStore; 14970 return true; 14971 } 14972 case Intrinsic::ppc_qpx_qvstfda: 14973 case Intrinsic::ppc_qpx_qvstfsa: 14974 case Intrinsic::ppc_qpx_qvstfcda: 14975 case Intrinsic::ppc_qpx_qvstfcsa: 14976 case Intrinsic::ppc_qpx_qvstfiwa: { 14977 EVT VT; 14978 switch (Intrinsic) { 14979 case Intrinsic::ppc_qpx_qvstfda: 14980 VT = MVT::v4f64; 14981 break; 14982 case Intrinsic::ppc_qpx_qvstfsa: 14983 VT = MVT::v4f32; 14984 break; 14985 case Intrinsic::ppc_qpx_qvstfcda: 14986 VT = MVT::v2f64; 14987 break; 14988 case Intrinsic::ppc_qpx_qvstfcsa: 14989 VT = MVT::v2f32; 14990 break; 14991 default: 14992 VT = MVT::v4i32; 14993 break; 14994 } 14995 14996 Info.opc = ISD::INTRINSIC_VOID; 14997 Info.memVT = VT; 14998 Info.ptrVal = I.getArgOperand(1); 14999 Info.offset = 0; 15000 Info.size = VT.getStoreSize(); 15001 Info.align = Align::None(); 15002 Info.flags = MachineMemOperand::MOStore; 15003 return true; 15004 } 15005 default: 15006 break; 15007 } 15008 15009 return false; 15010 } 15011 15012 /// getOptimalMemOpType - Returns the target specific optimal type for load 15013 /// and store operations as a result of memset, memcpy, and memmove 15014 /// lowering. If DstAlign is zero that means it's safe to destination 15015 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 15016 /// means there isn't a need to check it against alignment requirement, 15017 /// probably because the source does not need to be loaded. If 'IsMemset' is 15018 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 15019 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 15020 /// source is constant so it does not need to be loaded. 15021 /// It returns EVT::Other if the type should be determined using generic 15022 /// target-independent logic. 15023 EVT PPCTargetLowering::getOptimalMemOpType( 15024 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 15025 bool ZeroMemset, bool MemcpyStrSrc, 15026 const AttributeList &FuncAttributes) const { 15027 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15028 // When expanding a memset, require at least two QPX instructions to cover 15029 // the cost of loading the value to be stored from the constant pool. 15030 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 15031 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 15032 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15033 return MVT::v4f64; 15034 } 15035 15036 // We should use Altivec/VSX loads and stores when available. For unaligned 15037 // addresses, unaligned VSX loads are only fast starting with the P8. 15038 if (Subtarget.hasAltivec() && Size >= 16 && 15039 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 15040 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15041 return MVT::v4i32; 15042 } 15043 15044 if (Subtarget.isPPC64()) { 15045 return MVT::i64; 15046 } 15047 15048 return MVT::i32; 15049 } 15050 15051 /// Returns true if it is beneficial to convert a load of a constant 15052 /// to just the constant itself. 15053 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15054 Type *Ty) const { 15055 assert(Ty->isIntegerTy()); 15056 15057 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15058 return !(BitSize == 0 || BitSize > 64); 15059 } 15060 15061 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15062 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15063 return false; 15064 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15065 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15066 return NumBits1 == 64 && NumBits2 == 32; 15067 } 15068 15069 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15070 if (!VT1.isInteger() || !VT2.isInteger()) 15071 return false; 15072 unsigned NumBits1 = VT1.getSizeInBits(); 15073 unsigned NumBits2 = VT2.getSizeInBits(); 15074 return NumBits1 == 64 && NumBits2 == 32; 15075 } 15076 15077 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15078 // Generally speaking, zexts are not free, but they are free when they can be 15079 // folded with other operations. 15080 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15081 EVT MemVT = LD->getMemoryVT(); 15082 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15083 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15084 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15085 LD->getExtensionType() == ISD::ZEXTLOAD)) 15086 return true; 15087 } 15088 15089 // FIXME: Add other cases... 15090 // - 32-bit shifts with a zext to i64 15091 // - zext after ctlz, bswap, etc. 15092 // - zext after and by a constant mask 15093 15094 return TargetLowering::isZExtFree(Val, VT2); 15095 } 15096 15097 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15098 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15099 "invalid fpext types"); 15100 // Extending to float128 is not free. 15101 if (DestVT == MVT::f128) 15102 return false; 15103 return true; 15104 } 15105 15106 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15107 return isInt<16>(Imm) || isUInt<16>(Imm); 15108 } 15109 15110 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15111 return isInt<16>(Imm) || isUInt<16>(Imm); 15112 } 15113 15114 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15115 unsigned, 15116 unsigned, 15117 MachineMemOperand::Flags, 15118 bool *Fast) const { 15119 if (DisablePPCUnaligned) 15120 return false; 15121 15122 // PowerPC supports unaligned memory access for simple non-vector types. 15123 // Although accessing unaligned addresses is not as efficient as accessing 15124 // aligned addresses, it is generally more efficient than manual expansion, 15125 // and generally only traps for software emulation when crossing page 15126 // boundaries. 15127 15128 if (!VT.isSimple()) 15129 return false; 15130 15131 if (VT.getSimpleVT().isVector()) { 15132 if (Subtarget.hasVSX()) { 15133 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15134 VT != MVT::v4f32 && VT != MVT::v4i32) 15135 return false; 15136 } else { 15137 return false; 15138 } 15139 } 15140 15141 if (VT == MVT::ppcf128) 15142 return false; 15143 15144 if (Fast) 15145 *Fast = true; 15146 15147 return true; 15148 } 15149 15150 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15151 EVT VT) const { 15152 VT = VT.getScalarType(); 15153 15154 if (!VT.isSimple()) 15155 return false; 15156 15157 switch (VT.getSimpleVT().SimpleTy) { 15158 case MVT::f32: 15159 case MVT::f64: 15160 return true; 15161 case MVT::f128: 15162 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 15163 default: 15164 break; 15165 } 15166 15167 return false; 15168 } 15169 15170 const MCPhysReg * 15171 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15172 // LR is a callee-save register, but we must treat it as clobbered by any call 15173 // site. Hence we include LR in the scratch registers, which are in turn added 15174 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15175 // to CTR, which is used by any indirect call. 15176 static const MCPhysReg ScratchRegs[] = { 15177 PPC::X12, PPC::LR8, PPC::CTR8, 0 15178 }; 15179 15180 return ScratchRegs; 15181 } 15182 15183 unsigned PPCTargetLowering::getExceptionPointerRegister( 15184 const Constant *PersonalityFn) const { 15185 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15186 } 15187 15188 unsigned PPCTargetLowering::getExceptionSelectorRegister( 15189 const Constant *PersonalityFn) const { 15190 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15191 } 15192 15193 bool 15194 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15195 EVT VT , unsigned DefinedValues) const { 15196 if (VT == MVT::v2i64) 15197 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15198 15199 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15200 return true; 15201 15202 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15203 } 15204 15205 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15206 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15207 return TargetLowering::getSchedulingPreference(N); 15208 15209 return Sched::ILP; 15210 } 15211 15212 // Create a fast isel object. 15213 FastISel * 15214 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15215 const TargetLibraryInfo *LibInfo) const { 15216 return PPC::createFastISel(FuncInfo, LibInfo); 15217 } 15218 15219 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15220 if (Subtarget.isDarwinABI()) return; 15221 if (!Subtarget.isPPC64()) return; 15222 15223 // Update IsSplitCSR in PPCFunctionInfo 15224 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 15225 PFI->setIsSplitCSR(true); 15226 } 15227 15228 void PPCTargetLowering::insertCopiesSplitCSR( 15229 MachineBasicBlock *Entry, 15230 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15231 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 15232 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15233 if (!IStart) 15234 return; 15235 15236 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 15237 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15238 MachineBasicBlock::iterator MBBI = Entry->begin(); 15239 for (const MCPhysReg *I = IStart; *I; ++I) { 15240 const TargetRegisterClass *RC = nullptr; 15241 if (PPC::G8RCRegClass.contains(*I)) 15242 RC = &PPC::G8RCRegClass; 15243 else if (PPC::F8RCRegClass.contains(*I)) 15244 RC = &PPC::F8RCRegClass; 15245 else if (PPC::CRRCRegClass.contains(*I)) 15246 RC = &PPC::CRRCRegClass; 15247 else if (PPC::VRRCRegClass.contains(*I)) 15248 RC = &PPC::VRRCRegClass; 15249 else 15250 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15251 15252 Register NewVR = MRI->createVirtualRegister(RC); 15253 // Create copy from CSR to a virtual register. 15254 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15255 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15256 // nounwind. If we want to generalize this later, we may need to emit 15257 // CFI pseudo-instructions. 15258 assert(Entry->getParent()->getFunction().hasFnAttribute( 15259 Attribute::NoUnwind) && 15260 "Function should be nounwind in insertCopiesSplitCSR!"); 15261 Entry->addLiveIn(*I); 15262 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15263 .addReg(*I); 15264 15265 // Insert the copy-back instructions right before the terminator. 15266 for (auto *Exit : Exits) 15267 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15268 TII->get(TargetOpcode::COPY), *I) 15269 .addReg(NewVR); 15270 } 15271 } 15272 15273 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15274 bool PPCTargetLowering::useLoadStackGuardNode() const { 15275 if (!Subtarget.isTargetLinux()) 15276 return TargetLowering::useLoadStackGuardNode(); 15277 return true; 15278 } 15279 15280 // Override to disable global variable loading on Linux. 15281 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15282 if (!Subtarget.isTargetLinux()) 15283 return TargetLowering::insertSSPDeclarations(M); 15284 } 15285 15286 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15287 bool ForCodeSize) const { 15288 if (!VT.isSimple() || !Subtarget.hasVSX()) 15289 return false; 15290 15291 switch(VT.getSimpleVT().SimpleTy) { 15292 default: 15293 // For FP types that are currently not supported by PPC backend, return 15294 // false. Examples: f16, f80. 15295 return false; 15296 case MVT::f32: 15297 case MVT::f64: 15298 case MVT::ppcf128: 15299 return Imm.isPosZero(); 15300 } 15301 } 15302 15303 // For vector shift operation op, fold 15304 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15305 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15306 SelectionDAG &DAG) { 15307 SDValue N0 = N->getOperand(0); 15308 SDValue N1 = N->getOperand(1); 15309 EVT VT = N0.getValueType(); 15310 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15311 unsigned Opcode = N->getOpcode(); 15312 unsigned TargetOpcode; 15313 15314 switch (Opcode) { 15315 default: 15316 llvm_unreachable("Unexpected shift operation"); 15317 case ISD::SHL: 15318 TargetOpcode = PPCISD::SHL; 15319 break; 15320 case ISD::SRL: 15321 TargetOpcode = PPCISD::SRL; 15322 break; 15323 case ISD::SRA: 15324 TargetOpcode = PPCISD::SRA; 15325 break; 15326 } 15327 15328 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15329 N1->getOpcode() == ISD::AND) 15330 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15331 if (Mask->getZExtValue() == OpSizeInBits - 1) 15332 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15333 15334 return SDValue(); 15335 } 15336 15337 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15338 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15339 return Value; 15340 15341 SDValue N0 = N->getOperand(0); 15342 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15343 if (!Subtarget.isISA3_0() || 15344 N0.getOpcode() != ISD::SIGN_EXTEND || 15345 N0.getOperand(0).getValueType() != MVT::i32 || 15346 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15347 return SDValue(); 15348 15349 // We can't save an operation here if the value is already extended, and 15350 // the existing shift is easier to combine. 15351 SDValue ExtsSrc = N0.getOperand(0); 15352 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15353 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15354 return SDValue(); 15355 15356 SDLoc DL(N0); 15357 SDValue ShiftBy = SDValue(CN1, 0); 15358 // We want the shift amount to be i32 on the extswli, but the shift could 15359 // have an i64. 15360 if (ShiftBy.getValueType() == MVT::i64) 15361 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15362 15363 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15364 ShiftBy); 15365 } 15366 15367 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15368 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15369 return Value; 15370 15371 return SDValue(); 15372 } 15373 15374 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15375 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15376 return Value; 15377 15378 return SDValue(); 15379 } 15380 15381 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15382 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15383 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15384 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15385 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15386 const PPCSubtarget &Subtarget) { 15387 if (!Subtarget.isPPC64()) 15388 return SDValue(); 15389 15390 SDValue LHS = N->getOperand(0); 15391 SDValue RHS = N->getOperand(1); 15392 15393 auto isZextOfCompareWithConstant = [](SDValue Op) { 15394 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15395 Op.getValueType() != MVT::i64) 15396 return false; 15397 15398 SDValue Cmp = Op.getOperand(0); 15399 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15400 Cmp.getOperand(0).getValueType() != MVT::i64) 15401 return false; 15402 15403 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15404 int64_t NegConstant = 0 - Constant->getSExtValue(); 15405 // Due to the limitations of the addi instruction, 15406 // -C is required to be [-32768, 32767]. 15407 return isInt<16>(NegConstant); 15408 } 15409 15410 return false; 15411 }; 15412 15413 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15414 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15415 15416 // If there is a pattern, canonicalize a zext operand to the RHS. 15417 if (LHSHasPattern && !RHSHasPattern) 15418 std::swap(LHS, RHS); 15419 else if (!LHSHasPattern && !RHSHasPattern) 15420 return SDValue(); 15421 15422 SDLoc DL(N); 15423 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15424 SDValue Cmp = RHS.getOperand(0); 15425 SDValue Z = Cmp.getOperand(0); 15426 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15427 15428 assert(Constant && "Constant Should not be a null pointer."); 15429 int64_t NegConstant = 0 - Constant->getSExtValue(); 15430 15431 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15432 default: break; 15433 case ISD::SETNE: { 15434 // when C == 0 15435 // --> addze X, (addic Z, -1).carry 15436 // / 15437 // add X, (zext(setne Z, C))-- 15438 // \ when -32768 <= -C <= 32767 && C != 0 15439 // --> addze X, (addic (addi Z, -C), -1).carry 15440 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15441 DAG.getConstant(NegConstant, DL, MVT::i64)); 15442 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15443 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15444 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15445 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15446 SDValue(Addc.getNode(), 1)); 15447 } 15448 case ISD::SETEQ: { 15449 // when C == 0 15450 // --> addze X, (subfic Z, 0).carry 15451 // / 15452 // add X, (zext(sete Z, C))-- 15453 // \ when -32768 <= -C <= 32767 && C != 0 15454 // --> addze X, (subfic (addi Z, -C), 0).carry 15455 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15456 DAG.getConstant(NegConstant, DL, MVT::i64)); 15457 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15458 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15459 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15460 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15461 SDValue(Subc.getNode(), 1)); 15462 } 15463 } 15464 15465 return SDValue(); 15466 } 15467 15468 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 15469 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 15470 return Value; 15471 15472 return SDValue(); 15473 } 15474 15475 // Detect TRUNCATE operations on bitcasts of float128 values. 15476 // What we are looking for here is the situtation where we extract a subset 15477 // of bits from a 128 bit float. 15478 // This can be of two forms: 15479 // 1) BITCAST of f128 feeding TRUNCATE 15480 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 15481 // The reason this is required is because we do not have a legal i128 type 15482 // and so we want to prevent having to store the f128 and then reload part 15483 // of it. 15484 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 15485 DAGCombinerInfo &DCI) const { 15486 // If we are using CRBits then try that first. 15487 if (Subtarget.useCRBits()) { 15488 // Check if CRBits did anything and return that if it did. 15489 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 15490 return CRTruncValue; 15491 } 15492 15493 SDLoc dl(N); 15494 SDValue Op0 = N->getOperand(0); 15495 15496 // Looking for a truncate of i128 to i64. 15497 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 15498 return SDValue(); 15499 15500 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 15501 15502 // SRL feeding TRUNCATE. 15503 if (Op0.getOpcode() == ISD::SRL) { 15504 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 15505 // The right shift has to be by 64 bits. 15506 if (!ConstNode || ConstNode->getZExtValue() != 64) 15507 return SDValue(); 15508 15509 // Switch the element number to extract. 15510 EltToExtract = EltToExtract ? 0 : 1; 15511 // Update Op0 past the SRL. 15512 Op0 = Op0.getOperand(0); 15513 } 15514 15515 // BITCAST feeding a TRUNCATE possibly via SRL. 15516 if (Op0.getOpcode() == ISD::BITCAST && 15517 Op0.getValueType() == MVT::i128 && 15518 Op0.getOperand(0).getValueType() == MVT::f128) { 15519 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 15520 return DCI.DAG.getNode( 15521 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 15522 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 15523 } 15524 return SDValue(); 15525 } 15526 15527 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 15528 SelectionDAG &DAG = DCI.DAG; 15529 15530 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 15531 if (!ConstOpOrElement) 15532 return SDValue(); 15533 15534 // An imul is usually smaller than the alternative sequence for legal type. 15535 if (DAG.getMachineFunction().getFunction().hasMinSize() && 15536 isOperationLegal(ISD::MUL, N->getValueType(0))) 15537 return SDValue(); 15538 15539 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 15540 switch (this->Subtarget.getCPUDirective()) { 15541 default: 15542 // TODO: enhance the condition for subtarget before pwr8 15543 return false; 15544 case PPC::DIR_PWR8: 15545 // type mul add shl 15546 // scalar 4 1 1 15547 // vector 7 2 2 15548 return true; 15549 case PPC::DIR_PWR9: 15550 case PPC::DIR_PWR_FUTURE: 15551 // type mul add shl 15552 // scalar 5 2 2 15553 // vector 7 2 2 15554 15555 // The cycle RATIO of related operations are showed as a table above. 15556 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 15557 // scalar and vector type. For 2 instrs patterns, add/sub + shl 15558 // are 4, it is always profitable; but for 3 instrs patterns 15559 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 15560 // So we should only do it for vector type. 15561 return IsAddOne && IsNeg ? VT.isVector() : true; 15562 } 15563 }; 15564 15565 EVT VT = N->getValueType(0); 15566 SDLoc DL(N); 15567 15568 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 15569 bool IsNeg = MulAmt.isNegative(); 15570 APInt MulAmtAbs = MulAmt.abs(); 15571 15572 if ((MulAmtAbs - 1).isPowerOf2()) { 15573 // (mul x, 2^N + 1) => (add (shl x, N), x) 15574 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 15575 15576 if (!IsProfitable(IsNeg, true, VT)) 15577 return SDValue(); 15578 15579 SDValue Op0 = N->getOperand(0); 15580 SDValue Op1 = 15581 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15582 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 15583 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 15584 15585 if (!IsNeg) 15586 return Res; 15587 15588 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 15589 } else if ((MulAmtAbs + 1).isPowerOf2()) { 15590 // (mul x, 2^N - 1) => (sub (shl x, N), x) 15591 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 15592 15593 if (!IsProfitable(IsNeg, false, VT)) 15594 return SDValue(); 15595 15596 SDValue Op0 = N->getOperand(0); 15597 SDValue Op1 = 15598 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15599 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 15600 15601 if (!IsNeg) 15602 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 15603 else 15604 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 15605 15606 } else { 15607 return SDValue(); 15608 } 15609 } 15610 15611 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 15612 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 15613 if (!Subtarget.is64BitELFABI()) 15614 return false; 15615 15616 // If not a tail call then no need to proceed. 15617 if (!CI->isTailCall()) 15618 return false; 15619 15620 // If tail calls are disabled for the caller then we are done. 15621 const Function *Caller = CI->getParent()->getParent(); 15622 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 15623 if (Attr.getValueAsString() == "true") 15624 return false; 15625 15626 // If sibling calls have been disabled and tail-calls aren't guaranteed 15627 // there is no reason to duplicate. 15628 auto &TM = getTargetMachine(); 15629 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 15630 return false; 15631 15632 // Can't tail call a function called indirectly, or if it has variadic args. 15633 const Function *Callee = CI->getCalledFunction(); 15634 if (!Callee || Callee->isVarArg()) 15635 return false; 15636 15637 // Make sure the callee and caller calling conventions are eligible for tco. 15638 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 15639 CI->getCallingConv())) 15640 return false; 15641 15642 // If the function is local then we have a good chance at tail-calling it 15643 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 15644 } 15645 15646 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 15647 if (!Subtarget.hasVSX()) 15648 return false; 15649 if (Subtarget.hasP9Vector() && VT == MVT::f128) 15650 return true; 15651 return VT == MVT::f32 || VT == MVT::f64 || 15652 VT == MVT::v4f32 || VT == MVT::v2f64; 15653 } 15654 15655 bool PPCTargetLowering:: 15656 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 15657 const Value *Mask = AndI.getOperand(1); 15658 // If the mask is suitable for andi. or andis. we should sink the and. 15659 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 15660 // Can't handle constants wider than 64-bits. 15661 if (CI->getBitWidth() > 64) 15662 return false; 15663 int64_t ConstVal = CI->getZExtValue(); 15664 return isUInt<16>(ConstVal) || 15665 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 15666 } 15667 15668 // For non-constant masks, we can always use the record-form and. 15669 return true; 15670 } 15671 15672 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 15673 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 15674 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 15675 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 15676 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 15677 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 15678 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 15679 assert(Subtarget.hasP9Altivec() && 15680 "Only combine this when P9 altivec supported!"); 15681 EVT VT = N->getValueType(0); 15682 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15683 return SDValue(); 15684 15685 SelectionDAG &DAG = DCI.DAG; 15686 SDLoc dl(N); 15687 if (N->getOperand(0).getOpcode() == ISD::SUB) { 15688 // Even for signed integers, if it's known to be positive (as signed 15689 // integer) due to zero-extended inputs. 15690 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 15691 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 15692 if ((SubOpcd0 == ISD::ZERO_EXTEND || 15693 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 15694 (SubOpcd1 == ISD::ZERO_EXTEND || 15695 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 15696 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15697 N->getOperand(0)->getOperand(0), 15698 N->getOperand(0)->getOperand(1), 15699 DAG.getTargetConstant(0, dl, MVT::i32)); 15700 } 15701 15702 // For type v4i32, it can be optimized with xvnegsp + vabsduw 15703 if (N->getOperand(0).getValueType() == MVT::v4i32 && 15704 N->getOperand(0).hasOneUse()) { 15705 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15706 N->getOperand(0)->getOperand(0), 15707 N->getOperand(0)->getOperand(1), 15708 DAG.getTargetConstant(1, dl, MVT::i32)); 15709 } 15710 } 15711 15712 return SDValue(); 15713 } 15714 15715 // For type v4i32/v8ii16/v16i8, transform 15716 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 15717 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 15718 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 15719 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 15720 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 15721 DAGCombinerInfo &DCI) const { 15722 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 15723 assert(Subtarget.hasP9Altivec() && 15724 "Only combine this when P9 altivec supported!"); 15725 15726 SelectionDAG &DAG = DCI.DAG; 15727 SDLoc dl(N); 15728 SDValue Cond = N->getOperand(0); 15729 SDValue TrueOpnd = N->getOperand(1); 15730 SDValue FalseOpnd = N->getOperand(2); 15731 EVT VT = N->getOperand(1).getValueType(); 15732 15733 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 15734 FalseOpnd.getOpcode() != ISD::SUB) 15735 return SDValue(); 15736 15737 // ABSD only available for type v4i32/v8i16/v16i8 15738 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15739 return SDValue(); 15740 15741 // At least to save one more dependent computation 15742 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 15743 return SDValue(); 15744 15745 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15746 15747 // Can only handle unsigned comparison here 15748 switch (CC) { 15749 default: 15750 return SDValue(); 15751 case ISD::SETUGT: 15752 case ISD::SETUGE: 15753 break; 15754 case ISD::SETULT: 15755 case ISD::SETULE: 15756 std::swap(TrueOpnd, FalseOpnd); 15757 break; 15758 } 15759 15760 SDValue CmpOpnd1 = Cond.getOperand(0); 15761 SDValue CmpOpnd2 = Cond.getOperand(1); 15762 15763 // SETCC CmpOpnd1 CmpOpnd2 cond 15764 // TrueOpnd = CmpOpnd1 - CmpOpnd2 15765 // FalseOpnd = CmpOpnd2 - CmpOpnd1 15766 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 15767 TrueOpnd.getOperand(1) == CmpOpnd2 && 15768 FalseOpnd.getOperand(0) == CmpOpnd2 && 15769 FalseOpnd.getOperand(1) == CmpOpnd1) { 15770 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 15771 CmpOpnd1, CmpOpnd2, 15772 DAG.getTargetConstant(0, dl, MVT::i32)); 15773 } 15774 15775 return SDValue(); 15776 } 15777