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/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/IntrinsicsPowerPC.h" 70 #include "llvm/IR/Module.h" 71 #include "llvm/IR/Type.h" 72 #include "llvm/IR/Use.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/MC/MCContext.h" 75 #include "llvm/MC/MCExpr.h" 76 #include "llvm/MC/MCRegisterInfo.h" 77 #include "llvm/MC/MCSymbolXCOFF.h" 78 #include "llvm/Support/AtomicOrdering.h" 79 #include "llvm/Support/BranchProbability.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/CodeGen.h" 82 #include "llvm/Support/CommandLine.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/Debug.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/KnownBits.h" 88 #include "llvm/Support/MachineValueType.h" 89 #include "llvm/Support/MathExtras.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include "llvm/Target/TargetMachine.h" 92 #include "llvm/Target/TargetOptions.h" 93 #include <algorithm> 94 #include <cassert> 95 #include <cstdint> 96 #include <iterator> 97 #include <list> 98 #include <utility> 99 #include <vector> 100 101 using namespace llvm; 102 103 #define DEBUG_TYPE "ppc-lowering" 104 105 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 106 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 107 108 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 109 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 110 111 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 112 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 113 114 static cl::opt<bool> DisableSCO("disable-ppc-sco", 115 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 116 117 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 118 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 119 120 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 121 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 122 123 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 124 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 125 126 STATISTIC(NumTailCalls, "Number of tail calls"); 127 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 128 129 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 130 131 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 132 133 // FIXME: Remove this once the bug has been fixed! 134 extern cl::opt<bool> ANDIGlueBug; 135 136 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 137 const PPCSubtarget &STI) 138 : TargetLowering(TM), Subtarget(STI) { 139 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 140 // arguments are at least 4/8 bytes aligned. 141 bool isPPC64 = Subtarget.isPPC64(); 142 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 143 144 // Set up the register classes. 145 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 146 if (!useSoftFloat()) { 147 if (hasSPE()) { 148 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 149 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 150 } else { 151 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 152 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 153 } 154 } 155 156 // Match BITREVERSE to customized fast code sequence in the td file. 157 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 158 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 159 160 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 161 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 162 163 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 164 for (MVT VT : MVT::integer_valuetypes()) { 165 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 167 } 168 169 if (Subtarget.isISA3_0()) { 170 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 171 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 172 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 173 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 174 } else { 175 // No extending loads from f16 or HW conversions back and forth. 176 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 177 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 178 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 179 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 180 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 181 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 182 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 183 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 184 } 185 186 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 187 188 // PowerPC has pre-inc load and store's. 189 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 190 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 191 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 192 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 193 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 194 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 195 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 196 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 197 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 198 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 199 if (!Subtarget.hasSPE()) { 200 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 201 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 202 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 204 } 205 206 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 207 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 208 for (MVT VT : ScalarIntVTs) { 209 setOperationAction(ISD::ADDC, VT, Legal); 210 setOperationAction(ISD::ADDE, VT, Legal); 211 setOperationAction(ISD::SUBC, VT, Legal); 212 setOperationAction(ISD::SUBE, VT, Legal); 213 } 214 215 if (Subtarget.useCRBits()) { 216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 217 218 if (isPPC64 || Subtarget.hasFPCVT()) { 219 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 220 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 221 isPPC64 ? MVT::i64 : MVT::i32); 222 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 223 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 224 isPPC64 ? MVT::i64 : MVT::i32); 225 } else { 226 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 227 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 228 } 229 230 // PowerPC does not support direct load/store of condition registers. 231 setOperationAction(ISD::LOAD, MVT::i1, Custom); 232 setOperationAction(ISD::STORE, MVT::i1, Custom); 233 234 // FIXME: Remove this once the ANDI glue bug is fixed: 235 if (ANDIGlueBug) 236 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 237 238 for (MVT VT : MVT::integer_valuetypes()) { 239 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 240 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 241 setTruncStoreAction(VT, MVT::i1, Expand); 242 } 243 244 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 245 } 246 247 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 248 // PPC (the libcall is not available). 249 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 250 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 251 252 // We do not currently implement these libm ops for PowerPC. 253 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 254 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 255 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 256 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 257 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 258 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 259 260 // PowerPC has no SREM/UREM instructions unless we are on P9 261 // On P9 we may use a hardware instruction to compute the remainder. 262 // The instructions are not legalized directly because in the cases where the 263 // result of both the remainder and the division is required it is more 264 // efficient to compute the remainder from the result of the division rather 265 // than use the remainder instruction. 266 if (Subtarget.isISA3_0()) { 267 setOperationAction(ISD::SREM, MVT::i32, Custom); 268 setOperationAction(ISD::UREM, MVT::i32, Custom); 269 setOperationAction(ISD::SREM, MVT::i64, Custom); 270 setOperationAction(ISD::UREM, MVT::i64, Custom); 271 } else { 272 setOperationAction(ISD::SREM, MVT::i32, Expand); 273 setOperationAction(ISD::UREM, MVT::i32, Expand); 274 setOperationAction(ISD::SREM, MVT::i64, Expand); 275 setOperationAction(ISD::UREM, MVT::i64, Expand); 276 } 277 278 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 279 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 280 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 281 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 282 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 283 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 284 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 285 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 286 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 287 288 // Handle constrained floating-point operations of scalar. 289 // TODO: Handle SPE specific operation. 290 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 291 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 292 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 293 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 294 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 295 296 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 297 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 298 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 299 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 300 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 301 302 if (Subtarget.hasFSQRT()) { 303 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 304 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 305 } 306 307 // We don't support sin/cos/sqrt/fmod/pow 308 setOperationAction(ISD::FSIN , MVT::f64, Expand); 309 setOperationAction(ISD::FCOS , MVT::f64, Expand); 310 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 311 setOperationAction(ISD::FREM , MVT::f64, Expand); 312 setOperationAction(ISD::FPOW , MVT::f64, Expand); 313 setOperationAction(ISD::FSIN , MVT::f32, Expand); 314 setOperationAction(ISD::FCOS , MVT::f32, Expand); 315 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 316 setOperationAction(ISD::FREM , MVT::f32, Expand); 317 setOperationAction(ISD::FPOW , MVT::f32, Expand); 318 if (Subtarget.hasSPE()) { 319 setOperationAction(ISD::FMA , MVT::f64, Expand); 320 setOperationAction(ISD::FMA , MVT::f32, Expand); 321 } else { 322 setOperationAction(ISD::FMA , MVT::f64, Legal); 323 setOperationAction(ISD::FMA , MVT::f32, Legal); 324 } 325 326 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 327 328 // If we're enabling GP optimizations, use hardware square root 329 if (!Subtarget.hasFSQRT() && 330 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 331 Subtarget.hasFRE())) 332 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 333 334 if (!Subtarget.hasFSQRT() && 335 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 336 Subtarget.hasFRES())) 337 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 338 339 if (Subtarget.hasFCPSGN()) { 340 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 341 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 342 } else { 343 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 344 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 345 } 346 347 if (Subtarget.hasFPRND()) { 348 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 349 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 350 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 351 setOperationAction(ISD::FROUND, MVT::f64, Legal); 352 353 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 354 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 355 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 356 setOperationAction(ISD::FROUND, MVT::f32, Legal); 357 } 358 359 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 360 // to speed up scalar BSWAP64. 361 // CTPOP or CTTZ were introduced in P8/P9 respectively 362 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 363 if (Subtarget.hasP9Vector()) 364 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 365 else 366 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 367 if (Subtarget.isISA3_0()) { 368 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 369 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 370 } else { 371 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 372 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 373 } 374 375 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 376 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 377 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 378 } else { 379 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 380 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 381 } 382 383 // PowerPC does not have ROTR 384 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 385 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 386 387 if (!Subtarget.useCRBits()) { 388 // PowerPC does not have Select 389 setOperationAction(ISD::SELECT, MVT::i32, Expand); 390 setOperationAction(ISD::SELECT, MVT::i64, Expand); 391 setOperationAction(ISD::SELECT, MVT::f32, Expand); 392 setOperationAction(ISD::SELECT, MVT::f64, Expand); 393 } 394 395 // PowerPC wants to turn select_cc of FP into fsel when possible. 396 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 397 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 398 399 // PowerPC wants to optimize integer setcc a bit 400 if (!Subtarget.useCRBits()) 401 setOperationAction(ISD::SETCC, MVT::i32, Custom); 402 403 // PowerPC does not have BRCOND which requires SetCC 404 if (!Subtarget.useCRBits()) 405 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 406 407 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 408 409 if (Subtarget.hasSPE()) { 410 // SPE has built-in conversions 411 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 412 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 413 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 414 } else { 415 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 416 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 417 418 // PowerPC does not have [U|S]INT_TO_FP 419 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 420 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 421 } 422 423 if (Subtarget.hasDirectMove() && isPPC64) { 424 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 425 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 426 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 427 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 428 if (TM.Options.UnsafeFPMath) { 429 setOperationAction(ISD::LRINT, MVT::f64, Legal); 430 setOperationAction(ISD::LRINT, MVT::f32, Legal); 431 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 432 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 433 setOperationAction(ISD::LROUND, MVT::f64, Legal); 434 setOperationAction(ISD::LROUND, MVT::f32, Legal); 435 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 436 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 437 } 438 } else { 439 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 440 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 441 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 442 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 443 } 444 445 // We cannot sextinreg(i1). Expand to shifts. 446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 447 448 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 449 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 450 // support continuation, user-level threading, and etc.. As a result, no 451 // other SjLj exception interfaces are implemented and please don't build 452 // your own exception handling based on them. 453 // LLVM/Clang supports zero-cost DWARF exception handling. 454 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 455 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 456 457 // We want to legalize GlobalAddress and ConstantPool nodes into the 458 // appropriate instructions to materialize the address. 459 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 460 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 461 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 462 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 463 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 464 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 465 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 466 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 467 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 468 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 469 470 // TRAP is legal. 471 setOperationAction(ISD::TRAP, MVT::Other, Legal); 472 473 // TRAMPOLINE is custom lowered. 474 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 475 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 476 477 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 478 setOperationAction(ISD::VASTART , MVT::Other, Custom); 479 480 if (Subtarget.is64BitELFABI()) { 481 // VAARG always uses double-word chunks, so promote anything smaller. 482 setOperationAction(ISD::VAARG, MVT::i1, Promote); 483 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 484 setOperationAction(ISD::VAARG, MVT::i8, Promote); 485 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 486 setOperationAction(ISD::VAARG, MVT::i16, Promote); 487 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 488 setOperationAction(ISD::VAARG, MVT::i32, Promote); 489 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 490 setOperationAction(ISD::VAARG, MVT::Other, Expand); 491 } else if (Subtarget.is32BitELFABI()) { 492 // VAARG is custom lowered with the 32-bit SVR4 ABI. 493 setOperationAction(ISD::VAARG, MVT::Other, Custom); 494 setOperationAction(ISD::VAARG, MVT::i64, Custom); 495 } else 496 setOperationAction(ISD::VAARG, MVT::Other, Expand); 497 498 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 499 if (Subtarget.is32BitELFABI()) 500 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 501 else 502 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 503 504 // Use the default implementation. 505 setOperationAction(ISD::VAEND , MVT::Other, Expand); 506 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 507 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 508 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 509 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 510 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 511 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 512 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 513 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 514 515 // We want to custom lower some of our intrinsics. 516 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 517 518 // To handle counter-based loop conditions. 519 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 520 521 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 522 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 523 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 524 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 525 526 // Comparisons that require checking two conditions. 527 if (Subtarget.hasSPE()) { 528 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 529 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 530 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 531 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 532 } 533 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 534 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 535 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 536 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 537 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 538 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 539 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 540 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 541 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 542 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 543 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 544 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 545 546 if (Subtarget.has64BitSupport()) { 547 // They also have instructions for converting between i64 and fp. 548 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 549 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 550 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 551 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 552 // This is just the low 32 bits of a (signed) fp->i64 conversion. 553 // We cannot do this with Promote because i64 is not a legal type. 554 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 555 556 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 557 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 558 } else { 559 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 560 if (Subtarget.hasSPE()) 561 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 562 else 563 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 564 } 565 566 // With the instructions enabled under FPCVT, we can do everything. 567 if (Subtarget.hasFPCVT()) { 568 if (Subtarget.has64BitSupport()) { 569 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 570 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 571 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 572 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 573 } 574 575 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 576 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 577 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 578 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 579 } 580 581 if (Subtarget.use64BitRegs()) { 582 // 64-bit PowerPC implementations can support i64 types directly 583 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 584 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 585 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 586 // 64-bit PowerPC wants to expand i128 shifts itself. 587 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 588 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 589 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 590 } else { 591 // 32-bit PowerPC wants to expand i64 shifts itself. 592 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 593 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 594 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 595 } 596 597 if (Subtarget.hasVSX()) { 598 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 599 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 600 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 601 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 602 } 603 604 if (Subtarget.hasAltivec()) { 605 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 606 setOperationAction(ISD::SADDSAT, VT, Legal); 607 setOperationAction(ISD::SSUBSAT, VT, Legal); 608 setOperationAction(ISD::UADDSAT, VT, Legal); 609 setOperationAction(ISD::USUBSAT, VT, Legal); 610 } 611 // First set operation action for all vector types to expand. Then we 612 // will selectively turn on ones that can be effectively codegen'd. 613 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 614 // add/sub are legal for all supported vector VT's. 615 setOperationAction(ISD::ADD, VT, Legal); 616 setOperationAction(ISD::SUB, VT, Legal); 617 618 // For v2i64, these are only valid with P8Vector. This is corrected after 619 // the loop. 620 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 621 setOperationAction(ISD::SMAX, VT, Legal); 622 setOperationAction(ISD::SMIN, VT, Legal); 623 setOperationAction(ISD::UMAX, VT, Legal); 624 setOperationAction(ISD::UMIN, VT, Legal); 625 } 626 else { 627 setOperationAction(ISD::SMAX, VT, Expand); 628 setOperationAction(ISD::SMIN, VT, Expand); 629 setOperationAction(ISD::UMAX, VT, Expand); 630 setOperationAction(ISD::UMIN, VT, Expand); 631 } 632 633 if (Subtarget.hasVSX()) { 634 setOperationAction(ISD::FMAXNUM, VT, Legal); 635 setOperationAction(ISD::FMINNUM, VT, Legal); 636 } 637 638 // Vector instructions introduced in P8 639 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 640 setOperationAction(ISD::CTPOP, VT, Legal); 641 setOperationAction(ISD::CTLZ, VT, Legal); 642 } 643 else { 644 setOperationAction(ISD::CTPOP, VT, Expand); 645 setOperationAction(ISD::CTLZ, VT, Expand); 646 } 647 648 // Vector instructions introduced in P9 649 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 650 setOperationAction(ISD::CTTZ, VT, Legal); 651 else 652 setOperationAction(ISD::CTTZ, VT, Expand); 653 654 // We promote all shuffles to v16i8. 655 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 656 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 657 658 // We promote all non-typed operations to v4i32. 659 setOperationAction(ISD::AND , VT, Promote); 660 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 661 setOperationAction(ISD::OR , VT, Promote); 662 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 663 setOperationAction(ISD::XOR , VT, Promote); 664 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 665 setOperationAction(ISD::LOAD , VT, Promote); 666 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 667 setOperationAction(ISD::SELECT, VT, Promote); 668 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 669 setOperationAction(ISD::VSELECT, VT, Legal); 670 setOperationAction(ISD::SELECT_CC, VT, Promote); 671 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 672 setOperationAction(ISD::STORE, VT, Promote); 673 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 674 675 // No other operations are legal. 676 setOperationAction(ISD::MUL , VT, Expand); 677 setOperationAction(ISD::SDIV, VT, Expand); 678 setOperationAction(ISD::SREM, VT, Expand); 679 setOperationAction(ISD::UDIV, VT, Expand); 680 setOperationAction(ISD::UREM, VT, Expand); 681 setOperationAction(ISD::FDIV, VT, Expand); 682 setOperationAction(ISD::FREM, VT, Expand); 683 setOperationAction(ISD::FNEG, VT, Expand); 684 setOperationAction(ISD::FSQRT, VT, Expand); 685 setOperationAction(ISD::FLOG, VT, Expand); 686 setOperationAction(ISD::FLOG10, VT, Expand); 687 setOperationAction(ISD::FLOG2, VT, Expand); 688 setOperationAction(ISD::FEXP, VT, Expand); 689 setOperationAction(ISD::FEXP2, VT, Expand); 690 setOperationAction(ISD::FSIN, VT, Expand); 691 setOperationAction(ISD::FCOS, VT, Expand); 692 setOperationAction(ISD::FABS, VT, Expand); 693 setOperationAction(ISD::FFLOOR, VT, Expand); 694 setOperationAction(ISD::FCEIL, VT, Expand); 695 setOperationAction(ISD::FTRUNC, VT, Expand); 696 setOperationAction(ISD::FRINT, VT, Expand); 697 setOperationAction(ISD::FNEARBYINT, VT, Expand); 698 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 699 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 700 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 701 setOperationAction(ISD::MULHU, VT, Expand); 702 setOperationAction(ISD::MULHS, VT, Expand); 703 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 704 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 705 setOperationAction(ISD::UDIVREM, VT, Expand); 706 setOperationAction(ISD::SDIVREM, VT, Expand); 707 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 708 setOperationAction(ISD::FPOW, VT, Expand); 709 setOperationAction(ISD::BSWAP, VT, Expand); 710 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 711 setOperationAction(ISD::ROTL, VT, Expand); 712 setOperationAction(ISD::ROTR, VT, Expand); 713 714 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 715 setTruncStoreAction(VT, InnerVT, Expand); 716 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 717 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 718 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 719 } 720 } 721 if (!Subtarget.hasP8Vector()) { 722 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 723 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 724 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 725 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 726 } 727 728 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 729 setOperationAction(ISD::ABS, VT, Custom); 730 731 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 732 // with merges, splats, etc. 733 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 734 735 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 736 // are cheap, so handle them before they get expanded to scalar. 737 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 738 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 739 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 740 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 741 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 742 743 setOperationAction(ISD::AND , MVT::v4i32, Legal); 744 setOperationAction(ISD::OR , MVT::v4i32, Legal); 745 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 746 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 747 setOperationAction(ISD::SELECT, MVT::v4i32, 748 Subtarget.useCRBits() ? Legal : Expand); 749 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 750 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 751 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 752 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 753 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 754 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 755 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 756 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 757 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 758 759 // Without hasP8Altivec set, v2i64 SMAX isn't available. 760 // But ABS custom lowering requires SMAX support. 761 if (!Subtarget.hasP8Altivec()) 762 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 763 764 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 765 if (Subtarget.hasAltivec()) 766 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 767 setOperationAction(ISD::ROTL, VT, Legal); 768 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 769 if (Subtarget.hasP8Altivec()) 770 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 771 772 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 773 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 774 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 775 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 776 777 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 778 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 779 780 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 781 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 782 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 783 } 784 785 if (Subtarget.hasP8Altivec()) 786 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 787 else 788 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 789 790 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 791 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 792 793 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 794 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 795 796 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 797 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 798 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 799 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 800 801 // Altivec does not contain unordered floating-point compare instructions 802 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 803 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 804 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 805 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 806 807 if (Subtarget.hasVSX()) { 808 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 809 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 810 if (Subtarget.hasP8Vector()) { 811 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 812 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 813 } 814 if (Subtarget.hasDirectMove() && isPPC64) { 815 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 816 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 817 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 818 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 819 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 820 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 821 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 822 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 823 } 824 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 825 826 // The nearbyint variants are not allowed to raise the inexact exception 827 // so we can only code-gen them with unsafe math. 828 if (TM.Options.UnsafeFPMath) { 829 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 830 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 831 } 832 833 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 834 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 835 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 836 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 837 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 838 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 839 setOperationAction(ISD::FROUND, MVT::f64, Legal); 840 setOperationAction(ISD::FRINT, MVT::f64, Legal); 841 842 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 843 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 844 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 845 setOperationAction(ISD::FROUND, MVT::f32, Legal); 846 setOperationAction(ISD::FRINT, MVT::f32, Legal); 847 848 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 849 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 850 851 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 852 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 853 854 // Share the Altivec comparison restrictions. 855 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 856 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 857 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 858 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 859 860 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 861 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 862 863 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 864 865 if (Subtarget.hasP8Vector()) 866 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 867 868 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 869 870 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 871 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 872 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 873 874 if (Subtarget.hasP8Altivec()) { 875 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 876 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 877 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 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. However due to direct move costs, it's not worth 882 // doing 883 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 884 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 885 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 886 887 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 888 } 889 else { 890 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 891 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 892 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 893 894 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 895 896 // VSX v2i64 only supports non-arithmetic operations. 897 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 898 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 899 } 900 901 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 902 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 903 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 904 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 905 906 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 907 908 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 909 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 910 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 911 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 912 913 // Custom handling for partial vectors of integers converted to 914 // floating point. We already have optimal handling for v2i32 through 915 // the DAG combine, so those aren't necessary. 916 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 917 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 918 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 919 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 920 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 921 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 922 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 923 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 924 925 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 926 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 927 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 928 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 929 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 930 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 931 932 if (Subtarget.hasDirectMove()) 933 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 934 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 935 936 // Handle constrained floating-point operations of vector. 937 // The predictor is `hasVSX` because altivec instruction has 938 // no exception but VSX vector instruction has. 939 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 940 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 941 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 942 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 943 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 944 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 945 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 946 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 947 948 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 949 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 950 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 951 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 952 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 953 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 954 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 955 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 956 957 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 958 } 959 960 if (Subtarget.hasP8Altivec()) { 961 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 962 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 963 } 964 965 if (Subtarget.hasP9Vector()) { 966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 968 969 // 128 bit shifts can be accomplished via 3 instructions for SHL and 970 // SRL, but not for SRA because of the instructions available: 971 // VS{RL} and VS{RL}O. 972 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 973 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 974 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 975 976 if (EnableQuadPrecision) { 977 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 978 setOperationAction(ISD::FADD, MVT::f128, Legal); 979 setOperationAction(ISD::FSUB, MVT::f128, Legal); 980 setOperationAction(ISD::FDIV, MVT::f128, Legal); 981 setOperationAction(ISD::FMUL, MVT::f128, Legal); 982 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 983 // No extending loads to f128 on PPC. 984 for (MVT FPT : MVT::fp_valuetypes()) 985 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 986 setOperationAction(ISD::FMA, MVT::f128, Legal); 987 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 988 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 989 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 990 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 991 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 992 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 993 994 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 995 setOperationAction(ISD::FRINT, MVT::f128, Legal); 996 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 997 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 998 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 999 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1000 1001 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1002 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1003 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1004 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1005 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1006 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1007 // No implementation for these ops for PowerPC. 1008 setOperationAction(ISD::FSIN , MVT::f128, Expand); 1009 setOperationAction(ISD::FCOS , MVT::f128, Expand); 1010 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1011 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1012 setOperationAction(ISD::FREM, MVT::f128, Expand); 1013 1014 // Handle constrained floating-point operations of fp128 1015 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1016 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1017 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1018 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1019 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1020 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1021 } 1022 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1023 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1024 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1025 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1026 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1027 } 1028 1029 if (Subtarget.hasP9Altivec()) { 1030 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1031 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1032 1033 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1034 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1035 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1036 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1037 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1038 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1039 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1040 } 1041 } 1042 1043 if (Subtarget.hasQPX()) { 1044 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1045 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1046 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1047 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 1048 1049 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 1050 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 1051 1052 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 1053 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 1054 1055 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 1056 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 1057 1058 if (!Subtarget.useCRBits()) 1059 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 1060 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1061 1062 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 1063 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 1064 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 1065 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 1066 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 1067 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1068 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1069 1070 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1071 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1072 1073 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1074 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1075 1076 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1077 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1078 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1079 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1080 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1081 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1082 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1083 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1084 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1085 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1086 1087 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1088 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1089 1090 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1091 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1092 1093 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1094 1095 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1096 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1097 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1098 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1099 1100 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1101 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1102 1103 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1104 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1105 1106 if (!Subtarget.useCRBits()) 1107 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1108 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1109 1110 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1111 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1112 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1113 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1114 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1115 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1116 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1117 1118 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1119 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1120 1121 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1122 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1123 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1124 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1125 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1126 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1127 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1128 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1129 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1130 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1131 1132 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1133 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1134 1135 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1136 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1137 1138 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1139 1140 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1141 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1142 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1143 1144 if (!Subtarget.useCRBits()) 1145 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1146 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1147 1148 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1149 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1150 1151 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1152 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1153 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1154 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1155 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1156 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1157 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1158 1159 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1160 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1161 1162 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1163 1164 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1165 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1166 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1167 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1168 1169 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1170 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1171 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1172 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1173 1174 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1175 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1176 1177 // These need to set FE_INEXACT, and so cannot be vectorized here. 1178 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1179 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1180 1181 if (TM.Options.UnsafeFPMath) { 1182 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1183 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1184 1185 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1186 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1187 } else { 1188 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1189 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1190 1191 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1192 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1193 } 1194 1195 // TODO: Handle constrained floating-point operations of v4f64 1196 } 1197 1198 if (Subtarget.has64BitSupport()) 1199 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1200 1201 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1202 1203 if (!isPPC64) { 1204 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1205 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1206 } 1207 1208 setBooleanContents(ZeroOrOneBooleanContent); 1209 1210 if (Subtarget.hasAltivec()) { 1211 // Altivec instructions set fields to all zeros or all ones. 1212 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1213 } 1214 1215 if (!isPPC64) { 1216 // These libcalls are not available in 32-bit. 1217 setLibcallName(RTLIB::SHL_I128, nullptr); 1218 setLibcallName(RTLIB::SRL_I128, nullptr); 1219 setLibcallName(RTLIB::SRA_I128, nullptr); 1220 } 1221 1222 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1223 1224 // We have target-specific dag combine patterns for the following nodes: 1225 setTargetDAGCombine(ISD::ADD); 1226 setTargetDAGCombine(ISD::SHL); 1227 setTargetDAGCombine(ISD::SRA); 1228 setTargetDAGCombine(ISD::SRL); 1229 setTargetDAGCombine(ISD::MUL); 1230 setTargetDAGCombine(ISD::SINT_TO_FP); 1231 setTargetDAGCombine(ISD::BUILD_VECTOR); 1232 if (Subtarget.hasFPCVT()) 1233 setTargetDAGCombine(ISD::UINT_TO_FP); 1234 setTargetDAGCombine(ISD::LOAD); 1235 setTargetDAGCombine(ISD::STORE); 1236 setTargetDAGCombine(ISD::BR_CC); 1237 if (Subtarget.useCRBits()) 1238 setTargetDAGCombine(ISD::BRCOND); 1239 setTargetDAGCombine(ISD::BSWAP); 1240 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1241 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1242 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1243 1244 setTargetDAGCombine(ISD::SIGN_EXTEND); 1245 setTargetDAGCombine(ISD::ZERO_EXTEND); 1246 setTargetDAGCombine(ISD::ANY_EXTEND); 1247 1248 setTargetDAGCombine(ISD::TRUNCATE); 1249 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1250 1251 1252 if (Subtarget.useCRBits()) { 1253 setTargetDAGCombine(ISD::TRUNCATE); 1254 setTargetDAGCombine(ISD::SETCC); 1255 setTargetDAGCombine(ISD::SELECT_CC); 1256 } 1257 1258 // Use reciprocal estimates. 1259 if (TM.Options.UnsafeFPMath) { 1260 setTargetDAGCombine(ISD::FDIV); 1261 setTargetDAGCombine(ISD::FSQRT); 1262 } 1263 1264 if (Subtarget.hasP9Altivec()) { 1265 setTargetDAGCombine(ISD::ABS); 1266 setTargetDAGCombine(ISD::VSELECT); 1267 } 1268 1269 if (EnableQuadPrecision) { 1270 setLibcallName(RTLIB::LOG_F128, "logf128"); 1271 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1272 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1273 setLibcallName(RTLIB::EXP_F128, "expf128"); 1274 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1275 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1276 setLibcallName(RTLIB::COS_F128, "cosf128"); 1277 setLibcallName(RTLIB::POW_F128, "powf128"); 1278 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1279 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1280 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1281 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1282 } 1283 1284 // With 32 condition bits, we don't need to sink (and duplicate) compares 1285 // aggressively in CodeGenPrep. 1286 if (Subtarget.useCRBits()) { 1287 setHasMultipleConditionRegisters(); 1288 setJumpIsExpensive(); 1289 } 1290 1291 setMinFunctionAlignment(Align(4)); 1292 1293 switch (Subtarget.getCPUDirective()) { 1294 default: break; 1295 case PPC::DIR_970: 1296 case PPC::DIR_A2: 1297 case PPC::DIR_E500: 1298 case PPC::DIR_E500mc: 1299 case PPC::DIR_E5500: 1300 case PPC::DIR_PWR4: 1301 case PPC::DIR_PWR5: 1302 case PPC::DIR_PWR5X: 1303 case PPC::DIR_PWR6: 1304 case PPC::DIR_PWR6X: 1305 case PPC::DIR_PWR7: 1306 case PPC::DIR_PWR8: 1307 case PPC::DIR_PWR9: 1308 case PPC::DIR_PWR_FUTURE: 1309 setPrefLoopAlignment(Align(16)); 1310 setPrefFunctionAlignment(Align(16)); 1311 break; 1312 } 1313 1314 if (Subtarget.enableMachineScheduler()) 1315 setSchedulingPreference(Sched::Source); 1316 else 1317 setSchedulingPreference(Sched::Hybrid); 1318 1319 computeRegisterProperties(STI.getRegisterInfo()); 1320 1321 // The Freescale cores do better with aggressive inlining of memcpy and 1322 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1323 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1324 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1325 MaxStoresPerMemset = 32; 1326 MaxStoresPerMemsetOptSize = 16; 1327 MaxStoresPerMemcpy = 32; 1328 MaxStoresPerMemcpyOptSize = 8; 1329 MaxStoresPerMemmove = 32; 1330 MaxStoresPerMemmoveOptSize = 8; 1331 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1332 // The A2 also benefits from (very) aggressive inlining of memcpy and 1333 // friends. The overhead of a the function call, even when warm, can be 1334 // over one hundred cycles. 1335 MaxStoresPerMemset = 128; 1336 MaxStoresPerMemcpy = 128; 1337 MaxStoresPerMemmove = 128; 1338 MaxLoadsPerMemcmp = 128; 1339 } else { 1340 MaxLoadsPerMemcmp = 8; 1341 MaxLoadsPerMemcmpOptSize = 4; 1342 } 1343 1344 // Let the subtarget (CPU) decide if a predictable select is more expensive 1345 // than the corresponding branch. This information is used in CGP to decide 1346 // when to convert selects into branches. 1347 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1348 } 1349 1350 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1351 /// the desired ByVal argument alignment. 1352 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1353 unsigned MaxMaxAlign) { 1354 if (MaxAlign == MaxMaxAlign) 1355 return; 1356 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1357 if (MaxMaxAlign >= 32 && 1358 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1359 MaxAlign = 32; 1360 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1361 MaxAlign < 16) 1362 MaxAlign = 16; 1363 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1364 unsigned EltAlign = 0; 1365 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1366 if (EltAlign > MaxAlign) 1367 MaxAlign = EltAlign; 1368 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1369 for (auto *EltTy : STy->elements()) { 1370 unsigned EltAlign = 0; 1371 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1372 if (EltAlign > MaxAlign) 1373 MaxAlign = EltAlign; 1374 if (MaxAlign == MaxMaxAlign) 1375 break; 1376 } 1377 } 1378 } 1379 1380 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1381 /// function arguments in the caller parameter area. 1382 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1383 const DataLayout &DL) const { 1384 // 16byte and wider vectors are passed on 16byte boundary. 1385 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1386 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1387 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1388 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1389 return Align; 1390 } 1391 1392 bool PPCTargetLowering::useSoftFloat() const { 1393 return Subtarget.useSoftFloat(); 1394 } 1395 1396 bool PPCTargetLowering::hasSPE() const { 1397 return Subtarget.hasSPE(); 1398 } 1399 1400 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1401 return VT.isScalarInteger(); 1402 } 1403 1404 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1405 switch ((PPCISD::NodeType)Opcode) { 1406 case PPCISD::FIRST_NUMBER: break; 1407 case PPCISD::FSEL: return "PPCISD::FSEL"; 1408 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1409 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1410 case PPCISD::FCFID: return "PPCISD::FCFID"; 1411 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1412 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1413 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1414 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1415 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1416 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1417 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1418 case PPCISD::FP_TO_UINT_IN_VSR: 1419 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1420 case PPCISD::FP_TO_SINT_IN_VSR: 1421 return "PPCISD::FP_TO_SINT_IN_VSR"; 1422 case PPCISD::FRE: return "PPCISD::FRE"; 1423 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1424 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1425 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1426 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1427 case PPCISD::VPERM: return "PPCISD::VPERM"; 1428 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1429 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1430 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1431 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1432 case PPCISD::CMPB: return "PPCISD::CMPB"; 1433 case PPCISD::Hi: return "PPCISD::Hi"; 1434 case PPCISD::Lo: return "PPCISD::Lo"; 1435 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1436 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1437 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1438 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1439 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1440 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1441 case PPCISD::SRL: return "PPCISD::SRL"; 1442 case PPCISD::SRA: return "PPCISD::SRA"; 1443 case PPCISD::SHL: return "PPCISD::SHL"; 1444 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1445 case PPCISD::CALL: return "PPCISD::CALL"; 1446 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1447 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1448 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1449 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1450 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1451 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1452 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1453 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1454 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1455 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1456 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1457 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1458 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1459 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1460 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1461 case PPCISD::ANDI_rec_1_EQ_BIT: 1462 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1463 case PPCISD::ANDI_rec_1_GT_BIT: 1464 return "PPCISD::ANDI_rec_1_GT_BIT"; 1465 case PPCISD::VCMP: return "PPCISD::VCMP"; 1466 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1467 case PPCISD::LBRX: return "PPCISD::LBRX"; 1468 case PPCISD::STBRX: return "PPCISD::STBRX"; 1469 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1470 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1471 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1472 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1473 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1474 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1475 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1476 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1477 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1478 case PPCISD::ST_VSR_SCAL_INT: 1479 return "PPCISD::ST_VSR_SCAL_INT"; 1480 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1481 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1482 case PPCISD::BDZ: return "PPCISD::BDZ"; 1483 case PPCISD::MFFS: return "PPCISD::MFFS"; 1484 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1485 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1486 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1487 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1488 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1489 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1490 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1491 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1492 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1493 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1494 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1495 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1496 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1497 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1498 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1499 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1500 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1501 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1502 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1503 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1504 case PPCISD::SC: return "PPCISD::SC"; 1505 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1506 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1507 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1508 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1509 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1510 case PPCISD::VABSD: return "PPCISD::VABSD"; 1511 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1512 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1513 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1514 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1515 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1516 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1517 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1518 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1519 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1520 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1521 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1522 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1523 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1524 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1525 } 1526 return nullptr; 1527 } 1528 1529 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1530 EVT VT) const { 1531 if (!VT.isVector()) 1532 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1533 1534 if (Subtarget.hasQPX()) 1535 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1536 1537 return VT.changeVectorElementTypeToInteger(); 1538 } 1539 1540 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1541 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1542 return true; 1543 } 1544 1545 //===----------------------------------------------------------------------===// 1546 // Node matching predicates, for use by the tblgen matching code. 1547 //===----------------------------------------------------------------------===// 1548 1549 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1550 static bool isFloatingPointZero(SDValue Op) { 1551 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1552 return CFP->getValueAPF().isZero(); 1553 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1554 // Maybe this has already been legalized into the constant pool? 1555 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1556 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1557 return CFP->getValueAPF().isZero(); 1558 } 1559 return false; 1560 } 1561 1562 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1563 /// true if Op is undef or if it matches the specified value. 1564 static bool isConstantOrUndef(int Op, int Val) { 1565 return Op < 0 || Op == Val; 1566 } 1567 1568 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1569 /// VPKUHUM instruction. 1570 /// The ShuffleKind distinguishes between big-endian operations with 1571 /// two different inputs (0), either-endian operations with two identical 1572 /// inputs (1), and little-endian operations with two different inputs (2). 1573 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1574 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1575 SelectionDAG &DAG) { 1576 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1577 if (ShuffleKind == 0) { 1578 if (IsLE) 1579 return false; 1580 for (unsigned i = 0; i != 16; ++i) 1581 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1582 return false; 1583 } else if (ShuffleKind == 2) { 1584 if (!IsLE) 1585 return false; 1586 for (unsigned i = 0; i != 16; ++i) 1587 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1588 return false; 1589 } else if (ShuffleKind == 1) { 1590 unsigned j = IsLE ? 0 : 1; 1591 for (unsigned i = 0; i != 8; ++i) 1592 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1593 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1594 return false; 1595 } 1596 return true; 1597 } 1598 1599 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1600 /// VPKUWUM instruction. 1601 /// The ShuffleKind distinguishes between big-endian operations with 1602 /// two different inputs (0), either-endian operations with two identical 1603 /// inputs (1), and little-endian operations with two different inputs (2). 1604 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1605 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1606 SelectionDAG &DAG) { 1607 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1608 if (ShuffleKind == 0) { 1609 if (IsLE) 1610 return false; 1611 for (unsigned i = 0; i != 16; i += 2) 1612 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1613 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1614 return false; 1615 } else if (ShuffleKind == 2) { 1616 if (!IsLE) 1617 return false; 1618 for (unsigned i = 0; i != 16; i += 2) 1619 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1620 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1621 return false; 1622 } else if (ShuffleKind == 1) { 1623 unsigned j = IsLE ? 0 : 2; 1624 for (unsigned i = 0; i != 8; i += 2) 1625 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1626 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1627 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1628 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1629 return false; 1630 } 1631 return true; 1632 } 1633 1634 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1635 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1636 /// current subtarget. 1637 /// 1638 /// The ShuffleKind distinguishes between big-endian operations with 1639 /// two different inputs (0), either-endian operations with two identical 1640 /// inputs (1), and little-endian operations with two different inputs (2). 1641 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1642 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1643 SelectionDAG &DAG) { 1644 const PPCSubtarget& Subtarget = 1645 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1646 if (!Subtarget.hasP8Vector()) 1647 return false; 1648 1649 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1650 if (ShuffleKind == 0) { 1651 if (IsLE) 1652 return false; 1653 for (unsigned i = 0; i != 16; i += 4) 1654 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1655 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1656 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1657 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1658 return false; 1659 } else if (ShuffleKind == 2) { 1660 if (!IsLE) 1661 return false; 1662 for (unsigned i = 0; i != 16; i += 4) 1663 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1664 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1665 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1666 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1667 return false; 1668 } else if (ShuffleKind == 1) { 1669 unsigned j = IsLE ? 0 : 4; 1670 for (unsigned i = 0; i != 8; i += 4) 1671 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1672 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1673 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1674 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1675 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1676 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1677 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1678 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1679 return false; 1680 } 1681 return true; 1682 } 1683 1684 /// isVMerge - Common function, used to match vmrg* shuffles. 1685 /// 1686 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1687 unsigned LHSStart, unsigned RHSStart) { 1688 if (N->getValueType(0) != MVT::v16i8) 1689 return false; 1690 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1691 "Unsupported merge size!"); 1692 1693 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1694 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1695 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1696 LHSStart+j+i*UnitSize) || 1697 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1698 RHSStart+j+i*UnitSize)) 1699 return false; 1700 } 1701 return true; 1702 } 1703 1704 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1705 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1706 /// The ShuffleKind distinguishes between big-endian merges with two 1707 /// different inputs (0), either-endian merges with two identical inputs (1), 1708 /// and little-endian merges with two different inputs (2). For the latter, 1709 /// the input operands are swapped (see PPCInstrAltivec.td). 1710 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1711 unsigned ShuffleKind, SelectionDAG &DAG) { 1712 if (DAG.getDataLayout().isLittleEndian()) { 1713 if (ShuffleKind == 1) // unary 1714 return isVMerge(N, UnitSize, 0, 0); 1715 else if (ShuffleKind == 2) // swapped 1716 return isVMerge(N, UnitSize, 0, 16); 1717 else 1718 return false; 1719 } else { 1720 if (ShuffleKind == 1) // unary 1721 return isVMerge(N, UnitSize, 8, 8); 1722 else if (ShuffleKind == 0) // normal 1723 return isVMerge(N, UnitSize, 8, 24); 1724 else 1725 return false; 1726 } 1727 } 1728 1729 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1730 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1731 /// The ShuffleKind distinguishes between big-endian merges with two 1732 /// different inputs (0), either-endian merges with two identical inputs (1), 1733 /// and little-endian merges with two different inputs (2). For the latter, 1734 /// the input operands are swapped (see PPCInstrAltivec.td). 1735 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1736 unsigned ShuffleKind, SelectionDAG &DAG) { 1737 if (DAG.getDataLayout().isLittleEndian()) { 1738 if (ShuffleKind == 1) // unary 1739 return isVMerge(N, UnitSize, 8, 8); 1740 else if (ShuffleKind == 2) // swapped 1741 return isVMerge(N, UnitSize, 8, 24); 1742 else 1743 return false; 1744 } else { 1745 if (ShuffleKind == 1) // unary 1746 return isVMerge(N, UnitSize, 0, 0); 1747 else if (ShuffleKind == 0) // normal 1748 return isVMerge(N, UnitSize, 0, 16); 1749 else 1750 return false; 1751 } 1752 } 1753 1754 /** 1755 * Common function used to match vmrgew and vmrgow shuffles 1756 * 1757 * The indexOffset determines whether to look for even or odd words in 1758 * the shuffle mask. This is based on the of the endianness of the target 1759 * machine. 1760 * - Little Endian: 1761 * - Use offset of 0 to check for odd elements 1762 * - Use offset of 4 to check for even elements 1763 * - Big Endian: 1764 * - Use offset of 0 to check for even elements 1765 * - Use offset of 4 to check for odd elements 1766 * A detailed description of the vector element ordering for little endian and 1767 * big endian can be found at 1768 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1769 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1770 * compiler differences mean to you 1771 * 1772 * The mask to the shuffle vector instruction specifies the indices of the 1773 * elements from the two input vectors to place in the result. The elements are 1774 * numbered in array-access order, starting with the first vector. These vectors 1775 * are always of type v16i8, thus each vector will contain 16 elements of size 1776 * 8. More info on the shuffle vector can be found in the 1777 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1778 * Language Reference. 1779 * 1780 * The RHSStartValue indicates whether the same input vectors are used (unary) 1781 * or two different input vectors are used, based on the following: 1782 * - If the instruction uses the same vector for both inputs, the range of the 1783 * indices will be 0 to 15. In this case, the RHSStart value passed should 1784 * be 0. 1785 * - If the instruction has two different vectors then the range of the 1786 * indices will be 0 to 31. In this case, the RHSStart value passed should 1787 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1788 * to 31 specify elements in the second vector). 1789 * 1790 * \param[in] N The shuffle vector SD Node to analyze 1791 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1792 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1793 * vector to the shuffle_vector instruction 1794 * \return true iff this shuffle vector represents an even or odd word merge 1795 */ 1796 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1797 unsigned RHSStartValue) { 1798 if (N->getValueType(0) != MVT::v16i8) 1799 return false; 1800 1801 for (unsigned i = 0; i < 2; ++i) 1802 for (unsigned j = 0; j < 4; ++j) 1803 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1804 i*RHSStartValue+j+IndexOffset) || 1805 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1806 i*RHSStartValue+j+IndexOffset+8)) 1807 return false; 1808 return true; 1809 } 1810 1811 /** 1812 * Determine if the specified shuffle mask is suitable for the vmrgew or 1813 * vmrgow instructions. 1814 * 1815 * \param[in] N The shuffle vector SD Node to analyze 1816 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1817 * \param[in] ShuffleKind Identify the type of merge: 1818 * - 0 = big-endian merge with two different inputs; 1819 * - 1 = either-endian merge with two identical inputs; 1820 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1821 * little-endian merges). 1822 * \param[in] DAG The current SelectionDAG 1823 * \return true iff this shuffle mask 1824 */ 1825 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1826 unsigned ShuffleKind, SelectionDAG &DAG) { 1827 if (DAG.getDataLayout().isLittleEndian()) { 1828 unsigned indexOffset = CheckEven ? 4 : 0; 1829 if (ShuffleKind == 1) // Unary 1830 return isVMerge(N, indexOffset, 0); 1831 else if (ShuffleKind == 2) // swapped 1832 return isVMerge(N, indexOffset, 16); 1833 else 1834 return false; 1835 } 1836 else { 1837 unsigned indexOffset = CheckEven ? 0 : 4; 1838 if (ShuffleKind == 1) // Unary 1839 return isVMerge(N, indexOffset, 0); 1840 else if (ShuffleKind == 0) // Normal 1841 return isVMerge(N, indexOffset, 16); 1842 else 1843 return false; 1844 } 1845 return false; 1846 } 1847 1848 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1849 /// amount, otherwise return -1. 1850 /// The ShuffleKind distinguishes between big-endian operations with two 1851 /// different inputs (0), either-endian operations with two identical inputs 1852 /// (1), and little-endian operations with two different inputs (2). For the 1853 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1854 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1855 SelectionDAG &DAG) { 1856 if (N->getValueType(0) != MVT::v16i8) 1857 return -1; 1858 1859 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1860 1861 // Find the first non-undef value in the shuffle mask. 1862 unsigned i; 1863 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1864 /*search*/; 1865 1866 if (i == 16) return -1; // all undef. 1867 1868 // Otherwise, check to see if the rest of the elements are consecutively 1869 // numbered from this value. 1870 unsigned ShiftAmt = SVOp->getMaskElt(i); 1871 if (ShiftAmt < i) return -1; 1872 1873 ShiftAmt -= i; 1874 bool isLE = DAG.getDataLayout().isLittleEndian(); 1875 1876 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1877 // Check the rest of the elements to see if they are consecutive. 1878 for (++i; i != 16; ++i) 1879 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1880 return -1; 1881 } else if (ShuffleKind == 1) { 1882 // Check the rest of the elements to see if they are consecutive. 1883 for (++i; i != 16; ++i) 1884 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1885 return -1; 1886 } else 1887 return -1; 1888 1889 if (isLE) 1890 ShiftAmt = 16 - ShiftAmt; 1891 1892 return ShiftAmt; 1893 } 1894 1895 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1896 /// specifies a splat of a single element that is suitable for input to 1897 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1898 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1899 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1900 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1901 1902 // The consecutive indices need to specify an element, not part of two 1903 // different elements. So abandon ship early if this isn't the case. 1904 if (N->getMaskElt(0) % EltSize != 0) 1905 return false; 1906 1907 // This is a splat operation if each element of the permute is the same, and 1908 // if the value doesn't reference the second vector. 1909 unsigned ElementBase = N->getMaskElt(0); 1910 1911 // FIXME: Handle UNDEF elements too! 1912 if (ElementBase >= 16) 1913 return false; 1914 1915 // Check that the indices are consecutive, in the case of a multi-byte element 1916 // splatted with a v16i8 mask. 1917 for (unsigned i = 1; i != EltSize; ++i) 1918 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1919 return false; 1920 1921 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1922 if (N->getMaskElt(i) < 0) continue; 1923 for (unsigned j = 0; j != EltSize; ++j) 1924 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1925 return false; 1926 } 1927 return true; 1928 } 1929 1930 /// Check that the mask is shuffling N byte elements. Within each N byte 1931 /// element of the mask, the indices could be either in increasing or 1932 /// decreasing order as long as they are consecutive. 1933 /// \param[in] N the shuffle vector SD Node to analyze 1934 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1935 /// Word/DoubleWord/QuadWord). 1936 /// \param[in] StepLen the delta indices number among the N byte element, if 1937 /// the mask is in increasing/decreasing order then it is 1/-1. 1938 /// \return true iff the mask is shuffling N byte elements. 1939 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1940 int StepLen) { 1941 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1942 "Unexpected element width."); 1943 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1944 1945 unsigned NumOfElem = 16 / Width; 1946 unsigned MaskVal[16]; // Width is never greater than 16 1947 for (unsigned i = 0; i < NumOfElem; ++i) { 1948 MaskVal[0] = N->getMaskElt(i * Width); 1949 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1950 return false; 1951 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1952 return false; 1953 } 1954 1955 for (unsigned int j = 1; j < Width; ++j) { 1956 MaskVal[j] = N->getMaskElt(i * Width + j); 1957 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1958 return false; 1959 } 1960 } 1961 } 1962 1963 return true; 1964 } 1965 1966 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1967 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1968 if (!isNByteElemShuffleMask(N, 4, 1)) 1969 return false; 1970 1971 // Now we look at mask elements 0,4,8,12 1972 unsigned M0 = N->getMaskElt(0) / 4; 1973 unsigned M1 = N->getMaskElt(4) / 4; 1974 unsigned M2 = N->getMaskElt(8) / 4; 1975 unsigned M3 = N->getMaskElt(12) / 4; 1976 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1977 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1978 1979 // Below, let H and L be arbitrary elements of the shuffle mask 1980 // where H is in the range [4,7] and L is in the range [0,3]. 1981 // H, 1, 2, 3 or L, 5, 6, 7 1982 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1983 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1984 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1985 InsertAtByte = IsLE ? 12 : 0; 1986 Swap = M0 < 4; 1987 return true; 1988 } 1989 // 0, H, 2, 3 or 4, L, 6, 7 1990 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1991 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1992 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1993 InsertAtByte = IsLE ? 8 : 4; 1994 Swap = M1 < 4; 1995 return true; 1996 } 1997 // 0, 1, H, 3 or 4, 5, L, 7 1998 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1999 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2000 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2001 InsertAtByte = IsLE ? 4 : 8; 2002 Swap = M2 < 4; 2003 return true; 2004 } 2005 // 0, 1, 2, H or 4, 5, 6, L 2006 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2007 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2008 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2009 InsertAtByte = IsLE ? 0 : 12; 2010 Swap = M3 < 4; 2011 return true; 2012 } 2013 2014 // If both vector operands for the shuffle are the same vector, the mask will 2015 // contain only elements from the first one and the second one will be undef. 2016 if (N->getOperand(1).isUndef()) { 2017 ShiftElts = 0; 2018 Swap = true; 2019 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2020 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2021 InsertAtByte = IsLE ? 12 : 0; 2022 return true; 2023 } 2024 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2025 InsertAtByte = IsLE ? 8 : 4; 2026 return true; 2027 } 2028 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2029 InsertAtByte = IsLE ? 4 : 8; 2030 return true; 2031 } 2032 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2033 InsertAtByte = IsLE ? 0 : 12; 2034 return true; 2035 } 2036 } 2037 2038 return false; 2039 } 2040 2041 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2042 bool &Swap, bool IsLE) { 2043 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2044 // Ensure each byte index of the word is consecutive. 2045 if (!isNByteElemShuffleMask(N, 4, 1)) 2046 return false; 2047 2048 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2049 unsigned M0 = N->getMaskElt(0) / 4; 2050 unsigned M1 = N->getMaskElt(4) / 4; 2051 unsigned M2 = N->getMaskElt(8) / 4; 2052 unsigned M3 = N->getMaskElt(12) / 4; 2053 2054 // If both vector operands for the shuffle are the same vector, the mask will 2055 // contain only elements from the first one and the second one will be undef. 2056 if (N->getOperand(1).isUndef()) { 2057 assert(M0 < 4 && "Indexing into an undef vector?"); 2058 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2059 return false; 2060 2061 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2062 Swap = false; 2063 return true; 2064 } 2065 2066 // Ensure each word index of the ShuffleVector Mask is consecutive. 2067 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2068 return false; 2069 2070 if (IsLE) { 2071 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2072 // Input vectors don't need to be swapped if the leading element 2073 // of the result is one of the 3 left elements of the second vector 2074 // (or if there is no shift to be done at all). 2075 Swap = false; 2076 ShiftElts = (8 - M0) % 8; 2077 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2078 // Input vectors need to be swapped if the leading element 2079 // of the result is one of the 3 left elements of the first vector 2080 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2081 Swap = true; 2082 ShiftElts = (4 - M0) % 4; 2083 } 2084 2085 return true; 2086 } else { // BE 2087 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2088 // Input vectors don't need to be swapped if the leading element 2089 // of the result is one of the 4 elements of the first vector. 2090 Swap = false; 2091 ShiftElts = M0; 2092 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2093 // Input vectors need to be swapped if the leading element 2094 // of the result is one of the 4 elements of the right vector. 2095 Swap = true; 2096 ShiftElts = M0 - 4; 2097 } 2098 2099 return true; 2100 } 2101 } 2102 2103 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2104 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2105 2106 if (!isNByteElemShuffleMask(N, Width, -1)) 2107 return false; 2108 2109 for (int i = 0; i < 16; i += Width) 2110 if (N->getMaskElt(i) != i + Width - 1) 2111 return false; 2112 2113 return true; 2114 } 2115 2116 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2117 return isXXBRShuffleMaskHelper(N, 2); 2118 } 2119 2120 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2121 return isXXBRShuffleMaskHelper(N, 4); 2122 } 2123 2124 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2125 return isXXBRShuffleMaskHelper(N, 8); 2126 } 2127 2128 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2129 return isXXBRShuffleMaskHelper(N, 16); 2130 } 2131 2132 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2133 /// if the inputs to the instruction should be swapped and set \p DM to the 2134 /// value for the immediate. 2135 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2136 /// AND element 0 of the result comes from the first input (LE) or second input 2137 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2138 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2139 /// mask. 2140 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2141 bool &Swap, bool IsLE) { 2142 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2143 2144 // Ensure each byte index of the double word is consecutive. 2145 if (!isNByteElemShuffleMask(N, 8, 1)) 2146 return false; 2147 2148 unsigned M0 = N->getMaskElt(0) / 8; 2149 unsigned M1 = N->getMaskElt(8) / 8; 2150 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2151 2152 // If both vector operands for the shuffle are the same vector, the mask will 2153 // contain only elements from the first one and the second one will be undef. 2154 if (N->getOperand(1).isUndef()) { 2155 if ((M0 | M1) < 2) { 2156 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2157 Swap = false; 2158 return true; 2159 } else 2160 return false; 2161 } 2162 2163 if (IsLE) { 2164 if (M0 > 1 && M1 < 2) { 2165 Swap = false; 2166 } else if (M0 < 2 && M1 > 1) { 2167 M0 = (M0 + 2) % 4; 2168 M1 = (M1 + 2) % 4; 2169 Swap = true; 2170 } else 2171 return false; 2172 2173 // Note: if control flow comes here that means Swap is already set above 2174 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2175 return true; 2176 } else { // BE 2177 if (M0 < 2 && M1 > 1) { 2178 Swap = false; 2179 } else if (M0 > 1 && M1 < 2) { 2180 M0 = (M0 + 2) % 4; 2181 M1 = (M1 + 2) % 4; 2182 Swap = true; 2183 } else 2184 return false; 2185 2186 // Note: if control flow comes here that means Swap is already set above 2187 DM = (M0 << 1) + (M1 & 1); 2188 return true; 2189 } 2190 } 2191 2192 2193 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2194 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2195 /// elements are counted from the left of the vector register). 2196 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2197 SelectionDAG &DAG) { 2198 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2199 assert(isSplatShuffleMask(SVOp, EltSize)); 2200 if (DAG.getDataLayout().isLittleEndian()) 2201 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2202 else 2203 return SVOp->getMaskElt(0) / EltSize; 2204 } 2205 2206 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2207 /// by using a vspltis[bhw] instruction of the specified element size, return 2208 /// the constant being splatted. The ByteSize field indicates the number of 2209 /// bytes of each element [124] -> [bhw]. 2210 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2211 SDValue OpVal(nullptr, 0); 2212 2213 // If ByteSize of the splat is bigger than the element size of the 2214 // build_vector, then we have a case where we are checking for a splat where 2215 // multiple elements of the buildvector are folded together into a single 2216 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2217 unsigned EltSize = 16/N->getNumOperands(); 2218 if (EltSize < ByteSize) { 2219 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2220 SDValue UniquedVals[4]; 2221 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2222 2223 // See if all of the elements in the buildvector agree across. 2224 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2225 if (N->getOperand(i).isUndef()) continue; 2226 // If the element isn't a constant, bail fully out. 2227 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2228 2229 if (!UniquedVals[i&(Multiple-1)].getNode()) 2230 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2231 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2232 return SDValue(); // no match. 2233 } 2234 2235 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2236 // either constant or undef values that are identical for each chunk. See 2237 // if these chunks can form into a larger vspltis*. 2238 2239 // Check to see if all of the leading entries are either 0 or -1. If 2240 // neither, then this won't fit into the immediate field. 2241 bool LeadingZero = true; 2242 bool LeadingOnes = true; 2243 for (unsigned i = 0; i != Multiple-1; ++i) { 2244 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2245 2246 LeadingZero &= isNullConstant(UniquedVals[i]); 2247 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2248 } 2249 // Finally, check the least significant entry. 2250 if (LeadingZero) { 2251 if (!UniquedVals[Multiple-1].getNode()) 2252 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2253 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2254 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2255 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2256 } 2257 if (LeadingOnes) { 2258 if (!UniquedVals[Multiple-1].getNode()) 2259 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2260 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2261 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2262 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2263 } 2264 2265 return SDValue(); 2266 } 2267 2268 // Check to see if this buildvec has a single non-undef value in its elements. 2269 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2270 if (N->getOperand(i).isUndef()) continue; 2271 if (!OpVal.getNode()) 2272 OpVal = N->getOperand(i); 2273 else if (OpVal != N->getOperand(i)) 2274 return SDValue(); 2275 } 2276 2277 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2278 2279 unsigned ValSizeInBytes = EltSize; 2280 uint64_t Value = 0; 2281 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2282 Value = CN->getZExtValue(); 2283 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2284 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2285 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2286 } 2287 2288 // If the splat value is larger than the element value, then we can never do 2289 // this splat. The only case that we could fit the replicated bits into our 2290 // immediate field for would be zero, and we prefer to use vxor for it. 2291 if (ValSizeInBytes < ByteSize) return SDValue(); 2292 2293 // If the element value is larger than the splat value, check if it consists 2294 // of a repeated bit pattern of size ByteSize. 2295 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2296 return SDValue(); 2297 2298 // Properly sign extend the value. 2299 int MaskVal = SignExtend32(Value, ByteSize * 8); 2300 2301 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2302 if (MaskVal == 0) return SDValue(); 2303 2304 // Finally, if this value fits in a 5 bit sext field, return it 2305 if (SignExtend32<5>(MaskVal) == MaskVal) 2306 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2307 return SDValue(); 2308 } 2309 2310 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2311 /// amount, otherwise return -1. 2312 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2313 EVT VT = N->getValueType(0); 2314 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2315 return -1; 2316 2317 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2318 2319 // Find the first non-undef value in the shuffle mask. 2320 unsigned i; 2321 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2322 /*search*/; 2323 2324 if (i == 4) return -1; // all undef. 2325 2326 // Otherwise, check to see if the rest of the elements are consecutively 2327 // numbered from this value. 2328 unsigned ShiftAmt = SVOp->getMaskElt(i); 2329 if (ShiftAmt < i) return -1; 2330 ShiftAmt -= i; 2331 2332 // Check the rest of the elements to see if they are consecutive. 2333 for (++i; i != 4; ++i) 2334 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2335 return -1; 2336 2337 return ShiftAmt; 2338 } 2339 2340 //===----------------------------------------------------------------------===// 2341 // Addressing Mode Selection 2342 //===----------------------------------------------------------------------===// 2343 2344 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2345 /// or 64-bit immediate, and if the value can be accurately represented as a 2346 /// sign extension from a 16-bit value. If so, this returns true and the 2347 /// immediate. 2348 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2349 if (!isa<ConstantSDNode>(N)) 2350 return false; 2351 2352 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2353 if (N->getValueType(0) == MVT::i32) 2354 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2355 else 2356 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2357 } 2358 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2359 return isIntS16Immediate(Op.getNode(), Imm); 2360 } 2361 2362 2363 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2364 /// be represented as an indexed [r+r] operation. 2365 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2366 SDValue &Index, 2367 SelectionDAG &DAG) const { 2368 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2369 UI != E; ++UI) { 2370 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2371 if (Memop->getMemoryVT() == MVT::f64) { 2372 Base = N.getOperand(0); 2373 Index = N.getOperand(1); 2374 return true; 2375 } 2376 } 2377 } 2378 return false; 2379 } 2380 2381 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2382 /// can be represented as an indexed [r+r] operation. Returns false if it 2383 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2384 /// non-zero and N can be represented by a base register plus a signed 16-bit 2385 /// displacement, make a more precise judgement by checking (displacement % \p 2386 /// EncodingAlignment). 2387 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2388 SDValue &Index, SelectionDAG &DAG, 2389 unsigned EncodingAlignment) const { 2390 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2391 // a [pc+imm]. 2392 if (SelectAddressPCRel(N, Base)) 2393 return false; 2394 2395 int16_t imm = 0; 2396 if (N.getOpcode() == ISD::ADD) { 2397 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2398 // SPE load/store can only handle 8-bit offsets. 2399 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2400 return true; 2401 if (isIntS16Immediate(N.getOperand(1), imm) && 2402 (!EncodingAlignment || !(imm % EncodingAlignment))) 2403 return false; // r+i 2404 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2405 return false; // r+i 2406 2407 Base = N.getOperand(0); 2408 Index = N.getOperand(1); 2409 return true; 2410 } else if (N.getOpcode() == ISD::OR) { 2411 if (isIntS16Immediate(N.getOperand(1), imm) && 2412 (!EncodingAlignment || !(imm % EncodingAlignment))) 2413 return false; // r+i can fold it if we can. 2414 2415 // If this is an or of disjoint bitfields, we can codegen this as an add 2416 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2417 // disjoint. 2418 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2419 2420 if (LHSKnown.Zero.getBoolValue()) { 2421 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2422 // If all of the bits are known zero on the LHS or RHS, the add won't 2423 // carry. 2424 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2425 Base = N.getOperand(0); 2426 Index = N.getOperand(1); 2427 return true; 2428 } 2429 } 2430 } 2431 2432 return false; 2433 } 2434 2435 // If we happen to be doing an i64 load or store into a stack slot that has 2436 // less than a 4-byte alignment, then the frame-index elimination may need to 2437 // use an indexed load or store instruction (because the offset may not be a 2438 // multiple of 4). The extra register needed to hold the offset comes from the 2439 // register scavenger, and it is possible that the scavenger will need to use 2440 // an emergency spill slot. As a result, we need to make sure that a spill slot 2441 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2442 // stack slot. 2443 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2444 // FIXME: This does not handle the LWA case. 2445 if (VT != MVT::i64) 2446 return; 2447 2448 // NOTE: We'll exclude negative FIs here, which come from argument 2449 // lowering, because there are no known test cases triggering this problem 2450 // using packed structures (or similar). We can remove this exclusion if 2451 // we find such a test case. The reason why this is so test-case driven is 2452 // because this entire 'fixup' is only to prevent crashes (from the 2453 // register scavenger) on not-really-valid inputs. For example, if we have: 2454 // %a = alloca i1 2455 // %b = bitcast i1* %a to i64* 2456 // store i64* a, i64 b 2457 // then the store should really be marked as 'align 1', but is not. If it 2458 // were marked as 'align 1' then the indexed form would have been 2459 // instruction-selected initially, and the problem this 'fixup' is preventing 2460 // won't happen regardless. 2461 if (FrameIdx < 0) 2462 return; 2463 2464 MachineFunction &MF = DAG.getMachineFunction(); 2465 MachineFrameInfo &MFI = MF.getFrameInfo(); 2466 2467 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2468 return; 2469 2470 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2471 FuncInfo->setHasNonRISpills(); 2472 } 2473 2474 /// Returns true if the address N can be represented by a base register plus 2475 /// a signed 16-bit displacement [r+imm], and if it is not better 2476 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2477 /// displacements that are multiples of that value. 2478 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2479 SDValue &Base, 2480 SelectionDAG &DAG, 2481 unsigned EncodingAlignment) const { 2482 // FIXME dl should come from parent load or store, not from address 2483 SDLoc dl(N); 2484 2485 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2486 // a [pc+imm]. 2487 if (SelectAddressPCRel(N, Base)) 2488 return false; 2489 2490 // If this can be more profitably realized as r+r, fail. 2491 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2492 return false; 2493 2494 if (N.getOpcode() == ISD::ADD) { 2495 int16_t imm = 0; 2496 if (isIntS16Immediate(N.getOperand(1), imm) && 2497 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2498 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2499 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2500 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2501 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2502 } else { 2503 Base = N.getOperand(0); 2504 } 2505 return true; // [r+i] 2506 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2507 // Match LOAD (ADD (X, Lo(G))). 2508 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2509 && "Cannot handle constant offsets yet!"); 2510 Disp = N.getOperand(1).getOperand(0); // The global address. 2511 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2512 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2513 Disp.getOpcode() == ISD::TargetConstantPool || 2514 Disp.getOpcode() == ISD::TargetJumpTable); 2515 Base = N.getOperand(0); 2516 return true; // [&g+r] 2517 } 2518 } else if (N.getOpcode() == ISD::OR) { 2519 int16_t imm = 0; 2520 if (isIntS16Immediate(N.getOperand(1), imm) && 2521 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2522 // If this is an or of disjoint bitfields, we can codegen this as an add 2523 // (for better address arithmetic) if the LHS and RHS of the OR are 2524 // provably disjoint. 2525 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2526 2527 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2528 // If all of the bits are known zero on the LHS or RHS, the add won't 2529 // carry. 2530 if (FrameIndexSDNode *FI = 2531 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2532 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2533 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2534 } else { 2535 Base = N.getOperand(0); 2536 } 2537 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2538 return true; 2539 } 2540 } 2541 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2542 // Loading from a constant address. 2543 2544 // If this address fits entirely in a 16-bit sext immediate field, codegen 2545 // this as "d, 0" 2546 int16_t Imm; 2547 if (isIntS16Immediate(CN, Imm) && 2548 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2549 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2550 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2551 CN->getValueType(0)); 2552 return true; 2553 } 2554 2555 // Handle 32-bit sext immediates with LIS + addr mode. 2556 if ((CN->getValueType(0) == MVT::i32 || 2557 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2558 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2559 int Addr = (int)CN->getZExtValue(); 2560 2561 // Otherwise, break this down into an LIS + disp. 2562 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2563 2564 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2565 MVT::i32); 2566 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2567 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2568 return true; 2569 } 2570 } 2571 2572 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2573 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2574 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2575 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2576 } else 2577 Base = N; 2578 return true; // [r+0] 2579 } 2580 2581 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2582 /// represented as an indexed [r+r] operation. 2583 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2584 SDValue &Index, 2585 SelectionDAG &DAG) const { 2586 // Check to see if we can easily represent this as an [r+r] address. This 2587 // will fail if it thinks that the address is more profitably represented as 2588 // reg+imm, e.g. where imm = 0. 2589 if (SelectAddressRegReg(N, Base, Index, DAG)) 2590 return true; 2591 2592 // If the address is the result of an add, we will utilize the fact that the 2593 // address calculation includes an implicit add. However, we can reduce 2594 // register pressure if we do not materialize a constant just for use as the 2595 // index register. We only get rid of the add if it is not an add of a 2596 // value and a 16-bit signed constant and both have a single use. 2597 int16_t imm = 0; 2598 if (N.getOpcode() == ISD::ADD && 2599 (!isIntS16Immediate(N.getOperand(1), imm) || 2600 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2601 Base = N.getOperand(0); 2602 Index = N.getOperand(1); 2603 return true; 2604 } 2605 2606 // Otherwise, do it the hard way, using R0 as the base register. 2607 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2608 N.getValueType()); 2609 Index = N; 2610 return true; 2611 } 2612 2613 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2614 Ty *PCRelCand = dyn_cast<Ty>(N); 2615 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2616 } 2617 2618 /// Returns true if this address is a PC Relative address. 2619 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2620 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2621 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2622 // This is a materialize PC Relative node. Always select this as PC Relative. 2623 Base = N; 2624 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2625 return true; 2626 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2627 isValidPCRelNode<GlobalAddressSDNode>(N) || 2628 isValidPCRelNode<JumpTableSDNode>(N) || 2629 isValidPCRelNode<BlockAddressSDNode>(N)) 2630 return true; 2631 return false; 2632 } 2633 2634 /// Returns true if we should use a direct load into vector instruction 2635 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2636 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2637 2638 // If there are any other uses other than scalar to vector, then we should 2639 // keep it as a scalar load -> direct move pattern to prevent multiple 2640 // loads. 2641 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2642 if (!LD) 2643 return false; 2644 2645 EVT MemVT = LD->getMemoryVT(); 2646 if (!MemVT.isSimple()) 2647 return false; 2648 switch(MemVT.getSimpleVT().SimpleTy) { 2649 case MVT::i64: 2650 break; 2651 case MVT::i32: 2652 if (!ST.hasP8Vector()) 2653 return false; 2654 break; 2655 case MVT::i16: 2656 case MVT::i8: 2657 if (!ST.hasP9Vector()) 2658 return false; 2659 break; 2660 default: 2661 return false; 2662 } 2663 2664 SDValue LoadedVal(N, 0); 2665 if (!LoadedVal.hasOneUse()) 2666 return false; 2667 2668 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2669 UI != UE; ++UI) 2670 if (UI.getUse().get().getResNo() == 0 && 2671 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2672 return false; 2673 2674 return true; 2675 } 2676 2677 /// getPreIndexedAddressParts - returns true by value, base pointer and 2678 /// offset pointer and addressing mode by reference if the node's address 2679 /// can be legally represented as pre-indexed load / store address. 2680 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2681 SDValue &Offset, 2682 ISD::MemIndexedMode &AM, 2683 SelectionDAG &DAG) const { 2684 if (DisablePPCPreinc) return false; 2685 2686 bool isLoad = true; 2687 SDValue Ptr; 2688 EVT VT; 2689 unsigned Alignment; 2690 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2691 Ptr = LD->getBasePtr(); 2692 VT = LD->getMemoryVT(); 2693 Alignment = LD->getAlignment(); 2694 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2695 Ptr = ST->getBasePtr(); 2696 VT = ST->getMemoryVT(); 2697 Alignment = ST->getAlignment(); 2698 isLoad = false; 2699 } else 2700 return false; 2701 2702 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2703 // instructions because we can fold these into a more efficient instruction 2704 // instead, (such as LXSD). 2705 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2706 return false; 2707 } 2708 2709 // PowerPC doesn't have preinc load/store instructions for vectors (except 2710 // for QPX, which does have preinc r+r forms). 2711 if (VT.isVector()) { 2712 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2713 return false; 2714 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2715 AM = ISD::PRE_INC; 2716 return true; 2717 } 2718 } 2719 2720 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2721 // Common code will reject creating a pre-inc form if the base pointer 2722 // is a frame index, or if N is a store and the base pointer is either 2723 // the same as or a predecessor of the value being stored. Check for 2724 // those situations here, and try with swapped Base/Offset instead. 2725 bool Swap = false; 2726 2727 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2728 Swap = true; 2729 else if (!isLoad) { 2730 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2731 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2732 Swap = true; 2733 } 2734 2735 if (Swap) 2736 std::swap(Base, Offset); 2737 2738 AM = ISD::PRE_INC; 2739 return true; 2740 } 2741 2742 // LDU/STU can only handle immediates that are a multiple of 4. 2743 if (VT != MVT::i64) { 2744 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2745 return false; 2746 } else { 2747 // LDU/STU need an address with at least 4-byte alignment. 2748 if (Alignment < 4) 2749 return false; 2750 2751 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2752 return false; 2753 } 2754 2755 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2756 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2757 // sext i32 to i64 when addr mode is r+i. 2758 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2759 LD->getExtensionType() == ISD::SEXTLOAD && 2760 isa<ConstantSDNode>(Offset)) 2761 return false; 2762 } 2763 2764 AM = ISD::PRE_INC; 2765 return true; 2766 } 2767 2768 //===----------------------------------------------------------------------===// 2769 // LowerOperation implementation 2770 //===----------------------------------------------------------------------===// 2771 2772 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2773 /// and LoOpFlags to the target MO flags. 2774 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2775 unsigned &HiOpFlags, unsigned &LoOpFlags, 2776 const GlobalValue *GV = nullptr) { 2777 HiOpFlags = PPCII::MO_HA; 2778 LoOpFlags = PPCII::MO_LO; 2779 2780 // Don't use the pic base if not in PIC relocation model. 2781 if (IsPIC) { 2782 HiOpFlags |= PPCII::MO_PIC_FLAG; 2783 LoOpFlags |= PPCII::MO_PIC_FLAG; 2784 } 2785 } 2786 2787 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2788 SelectionDAG &DAG) { 2789 SDLoc DL(HiPart); 2790 EVT PtrVT = HiPart.getValueType(); 2791 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2792 2793 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2794 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2795 2796 // With PIC, the first instruction is actually "GR+hi(&G)". 2797 if (isPIC) 2798 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2799 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2800 2801 // Generate non-pic code that has direct accesses to the constant pool. 2802 // The address of the global is just (hi(&g)+lo(&g)). 2803 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2804 } 2805 2806 static void setUsesTOCBasePtr(MachineFunction &MF) { 2807 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2808 FuncInfo->setUsesTOCBasePtr(); 2809 } 2810 2811 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2812 setUsesTOCBasePtr(DAG.getMachineFunction()); 2813 } 2814 2815 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2816 SDValue GA) const { 2817 const bool Is64Bit = Subtarget.isPPC64(); 2818 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2819 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2820 : Subtarget.isAIXABI() 2821 ? DAG.getRegister(PPC::R2, VT) 2822 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2823 SDValue Ops[] = { GA, Reg }; 2824 return DAG.getMemIntrinsicNode( 2825 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2826 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2827 MachineMemOperand::MOLoad); 2828 } 2829 2830 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2831 SelectionDAG &DAG) const { 2832 EVT PtrVT = Op.getValueType(); 2833 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2834 const Constant *C = CP->getConstVal(); 2835 2836 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2837 // The actual address of the GlobalValue is stored in the TOC. 2838 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2839 if (Subtarget.isUsingPCRelativeCalls()) { 2840 SDLoc DL(CP); 2841 EVT Ty = getPointerTy(DAG.getDataLayout()); 2842 SDValue ConstPool = DAG.getTargetConstantPool( 2843 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2844 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2845 } 2846 setUsesTOCBasePtr(DAG); 2847 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2848 return getTOCEntry(DAG, SDLoc(CP), GA); 2849 } 2850 2851 unsigned MOHiFlag, MOLoFlag; 2852 bool IsPIC = isPositionIndependent(); 2853 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2854 2855 if (IsPIC && Subtarget.isSVR4ABI()) { 2856 SDValue GA = 2857 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2858 return getTOCEntry(DAG, SDLoc(CP), GA); 2859 } 2860 2861 SDValue CPIHi = 2862 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2863 SDValue CPILo = 2864 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2865 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2866 } 2867 2868 // For 64-bit PowerPC, prefer the more compact relative encodings. 2869 // This trades 32 bits per jump table entry for one or two instructions 2870 // on the jump site. 2871 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2872 if (isJumpTableRelative()) 2873 return MachineJumpTableInfo::EK_LabelDifference32; 2874 2875 return TargetLowering::getJumpTableEncoding(); 2876 } 2877 2878 bool PPCTargetLowering::isJumpTableRelative() const { 2879 if (UseAbsoluteJumpTables) 2880 return false; 2881 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2882 return true; 2883 return TargetLowering::isJumpTableRelative(); 2884 } 2885 2886 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2887 SelectionDAG &DAG) const { 2888 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2889 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2890 2891 switch (getTargetMachine().getCodeModel()) { 2892 case CodeModel::Small: 2893 case CodeModel::Medium: 2894 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2895 default: 2896 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2897 getPointerTy(DAG.getDataLayout())); 2898 } 2899 } 2900 2901 const MCExpr * 2902 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2903 unsigned JTI, 2904 MCContext &Ctx) const { 2905 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2906 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2907 2908 switch (getTargetMachine().getCodeModel()) { 2909 case CodeModel::Small: 2910 case CodeModel::Medium: 2911 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2912 default: 2913 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2914 } 2915 } 2916 2917 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2918 EVT PtrVT = Op.getValueType(); 2919 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2920 2921 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2922 if (Subtarget.isUsingPCRelativeCalls()) { 2923 SDLoc DL(JT); 2924 EVT Ty = getPointerTy(DAG.getDataLayout()); 2925 SDValue GA = 2926 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2927 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2928 return MatAddr; 2929 } 2930 2931 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2932 // The actual address of the GlobalValue is stored in the TOC. 2933 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2934 setUsesTOCBasePtr(DAG); 2935 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2936 return getTOCEntry(DAG, SDLoc(JT), GA); 2937 } 2938 2939 unsigned MOHiFlag, MOLoFlag; 2940 bool IsPIC = isPositionIndependent(); 2941 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2942 2943 if (IsPIC && Subtarget.isSVR4ABI()) { 2944 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2945 PPCII::MO_PIC_FLAG); 2946 return getTOCEntry(DAG, SDLoc(GA), GA); 2947 } 2948 2949 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2950 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2951 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2952 } 2953 2954 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2955 SelectionDAG &DAG) const { 2956 EVT PtrVT = Op.getValueType(); 2957 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2958 const BlockAddress *BA = BASDN->getBlockAddress(); 2959 2960 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2961 if (Subtarget.isUsingPCRelativeCalls()) { 2962 SDLoc DL(BASDN); 2963 EVT Ty = getPointerTy(DAG.getDataLayout()); 2964 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2965 PPCII::MO_PCREL_FLAG); 2966 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2967 return MatAddr; 2968 } 2969 2970 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2971 // The actual BlockAddress is stored in the TOC. 2972 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2973 setUsesTOCBasePtr(DAG); 2974 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2975 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2976 } 2977 2978 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2979 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2980 return getTOCEntry( 2981 DAG, SDLoc(BASDN), 2982 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2983 2984 unsigned MOHiFlag, MOLoFlag; 2985 bool IsPIC = isPositionIndependent(); 2986 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2987 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2988 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2989 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2990 } 2991 2992 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2993 SelectionDAG &DAG) const { 2994 // FIXME: TLS addresses currently use medium model code sequences, 2995 // which is the most useful form. Eventually support for small and 2996 // large models could be added if users need it, at the cost of 2997 // additional complexity. 2998 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2999 if (DAG.getTarget().useEmulatedTLS()) 3000 return LowerToTLSEmulatedModel(GA, DAG); 3001 3002 SDLoc dl(GA); 3003 const GlobalValue *GV = GA->getGlobal(); 3004 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3005 bool is64bit = Subtarget.isPPC64(); 3006 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3007 PICLevel::Level picLevel = M->getPICLevel(); 3008 3009 const TargetMachine &TM = getTargetMachine(); 3010 TLSModel::Model Model = TM.getTLSModel(GV); 3011 3012 if (Model == TLSModel::LocalExec) { 3013 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3014 PPCII::MO_TPREL_HA); 3015 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3016 PPCII::MO_TPREL_LO); 3017 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3018 : DAG.getRegister(PPC::R2, MVT::i32); 3019 3020 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3021 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3022 } 3023 3024 if (Model == TLSModel::InitialExec) { 3025 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3026 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3027 PPCII::MO_TLS); 3028 SDValue GOTPtr; 3029 if (is64bit) { 3030 setUsesTOCBasePtr(DAG); 3031 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3032 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 3033 PtrVT, GOTReg, TGA); 3034 } else { 3035 if (!TM.isPositionIndependent()) 3036 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3037 else if (picLevel == PICLevel::SmallPIC) 3038 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3039 else 3040 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3041 } 3042 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 3043 PtrVT, TGA, GOTPtr); 3044 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3045 } 3046 3047 if (Model == TLSModel::GeneralDynamic) { 3048 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3049 SDValue GOTPtr; 3050 if (is64bit) { 3051 setUsesTOCBasePtr(DAG); 3052 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3053 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3054 GOTReg, TGA); 3055 } else { 3056 if (picLevel == PICLevel::SmallPIC) 3057 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3058 else 3059 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3060 } 3061 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3062 GOTPtr, TGA, TGA); 3063 } 3064 3065 if (Model == TLSModel::LocalDynamic) { 3066 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3067 SDValue GOTPtr; 3068 if (is64bit) { 3069 setUsesTOCBasePtr(DAG); 3070 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3071 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3072 GOTReg, TGA); 3073 } else { 3074 if (picLevel == PICLevel::SmallPIC) 3075 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3076 else 3077 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3078 } 3079 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3080 PtrVT, GOTPtr, TGA, TGA); 3081 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3082 PtrVT, TLSAddr, TGA); 3083 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3084 } 3085 3086 llvm_unreachable("Unknown TLS model!"); 3087 } 3088 3089 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3090 SelectionDAG &DAG) const { 3091 EVT PtrVT = Op.getValueType(); 3092 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3093 SDLoc DL(GSDN); 3094 const GlobalValue *GV = GSDN->getGlobal(); 3095 3096 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3097 // The actual address of the GlobalValue is stored in the TOC. 3098 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3099 if (Subtarget.isUsingPCRelativeCalls()) { 3100 EVT Ty = getPointerTy(DAG.getDataLayout()); 3101 if (isAccessedAsGotIndirect(Op)) { 3102 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3103 PPCII::MO_PCREL_FLAG | 3104 PPCII::MO_GOT_FLAG); 3105 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3106 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3107 MachinePointerInfo()); 3108 return Load; 3109 } else { 3110 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3111 PPCII::MO_PCREL_FLAG); 3112 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3113 } 3114 } 3115 setUsesTOCBasePtr(DAG); 3116 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3117 return getTOCEntry(DAG, DL, GA); 3118 } 3119 3120 unsigned MOHiFlag, MOLoFlag; 3121 bool IsPIC = isPositionIndependent(); 3122 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3123 3124 if (IsPIC && Subtarget.isSVR4ABI()) { 3125 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3126 GSDN->getOffset(), 3127 PPCII::MO_PIC_FLAG); 3128 return getTOCEntry(DAG, DL, GA); 3129 } 3130 3131 SDValue GAHi = 3132 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3133 SDValue GALo = 3134 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3135 3136 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3137 } 3138 3139 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3140 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3141 SDLoc dl(Op); 3142 3143 if (Op.getValueType() == MVT::v2i64) { 3144 // When the operands themselves are v2i64 values, we need to do something 3145 // special because VSX has no underlying comparison operations for these. 3146 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3147 // Equality can be handled by casting to the legal type for Altivec 3148 // comparisons, everything else needs to be expanded. 3149 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3150 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3151 DAG.getSetCC(dl, MVT::v4i32, 3152 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3153 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3154 CC)); 3155 } 3156 3157 return SDValue(); 3158 } 3159 3160 // We handle most of these in the usual way. 3161 return Op; 3162 } 3163 3164 // If we're comparing for equality to zero, expose the fact that this is 3165 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3166 // fold the new nodes. 3167 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3168 return V; 3169 3170 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3171 // Leave comparisons against 0 and -1 alone for now, since they're usually 3172 // optimized. FIXME: revisit this when we can custom lower all setcc 3173 // optimizations. 3174 if (C->isAllOnesValue() || C->isNullValue()) 3175 return SDValue(); 3176 } 3177 3178 // If we have an integer seteq/setne, turn it into a compare against zero 3179 // by xor'ing the rhs with the lhs, which is faster than setting a 3180 // condition register, reading it back out, and masking the correct bit. The 3181 // normal approach here uses sub to do this instead of xor. Using xor exposes 3182 // the result to other bit-twiddling opportunities. 3183 EVT LHSVT = Op.getOperand(0).getValueType(); 3184 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3185 EVT VT = Op.getValueType(); 3186 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3187 Op.getOperand(1)); 3188 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3189 } 3190 return SDValue(); 3191 } 3192 3193 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3194 SDNode *Node = Op.getNode(); 3195 EVT VT = Node->getValueType(0); 3196 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3197 SDValue InChain = Node->getOperand(0); 3198 SDValue VAListPtr = Node->getOperand(1); 3199 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3200 SDLoc dl(Node); 3201 3202 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3203 3204 // gpr_index 3205 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3206 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3207 InChain = GprIndex.getValue(1); 3208 3209 if (VT == MVT::i64) { 3210 // Check if GprIndex is even 3211 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3212 DAG.getConstant(1, dl, MVT::i32)); 3213 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3214 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3215 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3216 DAG.getConstant(1, dl, MVT::i32)); 3217 // Align GprIndex to be even if it isn't 3218 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3219 GprIndex); 3220 } 3221 3222 // fpr index is 1 byte after gpr 3223 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3224 DAG.getConstant(1, dl, MVT::i32)); 3225 3226 // fpr 3227 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3228 FprPtr, MachinePointerInfo(SV), MVT::i8); 3229 InChain = FprIndex.getValue(1); 3230 3231 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3232 DAG.getConstant(8, dl, MVT::i32)); 3233 3234 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3235 DAG.getConstant(4, dl, MVT::i32)); 3236 3237 // areas 3238 SDValue OverflowArea = 3239 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3240 InChain = OverflowArea.getValue(1); 3241 3242 SDValue RegSaveArea = 3243 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3244 InChain = RegSaveArea.getValue(1); 3245 3246 // select overflow_area if index > 8 3247 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3248 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3249 3250 // adjustment constant gpr_index * 4/8 3251 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3252 VT.isInteger() ? GprIndex : FprIndex, 3253 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3254 MVT::i32)); 3255 3256 // OurReg = RegSaveArea + RegConstant 3257 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3258 RegConstant); 3259 3260 // Floating types are 32 bytes into RegSaveArea 3261 if (VT.isFloatingPoint()) 3262 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3263 DAG.getConstant(32, dl, MVT::i32)); 3264 3265 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3266 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3267 VT.isInteger() ? GprIndex : FprIndex, 3268 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3269 MVT::i32)); 3270 3271 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3272 VT.isInteger() ? VAListPtr : FprPtr, 3273 MachinePointerInfo(SV), MVT::i8); 3274 3275 // determine if we should load from reg_save_area or overflow_area 3276 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3277 3278 // increase overflow_area by 4/8 if gpr/fpr > 8 3279 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3280 DAG.getConstant(VT.isInteger() ? 4 : 8, 3281 dl, MVT::i32)); 3282 3283 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3284 OverflowAreaPlusN); 3285 3286 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3287 MachinePointerInfo(), MVT::i32); 3288 3289 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3290 } 3291 3292 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3293 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3294 3295 // We have to copy the entire va_list struct: 3296 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3297 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3298 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3299 false, true, false, MachinePointerInfo(), 3300 MachinePointerInfo()); 3301 } 3302 3303 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3304 SelectionDAG &DAG) const { 3305 if (Subtarget.isAIXABI()) 3306 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3307 3308 return Op.getOperand(0); 3309 } 3310 3311 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3312 SelectionDAG &DAG) const { 3313 if (Subtarget.isAIXABI()) 3314 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3315 3316 SDValue Chain = Op.getOperand(0); 3317 SDValue Trmp = Op.getOperand(1); // trampoline 3318 SDValue FPtr = Op.getOperand(2); // nested function 3319 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3320 SDLoc dl(Op); 3321 3322 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3323 bool isPPC64 = (PtrVT == MVT::i64); 3324 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3325 3326 TargetLowering::ArgListTy Args; 3327 TargetLowering::ArgListEntry Entry; 3328 3329 Entry.Ty = IntPtrTy; 3330 Entry.Node = Trmp; Args.push_back(Entry); 3331 3332 // TrampSize == (isPPC64 ? 48 : 40); 3333 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3334 isPPC64 ? MVT::i64 : MVT::i32); 3335 Args.push_back(Entry); 3336 3337 Entry.Node = FPtr; Args.push_back(Entry); 3338 Entry.Node = Nest; Args.push_back(Entry); 3339 3340 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3341 TargetLowering::CallLoweringInfo CLI(DAG); 3342 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3343 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3344 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3345 3346 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3347 return CallResult.second; 3348 } 3349 3350 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3351 MachineFunction &MF = DAG.getMachineFunction(); 3352 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3353 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3354 3355 SDLoc dl(Op); 3356 3357 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3358 // vastart just stores the address of the VarArgsFrameIndex slot into the 3359 // memory location argument. 3360 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3361 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3362 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3363 MachinePointerInfo(SV)); 3364 } 3365 3366 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3367 // We suppose the given va_list is already allocated. 3368 // 3369 // typedef struct { 3370 // char gpr; /* index into the array of 8 GPRs 3371 // * stored in the register save area 3372 // * gpr=0 corresponds to r3, 3373 // * gpr=1 to r4, etc. 3374 // */ 3375 // char fpr; /* index into the array of 8 FPRs 3376 // * stored in the register save area 3377 // * fpr=0 corresponds to f1, 3378 // * fpr=1 to f2, etc. 3379 // */ 3380 // char *overflow_arg_area; 3381 // /* location on stack that holds 3382 // * the next overflow argument 3383 // */ 3384 // char *reg_save_area; 3385 // /* where r3:r10 and f1:f8 (if saved) 3386 // * are stored 3387 // */ 3388 // } va_list[1]; 3389 3390 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3391 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3392 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3393 PtrVT); 3394 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3395 PtrVT); 3396 3397 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3398 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3399 3400 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3401 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3402 3403 uint64_t FPROffset = 1; 3404 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3405 3406 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3407 3408 // Store first byte : number of int regs 3409 SDValue firstStore = 3410 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3411 MachinePointerInfo(SV), MVT::i8); 3412 uint64_t nextOffset = FPROffset; 3413 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3414 ConstFPROffset); 3415 3416 // Store second byte : number of float regs 3417 SDValue secondStore = 3418 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3419 MachinePointerInfo(SV, nextOffset), MVT::i8); 3420 nextOffset += StackOffset; 3421 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3422 3423 // Store second word : arguments given on stack 3424 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3425 MachinePointerInfo(SV, nextOffset)); 3426 nextOffset += FrameOffset; 3427 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3428 3429 // Store third word : arguments given in registers 3430 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3431 MachinePointerInfo(SV, nextOffset)); 3432 } 3433 3434 /// FPR - The set of FP registers that should be allocated for arguments 3435 /// on Darwin and AIX. 3436 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3437 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3438 PPC::F11, PPC::F12, PPC::F13}; 3439 3440 /// QFPR - The set of QPX registers that should be allocated for arguments. 3441 static const MCPhysReg QFPR[] = { 3442 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3443 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3444 3445 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3446 /// the stack. 3447 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3448 unsigned PtrByteSize) { 3449 unsigned ArgSize = ArgVT.getStoreSize(); 3450 if (Flags.isByVal()) 3451 ArgSize = Flags.getByValSize(); 3452 3453 // Round up to multiples of the pointer size, except for array members, 3454 // which are always packed. 3455 if (!Flags.isInConsecutiveRegs()) 3456 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3457 3458 return ArgSize; 3459 } 3460 3461 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3462 /// on the stack. 3463 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3464 ISD::ArgFlagsTy Flags, 3465 unsigned PtrByteSize) { 3466 Align Alignment(PtrByteSize); 3467 3468 // Altivec parameters are padded to a 16 byte boundary. 3469 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3470 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3471 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3472 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3473 Alignment = Align(16); 3474 // QPX vector types stored in double-precision are padded to a 32 byte 3475 // boundary. 3476 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3477 Alignment = Align(32); 3478 3479 // ByVal parameters are aligned as requested. 3480 if (Flags.isByVal()) { 3481 auto BVAlign = Flags.getNonZeroByValAlign(); 3482 if (BVAlign > PtrByteSize) { 3483 if (BVAlign.value() % PtrByteSize != 0) 3484 llvm_unreachable( 3485 "ByVal alignment is not a multiple of the pointer size"); 3486 3487 Alignment = BVAlign; 3488 } 3489 } 3490 3491 // Array members are always packed to their original alignment. 3492 if (Flags.isInConsecutiveRegs()) { 3493 // If the array member was split into multiple registers, the first 3494 // needs to be aligned to the size of the full type. (Except for 3495 // ppcf128, which is only aligned as its f64 components.) 3496 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3497 Alignment = Align(OrigVT.getStoreSize()); 3498 else 3499 Alignment = Align(ArgVT.getStoreSize()); 3500 } 3501 3502 return Alignment; 3503 } 3504 3505 /// CalculateStackSlotUsed - Return whether this argument will use its 3506 /// stack slot (instead of being passed in registers). ArgOffset, 3507 /// AvailableFPRs, and AvailableVRs must hold the current argument 3508 /// position, and will be updated to account for this argument. 3509 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3510 ISD::ArgFlagsTy Flags, 3511 unsigned PtrByteSize, 3512 unsigned LinkageSize, 3513 unsigned ParamAreaSize, 3514 unsigned &ArgOffset, 3515 unsigned &AvailableFPRs, 3516 unsigned &AvailableVRs, bool HasQPX) { 3517 bool UseMemory = false; 3518 3519 // Respect alignment of argument on the stack. 3520 Align Alignment = 3521 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3522 ArgOffset = alignTo(ArgOffset, Alignment); 3523 // If there's no space left in the argument save area, we must 3524 // use memory (this check also catches zero-sized arguments). 3525 if (ArgOffset >= LinkageSize + ParamAreaSize) 3526 UseMemory = true; 3527 3528 // Allocate argument on the stack. 3529 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3530 if (Flags.isInConsecutiveRegsLast()) 3531 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3532 // If we overran the argument save area, we must use memory 3533 // (this check catches arguments passed partially in memory) 3534 if (ArgOffset > LinkageSize + ParamAreaSize) 3535 UseMemory = true; 3536 3537 // However, if the argument is actually passed in an FPR or a VR, 3538 // we don't use memory after all. 3539 if (!Flags.isByVal()) { 3540 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3541 // QPX registers overlap with the scalar FP registers. 3542 (HasQPX && (ArgVT == MVT::v4f32 || 3543 ArgVT == MVT::v4f64 || 3544 ArgVT == MVT::v4i1))) 3545 if (AvailableFPRs > 0) { 3546 --AvailableFPRs; 3547 return false; 3548 } 3549 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3550 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3551 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3552 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3553 if (AvailableVRs > 0) { 3554 --AvailableVRs; 3555 return false; 3556 } 3557 } 3558 3559 return UseMemory; 3560 } 3561 3562 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3563 /// ensure minimum alignment required for target. 3564 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3565 unsigned NumBytes) { 3566 return alignTo(NumBytes, Lowering->getStackAlign()); 3567 } 3568 3569 SDValue PPCTargetLowering::LowerFormalArguments( 3570 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3571 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3572 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3573 if (Subtarget.isAIXABI()) 3574 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3575 InVals); 3576 if (Subtarget.is64BitELFABI()) 3577 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3578 InVals); 3579 if (Subtarget.is32BitELFABI()) 3580 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3581 InVals); 3582 3583 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3584 InVals); 3585 } 3586 3587 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3588 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3589 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3590 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3591 3592 // 32-bit SVR4 ABI Stack Frame Layout: 3593 // +-----------------------------------+ 3594 // +--> | Back chain | 3595 // | +-----------------------------------+ 3596 // | | Floating-point register save area | 3597 // | +-----------------------------------+ 3598 // | | General register save area | 3599 // | +-----------------------------------+ 3600 // | | CR save word | 3601 // | +-----------------------------------+ 3602 // | | VRSAVE save word | 3603 // | +-----------------------------------+ 3604 // | | Alignment padding | 3605 // | +-----------------------------------+ 3606 // | | Vector register save area | 3607 // | +-----------------------------------+ 3608 // | | Local variable space | 3609 // | +-----------------------------------+ 3610 // | | Parameter list area | 3611 // | +-----------------------------------+ 3612 // | | LR save word | 3613 // | +-----------------------------------+ 3614 // SP--> +--- | Back chain | 3615 // +-----------------------------------+ 3616 // 3617 // Specifications: 3618 // System V Application Binary Interface PowerPC Processor Supplement 3619 // AltiVec Technology Programming Interface Manual 3620 3621 MachineFunction &MF = DAG.getMachineFunction(); 3622 MachineFrameInfo &MFI = MF.getFrameInfo(); 3623 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3624 3625 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3626 // Potential tail calls could cause overwriting of argument stack slots. 3627 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3628 (CallConv == CallingConv::Fast)); 3629 unsigned PtrByteSize = 4; 3630 3631 // Assign locations to all of the incoming arguments. 3632 SmallVector<CCValAssign, 16> ArgLocs; 3633 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3634 *DAG.getContext()); 3635 3636 // Reserve space for the linkage area on the stack. 3637 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3638 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3639 if (useSoftFloat()) 3640 CCInfo.PreAnalyzeFormalArguments(Ins); 3641 3642 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3643 CCInfo.clearWasPPCF128(); 3644 3645 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3646 CCValAssign &VA = ArgLocs[i]; 3647 3648 // Arguments stored in registers. 3649 if (VA.isRegLoc()) { 3650 const TargetRegisterClass *RC; 3651 EVT ValVT = VA.getValVT(); 3652 3653 switch (ValVT.getSimpleVT().SimpleTy) { 3654 default: 3655 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3656 case MVT::i1: 3657 case MVT::i32: 3658 RC = &PPC::GPRCRegClass; 3659 break; 3660 case MVT::f32: 3661 if (Subtarget.hasP8Vector()) 3662 RC = &PPC::VSSRCRegClass; 3663 else if (Subtarget.hasSPE()) 3664 RC = &PPC::GPRCRegClass; 3665 else 3666 RC = &PPC::F4RCRegClass; 3667 break; 3668 case MVT::f64: 3669 if (Subtarget.hasVSX()) 3670 RC = &PPC::VSFRCRegClass; 3671 else if (Subtarget.hasSPE()) 3672 // SPE passes doubles in GPR pairs. 3673 RC = &PPC::GPRCRegClass; 3674 else 3675 RC = &PPC::F8RCRegClass; 3676 break; 3677 case MVT::v16i8: 3678 case MVT::v8i16: 3679 case MVT::v4i32: 3680 RC = &PPC::VRRCRegClass; 3681 break; 3682 case MVT::v4f32: 3683 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3684 break; 3685 case MVT::v2f64: 3686 case MVT::v2i64: 3687 RC = &PPC::VRRCRegClass; 3688 break; 3689 case MVT::v4f64: 3690 RC = &PPC::QFRCRegClass; 3691 break; 3692 case MVT::v4i1: 3693 RC = &PPC::QBRCRegClass; 3694 break; 3695 } 3696 3697 SDValue ArgValue; 3698 // Transform the arguments stored in physical registers into 3699 // virtual ones. 3700 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3701 assert(i + 1 < e && "No second half of double precision argument"); 3702 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3703 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3704 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3705 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3706 if (!Subtarget.isLittleEndian()) 3707 std::swap (ArgValueLo, ArgValueHi); 3708 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3709 ArgValueHi); 3710 } else { 3711 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3712 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3713 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3714 if (ValVT == MVT::i1) 3715 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3716 } 3717 3718 InVals.push_back(ArgValue); 3719 } else { 3720 // Argument stored in memory. 3721 assert(VA.isMemLoc()); 3722 3723 // Get the extended size of the argument type in stack 3724 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3725 // Get the actual size of the argument type 3726 unsigned ObjSize = VA.getValVT().getStoreSize(); 3727 unsigned ArgOffset = VA.getLocMemOffset(); 3728 // Stack objects in PPC32 are right justified. 3729 ArgOffset += ArgSize - ObjSize; 3730 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3731 3732 // Create load nodes to retrieve arguments from the stack. 3733 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3734 InVals.push_back( 3735 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3736 } 3737 } 3738 3739 // Assign locations to all of the incoming aggregate by value arguments. 3740 // Aggregates passed by value are stored in the local variable space of the 3741 // caller's stack frame, right above the parameter list area. 3742 SmallVector<CCValAssign, 16> ByValArgLocs; 3743 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3744 ByValArgLocs, *DAG.getContext()); 3745 3746 // Reserve stack space for the allocations in CCInfo. 3747 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3748 3749 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3750 3751 // Area that is at least reserved in the caller of this function. 3752 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3753 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3754 3755 // Set the size that is at least reserved in caller of this function. Tail 3756 // call optimized function's reserved stack space needs to be aligned so that 3757 // taking the difference between two stack areas will result in an aligned 3758 // stack. 3759 MinReservedArea = 3760 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3761 FuncInfo->setMinReservedArea(MinReservedArea); 3762 3763 SmallVector<SDValue, 8> MemOps; 3764 3765 // If the function takes variable number of arguments, make a frame index for 3766 // the start of the first vararg value... for expansion of llvm.va_start. 3767 if (isVarArg) { 3768 static const MCPhysReg GPArgRegs[] = { 3769 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3770 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3771 }; 3772 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3773 3774 static const MCPhysReg FPArgRegs[] = { 3775 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3776 PPC::F8 3777 }; 3778 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3779 3780 if (useSoftFloat() || hasSPE()) 3781 NumFPArgRegs = 0; 3782 3783 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3784 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3785 3786 // Make room for NumGPArgRegs and NumFPArgRegs. 3787 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3788 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3789 3790 FuncInfo->setVarArgsStackOffset( 3791 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3792 CCInfo.getNextStackOffset(), true)); 3793 3794 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3795 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3796 3797 // The fixed integer arguments of a variadic function are stored to the 3798 // VarArgsFrameIndex on the stack so that they may be loaded by 3799 // dereferencing the result of va_next. 3800 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3801 // Get an existing live-in vreg, or add a new one. 3802 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3803 if (!VReg) 3804 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3805 3806 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3807 SDValue Store = 3808 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3809 MemOps.push_back(Store); 3810 // Increment the address by four for the next argument to store 3811 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3812 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3813 } 3814 3815 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3816 // is set. 3817 // The double arguments are stored to the VarArgsFrameIndex 3818 // on the stack. 3819 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3820 // Get an existing live-in vreg, or add a new one. 3821 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3822 if (!VReg) 3823 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3824 3825 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3826 SDValue Store = 3827 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3828 MemOps.push_back(Store); 3829 // Increment the address by eight for the next argument to store 3830 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3831 PtrVT); 3832 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3833 } 3834 } 3835 3836 if (!MemOps.empty()) 3837 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3838 3839 return Chain; 3840 } 3841 3842 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3843 // value to MVT::i64 and then truncate to the correct register size. 3844 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3845 EVT ObjectVT, SelectionDAG &DAG, 3846 SDValue ArgVal, 3847 const SDLoc &dl) const { 3848 if (Flags.isSExt()) 3849 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3850 DAG.getValueType(ObjectVT)); 3851 else if (Flags.isZExt()) 3852 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3853 DAG.getValueType(ObjectVT)); 3854 3855 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3856 } 3857 3858 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3859 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3860 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3861 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3862 // TODO: add description of PPC stack frame format, or at least some docs. 3863 // 3864 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3865 bool isLittleEndian = Subtarget.isLittleEndian(); 3866 MachineFunction &MF = DAG.getMachineFunction(); 3867 MachineFrameInfo &MFI = MF.getFrameInfo(); 3868 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3869 3870 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3871 "fastcc not supported on varargs functions"); 3872 3873 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3874 // Potential tail calls could cause overwriting of argument stack slots. 3875 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3876 (CallConv == CallingConv::Fast)); 3877 unsigned PtrByteSize = 8; 3878 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3879 3880 static const MCPhysReg GPR[] = { 3881 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3882 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3883 }; 3884 static const MCPhysReg VR[] = { 3885 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3886 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3887 }; 3888 3889 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3890 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3891 const unsigned Num_VR_Regs = array_lengthof(VR); 3892 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3893 3894 // Do a first pass over the arguments to determine whether the ABI 3895 // guarantees that our caller has allocated the parameter save area 3896 // on its stack frame. In the ELFv1 ABI, this is always the case; 3897 // in the ELFv2 ABI, it is true if this is a vararg function or if 3898 // any parameter is located in a stack slot. 3899 3900 bool HasParameterArea = !isELFv2ABI || isVarArg; 3901 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3902 unsigned NumBytes = LinkageSize; 3903 unsigned AvailableFPRs = Num_FPR_Regs; 3904 unsigned AvailableVRs = Num_VR_Regs; 3905 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3906 if (Ins[i].Flags.isNest()) 3907 continue; 3908 3909 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3910 PtrByteSize, LinkageSize, ParamAreaSize, 3911 NumBytes, AvailableFPRs, AvailableVRs, 3912 Subtarget.hasQPX())) 3913 HasParameterArea = true; 3914 } 3915 3916 // Add DAG nodes to load the arguments or copy them out of registers. On 3917 // entry to a function on PPC, the arguments start after the linkage area, 3918 // although the first ones are often in registers. 3919 3920 unsigned ArgOffset = LinkageSize; 3921 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3922 unsigned &QFPR_idx = FPR_idx; 3923 SmallVector<SDValue, 8> MemOps; 3924 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3925 unsigned CurArgIdx = 0; 3926 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3927 SDValue ArgVal; 3928 bool needsLoad = false; 3929 EVT ObjectVT = Ins[ArgNo].VT; 3930 EVT OrigVT = Ins[ArgNo].ArgVT; 3931 unsigned ObjSize = ObjectVT.getStoreSize(); 3932 unsigned ArgSize = ObjSize; 3933 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3934 if (Ins[ArgNo].isOrigArg()) { 3935 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3936 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3937 } 3938 // We re-align the argument offset for each argument, except when using the 3939 // fast calling convention, when we need to make sure we do that only when 3940 // we'll actually use a stack slot. 3941 unsigned CurArgOffset; 3942 Align Alignment; 3943 auto ComputeArgOffset = [&]() { 3944 /* Respect alignment of argument on the stack. */ 3945 Alignment = 3946 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3947 ArgOffset = alignTo(ArgOffset, Alignment); 3948 CurArgOffset = ArgOffset; 3949 }; 3950 3951 if (CallConv != CallingConv::Fast) { 3952 ComputeArgOffset(); 3953 3954 /* Compute GPR index associated with argument offset. */ 3955 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3956 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3957 } 3958 3959 // FIXME the codegen can be much improved in some cases. 3960 // We do not have to keep everything in memory. 3961 if (Flags.isByVal()) { 3962 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3963 3964 if (CallConv == CallingConv::Fast) 3965 ComputeArgOffset(); 3966 3967 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3968 ObjSize = Flags.getByValSize(); 3969 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3970 // Empty aggregate parameters do not take up registers. Examples: 3971 // struct { } a; 3972 // union { } b; 3973 // int c[0]; 3974 // etc. However, we have to provide a place-holder in InVals, so 3975 // pretend we have an 8-byte item at the current address for that 3976 // purpose. 3977 if (!ObjSize) { 3978 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3979 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3980 InVals.push_back(FIN); 3981 continue; 3982 } 3983 3984 // Create a stack object covering all stack doublewords occupied 3985 // by the argument. If the argument is (fully or partially) on 3986 // the stack, or if the argument is fully in registers but the 3987 // caller has allocated the parameter save anyway, we can refer 3988 // directly to the caller's stack frame. Otherwise, create a 3989 // local copy in our own frame. 3990 int FI; 3991 if (HasParameterArea || 3992 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3993 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3994 else 3995 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3996 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3997 3998 // Handle aggregates smaller than 8 bytes. 3999 if (ObjSize < PtrByteSize) { 4000 // The value of the object is its address, which differs from the 4001 // address of the enclosing doubleword on big-endian systems. 4002 SDValue Arg = FIN; 4003 if (!isLittleEndian) { 4004 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4005 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4006 } 4007 InVals.push_back(Arg); 4008 4009 if (GPR_idx != Num_GPR_Regs) { 4010 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4011 FuncInfo->addLiveInAttr(VReg, Flags); 4012 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4013 SDValue Store; 4014 4015 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4016 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4017 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4018 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4019 MachinePointerInfo(&*FuncArg), ObjType); 4020 } else { 4021 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4022 // store the whole register as-is to the parameter save area 4023 // slot. 4024 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4025 MachinePointerInfo(&*FuncArg)); 4026 } 4027 4028 MemOps.push_back(Store); 4029 } 4030 // Whether we copied from a register or not, advance the offset 4031 // into the parameter save area by a full doubleword. 4032 ArgOffset += PtrByteSize; 4033 continue; 4034 } 4035 4036 // The value of the object is its address, which is the address of 4037 // its first stack doubleword. 4038 InVals.push_back(FIN); 4039 4040 // Store whatever pieces of the object are in registers to memory. 4041 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4042 if (GPR_idx == Num_GPR_Regs) 4043 break; 4044 4045 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4046 FuncInfo->addLiveInAttr(VReg, Flags); 4047 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4048 SDValue Addr = FIN; 4049 if (j) { 4050 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4051 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4052 } 4053 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4054 MachinePointerInfo(&*FuncArg, j)); 4055 MemOps.push_back(Store); 4056 ++GPR_idx; 4057 } 4058 ArgOffset += ArgSize; 4059 continue; 4060 } 4061 4062 switch (ObjectVT.getSimpleVT().SimpleTy) { 4063 default: llvm_unreachable("Unhandled argument type!"); 4064 case MVT::i1: 4065 case MVT::i32: 4066 case MVT::i64: 4067 if (Flags.isNest()) { 4068 // The 'nest' parameter, if any, is passed in R11. 4069 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4070 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4071 4072 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4073 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4074 4075 break; 4076 } 4077 4078 // These can be scalar arguments or elements of an integer array type 4079 // passed directly. Clang may use those instead of "byval" aggregate 4080 // types to avoid forcing arguments to memory unnecessarily. 4081 if (GPR_idx != Num_GPR_Regs) { 4082 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4083 FuncInfo->addLiveInAttr(VReg, Flags); 4084 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4085 4086 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4087 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4088 // value to MVT::i64 and then truncate to the correct register size. 4089 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4090 } else { 4091 if (CallConv == CallingConv::Fast) 4092 ComputeArgOffset(); 4093 4094 needsLoad = true; 4095 ArgSize = PtrByteSize; 4096 } 4097 if (CallConv != CallingConv::Fast || needsLoad) 4098 ArgOffset += 8; 4099 break; 4100 4101 case MVT::f32: 4102 case MVT::f64: 4103 // These can be scalar arguments or elements of a float array type 4104 // passed directly. The latter are used to implement ELFv2 homogenous 4105 // float aggregates. 4106 if (FPR_idx != Num_FPR_Regs) { 4107 unsigned VReg; 4108 4109 if (ObjectVT == MVT::f32) 4110 VReg = MF.addLiveIn(FPR[FPR_idx], 4111 Subtarget.hasP8Vector() 4112 ? &PPC::VSSRCRegClass 4113 : &PPC::F4RCRegClass); 4114 else 4115 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4116 ? &PPC::VSFRCRegClass 4117 : &PPC::F8RCRegClass); 4118 4119 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4120 ++FPR_idx; 4121 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4122 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4123 // once we support fp <-> gpr moves. 4124 4125 // This can only ever happen in the presence of f32 array types, 4126 // since otherwise we never run out of FPRs before running out 4127 // of GPRs. 4128 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4129 FuncInfo->addLiveInAttr(VReg, Flags); 4130 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4131 4132 if (ObjectVT == MVT::f32) { 4133 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4134 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4135 DAG.getConstant(32, dl, MVT::i32)); 4136 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4137 } 4138 4139 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4140 } else { 4141 if (CallConv == CallingConv::Fast) 4142 ComputeArgOffset(); 4143 4144 needsLoad = true; 4145 } 4146 4147 // When passing an array of floats, the array occupies consecutive 4148 // space in the argument area; only round up to the next doubleword 4149 // at the end of the array. Otherwise, each float takes 8 bytes. 4150 if (CallConv != CallingConv::Fast || needsLoad) { 4151 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4152 ArgOffset += ArgSize; 4153 if (Flags.isInConsecutiveRegsLast()) 4154 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4155 } 4156 break; 4157 case MVT::v4f32: 4158 case MVT::v4i32: 4159 case MVT::v8i16: 4160 case MVT::v16i8: 4161 case MVT::v2f64: 4162 case MVT::v2i64: 4163 case MVT::v1i128: 4164 case MVT::f128: 4165 if (!Subtarget.hasQPX()) { 4166 // These can be scalar arguments or elements of a vector array type 4167 // passed directly. The latter are used to implement ELFv2 homogenous 4168 // vector aggregates. 4169 if (VR_idx != Num_VR_Regs) { 4170 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4171 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4172 ++VR_idx; 4173 } else { 4174 if (CallConv == CallingConv::Fast) 4175 ComputeArgOffset(); 4176 needsLoad = true; 4177 } 4178 if (CallConv != CallingConv::Fast || needsLoad) 4179 ArgOffset += 16; 4180 break; 4181 } // not QPX 4182 4183 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4184 "Invalid QPX parameter type"); 4185 LLVM_FALLTHROUGH; 4186 4187 case MVT::v4f64: 4188 case MVT::v4i1: 4189 // QPX vectors are treated like their scalar floating-point subregisters 4190 // (except that they're larger). 4191 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4192 if (QFPR_idx != Num_QFPR_Regs) { 4193 const TargetRegisterClass *RC; 4194 switch (ObjectVT.getSimpleVT().SimpleTy) { 4195 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4196 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4197 default: RC = &PPC::QBRCRegClass; break; 4198 } 4199 4200 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4201 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4202 ++QFPR_idx; 4203 } else { 4204 if (CallConv == CallingConv::Fast) 4205 ComputeArgOffset(); 4206 needsLoad = true; 4207 } 4208 if (CallConv != CallingConv::Fast || needsLoad) 4209 ArgOffset += Sz; 4210 break; 4211 } 4212 4213 // We need to load the argument to a virtual register if we determined 4214 // above that we ran out of physical registers of the appropriate type. 4215 if (needsLoad) { 4216 if (ObjSize < ArgSize && !isLittleEndian) 4217 CurArgOffset += ArgSize - ObjSize; 4218 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4219 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4220 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4221 } 4222 4223 InVals.push_back(ArgVal); 4224 } 4225 4226 // Area that is at least reserved in the caller of this function. 4227 unsigned MinReservedArea; 4228 if (HasParameterArea) 4229 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4230 else 4231 MinReservedArea = LinkageSize; 4232 4233 // Set the size that is at least reserved in caller of this function. Tail 4234 // call optimized functions' reserved stack space needs to be aligned so that 4235 // taking the difference between two stack areas will result in an aligned 4236 // stack. 4237 MinReservedArea = 4238 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4239 FuncInfo->setMinReservedArea(MinReservedArea); 4240 4241 // If the function takes variable number of arguments, make a frame index for 4242 // the start of the first vararg value... for expansion of llvm.va_start. 4243 if (isVarArg) { 4244 int Depth = ArgOffset; 4245 4246 FuncInfo->setVarArgsFrameIndex( 4247 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4248 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4249 4250 // If this function is vararg, store any remaining integer argument regs 4251 // to their spots on the stack so that they may be loaded by dereferencing 4252 // the result of va_next. 4253 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4254 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4255 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4256 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4257 SDValue Store = 4258 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4259 MemOps.push_back(Store); 4260 // Increment the address by four for the next argument to store 4261 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4262 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4263 } 4264 } 4265 4266 if (!MemOps.empty()) 4267 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4268 4269 return Chain; 4270 } 4271 4272 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4273 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4274 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4275 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4276 // TODO: add description of PPC stack frame format, or at least some docs. 4277 // 4278 MachineFunction &MF = DAG.getMachineFunction(); 4279 MachineFrameInfo &MFI = MF.getFrameInfo(); 4280 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4281 4282 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4283 bool isPPC64 = PtrVT == MVT::i64; 4284 // Potential tail calls could cause overwriting of argument stack slots. 4285 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4286 (CallConv == CallingConv::Fast)); 4287 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4288 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4289 unsigned ArgOffset = LinkageSize; 4290 // Area that is at least reserved in caller of this function. 4291 unsigned MinReservedArea = ArgOffset; 4292 4293 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4294 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4295 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4296 }; 4297 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4298 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4299 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4300 }; 4301 static const MCPhysReg VR[] = { 4302 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4303 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4304 }; 4305 4306 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4307 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4308 const unsigned Num_VR_Regs = array_lengthof( VR); 4309 4310 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4311 4312 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4313 4314 // In 32-bit non-varargs functions, the stack space for vectors is after the 4315 // stack space for non-vectors. We do not use this space unless we have 4316 // too many vectors to fit in registers, something that only occurs in 4317 // constructed examples:), but we have to walk the arglist to figure 4318 // that out...for the pathological case, compute VecArgOffset as the 4319 // start of the vector parameter area. Computing VecArgOffset is the 4320 // entire point of the following loop. 4321 unsigned VecArgOffset = ArgOffset; 4322 if (!isVarArg && !isPPC64) { 4323 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4324 ++ArgNo) { 4325 EVT ObjectVT = Ins[ArgNo].VT; 4326 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4327 4328 if (Flags.isByVal()) { 4329 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4330 unsigned ObjSize = Flags.getByValSize(); 4331 unsigned ArgSize = 4332 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4333 VecArgOffset += ArgSize; 4334 continue; 4335 } 4336 4337 switch(ObjectVT.getSimpleVT().SimpleTy) { 4338 default: llvm_unreachable("Unhandled argument type!"); 4339 case MVT::i1: 4340 case MVT::i32: 4341 case MVT::f32: 4342 VecArgOffset += 4; 4343 break; 4344 case MVT::i64: // PPC64 4345 case MVT::f64: 4346 // FIXME: We are guaranteed to be !isPPC64 at this point. 4347 // Does MVT::i64 apply? 4348 VecArgOffset += 8; 4349 break; 4350 case MVT::v4f32: 4351 case MVT::v4i32: 4352 case MVT::v8i16: 4353 case MVT::v16i8: 4354 // Nothing to do, we're only looking at Nonvector args here. 4355 break; 4356 } 4357 } 4358 } 4359 // We've found where the vector parameter area in memory is. Skip the 4360 // first 12 parameters; these don't use that memory. 4361 VecArgOffset = ((VecArgOffset+15)/16)*16; 4362 VecArgOffset += 12*16; 4363 4364 // Add DAG nodes to load the arguments or copy them out of registers. On 4365 // entry to a function on PPC, the arguments start after the linkage area, 4366 // although the first ones are often in registers. 4367 4368 SmallVector<SDValue, 8> MemOps; 4369 unsigned nAltivecParamsAtEnd = 0; 4370 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4371 unsigned CurArgIdx = 0; 4372 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4373 SDValue ArgVal; 4374 bool needsLoad = false; 4375 EVT ObjectVT = Ins[ArgNo].VT; 4376 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4377 unsigned ArgSize = ObjSize; 4378 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4379 if (Ins[ArgNo].isOrigArg()) { 4380 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4381 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4382 } 4383 unsigned CurArgOffset = ArgOffset; 4384 4385 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4386 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4387 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4388 if (isVarArg || isPPC64) { 4389 MinReservedArea = ((MinReservedArea+15)/16)*16; 4390 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4391 Flags, 4392 PtrByteSize); 4393 } else nAltivecParamsAtEnd++; 4394 } else 4395 // Calculate min reserved area. 4396 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4397 Flags, 4398 PtrByteSize); 4399 4400 // FIXME the codegen can be much improved in some cases. 4401 // We do not have to keep everything in memory. 4402 if (Flags.isByVal()) { 4403 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4404 4405 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4406 ObjSize = Flags.getByValSize(); 4407 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4408 // Objects of size 1 and 2 are right justified, everything else is 4409 // left justified. This means the memory address is adjusted forwards. 4410 if (ObjSize==1 || ObjSize==2) { 4411 CurArgOffset = CurArgOffset + (4 - ObjSize); 4412 } 4413 // The value of the object is its address. 4414 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4415 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4416 InVals.push_back(FIN); 4417 if (ObjSize==1 || ObjSize==2) { 4418 if (GPR_idx != Num_GPR_Regs) { 4419 unsigned VReg; 4420 if (isPPC64) 4421 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4422 else 4423 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4424 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4425 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4426 SDValue Store = 4427 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4428 MachinePointerInfo(&*FuncArg), ObjType); 4429 MemOps.push_back(Store); 4430 ++GPR_idx; 4431 } 4432 4433 ArgOffset += PtrByteSize; 4434 4435 continue; 4436 } 4437 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4438 // Store whatever pieces of the object are in registers 4439 // to memory. ArgOffset will be the address of the beginning 4440 // of the object. 4441 if (GPR_idx != Num_GPR_Regs) { 4442 unsigned VReg; 4443 if (isPPC64) 4444 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4445 else 4446 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4447 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4448 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4449 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4450 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4451 MachinePointerInfo(&*FuncArg, j)); 4452 MemOps.push_back(Store); 4453 ++GPR_idx; 4454 ArgOffset += PtrByteSize; 4455 } else { 4456 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4457 break; 4458 } 4459 } 4460 continue; 4461 } 4462 4463 switch (ObjectVT.getSimpleVT().SimpleTy) { 4464 default: llvm_unreachable("Unhandled argument type!"); 4465 case MVT::i1: 4466 case MVT::i32: 4467 if (!isPPC64) { 4468 if (GPR_idx != Num_GPR_Regs) { 4469 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4470 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4471 4472 if (ObjectVT == MVT::i1) 4473 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4474 4475 ++GPR_idx; 4476 } else { 4477 needsLoad = true; 4478 ArgSize = PtrByteSize; 4479 } 4480 // All int arguments reserve stack space in the Darwin ABI. 4481 ArgOffset += PtrByteSize; 4482 break; 4483 } 4484 LLVM_FALLTHROUGH; 4485 case MVT::i64: // PPC64 4486 if (GPR_idx != Num_GPR_Regs) { 4487 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4488 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4489 4490 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4491 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4492 // value to MVT::i64 and then truncate to the correct register size. 4493 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4494 4495 ++GPR_idx; 4496 } else { 4497 needsLoad = true; 4498 ArgSize = PtrByteSize; 4499 } 4500 // All int arguments reserve stack space in the Darwin ABI. 4501 ArgOffset += 8; 4502 break; 4503 4504 case MVT::f32: 4505 case MVT::f64: 4506 // Every 4 bytes of argument space consumes one of the GPRs available for 4507 // argument passing. 4508 if (GPR_idx != Num_GPR_Regs) { 4509 ++GPR_idx; 4510 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4511 ++GPR_idx; 4512 } 4513 if (FPR_idx != Num_FPR_Regs) { 4514 unsigned VReg; 4515 4516 if (ObjectVT == MVT::f32) 4517 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4518 else 4519 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4520 4521 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4522 ++FPR_idx; 4523 } else { 4524 needsLoad = true; 4525 } 4526 4527 // All FP arguments reserve stack space in the Darwin ABI. 4528 ArgOffset += isPPC64 ? 8 : ObjSize; 4529 break; 4530 case MVT::v4f32: 4531 case MVT::v4i32: 4532 case MVT::v8i16: 4533 case MVT::v16i8: 4534 // Note that vector arguments in registers don't reserve stack space, 4535 // except in varargs functions. 4536 if (VR_idx != Num_VR_Regs) { 4537 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4538 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4539 if (isVarArg) { 4540 while ((ArgOffset % 16) != 0) { 4541 ArgOffset += PtrByteSize; 4542 if (GPR_idx != Num_GPR_Regs) 4543 GPR_idx++; 4544 } 4545 ArgOffset += 16; 4546 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4547 } 4548 ++VR_idx; 4549 } else { 4550 if (!isVarArg && !isPPC64) { 4551 // Vectors go after all the nonvectors. 4552 CurArgOffset = VecArgOffset; 4553 VecArgOffset += 16; 4554 } else { 4555 // Vectors are aligned. 4556 ArgOffset = ((ArgOffset+15)/16)*16; 4557 CurArgOffset = ArgOffset; 4558 ArgOffset += 16; 4559 } 4560 needsLoad = true; 4561 } 4562 break; 4563 } 4564 4565 // We need to load the argument to a virtual register if we determined above 4566 // that we ran out of physical registers of the appropriate type. 4567 if (needsLoad) { 4568 int FI = MFI.CreateFixedObject(ObjSize, 4569 CurArgOffset + (ArgSize - ObjSize), 4570 isImmutable); 4571 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4572 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4573 } 4574 4575 InVals.push_back(ArgVal); 4576 } 4577 4578 // Allow for Altivec parameters at the end, if needed. 4579 if (nAltivecParamsAtEnd) { 4580 MinReservedArea = ((MinReservedArea+15)/16)*16; 4581 MinReservedArea += 16*nAltivecParamsAtEnd; 4582 } 4583 4584 // Area that is at least reserved in the caller of this function. 4585 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4586 4587 // Set the size that is at least reserved in caller of this function. Tail 4588 // call optimized functions' reserved stack space needs to be aligned so that 4589 // taking the difference between two stack areas will result in an aligned 4590 // stack. 4591 MinReservedArea = 4592 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4593 FuncInfo->setMinReservedArea(MinReservedArea); 4594 4595 // If the function takes variable number of arguments, make a frame index for 4596 // the start of the first vararg value... for expansion of llvm.va_start. 4597 if (isVarArg) { 4598 int Depth = ArgOffset; 4599 4600 FuncInfo->setVarArgsFrameIndex( 4601 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4602 Depth, true)); 4603 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4604 4605 // If this function is vararg, store any remaining integer argument regs 4606 // to their spots on the stack so that they may be loaded by dereferencing 4607 // the result of va_next. 4608 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4609 unsigned VReg; 4610 4611 if (isPPC64) 4612 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4613 else 4614 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4615 4616 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4617 SDValue Store = 4618 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4619 MemOps.push_back(Store); 4620 // Increment the address by four for the next argument to store 4621 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4622 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4623 } 4624 } 4625 4626 if (!MemOps.empty()) 4627 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4628 4629 return Chain; 4630 } 4631 4632 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4633 /// adjusted to accommodate the arguments for the tailcall. 4634 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4635 unsigned ParamSize) { 4636 4637 if (!isTailCall) return 0; 4638 4639 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4640 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4641 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4642 // Remember only if the new adjustment is bigger. 4643 if (SPDiff < FI->getTailCallSPDelta()) 4644 FI->setTailCallSPDelta(SPDiff); 4645 4646 return SPDiff; 4647 } 4648 4649 static bool isFunctionGlobalAddress(SDValue Callee); 4650 4651 static bool 4652 callsShareTOCBase(const Function *Caller, SDValue Callee, 4653 const TargetMachine &TM) { 4654 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4655 // don't have enough information to determine if the caller and calle share 4656 // the same TOC base, so we have to pessimistically assume they don't for 4657 // correctness. 4658 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4659 if (!G) 4660 return false; 4661 4662 const GlobalValue *GV = G->getGlobal(); 4663 // The medium and large code models are expected to provide a sufficiently 4664 // large TOC to provide all data addressing needs of a module with a 4665 // single TOC. Since each module will be addressed with a single TOC then we 4666 // only need to check that caller and callee don't cross dso boundaries. 4667 if (CodeModel::Medium == TM.getCodeModel() || 4668 CodeModel::Large == TM.getCodeModel()) 4669 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4670 4671 // Otherwise we need to ensure callee and caller are in the same section, 4672 // since the linker may allocate multiple TOCs, and we don't know which 4673 // sections will belong to the same TOC base. 4674 4675 if (!GV->isStrongDefinitionForLinker()) 4676 return false; 4677 4678 // Any explicitly-specified sections and section prefixes must also match. 4679 // Also, if we're using -ffunction-sections, then each function is always in 4680 // a different section (the same is true for COMDAT functions). 4681 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4682 GV->getSection() != Caller->getSection()) 4683 return false; 4684 if (const auto *F = dyn_cast<Function>(GV)) { 4685 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4686 return false; 4687 } 4688 4689 // If the callee might be interposed, then we can't assume the ultimate call 4690 // target will be in the same section. Even in cases where we can assume that 4691 // interposition won't happen, in any case where the linker might insert a 4692 // stub to allow for interposition, we must generate code as though 4693 // interposition might occur. To understand why this matters, consider a 4694 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4695 // in the same section, but a is in a different module (i.e. has a different 4696 // TOC base pointer). If the linker allows for interposition between b and c, 4697 // then it will generate a stub for the call edge between b and c which will 4698 // save the TOC pointer into the designated stack slot allocated by b. If we 4699 // return true here, and therefore allow a tail call between b and c, that 4700 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4701 // pointer into the stack slot allocated by a (where the a -> b stub saved 4702 // a's TOC base pointer). If we're not considering a tail call, but rather, 4703 // whether a nop is needed after the call instruction in b, because the linker 4704 // will insert a stub, it might complain about a missing nop if we omit it 4705 // (although many don't complain in this case). 4706 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4707 return false; 4708 4709 return true; 4710 } 4711 4712 static bool 4713 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4714 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4715 assert(Subtarget.is64BitELFABI()); 4716 4717 const unsigned PtrByteSize = 8; 4718 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4719 4720 static const MCPhysReg GPR[] = { 4721 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4722 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4723 }; 4724 static const MCPhysReg VR[] = { 4725 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4726 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4727 }; 4728 4729 const unsigned NumGPRs = array_lengthof(GPR); 4730 const unsigned NumFPRs = 13; 4731 const unsigned NumVRs = array_lengthof(VR); 4732 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4733 4734 unsigned NumBytes = LinkageSize; 4735 unsigned AvailableFPRs = NumFPRs; 4736 unsigned AvailableVRs = NumVRs; 4737 4738 for (const ISD::OutputArg& Param : Outs) { 4739 if (Param.Flags.isNest()) continue; 4740 4741 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4742 PtrByteSize, LinkageSize, ParamAreaSize, 4743 NumBytes, AvailableFPRs, AvailableVRs, 4744 Subtarget.hasQPX())) 4745 return true; 4746 } 4747 return false; 4748 } 4749 4750 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4751 if (CB.arg_size() != CallerFn->arg_size()) 4752 return false; 4753 4754 auto CalleeArgIter = CB.arg_begin(); 4755 auto CalleeArgEnd = CB.arg_end(); 4756 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4757 4758 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4759 const Value* CalleeArg = *CalleeArgIter; 4760 const Value* CallerArg = &(*CallerArgIter); 4761 if (CalleeArg == CallerArg) 4762 continue; 4763 4764 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4765 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4766 // } 4767 // 1st argument of callee is undef and has the same type as caller. 4768 if (CalleeArg->getType() == CallerArg->getType() && 4769 isa<UndefValue>(CalleeArg)) 4770 continue; 4771 4772 return false; 4773 } 4774 4775 return true; 4776 } 4777 4778 // Returns true if TCO is possible between the callers and callees 4779 // calling conventions. 4780 static bool 4781 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4782 CallingConv::ID CalleeCC) { 4783 // Tail calls are possible with fastcc and ccc. 4784 auto isTailCallableCC = [] (CallingConv::ID CC){ 4785 return CC == CallingConv::C || CC == CallingConv::Fast; 4786 }; 4787 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4788 return false; 4789 4790 // We can safely tail call both fastcc and ccc callees from a c calling 4791 // convention caller. If the caller is fastcc, we may have less stack space 4792 // than a non-fastcc caller with the same signature so disable tail-calls in 4793 // that case. 4794 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4795 } 4796 4797 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4798 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4799 const SmallVectorImpl<ISD::OutputArg> &Outs, 4800 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4801 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4802 4803 if (DisableSCO && !TailCallOpt) return false; 4804 4805 // Variadic argument functions are not supported. 4806 if (isVarArg) return false; 4807 4808 auto &Caller = DAG.getMachineFunction().getFunction(); 4809 // Check that the calling conventions are compatible for tco. 4810 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4811 return false; 4812 4813 // Caller contains any byval parameter is not supported. 4814 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4815 return false; 4816 4817 // Callee contains any byval parameter is not supported, too. 4818 // Note: This is a quick work around, because in some cases, e.g. 4819 // caller's stack size > callee's stack size, we are still able to apply 4820 // sibling call optimization. For example, gcc is able to do SCO for caller1 4821 // in the following example, but not for caller2. 4822 // struct test { 4823 // long int a; 4824 // char ary[56]; 4825 // } gTest; 4826 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4827 // b->a = v.a; 4828 // return 0; 4829 // } 4830 // void caller1(struct test a, struct test c, struct test *b) { 4831 // callee(gTest, b); } 4832 // void caller2(struct test *b) { callee(gTest, b); } 4833 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4834 return false; 4835 4836 // If callee and caller use different calling conventions, we cannot pass 4837 // parameters on stack since offsets for the parameter area may be different. 4838 if (Caller.getCallingConv() != CalleeCC && 4839 needStackSlotPassParameters(Subtarget, Outs)) 4840 return false; 4841 4842 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4843 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4844 // callee potentially have different TOC bases then we cannot tail call since 4845 // we need to restore the TOC pointer after the call. 4846 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4847 // We cannot guarantee this for indirect calls or calls to external functions. 4848 // When PC-Relative addressing is used, the concept of the TOC is no longer 4849 // applicable so this check is not required. 4850 // Check first for indirect calls. 4851 if (!Subtarget.isUsingPCRelativeCalls() && 4852 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4853 return false; 4854 4855 // Check if we share the TOC base. 4856 if (!Subtarget.isUsingPCRelativeCalls() && 4857 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4858 return false; 4859 4860 // TCO allows altering callee ABI, so we don't have to check further. 4861 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4862 return true; 4863 4864 if (DisableSCO) return false; 4865 4866 // If callee use the same argument list that caller is using, then we can 4867 // apply SCO on this case. If it is not, then we need to check if callee needs 4868 // stack for passing arguments. 4869 // PC Relative tail calls may not have a CallBase. 4870 // If there is no CallBase we cannot verify if we have the same argument 4871 // list so assume that we don't have the same argument list. 4872 if (CB && !hasSameArgumentList(&Caller, *CB) && 4873 needStackSlotPassParameters(Subtarget, Outs)) 4874 return false; 4875 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4876 return false; 4877 4878 return true; 4879 } 4880 4881 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4882 /// for tail call optimization. Targets which want to do tail call 4883 /// optimization should implement this function. 4884 bool 4885 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4886 CallingConv::ID CalleeCC, 4887 bool isVarArg, 4888 const SmallVectorImpl<ISD::InputArg> &Ins, 4889 SelectionDAG& DAG) const { 4890 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4891 return false; 4892 4893 // Variable argument functions are not supported. 4894 if (isVarArg) 4895 return false; 4896 4897 MachineFunction &MF = DAG.getMachineFunction(); 4898 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4899 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4900 // Functions containing by val parameters are not supported. 4901 for (unsigned i = 0; i != Ins.size(); i++) { 4902 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4903 if (Flags.isByVal()) return false; 4904 } 4905 4906 // Non-PIC/GOT tail calls are supported. 4907 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4908 return true; 4909 4910 // At the moment we can only do local tail calls (in same module, hidden 4911 // or protected) if we are generating PIC. 4912 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4913 return G->getGlobal()->hasHiddenVisibility() 4914 || G->getGlobal()->hasProtectedVisibility(); 4915 } 4916 4917 return false; 4918 } 4919 4920 /// isCallCompatibleAddress - Return the immediate to use if the specified 4921 /// 32-bit value is representable in the immediate field of a BxA instruction. 4922 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4923 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4924 if (!C) return nullptr; 4925 4926 int Addr = C->getZExtValue(); 4927 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4928 SignExtend32<26>(Addr) != Addr) 4929 return nullptr; // Top 6 bits have to be sext of immediate. 4930 4931 return DAG 4932 .getConstant( 4933 (int)C->getZExtValue() >> 2, SDLoc(Op), 4934 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4935 .getNode(); 4936 } 4937 4938 namespace { 4939 4940 struct TailCallArgumentInfo { 4941 SDValue Arg; 4942 SDValue FrameIdxOp; 4943 int FrameIdx = 0; 4944 4945 TailCallArgumentInfo() = default; 4946 }; 4947 4948 } // end anonymous namespace 4949 4950 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4951 static void StoreTailCallArgumentsToStackSlot( 4952 SelectionDAG &DAG, SDValue Chain, 4953 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4954 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4955 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4956 SDValue Arg = TailCallArgs[i].Arg; 4957 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4958 int FI = TailCallArgs[i].FrameIdx; 4959 // Store relative to framepointer. 4960 MemOpChains.push_back(DAG.getStore( 4961 Chain, dl, Arg, FIN, 4962 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4963 } 4964 } 4965 4966 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4967 /// the appropriate stack slot for the tail call optimized function call. 4968 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4969 SDValue OldRetAddr, SDValue OldFP, 4970 int SPDiff, const SDLoc &dl) { 4971 if (SPDiff) { 4972 // Calculate the new stack slot for the return address. 4973 MachineFunction &MF = DAG.getMachineFunction(); 4974 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4975 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4976 bool isPPC64 = Subtarget.isPPC64(); 4977 int SlotSize = isPPC64 ? 8 : 4; 4978 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4979 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4980 NewRetAddrLoc, true); 4981 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4982 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4983 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4984 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4985 } 4986 return Chain; 4987 } 4988 4989 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4990 /// the position of the argument. 4991 static void 4992 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4993 SDValue Arg, int SPDiff, unsigned ArgOffset, 4994 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4995 int Offset = ArgOffset + SPDiff; 4996 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4997 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4998 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4999 SDValue FIN = DAG.getFrameIndex(FI, VT); 5000 TailCallArgumentInfo Info; 5001 Info.Arg = Arg; 5002 Info.FrameIdxOp = FIN; 5003 Info.FrameIdx = FI; 5004 TailCallArguments.push_back(Info); 5005 } 5006 5007 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5008 /// stack slot. Returns the chain as result and the loaded frame pointers in 5009 /// LROpOut/FPOpout. Used when tail calling. 5010 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5011 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5012 SDValue &FPOpOut, const SDLoc &dl) const { 5013 if (SPDiff) { 5014 // Load the LR and FP stack slot for later adjusting. 5015 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5016 LROpOut = getReturnAddrFrameIndex(DAG); 5017 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5018 Chain = SDValue(LROpOut.getNode(), 1); 5019 } 5020 return Chain; 5021 } 5022 5023 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5024 /// by "Src" to address "Dst" of size "Size". Alignment information is 5025 /// specified by the specific parameter attribute. The copy will be passed as 5026 /// a byval function parameter. 5027 /// Sometimes what we are copying is the end of a larger object, the part that 5028 /// does not fit in registers. 5029 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5030 SDValue Chain, ISD::ArgFlagsTy Flags, 5031 SelectionDAG &DAG, const SDLoc &dl) { 5032 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5033 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5034 Flags.getNonZeroByValAlign(), false, false, false, 5035 MachinePointerInfo(), MachinePointerInfo()); 5036 } 5037 5038 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5039 /// tail calls. 5040 static void LowerMemOpCallTo( 5041 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5042 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5043 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5044 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5045 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5046 if (!isTailCall) { 5047 if (isVector) { 5048 SDValue StackPtr; 5049 if (isPPC64) 5050 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5051 else 5052 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5053 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5054 DAG.getConstant(ArgOffset, dl, PtrVT)); 5055 } 5056 MemOpChains.push_back( 5057 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5058 // Calculate and remember argument location. 5059 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5060 TailCallArguments); 5061 } 5062 5063 static void 5064 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5065 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5066 SDValue FPOp, 5067 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5068 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5069 // might overwrite each other in case of tail call optimization. 5070 SmallVector<SDValue, 8> MemOpChains2; 5071 // Do not flag preceding copytoreg stuff together with the following stuff. 5072 InFlag = SDValue(); 5073 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5074 MemOpChains2, dl); 5075 if (!MemOpChains2.empty()) 5076 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5077 5078 // Store the return address to the appropriate stack slot. 5079 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5080 5081 // Emit callseq_end just before tailcall node. 5082 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5083 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5084 InFlag = Chain.getValue(1); 5085 } 5086 5087 // Is this global address that of a function that can be called by name? (as 5088 // opposed to something that must hold a descriptor for an indirect call). 5089 static bool isFunctionGlobalAddress(SDValue Callee) { 5090 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5091 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5092 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5093 return false; 5094 5095 return G->getGlobal()->getValueType()->isFunctionTy(); 5096 } 5097 5098 return false; 5099 } 5100 5101 SDValue PPCTargetLowering::LowerCallResult( 5102 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5103 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5104 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5105 SmallVector<CCValAssign, 16> RVLocs; 5106 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5107 *DAG.getContext()); 5108 5109 CCRetInfo.AnalyzeCallResult( 5110 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5111 ? RetCC_PPC_Cold 5112 : RetCC_PPC); 5113 5114 // Copy all of the result registers out of their specified physreg. 5115 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5116 CCValAssign &VA = RVLocs[i]; 5117 assert(VA.isRegLoc() && "Can only return in registers!"); 5118 5119 SDValue Val; 5120 5121 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5122 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5123 InFlag); 5124 Chain = Lo.getValue(1); 5125 InFlag = Lo.getValue(2); 5126 VA = RVLocs[++i]; // skip ahead to next loc 5127 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5128 InFlag); 5129 Chain = Hi.getValue(1); 5130 InFlag = Hi.getValue(2); 5131 if (!Subtarget.isLittleEndian()) 5132 std::swap (Lo, Hi); 5133 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5134 } else { 5135 Val = DAG.getCopyFromReg(Chain, dl, 5136 VA.getLocReg(), VA.getLocVT(), InFlag); 5137 Chain = Val.getValue(1); 5138 InFlag = Val.getValue(2); 5139 } 5140 5141 switch (VA.getLocInfo()) { 5142 default: llvm_unreachable("Unknown loc info!"); 5143 case CCValAssign::Full: break; 5144 case CCValAssign::AExt: 5145 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5146 break; 5147 case CCValAssign::ZExt: 5148 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5149 DAG.getValueType(VA.getValVT())); 5150 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5151 break; 5152 case CCValAssign::SExt: 5153 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5154 DAG.getValueType(VA.getValVT())); 5155 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5156 break; 5157 } 5158 5159 InVals.push_back(Val); 5160 } 5161 5162 return Chain; 5163 } 5164 5165 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5166 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5167 // PatchPoint calls are not indirect. 5168 if (isPatchPoint) 5169 return false; 5170 5171 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5172 return false; 5173 5174 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5175 // becuase the immediate function pointer points to a descriptor instead of 5176 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5177 // pointer immediate points to the global entry point, while the BLA would 5178 // need to jump to the local entry point (see rL211174). 5179 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5180 isBLACompatibleAddress(Callee, DAG)) 5181 return false; 5182 5183 return true; 5184 } 5185 5186 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5187 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5188 return Subtarget.isAIXABI() || 5189 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5190 } 5191 5192 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5193 const Function &Caller, 5194 const SDValue &Callee, 5195 const PPCSubtarget &Subtarget, 5196 const TargetMachine &TM) { 5197 if (CFlags.IsTailCall) 5198 return PPCISD::TC_RETURN; 5199 5200 // This is a call through a function pointer. 5201 if (CFlags.IsIndirect) { 5202 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5203 // indirect calls. The save of the caller's TOC pointer to the stack will be 5204 // inserted into the DAG as part of call lowering. The restore of the TOC 5205 // pointer is modeled by using a pseudo instruction for the call opcode that 5206 // represents the 2 instruction sequence of an indirect branch and link, 5207 // immediately followed by a load of the TOC pointer from the the stack save 5208 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5209 // as it is not saved or used. 5210 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5211 : PPCISD::BCTRL; 5212 } 5213 5214 if (Subtarget.isUsingPCRelativeCalls()) { 5215 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5216 return PPCISD::CALL_NOTOC; 5217 } 5218 5219 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5220 // immediately following the call instruction if the caller and callee may 5221 // have different TOC bases. At link time if the linker determines the calls 5222 // may not share a TOC base, the call is redirected to a trampoline inserted 5223 // by the linker. The trampoline will (among other things) save the callers 5224 // TOC pointer at an ABI designated offset in the linkage area and the linker 5225 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5226 // into gpr2. 5227 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5228 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5229 : PPCISD::CALL_NOP; 5230 5231 return PPCISD::CALL; 5232 } 5233 5234 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5235 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5236 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5237 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5238 return SDValue(Dest, 0); 5239 5240 // Returns true if the callee is local, and false otherwise. 5241 auto isLocalCallee = [&]() { 5242 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5243 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5244 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5245 5246 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5247 !dyn_cast_or_null<GlobalIFunc>(GV); 5248 }; 5249 5250 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5251 // a static relocation model causes some versions of GNU LD (2.17.50, at 5252 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5253 // built with secure-PLT. 5254 bool UsePlt = 5255 Subtarget.is32BitELFABI() && !isLocalCallee() && 5256 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5257 5258 // On AIX, direct function calls reference the symbol for the function's 5259 // entry point, which is named by prepending a "." before the function's 5260 // C-linkage name. 5261 const auto getAIXFuncEntryPointSymbolSDNode = 5262 [&](StringRef FuncName, bool IsDeclaration, 5263 const XCOFF::StorageClass &SC) { 5264 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5265 5266 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5267 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5268 5269 if (IsDeclaration && !S->hasRepresentedCsectSet()) { 5270 // On AIX, an undefined symbol needs to be associated with a 5271 // MCSectionXCOFF to get the correct storage mapping class. 5272 // In this case, XCOFF::XMC_PR. 5273 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5274 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5275 SectionKind::getMetadata()); 5276 S->setRepresentedCsect(Sec); 5277 } 5278 5279 MVT PtrVT = 5280 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5281 return DAG.getMCSymbol(S, PtrVT); 5282 }; 5283 5284 if (isFunctionGlobalAddress(Callee)) { 5285 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5286 const GlobalValue *GV = G->getGlobal(); 5287 5288 if (!Subtarget.isAIXABI()) 5289 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5290 UsePlt ? PPCII::MO_PLT : 0); 5291 5292 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5293 const GlobalObject *GO = cast<GlobalObject>(GV); 5294 const XCOFF::StorageClass SC = 5295 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5296 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5297 SC); 5298 } 5299 5300 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5301 const char *SymName = S->getSymbol(); 5302 if (!Subtarget.isAIXABI()) 5303 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5304 UsePlt ? PPCII::MO_PLT : 0); 5305 5306 // If there exists a user-declared function whose name is the same as the 5307 // ExternalSymbol's, then we pick up the user-declared version. 5308 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5309 if (const Function *F = 5310 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5311 const XCOFF::StorageClass SC = 5312 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5313 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5314 SC); 5315 } 5316 5317 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5318 } 5319 5320 // No transformation needed. 5321 assert(Callee.getNode() && "What no callee?"); 5322 return Callee; 5323 } 5324 5325 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5326 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5327 "Expected a CALLSEQ_STARTSDNode."); 5328 5329 // The last operand is the chain, except when the node has glue. If the node 5330 // has glue, then the last operand is the glue, and the chain is the second 5331 // last operand. 5332 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5333 if (LastValue.getValueType() != MVT::Glue) 5334 return LastValue; 5335 5336 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5337 } 5338 5339 // Creates the node that moves a functions address into the count register 5340 // to prepare for an indirect call instruction. 5341 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5342 SDValue &Glue, SDValue &Chain, 5343 const SDLoc &dl) { 5344 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5345 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5346 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5347 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5348 // The glue is the second value produced. 5349 Glue = Chain.getValue(1); 5350 } 5351 5352 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5353 SDValue &Glue, SDValue &Chain, 5354 SDValue CallSeqStart, 5355 const CallBase *CB, const SDLoc &dl, 5356 bool hasNest, 5357 const PPCSubtarget &Subtarget) { 5358 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5359 // entry point, but to the function descriptor (the function entry point 5360 // address is part of the function descriptor though). 5361 // The function descriptor is a three doubleword structure with the 5362 // following fields: function entry point, TOC base address and 5363 // environment pointer. 5364 // Thus for a call through a function pointer, the following actions need 5365 // to be performed: 5366 // 1. Save the TOC of the caller in the TOC save area of its stack 5367 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5368 // 2. Load the address of the function entry point from the function 5369 // descriptor. 5370 // 3. Load the TOC of the callee from the function descriptor into r2. 5371 // 4. Load the environment pointer from the function descriptor into 5372 // r11. 5373 // 5. Branch to the function entry point address. 5374 // 6. On return of the callee, the TOC of the caller needs to be 5375 // restored (this is done in FinishCall()). 5376 // 5377 // The loads are scheduled at the beginning of the call sequence, and the 5378 // register copies are flagged together to ensure that no other 5379 // operations can be scheduled in between. E.g. without flagging the 5380 // copies together, a TOC access in the caller could be scheduled between 5381 // the assignment of the callee TOC and the branch to the callee, which leads 5382 // to incorrect code. 5383 5384 // Start by loading the function address from the descriptor. 5385 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5386 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5387 ? (MachineMemOperand::MODereferenceable | 5388 MachineMemOperand::MOInvariant) 5389 : MachineMemOperand::MONone; 5390 5391 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5392 5393 // Registers used in building the DAG. 5394 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5395 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5396 5397 // Offsets of descriptor members. 5398 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5399 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5400 5401 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5402 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5403 5404 // One load for the functions entry point address. 5405 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5406 Alignment, MMOFlags); 5407 5408 // One for loading the TOC anchor for the module that contains the called 5409 // function. 5410 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5411 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5412 SDValue TOCPtr = 5413 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5414 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5415 5416 // One for loading the environment pointer. 5417 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5418 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5419 SDValue LoadEnvPtr = 5420 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5421 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5422 5423 5424 // Then copy the newly loaded TOC anchor to the TOC pointer. 5425 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5426 Chain = TOCVal.getValue(0); 5427 Glue = TOCVal.getValue(1); 5428 5429 // If the function call has an explicit 'nest' parameter, it takes the 5430 // place of the environment pointer. 5431 assert((!hasNest || !Subtarget.isAIXABI()) && 5432 "Nest parameter is not supported on AIX."); 5433 if (!hasNest) { 5434 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5435 Chain = EnvVal.getValue(0); 5436 Glue = EnvVal.getValue(1); 5437 } 5438 5439 // The rest of the indirect call sequence is the same as the non-descriptor 5440 // DAG. 5441 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5442 } 5443 5444 static void 5445 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5446 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5447 SelectionDAG &DAG, 5448 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5449 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5450 const PPCSubtarget &Subtarget) { 5451 const bool IsPPC64 = Subtarget.isPPC64(); 5452 // MVT for a general purpose register. 5453 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5454 5455 // First operand is always the chain. 5456 Ops.push_back(Chain); 5457 5458 // If it's a direct call pass the callee as the second operand. 5459 if (!CFlags.IsIndirect) 5460 Ops.push_back(Callee); 5461 else { 5462 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5463 5464 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5465 // on the stack (this would have been done in `LowerCall_64SVR4` or 5466 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5467 // represents both the indirect branch and a load that restores the TOC 5468 // pointer from the linkage area. The operand for the TOC restore is an add 5469 // of the TOC save offset to the stack pointer. This must be the second 5470 // operand: after the chain input but before any other variadic arguments. 5471 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5472 // saved or used. 5473 if (isTOCSaveRestoreRequired(Subtarget)) { 5474 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5475 5476 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5477 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5478 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5479 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5480 Ops.push_back(AddTOC); 5481 } 5482 5483 // Add the register used for the environment pointer. 5484 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5485 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5486 RegVT)); 5487 5488 5489 // Add CTR register as callee so a bctr can be emitted later. 5490 if (CFlags.IsTailCall) 5491 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5492 } 5493 5494 // If this is a tail call add stack pointer delta. 5495 if (CFlags.IsTailCall) 5496 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5497 5498 // Add argument registers to the end of the list so that they are known live 5499 // into the call. 5500 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5501 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5502 RegsToPass[i].second.getValueType())); 5503 5504 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5505 // no way to mark dependencies as implicit here. 5506 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5507 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5508 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5509 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5510 5511 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5512 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5513 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5514 5515 // Add a register mask operand representing the call-preserved registers. 5516 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5517 const uint32_t *Mask = 5518 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5519 assert(Mask && "Missing call preserved mask for calling convention"); 5520 Ops.push_back(DAG.getRegisterMask(Mask)); 5521 5522 // If the glue is valid, it is the last operand. 5523 if (Glue.getNode()) 5524 Ops.push_back(Glue); 5525 } 5526 5527 SDValue PPCTargetLowering::FinishCall( 5528 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5529 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5530 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5531 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5532 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5533 5534 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5535 Subtarget.isAIXABI()) 5536 setUsesTOCBasePtr(DAG); 5537 5538 unsigned CallOpc = 5539 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5540 Subtarget, DAG.getTarget()); 5541 5542 if (!CFlags.IsIndirect) 5543 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5544 else if (Subtarget.usesFunctionDescriptors()) 5545 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5546 dl, CFlags.HasNest, Subtarget); 5547 else 5548 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5549 5550 // Build the operand list for the call instruction. 5551 SmallVector<SDValue, 8> Ops; 5552 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5553 SPDiff, Subtarget); 5554 5555 // Emit tail call. 5556 if (CFlags.IsTailCall) { 5557 // Indirect tail call when using PC Relative calls do not have the same 5558 // constraints. 5559 assert(((Callee.getOpcode() == ISD::Register && 5560 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5561 Callee.getOpcode() == ISD::TargetExternalSymbol || 5562 Callee.getOpcode() == ISD::TargetGlobalAddress || 5563 isa<ConstantSDNode>(Callee) || 5564 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5565 "Expecting a global address, external symbol, absolute value, " 5566 "register or an indirect tail call when PC Relative calls are " 5567 "used."); 5568 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5569 assert(CallOpc == PPCISD::TC_RETURN && 5570 "Unexpected call opcode for a tail call."); 5571 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5572 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5573 } 5574 5575 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5576 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5577 Glue = Chain.getValue(1); 5578 5579 // When performing tail call optimization the callee pops its arguments off 5580 // the stack. Account for this here so these bytes can be pushed back on in 5581 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5582 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5583 getTargetMachine().Options.GuaranteedTailCallOpt) 5584 ? NumBytes 5585 : 0; 5586 5587 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5588 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5589 Glue, dl); 5590 Glue = Chain.getValue(1); 5591 5592 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5593 DAG, InVals); 5594 } 5595 5596 SDValue 5597 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5598 SmallVectorImpl<SDValue> &InVals) const { 5599 SelectionDAG &DAG = CLI.DAG; 5600 SDLoc &dl = CLI.DL; 5601 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5602 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5603 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5604 SDValue Chain = CLI.Chain; 5605 SDValue Callee = CLI.Callee; 5606 bool &isTailCall = CLI.IsTailCall; 5607 CallingConv::ID CallConv = CLI.CallConv; 5608 bool isVarArg = CLI.IsVarArg; 5609 bool isPatchPoint = CLI.IsPatchPoint; 5610 const CallBase *CB = CLI.CB; 5611 5612 if (isTailCall) { 5613 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5614 isTailCall = false; 5615 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5616 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5617 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5618 else 5619 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5620 Ins, DAG); 5621 if (isTailCall) { 5622 ++NumTailCalls; 5623 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5624 ++NumSiblingCalls; 5625 5626 // PC Relative calls no longer guarantee that the callee is a Global 5627 // Address Node. The callee could be an indirect tail call in which 5628 // case the SDValue for the callee could be a load (to load the address 5629 // of a function pointer) or it may be a register copy (to move the 5630 // address of the callee from a function parameter into a virtual 5631 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5632 assert((Subtarget.isUsingPCRelativeCalls() || 5633 isa<GlobalAddressSDNode>(Callee)) && 5634 "Callee should be an llvm::Function object."); 5635 5636 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5637 << "\nTCO callee: "); 5638 LLVM_DEBUG(Callee.dump()); 5639 } 5640 } 5641 5642 if (!isTailCall && CB && CB->isMustTailCall()) 5643 report_fatal_error("failed to perform tail call elimination on a call " 5644 "site marked musttail"); 5645 5646 // When long calls (i.e. indirect calls) are always used, calls are always 5647 // made via function pointer. If we have a function name, first translate it 5648 // into a pointer. 5649 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5650 !isTailCall) 5651 Callee = LowerGlobalAddress(Callee, DAG); 5652 5653 CallFlags CFlags( 5654 CallConv, isTailCall, isVarArg, isPatchPoint, 5655 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5656 // hasNest 5657 Subtarget.is64BitELFABI() && 5658 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); })); 5659 5660 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5661 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5662 InVals, CB); 5663 5664 if (Subtarget.isSVR4ABI()) 5665 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5666 InVals, CB); 5667 5668 if (Subtarget.isAIXABI()) 5669 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5670 InVals, CB); 5671 5672 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5673 InVals, CB); 5674 } 5675 5676 SDValue PPCTargetLowering::LowerCall_32SVR4( 5677 SDValue Chain, SDValue Callee, CallFlags CFlags, 5678 const SmallVectorImpl<ISD::OutputArg> &Outs, 5679 const SmallVectorImpl<SDValue> &OutVals, 5680 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5681 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5682 const CallBase *CB) const { 5683 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5684 // of the 32-bit SVR4 ABI stack frame layout. 5685 5686 const CallingConv::ID CallConv = CFlags.CallConv; 5687 const bool IsVarArg = CFlags.IsVarArg; 5688 const bool IsTailCall = CFlags.IsTailCall; 5689 5690 assert((CallConv == CallingConv::C || 5691 CallConv == CallingConv::Cold || 5692 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5693 5694 unsigned PtrByteSize = 4; 5695 5696 MachineFunction &MF = DAG.getMachineFunction(); 5697 5698 // Mark this function as potentially containing a function that contains a 5699 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5700 // and restoring the callers stack pointer in this functions epilog. This is 5701 // done because by tail calling the called function might overwrite the value 5702 // in this function's (MF) stack pointer stack slot 0(SP). 5703 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5704 CallConv == CallingConv::Fast) 5705 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5706 5707 // Count how many bytes are to be pushed on the stack, including the linkage 5708 // area, parameter list area and the part of the local variable space which 5709 // contains copies of aggregates which are passed by value. 5710 5711 // Assign locations to all of the outgoing arguments. 5712 SmallVector<CCValAssign, 16> ArgLocs; 5713 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5714 5715 // Reserve space for the linkage area on the stack. 5716 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5717 PtrByteSize); 5718 if (useSoftFloat()) 5719 CCInfo.PreAnalyzeCallOperands(Outs); 5720 5721 if (IsVarArg) { 5722 // Handle fixed and variable vector arguments differently. 5723 // Fixed vector arguments go into registers as long as registers are 5724 // available. Variable vector arguments always go into memory. 5725 unsigned NumArgs = Outs.size(); 5726 5727 for (unsigned i = 0; i != NumArgs; ++i) { 5728 MVT ArgVT = Outs[i].VT; 5729 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5730 bool Result; 5731 5732 if (Outs[i].IsFixed) { 5733 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5734 CCInfo); 5735 } else { 5736 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5737 ArgFlags, CCInfo); 5738 } 5739 5740 if (Result) { 5741 #ifndef NDEBUG 5742 errs() << "Call operand #" << i << " has unhandled type " 5743 << EVT(ArgVT).getEVTString() << "\n"; 5744 #endif 5745 llvm_unreachable(nullptr); 5746 } 5747 } 5748 } else { 5749 // All arguments are treated the same. 5750 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5751 } 5752 CCInfo.clearWasPPCF128(); 5753 5754 // Assign locations to all of the outgoing aggregate by value arguments. 5755 SmallVector<CCValAssign, 16> ByValArgLocs; 5756 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5757 5758 // Reserve stack space for the allocations in CCInfo. 5759 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5760 5761 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5762 5763 // Size of the linkage area, parameter list area and the part of the local 5764 // space variable where copies of aggregates which are passed by value are 5765 // stored. 5766 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5767 5768 // Calculate by how many bytes the stack has to be adjusted in case of tail 5769 // call optimization. 5770 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5771 5772 // Adjust the stack pointer for the new arguments... 5773 // These operations are automatically eliminated by the prolog/epilog pass 5774 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5775 SDValue CallSeqStart = Chain; 5776 5777 // Load the return address and frame pointer so it can be moved somewhere else 5778 // later. 5779 SDValue LROp, FPOp; 5780 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5781 5782 // Set up a copy of the stack pointer for use loading and storing any 5783 // arguments that may not fit in the registers available for argument 5784 // passing. 5785 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5786 5787 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5788 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5789 SmallVector<SDValue, 8> MemOpChains; 5790 5791 bool seenFloatArg = false; 5792 // Walk the register/memloc assignments, inserting copies/loads. 5793 // i - Tracks the index into the list of registers allocated for the call 5794 // RealArgIdx - Tracks the index into the list of actual function arguments 5795 // j - Tracks the index into the list of byval arguments 5796 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5797 i != e; 5798 ++i, ++RealArgIdx) { 5799 CCValAssign &VA = ArgLocs[i]; 5800 SDValue Arg = OutVals[RealArgIdx]; 5801 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5802 5803 if (Flags.isByVal()) { 5804 // Argument is an aggregate which is passed by value, thus we need to 5805 // create a copy of it in the local variable space of the current stack 5806 // frame (which is the stack frame of the caller) and pass the address of 5807 // this copy to the callee. 5808 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5809 CCValAssign &ByValVA = ByValArgLocs[j++]; 5810 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5811 5812 // Memory reserved in the local variable space of the callers stack frame. 5813 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5814 5815 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5816 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5817 StackPtr, PtrOff); 5818 5819 // Create a copy of the argument in the local area of the current 5820 // stack frame. 5821 SDValue MemcpyCall = 5822 CreateCopyOfByValArgument(Arg, PtrOff, 5823 CallSeqStart.getNode()->getOperand(0), 5824 Flags, DAG, dl); 5825 5826 // This must go outside the CALLSEQ_START..END. 5827 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5828 SDLoc(MemcpyCall)); 5829 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5830 NewCallSeqStart.getNode()); 5831 Chain = CallSeqStart = NewCallSeqStart; 5832 5833 // Pass the address of the aggregate copy on the stack either in a 5834 // physical register or in the parameter list area of the current stack 5835 // frame to the callee. 5836 Arg = PtrOff; 5837 } 5838 5839 // When useCRBits() is true, there can be i1 arguments. 5840 // It is because getRegisterType(MVT::i1) => MVT::i1, 5841 // and for other integer types getRegisterType() => MVT::i32. 5842 // Extend i1 and ensure callee will get i32. 5843 if (Arg.getValueType() == MVT::i1) 5844 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5845 dl, MVT::i32, Arg); 5846 5847 if (VA.isRegLoc()) { 5848 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5849 // Put argument in a physical register. 5850 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5851 bool IsLE = Subtarget.isLittleEndian(); 5852 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5853 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5854 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5855 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5856 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5857 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5858 SVal.getValue(0))); 5859 } else 5860 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5861 } else { 5862 // Put argument in the parameter list area of the current stack frame. 5863 assert(VA.isMemLoc()); 5864 unsigned LocMemOffset = VA.getLocMemOffset(); 5865 5866 if (!IsTailCall) { 5867 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5868 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5869 StackPtr, PtrOff); 5870 5871 MemOpChains.push_back( 5872 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5873 } else { 5874 // Calculate and remember argument location. 5875 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5876 TailCallArguments); 5877 } 5878 } 5879 } 5880 5881 if (!MemOpChains.empty()) 5882 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5883 5884 // Build a sequence of copy-to-reg nodes chained together with token chain 5885 // and flag operands which copy the outgoing args into the appropriate regs. 5886 SDValue InFlag; 5887 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5888 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5889 RegsToPass[i].second, InFlag); 5890 InFlag = Chain.getValue(1); 5891 } 5892 5893 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5894 // registers. 5895 if (IsVarArg) { 5896 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5897 SDValue Ops[] = { Chain, InFlag }; 5898 5899 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5900 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5901 5902 InFlag = Chain.getValue(1); 5903 } 5904 5905 if (IsTailCall) 5906 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5907 TailCallArguments); 5908 5909 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5910 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5911 } 5912 5913 // Copy an argument into memory, being careful to do this outside the 5914 // call sequence for the call to which the argument belongs. 5915 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5916 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5917 SelectionDAG &DAG, const SDLoc &dl) const { 5918 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5919 CallSeqStart.getNode()->getOperand(0), 5920 Flags, DAG, dl); 5921 // The MEMCPY must go outside the CALLSEQ_START..END. 5922 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5923 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5924 SDLoc(MemcpyCall)); 5925 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5926 NewCallSeqStart.getNode()); 5927 return NewCallSeqStart; 5928 } 5929 5930 SDValue PPCTargetLowering::LowerCall_64SVR4( 5931 SDValue Chain, SDValue Callee, CallFlags CFlags, 5932 const SmallVectorImpl<ISD::OutputArg> &Outs, 5933 const SmallVectorImpl<SDValue> &OutVals, 5934 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5935 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5936 const CallBase *CB) const { 5937 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5938 bool isLittleEndian = Subtarget.isLittleEndian(); 5939 unsigned NumOps = Outs.size(); 5940 bool IsSibCall = false; 5941 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5942 5943 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5944 unsigned PtrByteSize = 8; 5945 5946 MachineFunction &MF = DAG.getMachineFunction(); 5947 5948 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5949 IsSibCall = true; 5950 5951 // Mark this function as potentially containing a function that contains a 5952 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5953 // and restoring the callers stack pointer in this functions epilog. This is 5954 // done because by tail calling the called function might overwrite the value 5955 // in this function's (MF) stack pointer stack slot 0(SP). 5956 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5957 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5958 5959 assert(!(IsFastCall && CFlags.IsVarArg) && 5960 "fastcc not supported on varargs functions"); 5961 5962 // Count how many bytes are to be pushed on the stack, including the linkage 5963 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5964 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5965 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5966 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5967 unsigned NumBytes = LinkageSize; 5968 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5969 unsigned &QFPR_idx = FPR_idx; 5970 5971 static const MCPhysReg GPR[] = { 5972 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5973 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5974 }; 5975 static const MCPhysReg VR[] = { 5976 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5977 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5978 }; 5979 5980 const unsigned NumGPRs = array_lengthof(GPR); 5981 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5982 const unsigned NumVRs = array_lengthof(VR); 5983 const unsigned NumQFPRs = NumFPRs; 5984 5985 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5986 // can be passed to the callee in registers. 5987 // For the fast calling convention, there is another check below. 5988 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5989 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5990 if (!HasParameterArea) { 5991 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5992 unsigned AvailableFPRs = NumFPRs; 5993 unsigned AvailableVRs = NumVRs; 5994 unsigned NumBytesTmp = NumBytes; 5995 for (unsigned i = 0; i != NumOps; ++i) { 5996 if (Outs[i].Flags.isNest()) continue; 5997 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5998 PtrByteSize, LinkageSize, ParamAreaSize, 5999 NumBytesTmp, AvailableFPRs, AvailableVRs, 6000 Subtarget.hasQPX())) 6001 HasParameterArea = true; 6002 } 6003 } 6004 6005 // When using the fast calling convention, we don't provide backing for 6006 // arguments that will be in registers. 6007 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6008 6009 // Avoid allocating parameter area for fastcc functions if all the arguments 6010 // can be passed in the registers. 6011 if (IsFastCall) 6012 HasParameterArea = false; 6013 6014 // Add up all the space actually used. 6015 for (unsigned i = 0; i != NumOps; ++i) { 6016 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6017 EVT ArgVT = Outs[i].VT; 6018 EVT OrigVT = Outs[i].ArgVT; 6019 6020 if (Flags.isNest()) 6021 continue; 6022 6023 if (IsFastCall) { 6024 if (Flags.isByVal()) { 6025 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6026 if (NumGPRsUsed > NumGPRs) 6027 HasParameterArea = true; 6028 } else { 6029 switch (ArgVT.getSimpleVT().SimpleTy) { 6030 default: llvm_unreachable("Unexpected ValueType for argument!"); 6031 case MVT::i1: 6032 case MVT::i32: 6033 case MVT::i64: 6034 if (++NumGPRsUsed <= NumGPRs) 6035 continue; 6036 break; 6037 case MVT::v4i32: 6038 case MVT::v8i16: 6039 case MVT::v16i8: 6040 case MVT::v2f64: 6041 case MVT::v2i64: 6042 case MVT::v1i128: 6043 case MVT::f128: 6044 if (++NumVRsUsed <= NumVRs) 6045 continue; 6046 break; 6047 case MVT::v4f32: 6048 // When using QPX, this is handled like a FP register, otherwise, it 6049 // is an Altivec register. 6050 if (Subtarget.hasQPX()) { 6051 if (++NumFPRsUsed <= NumFPRs) 6052 continue; 6053 } else { 6054 if (++NumVRsUsed <= NumVRs) 6055 continue; 6056 } 6057 break; 6058 case MVT::f32: 6059 case MVT::f64: 6060 case MVT::v4f64: // QPX 6061 case MVT::v4i1: // QPX 6062 if (++NumFPRsUsed <= NumFPRs) 6063 continue; 6064 break; 6065 } 6066 HasParameterArea = true; 6067 } 6068 } 6069 6070 /* Respect alignment of argument on the stack. */ 6071 auto Alignement = 6072 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6073 NumBytes = alignTo(NumBytes, Alignement); 6074 6075 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6076 if (Flags.isInConsecutiveRegsLast()) 6077 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6078 } 6079 6080 unsigned NumBytesActuallyUsed = NumBytes; 6081 6082 // In the old ELFv1 ABI, 6083 // the prolog code of the callee may store up to 8 GPR argument registers to 6084 // the stack, allowing va_start to index over them in memory if its varargs. 6085 // Because we cannot tell if this is needed on the caller side, we have to 6086 // conservatively assume that it is needed. As such, make sure we have at 6087 // least enough stack space for the caller to store the 8 GPRs. 6088 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6089 // really requires memory operands, e.g. a vararg function. 6090 if (HasParameterArea) 6091 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6092 else 6093 NumBytes = LinkageSize; 6094 6095 // Tail call needs the stack to be aligned. 6096 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6097 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6098 6099 int SPDiff = 0; 6100 6101 // Calculate by how many bytes the stack has to be adjusted in case of tail 6102 // call optimization. 6103 if (!IsSibCall) 6104 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6105 6106 // To protect arguments on the stack from being clobbered in a tail call, 6107 // force all the loads to happen before doing any other lowering. 6108 if (CFlags.IsTailCall) 6109 Chain = DAG.getStackArgumentTokenFactor(Chain); 6110 6111 // Adjust the stack pointer for the new arguments... 6112 // These operations are automatically eliminated by the prolog/epilog pass 6113 if (!IsSibCall) 6114 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6115 SDValue CallSeqStart = Chain; 6116 6117 // Load the return address and frame pointer so it can be move somewhere else 6118 // later. 6119 SDValue LROp, FPOp; 6120 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6121 6122 // Set up a copy of the stack pointer for use loading and storing any 6123 // arguments that may not fit in the registers available for argument 6124 // passing. 6125 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6126 6127 // Figure out which arguments are going to go in registers, and which in 6128 // memory. Also, if this is a vararg function, floating point operations 6129 // must be stored to our stack, and loaded into integer regs as well, if 6130 // any integer regs are available for argument passing. 6131 unsigned ArgOffset = LinkageSize; 6132 6133 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6134 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6135 6136 SmallVector<SDValue, 8> MemOpChains; 6137 for (unsigned i = 0; i != NumOps; ++i) { 6138 SDValue Arg = OutVals[i]; 6139 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6140 EVT ArgVT = Outs[i].VT; 6141 EVT OrigVT = Outs[i].ArgVT; 6142 6143 // PtrOff will be used to store the current argument to the stack if a 6144 // register cannot be found for it. 6145 SDValue PtrOff; 6146 6147 // We re-align the argument offset for each argument, except when using the 6148 // fast calling convention, when we need to make sure we do that only when 6149 // we'll actually use a stack slot. 6150 auto ComputePtrOff = [&]() { 6151 /* Respect alignment of argument on the stack. */ 6152 auto Alignment = 6153 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6154 ArgOffset = alignTo(ArgOffset, Alignment); 6155 6156 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6157 6158 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6159 }; 6160 6161 if (!IsFastCall) { 6162 ComputePtrOff(); 6163 6164 /* Compute GPR index associated with argument offset. */ 6165 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6166 GPR_idx = std::min(GPR_idx, NumGPRs); 6167 } 6168 6169 // Promote integers to 64-bit values. 6170 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6171 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6172 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6173 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6174 } 6175 6176 // FIXME memcpy is used way more than necessary. Correctness first. 6177 // Note: "by value" is code for passing a structure by value, not 6178 // basic types. 6179 if (Flags.isByVal()) { 6180 // Note: Size includes alignment padding, so 6181 // struct x { short a; char b; } 6182 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6183 // These are the proper values we need for right-justifying the 6184 // aggregate in a parameter register. 6185 unsigned Size = Flags.getByValSize(); 6186 6187 // An empty aggregate parameter takes up no storage and no 6188 // registers. 6189 if (Size == 0) 6190 continue; 6191 6192 if (IsFastCall) 6193 ComputePtrOff(); 6194 6195 // All aggregates smaller than 8 bytes must be passed right-justified. 6196 if (Size==1 || Size==2 || Size==4) { 6197 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6198 if (GPR_idx != NumGPRs) { 6199 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6200 MachinePointerInfo(), VT); 6201 MemOpChains.push_back(Load.getValue(1)); 6202 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6203 6204 ArgOffset += PtrByteSize; 6205 continue; 6206 } 6207 } 6208 6209 if (GPR_idx == NumGPRs && Size < 8) { 6210 SDValue AddPtr = PtrOff; 6211 if (!isLittleEndian) { 6212 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6213 PtrOff.getValueType()); 6214 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6215 } 6216 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6217 CallSeqStart, 6218 Flags, DAG, dl); 6219 ArgOffset += PtrByteSize; 6220 continue; 6221 } 6222 // Copy entire object into memory. There are cases where gcc-generated 6223 // code assumes it is there, even if it could be put entirely into 6224 // registers. (This is not what the doc says.) 6225 6226 // FIXME: The above statement is likely due to a misunderstanding of the 6227 // documents. All arguments must be copied into the parameter area BY 6228 // THE CALLEE in the event that the callee takes the address of any 6229 // formal argument. That has not yet been implemented. However, it is 6230 // reasonable to use the stack area as a staging area for the register 6231 // load. 6232 6233 // Skip this for small aggregates, as we will use the same slot for a 6234 // right-justified copy, below. 6235 if (Size >= 8) 6236 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6237 CallSeqStart, 6238 Flags, DAG, dl); 6239 6240 // When a register is available, pass a small aggregate right-justified. 6241 if (Size < 8 && GPR_idx != NumGPRs) { 6242 // The easiest way to get this right-justified in a register 6243 // is to copy the structure into the rightmost portion of a 6244 // local variable slot, then load the whole slot into the 6245 // register. 6246 // FIXME: The memcpy seems to produce pretty awful code for 6247 // small aggregates, particularly for packed ones. 6248 // FIXME: It would be preferable to use the slot in the 6249 // parameter save area instead of a new local variable. 6250 SDValue AddPtr = PtrOff; 6251 if (!isLittleEndian) { 6252 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6253 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6254 } 6255 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6256 CallSeqStart, 6257 Flags, DAG, dl); 6258 6259 // Load the slot into the register. 6260 SDValue Load = 6261 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6262 MemOpChains.push_back(Load.getValue(1)); 6263 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6264 6265 // Done with this argument. 6266 ArgOffset += PtrByteSize; 6267 continue; 6268 } 6269 6270 // For aggregates larger than PtrByteSize, copy the pieces of the 6271 // object that fit into registers from the parameter save area. 6272 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6273 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6274 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6275 if (GPR_idx != NumGPRs) { 6276 SDValue Load = 6277 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6278 MemOpChains.push_back(Load.getValue(1)); 6279 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6280 ArgOffset += PtrByteSize; 6281 } else { 6282 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6283 break; 6284 } 6285 } 6286 continue; 6287 } 6288 6289 switch (Arg.getSimpleValueType().SimpleTy) { 6290 default: llvm_unreachable("Unexpected ValueType for argument!"); 6291 case MVT::i1: 6292 case MVT::i32: 6293 case MVT::i64: 6294 if (Flags.isNest()) { 6295 // The 'nest' parameter, if any, is passed in R11. 6296 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6297 break; 6298 } 6299 6300 // These can be scalar arguments or elements of an integer array type 6301 // passed directly. Clang may use those instead of "byval" aggregate 6302 // types to avoid forcing arguments to memory unnecessarily. 6303 if (GPR_idx != NumGPRs) { 6304 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6305 } else { 6306 if (IsFastCall) 6307 ComputePtrOff(); 6308 6309 assert(HasParameterArea && 6310 "Parameter area must exist to pass an argument in memory."); 6311 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6312 true, CFlags.IsTailCall, false, MemOpChains, 6313 TailCallArguments, dl); 6314 if (IsFastCall) 6315 ArgOffset += PtrByteSize; 6316 } 6317 if (!IsFastCall) 6318 ArgOffset += PtrByteSize; 6319 break; 6320 case MVT::f32: 6321 case MVT::f64: { 6322 // These can be scalar arguments or elements of a float array type 6323 // passed directly. The latter are used to implement ELFv2 homogenous 6324 // float aggregates. 6325 6326 // Named arguments go into FPRs first, and once they overflow, the 6327 // remaining arguments go into GPRs and then the parameter save area. 6328 // Unnamed arguments for vararg functions always go to GPRs and 6329 // then the parameter save area. For now, put all arguments to vararg 6330 // routines always in both locations (FPR *and* GPR or stack slot). 6331 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6332 bool NeededLoad = false; 6333 6334 // First load the argument into the next available FPR. 6335 if (FPR_idx != NumFPRs) 6336 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6337 6338 // Next, load the argument into GPR or stack slot if needed. 6339 if (!NeedGPROrStack) 6340 ; 6341 else if (GPR_idx != NumGPRs && !IsFastCall) { 6342 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6343 // once we support fp <-> gpr moves. 6344 6345 // In the non-vararg case, this can only ever happen in the 6346 // presence of f32 array types, since otherwise we never run 6347 // out of FPRs before running out of GPRs. 6348 SDValue ArgVal; 6349 6350 // Double values are always passed in a single GPR. 6351 if (Arg.getValueType() != MVT::f32) { 6352 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6353 6354 // Non-array float values are extended and passed in a GPR. 6355 } else if (!Flags.isInConsecutiveRegs()) { 6356 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6357 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6358 6359 // If we have an array of floats, we collect every odd element 6360 // together with its predecessor into one GPR. 6361 } else if (ArgOffset % PtrByteSize != 0) { 6362 SDValue Lo, Hi; 6363 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6364 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6365 if (!isLittleEndian) 6366 std::swap(Lo, Hi); 6367 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6368 6369 // The final element, if even, goes into the first half of a GPR. 6370 } else if (Flags.isInConsecutiveRegsLast()) { 6371 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6372 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6373 if (!isLittleEndian) 6374 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6375 DAG.getConstant(32, dl, MVT::i32)); 6376 6377 // Non-final even elements are skipped; they will be handled 6378 // together the with subsequent argument on the next go-around. 6379 } else 6380 ArgVal = SDValue(); 6381 6382 if (ArgVal.getNode()) 6383 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6384 } else { 6385 if (IsFastCall) 6386 ComputePtrOff(); 6387 6388 // Single-precision floating-point values are mapped to the 6389 // second (rightmost) word of the stack doubleword. 6390 if (Arg.getValueType() == MVT::f32 && 6391 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6392 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6393 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6394 } 6395 6396 assert(HasParameterArea && 6397 "Parameter area must exist to pass an argument in memory."); 6398 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6399 true, CFlags.IsTailCall, false, MemOpChains, 6400 TailCallArguments, dl); 6401 6402 NeededLoad = true; 6403 } 6404 // When passing an array of floats, the array occupies consecutive 6405 // space in the argument area; only round up to the next doubleword 6406 // at the end of the array. Otherwise, each float takes 8 bytes. 6407 if (!IsFastCall || NeededLoad) { 6408 ArgOffset += (Arg.getValueType() == MVT::f32 && 6409 Flags.isInConsecutiveRegs()) ? 4 : 8; 6410 if (Flags.isInConsecutiveRegsLast()) 6411 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6412 } 6413 break; 6414 } 6415 case MVT::v4f32: 6416 case MVT::v4i32: 6417 case MVT::v8i16: 6418 case MVT::v16i8: 6419 case MVT::v2f64: 6420 case MVT::v2i64: 6421 case MVT::v1i128: 6422 case MVT::f128: 6423 if (!Subtarget.hasQPX()) { 6424 // These can be scalar arguments or elements of a vector array type 6425 // passed directly. The latter are used to implement ELFv2 homogenous 6426 // vector aggregates. 6427 6428 // For a varargs call, named arguments go into VRs or on the stack as 6429 // usual; unnamed arguments always go to the stack or the corresponding 6430 // GPRs when within range. For now, we always put the value in both 6431 // locations (or even all three). 6432 if (CFlags.IsVarArg) { 6433 assert(HasParameterArea && 6434 "Parameter area must exist if we have a varargs call."); 6435 // We could elide this store in the case where the object fits 6436 // entirely in R registers. Maybe later. 6437 SDValue Store = 6438 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6439 MemOpChains.push_back(Store); 6440 if (VR_idx != NumVRs) { 6441 SDValue Load = 6442 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6443 MemOpChains.push_back(Load.getValue(1)); 6444 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6445 } 6446 ArgOffset += 16; 6447 for (unsigned i=0; i<16; i+=PtrByteSize) { 6448 if (GPR_idx == NumGPRs) 6449 break; 6450 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6451 DAG.getConstant(i, dl, PtrVT)); 6452 SDValue Load = 6453 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6454 MemOpChains.push_back(Load.getValue(1)); 6455 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6456 } 6457 break; 6458 } 6459 6460 // Non-varargs Altivec params go into VRs or on the stack. 6461 if (VR_idx != NumVRs) { 6462 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6463 } else { 6464 if (IsFastCall) 6465 ComputePtrOff(); 6466 6467 assert(HasParameterArea && 6468 "Parameter area must exist to pass an argument in memory."); 6469 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6470 true, CFlags.IsTailCall, true, MemOpChains, 6471 TailCallArguments, dl); 6472 if (IsFastCall) 6473 ArgOffset += 16; 6474 } 6475 6476 if (!IsFastCall) 6477 ArgOffset += 16; 6478 break; 6479 } // not QPX 6480 6481 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6482 "Invalid QPX parameter type"); 6483 6484 LLVM_FALLTHROUGH; 6485 case MVT::v4f64: 6486 case MVT::v4i1: { 6487 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6488 if (CFlags.IsVarArg) { 6489 assert(HasParameterArea && 6490 "Parameter area must exist if we have a varargs call."); 6491 // We could elide this store in the case where the object fits 6492 // entirely in R registers. Maybe later. 6493 SDValue Store = 6494 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6495 MemOpChains.push_back(Store); 6496 if (QFPR_idx != NumQFPRs) { 6497 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6498 PtrOff, MachinePointerInfo()); 6499 MemOpChains.push_back(Load.getValue(1)); 6500 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6501 } 6502 ArgOffset += (IsF32 ? 16 : 32); 6503 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6504 if (GPR_idx == NumGPRs) 6505 break; 6506 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6507 DAG.getConstant(i, dl, PtrVT)); 6508 SDValue Load = 6509 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6510 MemOpChains.push_back(Load.getValue(1)); 6511 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6512 } 6513 break; 6514 } 6515 6516 // Non-varargs QPX params go into registers or on the stack. 6517 if (QFPR_idx != NumQFPRs) { 6518 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6519 } else { 6520 if (IsFastCall) 6521 ComputePtrOff(); 6522 6523 assert(HasParameterArea && 6524 "Parameter area must exist to pass an argument in memory."); 6525 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6526 true, CFlags.IsTailCall, true, MemOpChains, 6527 TailCallArguments, dl); 6528 if (IsFastCall) 6529 ArgOffset += (IsF32 ? 16 : 32); 6530 } 6531 6532 if (!IsFastCall) 6533 ArgOffset += (IsF32 ? 16 : 32); 6534 break; 6535 } 6536 } 6537 } 6538 6539 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6540 "mismatch in size of parameter area"); 6541 (void)NumBytesActuallyUsed; 6542 6543 if (!MemOpChains.empty()) 6544 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6545 6546 // Check if this is an indirect call (MTCTR/BCTRL). 6547 // See prepareDescriptorIndirectCall and buildCallOperands for more 6548 // information about calls through function pointers in the 64-bit SVR4 ABI. 6549 if (CFlags.IsIndirect) { 6550 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6551 // caller in the TOC save area. 6552 if (isTOCSaveRestoreRequired(Subtarget)) { 6553 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6554 // Load r2 into a virtual register and store it to the TOC save area. 6555 setUsesTOCBasePtr(DAG); 6556 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6557 // TOC save area offset. 6558 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6559 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6560 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6561 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6562 MachinePointerInfo::getStack( 6563 DAG.getMachineFunction(), TOCSaveOffset)); 6564 } 6565 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6566 // This does not mean the MTCTR instruction must use R12; it's easier 6567 // to model this as an extra parameter, so do that. 6568 if (isELFv2ABI && !CFlags.IsPatchPoint) 6569 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6570 } 6571 6572 // Build a sequence of copy-to-reg nodes chained together with token chain 6573 // and flag operands which copy the outgoing args into the appropriate regs. 6574 SDValue InFlag; 6575 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6576 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6577 RegsToPass[i].second, InFlag); 6578 InFlag = Chain.getValue(1); 6579 } 6580 6581 if (CFlags.IsTailCall && !IsSibCall) 6582 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6583 TailCallArguments); 6584 6585 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6586 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6587 } 6588 6589 SDValue PPCTargetLowering::LowerCall_Darwin( 6590 SDValue Chain, SDValue Callee, CallFlags CFlags, 6591 const SmallVectorImpl<ISD::OutputArg> &Outs, 6592 const SmallVectorImpl<SDValue> &OutVals, 6593 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6594 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6595 const CallBase *CB) const { 6596 unsigned NumOps = Outs.size(); 6597 6598 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6599 bool isPPC64 = PtrVT == MVT::i64; 6600 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6601 6602 MachineFunction &MF = DAG.getMachineFunction(); 6603 6604 // Mark this function as potentially containing a function that contains a 6605 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6606 // and restoring the callers stack pointer in this functions epilog. This is 6607 // done because by tail calling the called function might overwrite the value 6608 // in this function's (MF) stack pointer stack slot 0(SP). 6609 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6610 CFlags.CallConv == CallingConv::Fast) 6611 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6612 6613 // Count how many bytes are to be pushed on the stack, including the linkage 6614 // area, and parameter passing area. We start with 24/48 bytes, which is 6615 // prereserved space for [SP][CR][LR][3 x unused]. 6616 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6617 unsigned NumBytes = LinkageSize; 6618 6619 // Add up all the space actually used. 6620 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6621 // they all go in registers, but we must reserve stack space for them for 6622 // possible use by the caller. In varargs or 64-bit calls, parameters are 6623 // assigned stack space in order, with padding so Altivec parameters are 6624 // 16-byte aligned. 6625 unsigned nAltivecParamsAtEnd = 0; 6626 for (unsigned i = 0; i != NumOps; ++i) { 6627 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6628 EVT ArgVT = Outs[i].VT; 6629 // Varargs Altivec parameters are padded to a 16 byte boundary. 6630 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6631 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6632 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6633 if (!CFlags.IsVarArg && !isPPC64) { 6634 // Non-varargs Altivec parameters go after all the non-Altivec 6635 // parameters; handle those later so we know how much padding we need. 6636 nAltivecParamsAtEnd++; 6637 continue; 6638 } 6639 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6640 NumBytes = ((NumBytes+15)/16)*16; 6641 } 6642 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6643 } 6644 6645 // Allow for Altivec parameters at the end, if needed. 6646 if (nAltivecParamsAtEnd) { 6647 NumBytes = ((NumBytes+15)/16)*16; 6648 NumBytes += 16*nAltivecParamsAtEnd; 6649 } 6650 6651 // The prolog code of the callee may store up to 8 GPR argument registers to 6652 // the stack, allowing va_start to index over them in memory if its varargs. 6653 // Because we cannot tell if this is needed on the caller side, we have to 6654 // conservatively assume that it is needed. As such, make sure we have at 6655 // least enough stack space for the caller to store the 8 GPRs. 6656 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6657 6658 // Tail call needs the stack to be aligned. 6659 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6660 CFlags.CallConv == CallingConv::Fast) 6661 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6662 6663 // Calculate by how many bytes the stack has to be adjusted in case of tail 6664 // call optimization. 6665 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6666 6667 // To protect arguments on the stack from being clobbered in a tail call, 6668 // force all the loads to happen before doing any other lowering. 6669 if (CFlags.IsTailCall) 6670 Chain = DAG.getStackArgumentTokenFactor(Chain); 6671 6672 // Adjust the stack pointer for the new arguments... 6673 // These operations are automatically eliminated by the prolog/epilog pass 6674 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6675 SDValue CallSeqStart = Chain; 6676 6677 // Load the return address and frame pointer so it can be move somewhere else 6678 // later. 6679 SDValue LROp, FPOp; 6680 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6681 6682 // Set up a copy of the stack pointer for use loading and storing any 6683 // arguments that may not fit in the registers available for argument 6684 // passing. 6685 SDValue StackPtr; 6686 if (isPPC64) 6687 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6688 else 6689 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6690 6691 // Figure out which arguments are going to go in registers, and which in 6692 // memory. Also, if this is a vararg function, floating point operations 6693 // must be stored to our stack, and loaded into integer regs as well, if 6694 // any integer regs are available for argument passing. 6695 unsigned ArgOffset = LinkageSize; 6696 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6697 6698 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6699 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6700 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6701 }; 6702 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6703 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6704 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6705 }; 6706 static const MCPhysReg VR[] = { 6707 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6708 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6709 }; 6710 const unsigned NumGPRs = array_lengthof(GPR_32); 6711 const unsigned NumFPRs = 13; 6712 const unsigned NumVRs = array_lengthof(VR); 6713 6714 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6715 6716 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6717 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6718 6719 SmallVector<SDValue, 8> MemOpChains; 6720 for (unsigned i = 0; i != NumOps; ++i) { 6721 SDValue Arg = OutVals[i]; 6722 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6723 6724 // PtrOff will be used to store the current argument to the stack if a 6725 // register cannot be found for it. 6726 SDValue PtrOff; 6727 6728 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6729 6730 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6731 6732 // On PPC64, promote integers to 64-bit values. 6733 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6734 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6735 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6736 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6737 } 6738 6739 // FIXME memcpy is used way more than necessary. Correctness first. 6740 // Note: "by value" is code for passing a structure by value, not 6741 // basic types. 6742 if (Flags.isByVal()) { 6743 unsigned Size = Flags.getByValSize(); 6744 // Very small objects are passed right-justified. Everything else is 6745 // passed left-justified. 6746 if (Size==1 || Size==2) { 6747 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6748 if (GPR_idx != NumGPRs) { 6749 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6750 MachinePointerInfo(), VT); 6751 MemOpChains.push_back(Load.getValue(1)); 6752 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6753 6754 ArgOffset += PtrByteSize; 6755 } else { 6756 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6757 PtrOff.getValueType()); 6758 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6759 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6760 CallSeqStart, 6761 Flags, DAG, dl); 6762 ArgOffset += PtrByteSize; 6763 } 6764 continue; 6765 } 6766 // Copy entire object into memory. There are cases where gcc-generated 6767 // code assumes it is there, even if it could be put entirely into 6768 // registers. (This is not what the doc says.) 6769 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6770 CallSeqStart, 6771 Flags, DAG, dl); 6772 6773 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6774 // copy the pieces of the object that fit into registers from the 6775 // parameter save area. 6776 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6777 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6778 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6779 if (GPR_idx != NumGPRs) { 6780 SDValue Load = 6781 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6782 MemOpChains.push_back(Load.getValue(1)); 6783 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6784 ArgOffset += PtrByteSize; 6785 } else { 6786 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6787 break; 6788 } 6789 } 6790 continue; 6791 } 6792 6793 switch (Arg.getSimpleValueType().SimpleTy) { 6794 default: llvm_unreachable("Unexpected ValueType for argument!"); 6795 case MVT::i1: 6796 case MVT::i32: 6797 case MVT::i64: 6798 if (GPR_idx != NumGPRs) { 6799 if (Arg.getValueType() == MVT::i1) 6800 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6801 6802 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6803 } else { 6804 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6805 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6806 TailCallArguments, dl); 6807 } 6808 ArgOffset += PtrByteSize; 6809 break; 6810 case MVT::f32: 6811 case MVT::f64: 6812 if (FPR_idx != NumFPRs) { 6813 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6814 6815 if (CFlags.IsVarArg) { 6816 SDValue Store = 6817 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6818 MemOpChains.push_back(Store); 6819 6820 // Float varargs are always shadowed in available integer registers 6821 if (GPR_idx != NumGPRs) { 6822 SDValue Load = 6823 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6824 MemOpChains.push_back(Load.getValue(1)); 6825 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6826 } 6827 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6828 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6829 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6830 SDValue Load = 6831 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6832 MemOpChains.push_back(Load.getValue(1)); 6833 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6834 } 6835 } else { 6836 // If we have any FPRs remaining, we may also have GPRs remaining. 6837 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6838 // GPRs. 6839 if (GPR_idx != NumGPRs) 6840 ++GPR_idx; 6841 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6842 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6843 ++GPR_idx; 6844 } 6845 } else 6846 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6847 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6848 TailCallArguments, dl); 6849 if (isPPC64) 6850 ArgOffset += 8; 6851 else 6852 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6853 break; 6854 case MVT::v4f32: 6855 case MVT::v4i32: 6856 case MVT::v8i16: 6857 case MVT::v16i8: 6858 if (CFlags.IsVarArg) { 6859 // These go aligned on the stack, or in the corresponding R registers 6860 // when within range. The Darwin PPC ABI doc claims they also go in 6861 // V registers; in fact gcc does this only for arguments that are 6862 // prototyped, not for those that match the ... We do it for all 6863 // arguments, seems to work. 6864 while (ArgOffset % 16 !=0) { 6865 ArgOffset += PtrByteSize; 6866 if (GPR_idx != NumGPRs) 6867 GPR_idx++; 6868 } 6869 // We could elide this store in the case where the object fits 6870 // entirely in R registers. Maybe later. 6871 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6872 DAG.getConstant(ArgOffset, dl, PtrVT)); 6873 SDValue Store = 6874 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6875 MemOpChains.push_back(Store); 6876 if (VR_idx != NumVRs) { 6877 SDValue Load = 6878 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6879 MemOpChains.push_back(Load.getValue(1)); 6880 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6881 } 6882 ArgOffset += 16; 6883 for (unsigned i=0; i<16; i+=PtrByteSize) { 6884 if (GPR_idx == NumGPRs) 6885 break; 6886 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6887 DAG.getConstant(i, dl, PtrVT)); 6888 SDValue Load = 6889 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6890 MemOpChains.push_back(Load.getValue(1)); 6891 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6892 } 6893 break; 6894 } 6895 6896 // Non-varargs Altivec params generally go in registers, but have 6897 // stack space allocated at the end. 6898 if (VR_idx != NumVRs) { 6899 // Doesn't have GPR space allocated. 6900 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6901 } else if (nAltivecParamsAtEnd==0) { 6902 // We are emitting Altivec params in order. 6903 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6904 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6905 TailCallArguments, dl); 6906 ArgOffset += 16; 6907 } 6908 break; 6909 } 6910 } 6911 // If all Altivec parameters fit in registers, as they usually do, 6912 // they get stack space following the non-Altivec parameters. We 6913 // don't track this here because nobody below needs it. 6914 // If there are more Altivec parameters than fit in registers emit 6915 // the stores here. 6916 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6917 unsigned j = 0; 6918 // Offset is aligned; skip 1st 12 params which go in V registers. 6919 ArgOffset = ((ArgOffset+15)/16)*16; 6920 ArgOffset += 12*16; 6921 for (unsigned i = 0; i != NumOps; ++i) { 6922 SDValue Arg = OutVals[i]; 6923 EVT ArgType = Outs[i].VT; 6924 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6925 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6926 if (++j > NumVRs) { 6927 SDValue PtrOff; 6928 // We are emitting Altivec params in order. 6929 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6930 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6931 TailCallArguments, dl); 6932 ArgOffset += 16; 6933 } 6934 } 6935 } 6936 } 6937 6938 if (!MemOpChains.empty()) 6939 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6940 6941 // On Darwin, R12 must contain the address of an indirect callee. This does 6942 // not mean the MTCTR instruction must use R12; it's easier to model this as 6943 // an extra parameter, so do that. 6944 if (CFlags.IsIndirect) { 6945 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6946 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6947 PPC::R12), Callee)); 6948 } 6949 6950 // Build a sequence of copy-to-reg nodes chained together with token chain 6951 // and flag operands which copy the outgoing args into the appropriate regs. 6952 SDValue InFlag; 6953 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6954 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6955 RegsToPass[i].second, InFlag); 6956 InFlag = Chain.getValue(1); 6957 } 6958 6959 if (CFlags.IsTailCall) 6960 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6961 TailCallArguments); 6962 6963 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6964 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6965 } 6966 6967 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6968 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6969 CCState &State) { 6970 6971 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6972 State.getMachineFunction().getSubtarget()); 6973 const bool IsPPC64 = Subtarget.isPPC64(); 6974 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6975 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6976 6977 assert((!ValVT.isInteger() || 6978 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6979 "Integer argument exceeds register size: should have been legalized"); 6980 6981 if (ValVT == MVT::f128) 6982 report_fatal_error("f128 is unimplemented on AIX."); 6983 6984 if (ArgFlags.isNest()) 6985 report_fatal_error("Nest arguments are unimplemented."); 6986 6987 if (ValVT.isVector() || LocVT.isVector()) 6988 report_fatal_error("Vector arguments are unimplemented on AIX."); 6989 6990 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6991 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6992 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6993 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6994 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6995 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6996 6997 if (ArgFlags.isByVal()) { 6998 if (ArgFlags.getNonZeroByValAlign() > PtrByteSize) 6999 report_fatal_error("Pass-by-value arguments with alignment greater than " 7000 "register width are not supported."); 7001 7002 const unsigned ByValSize = ArgFlags.getByValSize(); 7003 7004 // An empty aggregate parameter takes up no storage and no registers, 7005 // but needs a MemLoc for a stack slot for the formal arguments side. 7006 if (ByValSize == 0) { 7007 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7008 State.getNextStackOffset(), RegVT, 7009 LocInfo)); 7010 return false; 7011 } 7012 7013 const unsigned StackSize = alignTo(ByValSize, PtrByteSize); 7014 unsigned Offset = State.AllocateStack(StackSize, PtrByteSize); 7015 for (const unsigned E = Offset + StackSize; Offset < E; 7016 Offset += PtrByteSize) { 7017 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7018 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7019 else { 7020 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7021 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 7022 LocInfo)); 7023 break; 7024 } 7025 } 7026 return false; 7027 } 7028 7029 // Arguments always reserve parameter save area. 7030 switch (ValVT.SimpleTy) { 7031 default: 7032 report_fatal_error("Unhandled value type for argument."); 7033 case MVT::i64: 7034 // i64 arguments should have been split to i32 for PPC32. 7035 assert(IsPPC64 && "PPC32 should have split i64 values."); 7036 LLVM_FALLTHROUGH; 7037 case MVT::i1: 7038 case MVT::i32: { 7039 const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize); 7040 // AIX integer arguments are always passed in register width. 7041 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 7042 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 7043 : CCValAssign::LocInfo::ZExt; 7044 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7045 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7046 else 7047 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 7048 7049 return false; 7050 } 7051 case MVT::f32: 7052 case MVT::f64: { 7053 // Parameter save area (PSA) is reserved even if the float passes in fpr. 7054 const unsigned StoreSize = LocVT.getStoreSize(); 7055 // Floats are always 4-byte aligned in the PSA on AIX. 7056 // This includes f64 in 64-bit mode for ABI compatibility. 7057 const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 7058 unsigned FReg = State.AllocateReg(FPR); 7059 if (FReg) 7060 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 7061 7062 // Reserve and initialize GPRs or initialize the PSA as required. 7063 for (unsigned I = 0; I < StoreSize; I += PtrByteSize) { 7064 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 7065 assert(FReg && "An FPR should be available when a GPR is reserved."); 7066 if (State.isVarArg()) { 7067 // Successfully reserved GPRs are only initialized for vararg calls. 7068 // Custom handling is required for: 7069 // f64 in PPC32 needs to be split into 2 GPRs. 7070 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 7071 State.addLoc( 7072 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7073 } 7074 } else { 7075 // If there are insufficient GPRs, the PSA needs to be initialized. 7076 // Initialization occurs even if an FPR was initialized for 7077 // compatibility with the AIX XL compiler. The full memory for the 7078 // argument will be initialized even if a prior word is saved in GPR. 7079 // A custom memLoc is used when the argument also passes in FPR so 7080 // that the callee handling can skip over it easily. 7081 State.addLoc( 7082 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 7083 LocInfo) 7084 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 7085 break; 7086 } 7087 } 7088 7089 return false; 7090 } 7091 } 7092 return true; 7093 } 7094 7095 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7096 bool IsPPC64) { 7097 assert((IsPPC64 || SVT != MVT::i64) && 7098 "i64 should have been split for 32-bit codegen."); 7099 7100 switch (SVT) { 7101 default: 7102 report_fatal_error("Unexpected value type for formal argument"); 7103 case MVT::i1: 7104 case MVT::i32: 7105 case MVT::i64: 7106 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7107 case MVT::f32: 7108 return &PPC::F4RCRegClass; 7109 case MVT::f64: 7110 return &PPC::F8RCRegClass; 7111 } 7112 } 7113 7114 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7115 SelectionDAG &DAG, SDValue ArgValue, 7116 MVT LocVT, const SDLoc &dl) { 7117 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7118 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7119 7120 if (Flags.isSExt()) 7121 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7122 DAG.getValueType(ValVT)); 7123 else if (Flags.isZExt()) 7124 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7125 DAG.getValueType(ValVT)); 7126 7127 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7128 } 7129 7130 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7131 const unsigned LASize = FL->getLinkageSize(); 7132 7133 if (PPC::GPRCRegClass.contains(Reg)) { 7134 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7135 "Reg must be a valid argument register!"); 7136 return LASize + 4 * (Reg - PPC::R3); 7137 } 7138 7139 if (PPC::G8RCRegClass.contains(Reg)) { 7140 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7141 "Reg must be a valid argument register!"); 7142 return LASize + 8 * (Reg - PPC::X3); 7143 } 7144 7145 llvm_unreachable("Only general purpose registers expected."); 7146 } 7147 7148 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7149 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7150 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7151 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7152 7153 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7154 CallConv == CallingConv::Fast) && 7155 "Unexpected calling convention!"); 7156 7157 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7158 report_fatal_error("Tail call support is unimplemented on AIX."); 7159 7160 if (useSoftFloat()) 7161 report_fatal_error("Soft float support is unimplemented on AIX."); 7162 7163 const PPCSubtarget &Subtarget = 7164 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7165 if (Subtarget.hasQPX()) 7166 report_fatal_error("QPX support is not supported on AIX."); 7167 7168 const bool IsPPC64 = Subtarget.isPPC64(); 7169 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7170 7171 // Assign locations to all of the incoming arguments. 7172 SmallVector<CCValAssign, 16> ArgLocs; 7173 MachineFunction &MF = DAG.getMachineFunction(); 7174 MachineFrameInfo &MFI = MF.getFrameInfo(); 7175 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7176 7177 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7178 // Reserve space for the linkage area on the stack. 7179 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7180 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7181 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7182 7183 SmallVector<SDValue, 8> MemOps; 7184 7185 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7186 CCValAssign &VA = ArgLocs[I++]; 7187 MVT LocVT = VA.getLocVT(); 7188 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7189 7190 // For compatibility with the AIX XL compiler, the float args in the 7191 // parameter save area are initialized even if the argument is available 7192 // in register. The caller is required to initialize both the register 7193 // and memory, however, the callee can choose to expect it in either. 7194 // The memloc is dismissed here because the argument is retrieved from 7195 // the register. 7196 if (VA.isMemLoc() && VA.needsCustom()) 7197 continue; 7198 7199 if (Flags.isByVal() && VA.isMemLoc()) { 7200 const unsigned Size = 7201 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7202 PtrByteSize); 7203 const int FI = MF.getFrameInfo().CreateFixedObject( 7204 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7205 /* IsAliased */ true); 7206 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7207 InVals.push_back(FIN); 7208 7209 continue; 7210 } 7211 7212 if (Flags.isByVal()) { 7213 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7214 7215 const MCPhysReg ArgReg = VA.getLocReg(); 7216 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7217 7218 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7219 report_fatal_error("Over aligned byvals not supported yet."); 7220 7221 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7222 const int FI = MF.getFrameInfo().CreateFixedObject( 7223 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7224 /* IsAliased */ true); 7225 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7226 InVals.push_back(FIN); 7227 7228 // Add live ins for all the RegLocs for the same ByVal. 7229 const TargetRegisterClass *RegClass = 7230 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7231 7232 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7233 unsigned Offset) { 7234 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7235 // Since the callers side has left justified the aggregate in the 7236 // register, we can simply store the entire register into the stack 7237 // slot. 7238 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7239 // The store to the fixedstack object is needed becuase accessing a 7240 // field of the ByVal will use a gep and load. Ideally we will optimize 7241 // to extracting the value from the register directly, and elide the 7242 // stores when the arguments address is not taken, but that will need to 7243 // be future work. 7244 SDValue Store = 7245 DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom, 7246 DAG.getObjectPtrOffset(dl, FIN, Offset), 7247 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7248 7249 MemOps.push_back(Store); 7250 }; 7251 7252 unsigned Offset = 0; 7253 HandleRegLoc(VA.getLocReg(), Offset); 7254 Offset += PtrByteSize; 7255 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7256 Offset += PtrByteSize) { 7257 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7258 "RegLocs should be for ByVal argument."); 7259 7260 const CCValAssign RL = ArgLocs[I++]; 7261 HandleRegLoc(RL.getLocReg(), Offset); 7262 } 7263 7264 if (Offset != StackSize) { 7265 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7266 "Expected MemLoc for remaining bytes."); 7267 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7268 // Consume the MemLoc.The InVal has already been emitted, so nothing 7269 // more needs to be done. 7270 ++I; 7271 } 7272 7273 continue; 7274 } 7275 7276 EVT ValVT = VA.getValVT(); 7277 if (VA.isRegLoc() && !VA.needsCustom()) { 7278 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7279 unsigned VReg = 7280 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7281 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7282 if (ValVT.isScalarInteger() && 7283 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7284 ArgValue = 7285 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7286 } 7287 InVals.push_back(ArgValue); 7288 continue; 7289 } 7290 if (VA.isMemLoc()) { 7291 const unsigned LocSize = LocVT.getStoreSize(); 7292 const unsigned ValSize = ValVT.getStoreSize(); 7293 assert((ValSize <= LocSize) && 7294 "Object size is larger than size of MemLoc"); 7295 int CurArgOffset = VA.getLocMemOffset(); 7296 // Objects are right-justified because AIX is big-endian. 7297 if (LocSize > ValSize) 7298 CurArgOffset += LocSize - ValSize; 7299 // Potential tail calls could cause overwriting of argument stack slots. 7300 const bool IsImmutable = 7301 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7302 (CallConv == CallingConv::Fast)); 7303 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7304 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7305 SDValue ArgValue = 7306 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7307 InVals.push_back(ArgValue); 7308 continue; 7309 } 7310 } 7311 7312 // On AIX a minimum of 8 words is saved to the parameter save area. 7313 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7314 // Area that is at least reserved in the caller of this function. 7315 unsigned CallerReservedArea = 7316 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7317 7318 // Set the size that is at least reserved in caller of this function. Tail 7319 // call optimized function's reserved stack space needs to be aligned so 7320 // that taking the difference between two stack areas will result in an 7321 // aligned stack. 7322 CallerReservedArea = 7323 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7324 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7325 FuncInfo->setMinReservedArea(CallerReservedArea); 7326 7327 if (isVarArg) { 7328 FuncInfo->setVarArgsFrameIndex( 7329 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7330 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7331 7332 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7333 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7334 7335 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7336 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7337 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7338 7339 // The fixed integer arguments of a variadic function are stored to the 7340 // VarArgsFrameIndex on the stack so that they may be loaded by 7341 // dereferencing the result of va_next. 7342 for (unsigned GPRIndex = 7343 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7344 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7345 7346 const unsigned VReg = 7347 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7348 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7349 7350 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7351 SDValue Store = 7352 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7353 MemOps.push_back(Store); 7354 // Increment the address for the next argument to store. 7355 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7356 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7357 } 7358 } 7359 7360 if (!MemOps.empty()) 7361 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7362 7363 return Chain; 7364 } 7365 7366 SDValue PPCTargetLowering::LowerCall_AIX( 7367 SDValue Chain, SDValue Callee, CallFlags CFlags, 7368 const SmallVectorImpl<ISD::OutputArg> &Outs, 7369 const SmallVectorImpl<SDValue> &OutVals, 7370 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7371 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7372 const CallBase *CB) const { 7373 7374 assert((CFlags.CallConv == CallingConv::C || 7375 CFlags.CallConv == CallingConv::Cold || 7376 CFlags.CallConv == CallingConv::Fast) && 7377 "Unexpected calling convention!"); 7378 7379 if (CFlags.IsPatchPoint) 7380 report_fatal_error("This call type is unimplemented on AIX."); 7381 7382 const PPCSubtarget& Subtarget = 7383 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7384 if (Subtarget.hasQPX()) 7385 report_fatal_error("QPX is not supported on AIX."); 7386 if (Subtarget.hasAltivec()) 7387 report_fatal_error("Altivec support is unimplemented on AIX."); 7388 7389 MachineFunction &MF = DAG.getMachineFunction(); 7390 SmallVector<CCValAssign, 16> ArgLocs; 7391 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7392 *DAG.getContext()); 7393 7394 // Reserve space for the linkage save area (LSA) on the stack. 7395 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7396 // [SP][CR][LR][2 x reserved][TOC]. 7397 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7398 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7399 const bool IsPPC64 = Subtarget.isPPC64(); 7400 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7401 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7402 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7403 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7404 7405 // The prolog code of the callee may store up to 8 GPR argument registers to 7406 // the stack, allowing va_start to index over them in memory if the callee 7407 // is variadic. 7408 // Because we cannot tell if this is needed on the caller side, we have to 7409 // conservatively assume that it is needed. As such, make sure we have at 7410 // least enough stack space for the caller to store the 8 GPRs. 7411 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7412 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7413 CCInfo.getNextStackOffset()); 7414 7415 // Adjust the stack pointer for the new arguments... 7416 // These operations are automatically eliminated by the prolog/epilog pass. 7417 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7418 SDValue CallSeqStart = Chain; 7419 7420 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7421 SmallVector<SDValue, 8> MemOpChains; 7422 7423 // Set up a copy of the stack pointer for loading and storing any 7424 // arguments that may not fit in the registers available for argument 7425 // passing. 7426 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7427 : DAG.getRegister(PPC::R1, MVT::i32); 7428 7429 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7430 const unsigned ValNo = ArgLocs[I].getValNo(); 7431 SDValue Arg = OutVals[ValNo]; 7432 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7433 7434 if (Flags.isByVal()) { 7435 const unsigned ByValSize = Flags.getByValSize(); 7436 7437 // Nothing to do for zero-sized ByVals on the caller side. 7438 if (!ByValSize) { 7439 ++I; 7440 continue; 7441 } 7442 7443 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7444 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, 7445 (LoadOffset != 0) 7446 ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7447 : Arg, 7448 MachinePointerInfo(), VT); 7449 }; 7450 7451 unsigned LoadOffset = 0; 7452 7453 // Initialize registers, which are fully occupied by the by-val argument. 7454 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7455 SDValue Load = GetLoad(PtrVT, LoadOffset); 7456 MemOpChains.push_back(Load.getValue(1)); 7457 LoadOffset += PtrByteSize; 7458 const CCValAssign &ByValVA = ArgLocs[I++]; 7459 assert(ByValVA.getValNo() == ValNo && 7460 "Unexpected location for pass-by-value argument."); 7461 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7462 } 7463 7464 if (LoadOffset == ByValSize) 7465 continue; 7466 7467 // There must be one more loc to handle the remainder. 7468 assert(ArgLocs[I].getValNo() == ValNo && 7469 "Expected additional location for by-value argument."); 7470 7471 if (ArgLocs[I].isMemLoc()) { 7472 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7473 const CCValAssign &ByValVA = ArgLocs[I++]; 7474 ISD::ArgFlagsTy MemcpyFlags = Flags; 7475 // Only memcpy the bytes that don't pass in register. 7476 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7477 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7478 (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7479 : Arg, 7480 DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()), 7481 CallSeqStart, MemcpyFlags, DAG, dl); 7482 continue; 7483 } 7484 7485 // Initialize the final register residue. 7486 // Any residue that occupies the final by-val arg register must be 7487 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7488 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7489 // 2 and 1 byte loads. 7490 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7491 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7492 "Unexpected register residue for by-value argument."); 7493 SDValue ResidueVal; 7494 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7495 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7496 const MVT VT = 7497 N == 1 ? MVT::i8 7498 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7499 SDValue Load = GetLoad(VT, LoadOffset); 7500 MemOpChains.push_back(Load.getValue(1)); 7501 LoadOffset += N; 7502 Bytes += N; 7503 7504 // By-val arguments are passed left-justfied in register. 7505 // Every load here needs to be shifted, otherwise a full register load 7506 // should have been used. 7507 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7508 "Unexpected load emitted during handling of pass-by-value " 7509 "argument."); 7510 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7511 EVT ShiftAmountTy = 7512 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7513 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7514 SDValue ShiftedLoad = 7515 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7516 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7517 ShiftedLoad) 7518 : ShiftedLoad; 7519 } 7520 7521 const CCValAssign &ByValVA = ArgLocs[I++]; 7522 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7523 continue; 7524 } 7525 7526 CCValAssign &VA = ArgLocs[I++]; 7527 const MVT LocVT = VA.getLocVT(); 7528 const MVT ValVT = VA.getValVT(); 7529 7530 switch (VA.getLocInfo()) { 7531 default: 7532 report_fatal_error("Unexpected argument extension type."); 7533 case CCValAssign::Full: 7534 break; 7535 case CCValAssign::ZExt: 7536 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7537 break; 7538 case CCValAssign::SExt: 7539 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7540 break; 7541 } 7542 7543 if (VA.isRegLoc() && !VA.needsCustom()) { 7544 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7545 continue; 7546 } 7547 7548 if (VA.isMemLoc()) { 7549 SDValue PtrOff = 7550 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7551 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7552 MemOpChains.push_back( 7553 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7554 7555 continue; 7556 } 7557 7558 // Custom handling is used for GPR initializations for vararg float 7559 // arguments. 7560 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7561 ValVT.isFloatingPoint() && LocVT.isInteger() && 7562 "Unexpected register handling for calling convention."); 7563 7564 SDValue ArgAsInt = 7565 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7566 7567 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7568 // f32 in 32-bit GPR 7569 // f64 in 64-bit GPR 7570 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7571 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7572 // f32 in 64-bit GPR. 7573 RegsToPass.push_back(std::make_pair( 7574 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7575 else { 7576 // f64 in two 32-bit GPRs 7577 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7578 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7579 "Unexpected custom register for argument!"); 7580 CCValAssign &GPR1 = VA; 7581 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7582 DAG.getConstant(32, dl, MVT::i8)); 7583 RegsToPass.push_back(std::make_pair( 7584 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7585 7586 if (I != E) { 7587 // If only 1 GPR was available, there will only be one custom GPR and 7588 // the argument will also pass in memory. 7589 CCValAssign &PeekArg = ArgLocs[I]; 7590 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7591 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7592 CCValAssign &GPR2 = ArgLocs[I++]; 7593 RegsToPass.push_back(std::make_pair( 7594 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7595 } 7596 } 7597 } 7598 } 7599 7600 if (!MemOpChains.empty()) 7601 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7602 7603 // For indirect calls, we need to save the TOC base to the stack for 7604 // restoration after the call. 7605 if (CFlags.IsIndirect) { 7606 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7607 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7608 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7609 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7610 const unsigned TOCSaveOffset = 7611 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7612 7613 setUsesTOCBasePtr(DAG); 7614 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7615 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7616 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7617 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7618 Chain = DAG.getStore( 7619 Val.getValue(1), dl, Val, AddPtr, 7620 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7621 } 7622 7623 // Build a sequence of copy-to-reg nodes chained together with token chain 7624 // and flag operands which copy the outgoing args into the appropriate regs. 7625 SDValue InFlag; 7626 for (auto Reg : RegsToPass) { 7627 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7628 InFlag = Chain.getValue(1); 7629 } 7630 7631 const int SPDiff = 0; 7632 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7633 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7634 } 7635 7636 bool 7637 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7638 MachineFunction &MF, bool isVarArg, 7639 const SmallVectorImpl<ISD::OutputArg> &Outs, 7640 LLVMContext &Context) const { 7641 SmallVector<CCValAssign, 16> RVLocs; 7642 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7643 return CCInfo.CheckReturn( 7644 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7645 ? RetCC_PPC_Cold 7646 : RetCC_PPC); 7647 } 7648 7649 SDValue 7650 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7651 bool isVarArg, 7652 const SmallVectorImpl<ISD::OutputArg> &Outs, 7653 const SmallVectorImpl<SDValue> &OutVals, 7654 const SDLoc &dl, SelectionDAG &DAG) const { 7655 SmallVector<CCValAssign, 16> RVLocs; 7656 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7657 *DAG.getContext()); 7658 CCInfo.AnalyzeReturn(Outs, 7659 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7660 ? RetCC_PPC_Cold 7661 : RetCC_PPC); 7662 7663 SDValue Flag; 7664 SmallVector<SDValue, 4> RetOps(1, Chain); 7665 7666 // Copy the result values into the output registers. 7667 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7668 CCValAssign &VA = RVLocs[i]; 7669 assert(VA.isRegLoc() && "Can only return in registers!"); 7670 7671 SDValue Arg = OutVals[RealResIdx]; 7672 7673 switch (VA.getLocInfo()) { 7674 default: llvm_unreachable("Unknown loc info!"); 7675 case CCValAssign::Full: break; 7676 case CCValAssign::AExt: 7677 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7678 break; 7679 case CCValAssign::ZExt: 7680 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7681 break; 7682 case CCValAssign::SExt: 7683 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7684 break; 7685 } 7686 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7687 bool isLittleEndian = Subtarget.isLittleEndian(); 7688 // Legalize ret f64 -> ret 2 x i32. 7689 SDValue SVal = 7690 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7691 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7692 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7693 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7694 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7695 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7696 Flag = Chain.getValue(1); 7697 VA = RVLocs[++i]; // skip ahead to next loc 7698 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7699 } else 7700 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7701 Flag = Chain.getValue(1); 7702 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7703 } 7704 7705 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 7706 const MCPhysReg *I = 7707 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 7708 if (I) { 7709 for (; *I; ++I) { 7710 7711 if (PPC::G8RCRegClass.contains(*I)) 7712 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 7713 else if (PPC::F8RCRegClass.contains(*I)) 7714 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 7715 else if (PPC::CRRCRegClass.contains(*I)) 7716 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 7717 else if (PPC::VRRCRegClass.contains(*I)) 7718 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 7719 else 7720 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 7721 } 7722 } 7723 7724 RetOps[0] = Chain; // Update chain. 7725 7726 // Add the flag if we have it. 7727 if (Flag.getNode()) 7728 RetOps.push_back(Flag); 7729 7730 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7731 } 7732 7733 SDValue 7734 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7735 SelectionDAG &DAG) const { 7736 SDLoc dl(Op); 7737 7738 // Get the correct type for integers. 7739 EVT IntVT = Op.getValueType(); 7740 7741 // Get the inputs. 7742 SDValue Chain = Op.getOperand(0); 7743 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7744 // Build a DYNAREAOFFSET node. 7745 SDValue Ops[2] = {Chain, FPSIdx}; 7746 SDVTList VTs = DAG.getVTList(IntVT); 7747 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7748 } 7749 7750 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7751 SelectionDAG &DAG) const { 7752 // When we pop the dynamic allocation we need to restore the SP link. 7753 SDLoc dl(Op); 7754 7755 // Get the correct type for pointers. 7756 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7757 7758 // Construct the stack pointer operand. 7759 bool isPPC64 = Subtarget.isPPC64(); 7760 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7761 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7762 7763 // Get the operands for the STACKRESTORE. 7764 SDValue Chain = Op.getOperand(0); 7765 SDValue SaveSP = Op.getOperand(1); 7766 7767 // Load the old link SP. 7768 SDValue LoadLinkSP = 7769 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7770 7771 // Restore the stack pointer. 7772 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7773 7774 // Store the old link SP. 7775 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7776 } 7777 7778 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7779 MachineFunction &MF = DAG.getMachineFunction(); 7780 bool isPPC64 = Subtarget.isPPC64(); 7781 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7782 7783 // Get current frame pointer save index. The users of this index will be 7784 // primarily DYNALLOC instructions. 7785 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7786 int RASI = FI->getReturnAddrSaveIndex(); 7787 7788 // If the frame pointer save index hasn't been defined yet. 7789 if (!RASI) { 7790 // Find out what the fix offset of the frame pointer save area. 7791 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7792 // Allocate the frame index for frame pointer save area. 7793 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7794 // Save the result. 7795 FI->setReturnAddrSaveIndex(RASI); 7796 } 7797 return DAG.getFrameIndex(RASI, PtrVT); 7798 } 7799 7800 SDValue 7801 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7802 MachineFunction &MF = DAG.getMachineFunction(); 7803 bool isPPC64 = Subtarget.isPPC64(); 7804 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7805 7806 // Get current frame pointer save index. The users of this index will be 7807 // primarily DYNALLOC instructions. 7808 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7809 int FPSI = FI->getFramePointerSaveIndex(); 7810 7811 // If the frame pointer save index hasn't been defined yet. 7812 if (!FPSI) { 7813 // Find out what the fix offset of the frame pointer save area. 7814 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7815 // Allocate the frame index for frame pointer save area. 7816 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7817 // Save the result. 7818 FI->setFramePointerSaveIndex(FPSI); 7819 } 7820 return DAG.getFrameIndex(FPSI, PtrVT); 7821 } 7822 7823 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7824 SelectionDAG &DAG) const { 7825 // Get the inputs. 7826 SDValue Chain = Op.getOperand(0); 7827 SDValue Size = Op.getOperand(1); 7828 SDLoc dl(Op); 7829 7830 // Get the correct type for pointers. 7831 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7832 // Negate the size. 7833 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7834 DAG.getConstant(0, dl, PtrVT), Size); 7835 // Construct a node for the frame pointer save index. 7836 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7837 // Build a DYNALLOC node. 7838 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7839 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7840 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7841 } 7842 7843 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7844 SelectionDAG &DAG) const { 7845 MachineFunction &MF = DAG.getMachineFunction(); 7846 7847 bool isPPC64 = Subtarget.isPPC64(); 7848 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7849 7850 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7851 return DAG.getFrameIndex(FI, PtrVT); 7852 } 7853 7854 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7855 SelectionDAG &DAG) const { 7856 SDLoc DL(Op); 7857 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7858 DAG.getVTList(MVT::i32, MVT::Other), 7859 Op.getOperand(0), Op.getOperand(1)); 7860 } 7861 7862 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7863 SelectionDAG &DAG) const { 7864 SDLoc DL(Op); 7865 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7866 Op.getOperand(0), Op.getOperand(1)); 7867 } 7868 7869 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7870 if (Op.getValueType().isVector()) 7871 return LowerVectorLoad(Op, DAG); 7872 7873 assert(Op.getValueType() == MVT::i1 && 7874 "Custom lowering only for i1 loads"); 7875 7876 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7877 7878 SDLoc dl(Op); 7879 LoadSDNode *LD = cast<LoadSDNode>(Op); 7880 7881 SDValue Chain = LD->getChain(); 7882 SDValue BasePtr = LD->getBasePtr(); 7883 MachineMemOperand *MMO = LD->getMemOperand(); 7884 7885 SDValue NewLD = 7886 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7887 BasePtr, MVT::i8, MMO); 7888 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7889 7890 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7891 return DAG.getMergeValues(Ops, dl); 7892 } 7893 7894 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7895 if (Op.getOperand(1).getValueType().isVector()) 7896 return LowerVectorStore(Op, DAG); 7897 7898 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7899 "Custom lowering only for i1 stores"); 7900 7901 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7902 7903 SDLoc dl(Op); 7904 StoreSDNode *ST = cast<StoreSDNode>(Op); 7905 7906 SDValue Chain = ST->getChain(); 7907 SDValue BasePtr = ST->getBasePtr(); 7908 SDValue Value = ST->getValue(); 7909 MachineMemOperand *MMO = ST->getMemOperand(); 7910 7911 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7912 Value); 7913 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7914 } 7915 7916 // FIXME: Remove this once the ANDI glue bug is fixed: 7917 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7918 assert(Op.getValueType() == MVT::i1 && 7919 "Custom lowering only for i1 results"); 7920 7921 SDLoc DL(Op); 7922 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7923 } 7924 7925 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7926 SelectionDAG &DAG) const { 7927 7928 // Implements a vector truncate that fits in a vector register as a shuffle. 7929 // We want to legalize vector truncates down to where the source fits in 7930 // a vector register (and target is therefore smaller than vector register 7931 // size). At that point legalization will try to custom lower the sub-legal 7932 // result and get here - where we can contain the truncate as a single target 7933 // operation. 7934 7935 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7936 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7937 // 7938 // We will implement it for big-endian ordering as this (where x denotes 7939 // undefined): 7940 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7941 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7942 // 7943 // The same operation in little-endian ordering will be: 7944 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7945 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7946 7947 assert(Op.getValueType().isVector() && "Vector type expected."); 7948 7949 SDLoc DL(Op); 7950 SDValue N1 = Op.getOperand(0); 7951 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7952 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7953 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7954 7955 EVT TrgVT = Op.getValueType(); 7956 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7957 EVT EltVT = TrgVT.getVectorElementType(); 7958 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7959 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7960 7961 // First list the elements we want to keep. 7962 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7963 SmallVector<int, 16> ShuffV; 7964 if (Subtarget.isLittleEndian()) 7965 for (unsigned i = 0; i < TrgNumElts; ++i) 7966 ShuffV.push_back(i * SizeMult); 7967 else 7968 for (unsigned i = 1; i <= TrgNumElts; ++i) 7969 ShuffV.push_back(i * SizeMult - 1); 7970 7971 // Populate the remaining elements with undefs. 7972 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7973 // ShuffV.push_back(i + WideNumElts); 7974 ShuffV.push_back(WideNumElts + 1); 7975 7976 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7977 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7978 } 7979 7980 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7981 /// possible. 7982 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7983 // Not FP? Not a fsel. 7984 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7985 !Op.getOperand(2).getValueType().isFloatingPoint()) 7986 return Op; 7987 7988 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7989 7990 EVT ResVT = Op.getValueType(); 7991 EVT CmpVT = Op.getOperand(0).getValueType(); 7992 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7993 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7994 SDLoc dl(Op); 7995 7996 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7997 // presence of infinities. 7998 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7999 switch (CC) { 8000 default: 8001 break; 8002 case ISD::SETOGT: 8003 case ISD::SETGT: 8004 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 8005 case ISD::SETOLT: 8006 case ISD::SETLT: 8007 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 8008 } 8009 } 8010 8011 // We might be able to do better than this under some circumstances, but in 8012 // general, fsel-based lowering of select is a finite-math-only optimization. 8013 // For more information, see section F.3 of the 2.06 ISA specification. 8014 // With ISA 3.0 8015 if (!DAG.getTarget().Options.NoInfsFPMath || 8016 !DAG.getTarget().Options.NoNaNsFPMath) 8017 return Op; 8018 8019 // TODO: Propagate flags from the select rather than global settings. 8020 SDNodeFlags Flags; 8021 Flags.setNoInfs(true); 8022 Flags.setNoNaNs(true); 8023 8024 // If the RHS of the comparison is a 0.0, we don't need to do the 8025 // subtraction at all. 8026 SDValue Sel1; 8027 if (isFloatingPointZero(RHS)) 8028 switch (CC) { 8029 default: break; // SETUO etc aren't handled by fsel. 8030 case ISD::SETNE: 8031 std::swap(TV, FV); 8032 LLVM_FALLTHROUGH; 8033 case ISD::SETEQ: 8034 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8035 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8036 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8037 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8038 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8039 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8040 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 8041 case ISD::SETULT: 8042 case ISD::SETLT: 8043 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8044 LLVM_FALLTHROUGH; 8045 case ISD::SETOGE: 8046 case ISD::SETGE: 8047 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8048 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8049 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8050 case ISD::SETUGT: 8051 case ISD::SETGT: 8052 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8053 LLVM_FALLTHROUGH; 8054 case ISD::SETOLE: 8055 case ISD::SETLE: 8056 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8057 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8058 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8059 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8060 } 8061 8062 SDValue Cmp; 8063 switch (CC) { 8064 default: break; // SETUO etc aren't handled by fsel. 8065 case ISD::SETNE: 8066 std::swap(TV, FV); 8067 LLVM_FALLTHROUGH; 8068 case ISD::SETEQ: 8069 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8070 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8071 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8072 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8073 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8074 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8075 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8076 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8077 case ISD::SETULT: 8078 case ISD::SETLT: 8079 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8080 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8081 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8082 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8083 case ISD::SETOGE: 8084 case ISD::SETGE: 8085 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8086 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8087 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8088 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8089 case ISD::SETUGT: 8090 case ISD::SETGT: 8091 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8092 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8093 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8094 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8095 case ISD::SETOLE: 8096 case ISD::SETLE: 8097 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8098 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8099 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8100 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8101 } 8102 return Op; 8103 } 8104 8105 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8106 SelectionDAG &DAG, 8107 const SDLoc &dl) const { 8108 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8109 SDValue Src = Op.getOperand(0); 8110 if (Src.getValueType() == MVT::f32) 8111 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8112 8113 SDValue Tmp; 8114 switch (Op.getSimpleValueType().SimpleTy) { 8115 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8116 case MVT::i32: 8117 Tmp = DAG.getNode( 8118 Op.getOpcode() == ISD::FP_TO_SINT 8119 ? PPCISD::FCTIWZ 8120 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8121 dl, MVT::f64, Src); 8122 break; 8123 case MVT::i64: 8124 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8125 "i64 FP_TO_UINT is supported only with FPCVT"); 8126 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8127 PPCISD::FCTIDUZ, 8128 dl, MVT::f64, Src); 8129 break; 8130 } 8131 8132 // Convert the FP value to an int value through memory. 8133 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8134 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 8135 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8136 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8137 MachinePointerInfo MPI = 8138 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8139 8140 // Emit a store to the stack slot. 8141 SDValue Chain; 8142 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8143 if (i32Stack) { 8144 MachineFunction &MF = DAG.getMachineFunction(); 8145 Alignment = Align(4); 8146 MachineMemOperand *MMO = 8147 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8148 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 8149 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8150 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8151 } else 8152 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment); 8153 8154 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8155 // add in a bias on big endian. 8156 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8157 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8158 DAG.getConstant(4, dl, FIPtr.getValueType())); 8159 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8160 } 8161 8162 RLI.Chain = Chain; 8163 RLI.Ptr = FIPtr; 8164 RLI.MPI = MPI; 8165 RLI.Alignment = Alignment; 8166 } 8167 8168 /// Custom lowers floating point to integer conversions to use 8169 /// the direct move instructions available in ISA 2.07 to avoid the 8170 /// need for load/store combinations. 8171 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8172 SelectionDAG &DAG, 8173 const SDLoc &dl) const { 8174 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8175 SDValue Src = Op.getOperand(0); 8176 8177 if (Src.getValueType() == MVT::f32) 8178 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8179 8180 SDValue Tmp; 8181 switch (Op.getSimpleValueType().SimpleTy) { 8182 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8183 case MVT::i32: 8184 Tmp = DAG.getNode( 8185 Op.getOpcode() == ISD::FP_TO_SINT 8186 ? PPCISD::FCTIWZ 8187 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8188 dl, MVT::f64, Src); 8189 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 8190 break; 8191 case MVT::i64: 8192 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8193 "i64 FP_TO_UINT is supported only with FPCVT"); 8194 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8195 PPCISD::FCTIDUZ, 8196 dl, MVT::f64, Src); 8197 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 8198 break; 8199 } 8200 return Tmp; 8201 } 8202 8203 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8204 const SDLoc &dl) const { 8205 8206 // FP to INT conversions are legal for f128. 8207 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 8208 return Op; 8209 8210 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8211 // PPC (the libcall is not available). 8212 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 8213 if (Op.getValueType() == MVT::i32) { 8214 if (Op.getOpcode() == ISD::FP_TO_SINT) { 8215 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8216 MVT::f64, Op.getOperand(0), 8217 DAG.getIntPtrConstant(0, dl)); 8218 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8219 MVT::f64, Op.getOperand(0), 8220 DAG.getIntPtrConstant(1, dl)); 8221 8222 // Add the two halves of the long double in round-to-zero mode. 8223 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8224 8225 // Now use a smaller FP_TO_SINT. 8226 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8227 } 8228 if (Op.getOpcode() == ISD::FP_TO_UINT) { 8229 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8230 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8231 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8232 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8233 // FIXME: generated code sucks. 8234 // TODO: Are there fast-math-flags to propagate to this FSUB? 8235 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 8236 Op.getOperand(0), Tmp); 8237 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8238 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8239 DAG.getConstant(0x80000000, dl, MVT::i32)); 8240 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 8241 Op.getOperand(0)); 8242 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 8243 ISD::SETGE); 8244 } 8245 } 8246 8247 return SDValue(); 8248 } 8249 8250 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8251 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8252 8253 ReuseLoadInfo RLI; 8254 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8255 8256 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8257 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8258 } 8259 8260 // We're trying to insert a regular store, S, and then a load, L. If the 8261 // incoming value, O, is a load, we might just be able to have our load use the 8262 // address used by O. However, we don't know if anything else will store to 8263 // that address before we can load from it. To prevent this situation, we need 8264 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8265 // the same chain operand as O, we create a token factor from the chain results 8266 // of O and L, and we replace all uses of O's chain result with that token 8267 // factor (see spliceIntoChain below for this last part). 8268 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8269 ReuseLoadInfo &RLI, 8270 SelectionDAG &DAG, 8271 ISD::LoadExtType ET) const { 8272 SDLoc dl(Op); 8273 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8274 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8275 if (ET == ISD::NON_EXTLOAD && 8276 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8277 isOperationLegalOrCustom(Op.getOpcode(), 8278 Op.getOperand(0).getValueType())) { 8279 8280 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8281 return true; 8282 } 8283 8284 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8285 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8286 LD->isNonTemporal()) 8287 return false; 8288 if (LD->getMemoryVT() != MemVT) 8289 return false; 8290 8291 RLI.Ptr = LD->getBasePtr(); 8292 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8293 assert(LD->getAddressingMode() == ISD::PRE_INC && 8294 "Non-pre-inc AM on PPC?"); 8295 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8296 LD->getOffset()); 8297 } 8298 8299 RLI.Chain = LD->getChain(); 8300 RLI.MPI = LD->getPointerInfo(); 8301 RLI.IsDereferenceable = LD->isDereferenceable(); 8302 RLI.IsInvariant = LD->isInvariant(); 8303 RLI.Alignment = LD->getAlign(); 8304 RLI.AAInfo = LD->getAAInfo(); 8305 RLI.Ranges = LD->getRanges(); 8306 8307 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8308 return true; 8309 } 8310 8311 // Given the head of the old chain, ResChain, insert a token factor containing 8312 // it and NewResChain, and make users of ResChain now be users of that token 8313 // factor. 8314 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8315 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8316 SDValue NewResChain, 8317 SelectionDAG &DAG) const { 8318 if (!ResChain) 8319 return; 8320 8321 SDLoc dl(NewResChain); 8322 8323 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8324 NewResChain, DAG.getUNDEF(MVT::Other)); 8325 assert(TF.getNode() != NewResChain.getNode() && 8326 "A new TF really is required here"); 8327 8328 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8329 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8330 } 8331 8332 /// Analyze profitability of direct move 8333 /// prefer float load to int load plus direct move 8334 /// when there is no integer use of int load 8335 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8336 SDNode *Origin = Op.getOperand(0).getNode(); 8337 if (Origin->getOpcode() != ISD::LOAD) 8338 return true; 8339 8340 // If there is no LXSIBZX/LXSIHZX, like Power8, 8341 // prefer direct move if the memory size is 1 or 2 bytes. 8342 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8343 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8344 return true; 8345 8346 for (SDNode::use_iterator UI = Origin->use_begin(), 8347 UE = Origin->use_end(); 8348 UI != UE; ++UI) { 8349 8350 // Only look at the users of the loaded value. 8351 if (UI.getUse().get().getResNo() != 0) 8352 continue; 8353 8354 if (UI->getOpcode() != ISD::SINT_TO_FP && 8355 UI->getOpcode() != ISD::UINT_TO_FP) 8356 return true; 8357 } 8358 8359 return false; 8360 } 8361 8362 /// Custom lowers integer to floating point conversions to use 8363 /// the direct move instructions available in ISA 2.07 to avoid the 8364 /// need for load/store combinations. 8365 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8366 SelectionDAG &DAG, 8367 const SDLoc &dl) const { 8368 assert((Op.getValueType() == MVT::f32 || 8369 Op.getValueType() == MVT::f64) && 8370 "Invalid floating point type as target of conversion"); 8371 assert(Subtarget.hasFPCVT() && 8372 "Int to FP conversions with direct moves require FPCVT"); 8373 SDValue FP; 8374 SDValue Src = Op.getOperand(0); 8375 bool SinglePrec = Op.getValueType() == MVT::f32; 8376 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8377 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 8378 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 8379 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 8380 8381 if (WordInt) { 8382 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 8383 dl, MVT::f64, Src); 8384 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8385 } 8386 else { 8387 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 8388 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8389 } 8390 8391 return FP; 8392 } 8393 8394 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8395 8396 EVT VecVT = Vec.getValueType(); 8397 assert(VecVT.isVector() && "Expected a vector type."); 8398 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8399 8400 EVT EltVT = VecVT.getVectorElementType(); 8401 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8402 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8403 8404 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8405 SmallVector<SDValue, 16> Ops(NumConcat); 8406 Ops[0] = Vec; 8407 SDValue UndefVec = DAG.getUNDEF(VecVT); 8408 for (unsigned i = 1; i < NumConcat; ++i) 8409 Ops[i] = UndefVec; 8410 8411 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8412 } 8413 8414 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8415 const SDLoc &dl) const { 8416 8417 unsigned Opc = Op.getOpcode(); 8418 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8419 "Unexpected conversion type"); 8420 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8421 "Supports conversions to v2f64/v4f32 only."); 8422 8423 bool SignedConv = Opc == ISD::SINT_TO_FP; 8424 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8425 8426 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8427 EVT WideVT = Wide.getValueType(); 8428 unsigned WideNumElts = WideVT.getVectorNumElements(); 8429 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8430 8431 SmallVector<int, 16> ShuffV; 8432 for (unsigned i = 0; i < WideNumElts; ++i) 8433 ShuffV.push_back(i + WideNumElts); 8434 8435 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8436 int SaveElts = FourEltRes ? 4 : 2; 8437 if (Subtarget.isLittleEndian()) 8438 for (int i = 0; i < SaveElts; i++) 8439 ShuffV[i * Stride] = i; 8440 else 8441 for (int i = 1; i <= SaveElts; i++) 8442 ShuffV[i * Stride - 1] = i - 1; 8443 8444 SDValue ShuffleSrc2 = 8445 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8446 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8447 8448 SDValue Extend; 8449 if (SignedConv) { 8450 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8451 EVT ExtVT = Op.getOperand(0).getValueType(); 8452 if (Subtarget.hasP9Altivec()) 8453 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8454 IntermediateVT.getVectorNumElements()); 8455 8456 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8457 DAG.getValueType(ExtVT)); 8458 } else 8459 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8460 8461 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8462 } 8463 8464 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8465 SelectionDAG &DAG) const { 8466 SDLoc dl(Op); 8467 8468 EVT InVT = Op.getOperand(0).getValueType(); 8469 EVT OutVT = Op.getValueType(); 8470 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8471 isOperationCustom(Op.getOpcode(), InVT)) 8472 return LowerINT_TO_FPVector(Op, DAG, dl); 8473 8474 // Conversions to f128 are legal. 8475 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 8476 return Op; 8477 8478 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8479 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8480 return SDValue(); 8481 8482 SDValue Value = Op.getOperand(0); 8483 // The values are now known to be -1 (false) or 1 (true). To convert this 8484 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8485 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8486 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8487 8488 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8489 8490 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8491 8492 if (Op.getValueType() != MVT::v4f64) 8493 Value = DAG.getNode(ISD::FP_ROUND, dl, 8494 Op.getValueType(), Value, 8495 DAG.getIntPtrConstant(1, dl)); 8496 return Value; 8497 } 8498 8499 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8500 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8501 return SDValue(); 8502 8503 if (Op.getOperand(0).getValueType() == MVT::i1) 8504 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8505 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8506 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8507 8508 // If we have direct moves, we can do all the conversion, skip the store/load 8509 // however, without FPCVT we can't do most conversions. 8510 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8511 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8512 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8513 8514 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8515 "UINT_TO_FP is supported only with FPCVT"); 8516 8517 // If we have FCFIDS, then use it when converting to single-precision. 8518 // Otherwise, convert to double-precision and then round. 8519 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8520 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8521 : PPCISD::FCFIDS) 8522 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8523 : PPCISD::FCFID); 8524 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8525 ? MVT::f32 8526 : MVT::f64; 8527 8528 if (Op.getOperand(0).getValueType() == MVT::i64) { 8529 SDValue SINT = Op.getOperand(0); 8530 // When converting to single-precision, we actually need to convert 8531 // to double-precision first and then round to single-precision. 8532 // To avoid double-rounding effects during that operation, we have 8533 // to prepare the input operand. Bits that might be truncated when 8534 // converting to double-precision are replaced by a bit that won't 8535 // be lost at this stage, but is below the single-precision rounding 8536 // position. 8537 // 8538 // However, if -enable-unsafe-fp-math is in effect, accept double 8539 // rounding to avoid the extra overhead. 8540 if (Op.getValueType() == MVT::f32 && 8541 !Subtarget.hasFPCVT() && 8542 !DAG.getTarget().Options.UnsafeFPMath) { 8543 8544 // Twiddle input to make sure the low 11 bits are zero. (If this 8545 // is the case, we are guaranteed the value will fit into the 53 bit 8546 // mantissa of an IEEE double-precision value without rounding.) 8547 // If any of those low 11 bits were not zero originally, make sure 8548 // bit 12 (value 2048) is set instead, so that the final rounding 8549 // to single-precision gets the correct result. 8550 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8551 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8552 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8553 Round, DAG.getConstant(2047, dl, MVT::i64)); 8554 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8555 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8556 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8557 8558 // However, we cannot use that value unconditionally: if the magnitude 8559 // of the input value is small, the bit-twiddling we did above might 8560 // end up visibly changing the output. Fortunately, in that case, we 8561 // don't need to twiddle bits since the original input will convert 8562 // exactly to double-precision floating-point already. Therefore, 8563 // construct a conditional to use the original value if the top 11 8564 // bits are all sign-bit copies, and use the rounded value computed 8565 // above otherwise. 8566 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8567 SINT, DAG.getConstant(53, dl, MVT::i32)); 8568 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8569 Cond, DAG.getConstant(1, dl, MVT::i64)); 8570 Cond = DAG.getSetCC( 8571 dl, 8572 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8573 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8574 8575 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8576 } 8577 8578 ReuseLoadInfo RLI; 8579 SDValue Bits; 8580 8581 MachineFunction &MF = DAG.getMachineFunction(); 8582 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8583 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8584 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8585 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8586 } else if (Subtarget.hasLFIWAX() && 8587 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8588 MachineMemOperand *MMO = 8589 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8590 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8591 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8592 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8593 DAG.getVTList(MVT::f64, MVT::Other), 8594 Ops, MVT::i32, MMO); 8595 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8596 } else if (Subtarget.hasFPCVT() && 8597 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8598 MachineMemOperand *MMO = 8599 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8600 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8601 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8602 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8603 DAG.getVTList(MVT::f64, MVT::Other), 8604 Ops, MVT::i32, MMO); 8605 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8606 } else if (((Subtarget.hasLFIWAX() && 8607 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8608 (Subtarget.hasFPCVT() && 8609 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8610 SINT.getOperand(0).getValueType() == MVT::i32) { 8611 MachineFrameInfo &MFI = MF.getFrameInfo(); 8612 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8613 8614 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8615 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8616 8617 SDValue Store = 8618 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8619 MachinePointerInfo::getFixedStack( 8620 DAG.getMachineFunction(), FrameIdx)); 8621 8622 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8623 "Expected an i32 store"); 8624 8625 RLI.Ptr = FIdx; 8626 RLI.Chain = Store; 8627 RLI.MPI = 8628 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8629 RLI.Alignment = Align(4); 8630 8631 MachineMemOperand *MMO = 8632 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8633 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8634 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8635 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8636 PPCISD::LFIWZX : PPCISD::LFIWAX, 8637 dl, DAG.getVTList(MVT::f64, MVT::Other), 8638 Ops, MVT::i32, MMO); 8639 } else 8640 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8641 8642 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8643 8644 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8645 FP = DAG.getNode(ISD::FP_ROUND, dl, 8646 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8647 return FP; 8648 } 8649 8650 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8651 "Unhandled INT_TO_FP type in custom expander!"); 8652 // Since we only generate this in 64-bit mode, we can take advantage of 8653 // 64-bit registers. In particular, sign extend the input value into the 8654 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8655 // then lfd it and fcfid it. 8656 MachineFunction &MF = DAG.getMachineFunction(); 8657 MachineFrameInfo &MFI = MF.getFrameInfo(); 8658 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8659 8660 SDValue Ld; 8661 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8662 ReuseLoadInfo RLI; 8663 bool ReusingLoad; 8664 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8665 DAG))) { 8666 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8667 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8668 8669 SDValue Store = 8670 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8671 MachinePointerInfo::getFixedStack( 8672 DAG.getMachineFunction(), FrameIdx)); 8673 8674 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8675 "Expected an i32 store"); 8676 8677 RLI.Ptr = FIdx; 8678 RLI.Chain = Store; 8679 RLI.MPI = 8680 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8681 RLI.Alignment = Align(4); 8682 } 8683 8684 MachineMemOperand *MMO = 8685 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8686 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8687 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8688 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8689 PPCISD::LFIWZX : PPCISD::LFIWAX, 8690 dl, DAG.getVTList(MVT::f64, MVT::Other), 8691 Ops, MVT::i32, MMO); 8692 if (ReusingLoad) 8693 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8694 } else { 8695 assert(Subtarget.isPPC64() && 8696 "i32->FP without LFIWAX supported only on PPC64"); 8697 8698 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8699 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8700 8701 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8702 Op.getOperand(0)); 8703 8704 // STD the extended value into the stack slot. 8705 SDValue Store = DAG.getStore( 8706 DAG.getEntryNode(), dl, Ext64, FIdx, 8707 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8708 8709 // Load the value as a double. 8710 Ld = DAG.getLoad( 8711 MVT::f64, dl, Store, FIdx, 8712 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8713 } 8714 8715 // FCFID it and return it. 8716 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8717 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8718 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8719 DAG.getIntPtrConstant(0, dl)); 8720 return FP; 8721 } 8722 8723 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8724 SelectionDAG &DAG) const { 8725 SDLoc dl(Op); 8726 /* 8727 The rounding mode is in bits 30:31 of FPSR, and has the following 8728 settings: 8729 00 Round to nearest 8730 01 Round to 0 8731 10 Round to +inf 8732 11 Round to -inf 8733 8734 FLT_ROUNDS, on the other hand, expects the following: 8735 -1 Undefined 8736 0 Round to 0 8737 1 Round to nearest 8738 2 Round to +inf 8739 3 Round to -inf 8740 8741 To perform the conversion, we do: 8742 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8743 */ 8744 8745 MachineFunction &MF = DAG.getMachineFunction(); 8746 EVT VT = Op.getValueType(); 8747 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8748 8749 // Save FP Control Word to register 8750 SDValue Chain = Op.getOperand(0); 8751 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8752 Chain = MFFS.getValue(1); 8753 8754 // Save FP register to stack slot 8755 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8756 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8757 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8758 8759 // Load FP Control Word from low 32 bits of stack slot. 8760 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8761 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8762 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8763 Chain = CWD.getValue(1); 8764 8765 // Transform as necessary 8766 SDValue CWD1 = 8767 DAG.getNode(ISD::AND, dl, MVT::i32, 8768 CWD, DAG.getConstant(3, dl, MVT::i32)); 8769 SDValue CWD2 = 8770 DAG.getNode(ISD::SRL, dl, MVT::i32, 8771 DAG.getNode(ISD::AND, dl, MVT::i32, 8772 DAG.getNode(ISD::XOR, dl, MVT::i32, 8773 CWD, DAG.getConstant(3, dl, MVT::i32)), 8774 DAG.getConstant(3, dl, MVT::i32)), 8775 DAG.getConstant(1, dl, MVT::i32)); 8776 8777 SDValue RetVal = 8778 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8779 8780 RetVal = 8781 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8782 dl, VT, RetVal); 8783 8784 return DAG.getMergeValues({RetVal, Chain}, dl); 8785 } 8786 8787 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8788 EVT VT = Op.getValueType(); 8789 unsigned BitWidth = VT.getSizeInBits(); 8790 SDLoc dl(Op); 8791 assert(Op.getNumOperands() == 3 && 8792 VT == Op.getOperand(1).getValueType() && 8793 "Unexpected SHL!"); 8794 8795 // Expand into a bunch of logical ops. Note that these ops 8796 // depend on the PPC behavior for oversized shift amounts. 8797 SDValue Lo = Op.getOperand(0); 8798 SDValue Hi = Op.getOperand(1); 8799 SDValue Amt = Op.getOperand(2); 8800 EVT AmtVT = Amt.getValueType(); 8801 8802 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8803 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8804 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8805 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8806 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8807 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8808 DAG.getConstant(-BitWidth, dl, AmtVT)); 8809 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8810 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8811 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8812 SDValue OutOps[] = { OutLo, OutHi }; 8813 return DAG.getMergeValues(OutOps, dl); 8814 } 8815 8816 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8817 EVT VT = Op.getValueType(); 8818 SDLoc dl(Op); 8819 unsigned BitWidth = VT.getSizeInBits(); 8820 assert(Op.getNumOperands() == 3 && 8821 VT == Op.getOperand(1).getValueType() && 8822 "Unexpected SRL!"); 8823 8824 // Expand into a bunch of logical ops. Note that these ops 8825 // depend on the PPC behavior for oversized shift amounts. 8826 SDValue Lo = Op.getOperand(0); 8827 SDValue Hi = Op.getOperand(1); 8828 SDValue Amt = Op.getOperand(2); 8829 EVT AmtVT = Amt.getValueType(); 8830 8831 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8832 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8833 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8834 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8835 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8836 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8837 DAG.getConstant(-BitWidth, dl, AmtVT)); 8838 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8839 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8840 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8841 SDValue OutOps[] = { OutLo, OutHi }; 8842 return DAG.getMergeValues(OutOps, dl); 8843 } 8844 8845 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8846 SDLoc dl(Op); 8847 EVT VT = Op.getValueType(); 8848 unsigned BitWidth = VT.getSizeInBits(); 8849 assert(Op.getNumOperands() == 3 && 8850 VT == Op.getOperand(1).getValueType() && 8851 "Unexpected SRA!"); 8852 8853 // Expand into a bunch of logical ops, followed by a select_cc. 8854 SDValue Lo = Op.getOperand(0); 8855 SDValue Hi = Op.getOperand(1); 8856 SDValue Amt = Op.getOperand(2); 8857 EVT AmtVT = Amt.getValueType(); 8858 8859 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8860 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8861 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8862 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8863 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8864 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8865 DAG.getConstant(-BitWidth, dl, AmtVT)); 8866 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8867 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8868 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8869 Tmp4, Tmp6, ISD::SETLE); 8870 SDValue OutOps[] = { OutLo, OutHi }; 8871 return DAG.getMergeValues(OutOps, dl); 8872 } 8873 8874 //===----------------------------------------------------------------------===// 8875 // Vector related lowering. 8876 // 8877 8878 /// BuildSplatI - Build a canonical splati of Val with an element size of 8879 /// SplatSize. Cast the result to VT. 8880 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8881 SelectionDAG &DAG, const SDLoc &dl) { 8882 static const MVT VTys[] = { // canonical VT to use for each size. 8883 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8884 }; 8885 8886 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8887 8888 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8889 if (Val == -1) 8890 SplatSize = 1; 8891 8892 EVT CanonicalVT = VTys[SplatSize-1]; 8893 8894 // Build a canonical splat for this value. 8895 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8896 } 8897 8898 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8899 /// specified intrinsic ID. 8900 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8901 const SDLoc &dl, EVT DestVT = MVT::Other) { 8902 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8903 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8904 DAG.getConstant(IID, dl, MVT::i32), Op); 8905 } 8906 8907 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8908 /// specified intrinsic ID. 8909 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8910 SelectionDAG &DAG, const SDLoc &dl, 8911 EVT DestVT = MVT::Other) { 8912 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8913 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8914 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8915 } 8916 8917 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8918 /// specified intrinsic ID. 8919 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8920 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8921 EVT DestVT = MVT::Other) { 8922 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8923 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8924 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8925 } 8926 8927 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8928 /// amount. The result has the specified value type. 8929 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8930 SelectionDAG &DAG, const SDLoc &dl) { 8931 // Force LHS/RHS to be the right type. 8932 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8933 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8934 8935 int Ops[16]; 8936 for (unsigned i = 0; i != 16; ++i) 8937 Ops[i] = i + Amt; 8938 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8939 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8940 } 8941 8942 /// Do we have an efficient pattern in a .td file for this node? 8943 /// 8944 /// \param V - pointer to the BuildVectorSDNode being matched 8945 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8946 /// 8947 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8948 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8949 /// the opposite is true (expansion is beneficial) are: 8950 /// - The node builds a vector out of integers that are not 32 or 64-bits 8951 /// - The node builds a vector out of constants 8952 /// - The node is a "load-and-splat" 8953 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8954 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8955 bool HasDirectMove, 8956 bool HasP8Vector) { 8957 EVT VecVT = V->getValueType(0); 8958 bool RightType = VecVT == MVT::v2f64 || 8959 (HasP8Vector && VecVT == MVT::v4f32) || 8960 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8961 if (!RightType) 8962 return false; 8963 8964 bool IsSplat = true; 8965 bool IsLoad = false; 8966 SDValue Op0 = V->getOperand(0); 8967 8968 // This function is called in a block that confirms the node is not a constant 8969 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8970 // different constants. 8971 if (V->isConstant()) 8972 return false; 8973 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8974 if (V->getOperand(i).isUndef()) 8975 return false; 8976 // We want to expand nodes that represent load-and-splat even if the 8977 // loaded value is a floating point truncation or conversion to int. 8978 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8979 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8980 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8981 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8982 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8983 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8984 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8985 IsLoad = true; 8986 // If the operands are different or the input is not a load and has more 8987 // uses than just this BV node, then it isn't a splat. 8988 if (V->getOperand(i) != Op0 || 8989 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8990 IsSplat = false; 8991 } 8992 return !(IsSplat && IsLoad); 8993 } 8994 8995 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8996 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8997 8998 SDLoc dl(Op); 8999 SDValue Op0 = Op->getOperand(0); 9000 9001 if (!EnableQuadPrecision || 9002 (Op.getValueType() != MVT::f128 ) || 9003 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9004 (Op0.getOperand(0).getValueType() != MVT::i64) || 9005 (Op0.getOperand(1).getValueType() != MVT::i64)) 9006 return SDValue(); 9007 9008 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9009 Op0.getOperand(1)); 9010 } 9011 9012 static const SDValue *getNormalLoadInput(const SDValue &Op) { 9013 const SDValue *InputLoad = &Op; 9014 if (InputLoad->getOpcode() == ISD::BITCAST) 9015 InputLoad = &InputLoad->getOperand(0); 9016 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 9017 InputLoad = &InputLoad->getOperand(0); 9018 if (InputLoad->getOpcode() != ISD::LOAD) 9019 return nullptr; 9020 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9021 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9022 } 9023 9024 // If this is a case we can't handle, return null and let the default 9025 // expansion code take care of it. If we CAN select this case, and if it 9026 // selects to a single instruction, return Op. Otherwise, if we can codegen 9027 // this case more efficiently than a constant pool load, lower it to the 9028 // sequence of ops that should be used. 9029 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9030 SelectionDAG &DAG) const { 9031 SDLoc dl(Op); 9032 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9033 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9034 9035 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 9036 // We first build an i32 vector, load it into a QPX register, 9037 // then convert it to a floating-point vector and compare it 9038 // to a zero vector to get the boolean result. 9039 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9040 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9041 MachinePointerInfo PtrInfo = 9042 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9043 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9044 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9045 9046 assert(BVN->getNumOperands() == 4 && 9047 "BUILD_VECTOR for v4i1 does not have 4 operands"); 9048 9049 bool IsConst = true; 9050 for (unsigned i = 0; i < 4; ++i) { 9051 if (BVN->getOperand(i).isUndef()) continue; 9052 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 9053 IsConst = false; 9054 break; 9055 } 9056 } 9057 9058 if (IsConst) { 9059 Constant *One = 9060 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 9061 Constant *NegOne = 9062 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 9063 9064 Constant *CV[4]; 9065 for (unsigned i = 0; i < 4; ++i) { 9066 if (BVN->getOperand(i).isUndef()) 9067 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 9068 else if (isNullConstant(BVN->getOperand(i))) 9069 CV[i] = NegOne; 9070 else 9071 CV[i] = One; 9072 } 9073 9074 Constant *CP = ConstantVector::get(CV); 9075 SDValue CPIdx = 9076 DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), Align(16)); 9077 9078 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 9079 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 9080 return DAG.getMemIntrinsicNode( 9081 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 9082 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 9083 } 9084 9085 SmallVector<SDValue, 4> Stores; 9086 for (unsigned i = 0; i < 4; ++i) { 9087 if (BVN->getOperand(i).isUndef()) continue; 9088 9089 unsigned Offset = 4*i; 9090 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9091 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9092 9093 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 9094 if (StoreSize > 4) { 9095 Stores.push_back( 9096 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 9097 PtrInfo.getWithOffset(Offset), MVT::i32)); 9098 } else { 9099 SDValue StoreValue = BVN->getOperand(i); 9100 if (StoreSize < 4) 9101 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 9102 9103 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 9104 PtrInfo.getWithOffset(Offset))); 9105 } 9106 } 9107 9108 SDValue StoreChain; 9109 if (!Stores.empty()) 9110 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9111 else 9112 StoreChain = DAG.getEntryNode(); 9113 9114 // Now load from v4i32 into the QPX register; this will extend it to 9115 // v4i64 but not yet convert it to a floating point. Nevertheless, this 9116 // is typed as v4f64 because the QPX register integer states are not 9117 // explicitly represented. 9118 9119 SDValue Ops[] = {StoreChain, 9120 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 9121 FIdx}; 9122 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 9123 9124 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 9125 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9126 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9127 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 9128 LoadedVect); 9129 9130 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 9131 9132 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 9133 } 9134 9135 // All other QPX vectors are handled by generic code. 9136 if (Subtarget.hasQPX()) 9137 return SDValue(); 9138 9139 // Check if this is a splat of a constant value. 9140 APInt APSplatBits, APSplatUndef; 9141 unsigned SplatBitSize; 9142 bool HasAnyUndefs; 9143 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9144 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9145 SplatBitSize > 32) { 9146 9147 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 9148 // Handle load-and-splat patterns as we have instructions that will do this 9149 // in one go. 9150 if (InputLoad && DAG.isSplatValue(Op, true)) { 9151 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9152 9153 // We have handling for 4 and 8 byte elements. 9154 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9155 9156 // Checking for a single use of this load, we have to check for vector 9157 // width (128 bits) / ElementSize uses (since each operand of the 9158 // BUILD_VECTOR is a separate use of the value. 9159 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9160 ((Subtarget.hasVSX() && ElementSize == 64) || 9161 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9162 SDValue Ops[] = { 9163 LD->getChain(), // Chain 9164 LD->getBasePtr(), // Ptr 9165 DAG.getValueType(Op.getValueType()) // VT 9166 }; 9167 return 9168 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9169 DAG.getVTList(Op.getValueType(), MVT::Other), 9170 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9171 } 9172 } 9173 9174 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9175 // lowered to VSX instructions under certain conditions. 9176 // Without VSX, there is no pattern more efficient than expanding the node. 9177 if (Subtarget.hasVSX() && 9178 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9179 Subtarget.hasP8Vector())) 9180 return Op; 9181 return SDValue(); 9182 } 9183 9184 unsigned SplatBits = APSplatBits.getZExtValue(); 9185 unsigned SplatUndef = APSplatUndef.getZExtValue(); 9186 unsigned SplatSize = SplatBitSize / 8; 9187 9188 // First, handle single instruction cases. 9189 9190 // All zeros? 9191 if (SplatBits == 0) { 9192 // Canonicalize all zero vectors to be v4i32. 9193 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9194 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9195 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9196 } 9197 return Op; 9198 } 9199 9200 // We have XXSPLTIB for constant splats one byte wide 9201 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 9202 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 9203 if (Subtarget.hasP9Vector() && SplatSize == 1) 9204 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 9205 9206 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9207 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9208 (32-SplatBitSize)); 9209 if (SextVal >= -16 && SextVal <= 15) 9210 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 9211 9212 // Two instruction sequences. 9213 9214 // If this value is in the range [-32,30] and is even, use: 9215 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9216 // If this value is in the range [17,31] and is odd, use: 9217 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9218 // If this value is in the range [-31,-17] and is odd, use: 9219 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9220 // Note the last two are three-instruction sequences. 9221 if (SextVal >= -32 && SextVal <= 31) { 9222 // To avoid having these optimizations undone by constant folding, 9223 // we convert to a pseudo that will be expanded later into one of 9224 // the above forms. 9225 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9226 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9227 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9228 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9229 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9230 if (VT == Op.getValueType()) 9231 return RetVal; 9232 else 9233 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9234 } 9235 9236 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9237 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9238 // for fneg/fabs. 9239 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9240 // Make -1 and vspltisw -1: 9241 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 9242 9243 // Make the VSLW intrinsic, computing 0x8000_0000. 9244 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9245 OnesV, DAG, dl); 9246 9247 // xor by OnesV to invert it. 9248 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9249 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9250 } 9251 9252 // Check to see if this is a wide variety of vsplti*, binop self cases. 9253 static const signed char SplatCsts[] = { 9254 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9255 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9256 }; 9257 9258 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9259 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9260 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9261 int i = SplatCsts[idx]; 9262 9263 // Figure out what shift amount will be used by altivec if shifted by i in 9264 // this splat size. 9265 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9266 9267 // vsplti + shl self. 9268 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9269 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9270 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9271 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9272 Intrinsic::ppc_altivec_vslw 9273 }; 9274 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9275 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9276 } 9277 9278 // vsplti + srl self. 9279 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9280 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9281 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9282 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9283 Intrinsic::ppc_altivec_vsrw 9284 }; 9285 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9286 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9287 } 9288 9289 // vsplti + sra self. 9290 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9291 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9292 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9293 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9294 Intrinsic::ppc_altivec_vsraw 9295 }; 9296 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9297 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9298 } 9299 9300 // vsplti + rol self. 9301 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9302 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9303 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9304 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9305 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9306 Intrinsic::ppc_altivec_vrlw 9307 }; 9308 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9309 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9310 } 9311 9312 // t = vsplti c, result = vsldoi t, t, 1 9313 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9314 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9315 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9316 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9317 } 9318 // t = vsplti c, result = vsldoi t, t, 2 9319 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9320 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9321 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9322 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9323 } 9324 // t = vsplti c, result = vsldoi t, t, 3 9325 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9326 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9327 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9328 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9329 } 9330 } 9331 9332 return SDValue(); 9333 } 9334 9335 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9336 /// the specified operations to build the shuffle. 9337 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9338 SDValue RHS, SelectionDAG &DAG, 9339 const SDLoc &dl) { 9340 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9341 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9342 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9343 9344 enum { 9345 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9346 OP_VMRGHW, 9347 OP_VMRGLW, 9348 OP_VSPLTISW0, 9349 OP_VSPLTISW1, 9350 OP_VSPLTISW2, 9351 OP_VSPLTISW3, 9352 OP_VSLDOI4, 9353 OP_VSLDOI8, 9354 OP_VSLDOI12 9355 }; 9356 9357 if (OpNum == OP_COPY) { 9358 if (LHSID == (1*9+2)*9+3) return LHS; 9359 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9360 return RHS; 9361 } 9362 9363 SDValue OpLHS, OpRHS; 9364 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9365 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9366 9367 int ShufIdxs[16]; 9368 switch (OpNum) { 9369 default: llvm_unreachable("Unknown i32 permute!"); 9370 case OP_VMRGHW: 9371 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9372 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9373 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9374 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9375 break; 9376 case OP_VMRGLW: 9377 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9378 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9379 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9380 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9381 break; 9382 case OP_VSPLTISW0: 9383 for (unsigned i = 0; i != 16; ++i) 9384 ShufIdxs[i] = (i&3)+0; 9385 break; 9386 case OP_VSPLTISW1: 9387 for (unsigned i = 0; i != 16; ++i) 9388 ShufIdxs[i] = (i&3)+4; 9389 break; 9390 case OP_VSPLTISW2: 9391 for (unsigned i = 0; i != 16; ++i) 9392 ShufIdxs[i] = (i&3)+8; 9393 break; 9394 case OP_VSPLTISW3: 9395 for (unsigned i = 0; i != 16; ++i) 9396 ShufIdxs[i] = (i&3)+12; 9397 break; 9398 case OP_VSLDOI4: 9399 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9400 case OP_VSLDOI8: 9401 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9402 case OP_VSLDOI12: 9403 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9404 } 9405 EVT VT = OpLHS.getValueType(); 9406 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9407 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9408 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9409 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9410 } 9411 9412 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9413 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9414 /// SDValue. 9415 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9416 SelectionDAG &DAG) const { 9417 const unsigned BytesInVector = 16; 9418 bool IsLE = Subtarget.isLittleEndian(); 9419 SDLoc dl(N); 9420 SDValue V1 = N->getOperand(0); 9421 SDValue V2 = N->getOperand(1); 9422 unsigned ShiftElts = 0, InsertAtByte = 0; 9423 bool Swap = false; 9424 9425 // Shifts required to get the byte we want at element 7. 9426 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9427 0, 15, 14, 13, 12, 11, 10, 9}; 9428 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9429 1, 2, 3, 4, 5, 6, 7, 8}; 9430 9431 ArrayRef<int> Mask = N->getMask(); 9432 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9433 9434 // For each mask element, find out if we're just inserting something 9435 // from V2 into V1 or vice versa. 9436 // Possible permutations inserting an element from V2 into V1: 9437 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9438 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9439 // ... 9440 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9441 // Inserting from V1 into V2 will be similar, except mask range will be 9442 // [16,31]. 9443 9444 bool FoundCandidate = false; 9445 // If both vector operands for the shuffle are the same vector, the mask 9446 // will contain only elements from the first one and the second one will be 9447 // undef. 9448 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9449 // Go through the mask of half-words to find an element that's being moved 9450 // from one vector to the other. 9451 for (unsigned i = 0; i < BytesInVector; ++i) { 9452 unsigned CurrentElement = Mask[i]; 9453 // If 2nd operand is undefined, we should only look for element 7 in the 9454 // Mask. 9455 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9456 continue; 9457 9458 bool OtherElementsInOrder = true; 9459 // Examine the other elements in the Mask to see if they're in original 9460 // order. 9461 for (unsigned j = 0; j < BytesInVector; ++j) { 9462 if (j == i) 9463 continue; 9464 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9465 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9466 // in which we always assume we're always picking from the 1st operand. 9467 int MaskOffset = 9468 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9469 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9470 OtherElementsInOrder = false; 9471 break; 9472 } 9473 } 9474 // If other elements are in original order, we record the number of shifts 9475 // we need to get the element we want into element 7. Also record which byte 9476 // in the vector we should insert into. 9477 if (OtherElementsInOrder) { 9478 // If 2nd operand is undefined, we assume no shifts and no swapping. 9479 if (V2.isUndef()) { 9480 ShiftElts = 0; 9481 Swap = false; 9482 } else { 9483 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9484 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9485 : BigEndianShifts[CurrentElement & 0xF]; 9486 Swap = CurrentElement < BytesInVector; 9487 } 9488 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9489 FoundCandidate = true; 9490 break; 9491 } 9492 } 9493 9494 if (!FoundCandidate) 9495 return SDValue(); 9496 9497 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9498 // optionally with VECSHL if shift is required. 9499 if (Swap) 9500 std::swap(V1, V2); 9501 if (V2.isUndef()) 9502 V2 = V1; 9503 if (ShiftElts) { 9504 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9505 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9506 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9507 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9508 } 9509 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9510 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9511 } 9512 9513 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9514 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9515 /// SDValue. 9516 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9517 SelectionDAG &DAG) const { 9518 const unsigned NumHalfWords = 8; 9519 const unsigned BytesInVector = NumHalfWords * 2; 9520 // Check that the shuffle is on half-words. 9521 if (!isNByteElemShuffleMask(N, 2, 1)) 9522 return SDValue(); 9523 9524 bool IsLE = Subtarget.isLittleEndian(); 9525 SDLoc dl(N); 9526 SDValue V1 = N->getOperand(0); 9527 SDValue V2 = N->getOperand(1); 9528 unsigned ShiftElts = 0, InsertAtByte = 0; 9529 bool Swap = false; 9530 9531 // Shifts required to get the half-word we want at element 3. 9532 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9533 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9534 9535 uint32_t Mask = 0; 9536 uint32_t OriginalOrderLow = 0x1234567; 9537 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9538 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9539 // 32-bit space, only need 4-bit nibbles per element. 9540 for (unsigned i = 0; i < NumHalfWords; ++i) { 9541 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9542 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9543 } 9544 9545 // For each mask element, find out if we're just inserting something 9546 // from V2 into V1 or vice versa. Possible permutations inserting an element 9547 // from V2 into V1: 9548 // X, 1, 2, 3, 4, 5, 6, 7 9549 // 0, X, 2, 3, 4, 5, 6, 7 9550 // 0, 1, X, 3, 4, 5, 6, 7 9551 // 0, 1, 2, X, 4, 5, 6, 7 9552 // 0, 1, 2, 3, X, 5, 6, 7 9553 // 0, 1, 2, 3, 4, X, 6, 7 9554 // 0, 1, 2, 3, 4, 5, X, 7 9555 // 0, 1, 2, 3, 4, 5, 6, X 9556 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9557 9558 bool FoundCandidate = false; 9559 // Go through the mask of half-words to find an element that's being moved 9560 // from one vector to the other. 9561 for (unsigned i = 0; i < NumHalfWords; ++i) { 9562 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9563 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9564 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9565 uint32_t TargetOrder = 0x0; 9566 9567 // If both vector operands for the shuffle are the same vector, the mask 9568 // will contain only elements from the first one and the second one will be 9569 // undef. 9570 if (V2.isUndef()) { 9571 ShiftElts = 0; 9572 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9573 TargetOrder = OriginalOrderLow; 9574 Swap = false; 9575 // Skip if not the correct element or mask of other elements don't equal 9576 // to our expected order. 9577 if (MaskOneElt == VINSERTHSrcElem && 9578 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9579 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9580 FoundCandidate = true; 9581 break; 9582 } 9583 } else { // If both operands are defined. 9584 // Target order is [8,15] if the current mask is between [0,7]. 9585 TargetOrder = 9586 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9587 // Skip if mask of other elements don't equal our expected order. 9588 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9589 // We only need the last 3 bits for the number of shifts. 9590 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9591 : BigEndianShifts[MaskOneElt & 0x7]; 9592 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9593 Swap = MaskOneElt < NumHalfWords; 9594 FoundCandidate = true; 9595 break; 9596 } 9597 } 9598 } 9599 9600 if (!FoundCandidate) 9601 return SDValue(); 9602 9603 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9604 // optionally with VECSHL if shift is required. 9605 if (Swap) 9606 std::swap(V1, V2); 9607 if (V2.isUndef()) 9608 V2 = V1; 9609 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9610 if (ShiftElts) { 9611 // Double ShiftElts because we're left shifting on v16i8 type. 9612 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9613 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9614 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9615 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9616 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9617 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9618 } 9619 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9620 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9621 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9622 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9623 } 9624 9625 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9626 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9627 /// return the code it can be lowered into. Worst case, it can always be 9628 /// lowered into a vperm. 9629 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9630 SelectionDAG &DAG) const { 9631 SDLoc dl(Op); 9632 SDValue V1 = Op.getOperand(0); 9633 SDValue V2 = Op.getOperand(1); 9634 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9635 EVT VT = Op.getValueType(); 9636 bool isLittleEndian = Subtarget.isLittleEndian(); 9637 9638 unsigned ShiftElts, InsertAtByte; 9639 bool Swap = false; 9640 9641 // If this is a load-and-splat, we can do that with a single instruction 9642 // in some cases. However if the load has multiple uses, we don't want to 9643 // combine it because that will just produce multiple loads. 9644 const SDValue *InputLoad = getNormalLoadInput(V1); 9645 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9646 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9647 InputLoad->hasOneUse()) { 9648 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9649 int SplatIdx = 9650 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9651 9652 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9653 // For 4-byte load-and-splat, we need Power9. 9654 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9655 uint64_t Offset = 0; 9656 if (IsFourByte) 9657 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9658 else 9659 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9660 SDValue BasePtr = LD->getBasePtr(); 9661 if (Offset != 0) 9662 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9663 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9664 SDValue Ops[] = { 9665 LD->getChain(), // Chain 9666 BasePtr, // BasePtr 9667 DAG.getValueType(Op.getValueType()) // VT 9668 }; 9669 SDVTList VTL = 9670 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9671 SDValue LdSplt = 9672 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9673 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9674 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9675 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9676 return LdSplt; 9677 } 9678 } 9679 if (Subtarget.hasP9Vector() && 9680 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9681 isLittleEndian)) { 9682 if (Swap) 9683 std::swap(V1, V2); 9684 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9685 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9686 if (ShiftElts) { 9687 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9688 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9689 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9690 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9691 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9692 } 9693 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9694 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9695 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9696 } 9697 9698 if (Subtarget.hasP9Altivec()) { 9699 SDValue NewISDNode; 9700 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9701 return NewISDNode; 9702 9703 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9704 return NewISDNode; 9705 } 9706 9707 if (Subtarget.hasVSX() && 9708 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9709 if (Swap) 9710 std::swap(V1, V2); 9711 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9712 SDValue Conv2 = 9713 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9714 9715 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9716 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9717 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9718 } 9719 9720 if (Subtarget.hasVSX() && 9721 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9722 if (Swap) 9723 std::swap(V1, V2); 9724 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9725 SDValue Conv2 = 9726 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9727 9728 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9729 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9730 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9731 } 9732 9733 if (Subtarget.hasP9Vector()) { 9734 if (PPC::isXXBRHShuffleMask(SVOp)) { 9735 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9736 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9737 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9738 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9739 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9740 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9741 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9742 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9743 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9744 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9745 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9746 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9747 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9748 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9749 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9750 } 9751 } 9752 9753 if (Subtarget.hasVSX()) { 9754 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9755 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9756 9757 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9758 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9759 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9760 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9761 } 9762 9763 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9764 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9765 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9766 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9767 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9768 } 9769 } 9770 9771 if (Subtarget.hasQPX()) { 9772 if (VT.getVectorNumElements() != 4) 9773 return SDValue(); 9774 9775 if (V2.isUndef()) V2 = V1; 9776 9777 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9778 if (AlignIdx != -1) { 9779 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9780 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9781 } else if (SVOp->isSplat()) { 9782 int SplatIdx = SVOp->getSplatIndex(); 9783 if (SplatIdx >= 4) { 9784 std::swap(V1, V2); 9785 SplatIdx -= 4; 9786 } 9787 9788 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9789 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9790 } 9791 9792 // Lower this into a qvgpci/qvfperm pair. 9793 9794 // Compute the qvgpci literal 9795 unsigned idx = 0; 9796 for (unsigned i = 0; i < 4; ++i) { 9797 int m = SVOp->getMaskElt(i); 9798 unsigned mm = m >= 0 ? (unsigned) m : i; 9799 idx |= mm << (3-i)*3; 9800 } 9801 9802 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9803 DAG.getConstant(idx, dl, MVT::i32)); 9804 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9805 } 9806 9807 // Cases that are handled by instructions that take permute immediates 9808 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9809 // selected by the instruction selector. 9810 if (V2.isUndef()) { 9811 if (PPC::isSplatShuffleMask(SVOp, 1) || 9812 PPC::isSplatShuffleMask(SVOp, 2) || 9813 PPC::isSplatShuffleMask(SVOp, 4) || 9814 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9815 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9816 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9817 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9818 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9819 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9820 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9821 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9822 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9823 (Subtarget.hasP8Altivec() && ( 9824 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9825 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9826 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9827 return Op; 9828 } 9829 } 9830 9831 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9832 // and produce a fixed permutation. If any of these match, do not lower to 9833 // VPERM. 9834 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9835 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9836 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9837 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9838 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9839 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9840 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9841 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9842 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9843 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9844 (Subtarget.hasP8Altivec() && ( 9845 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9846 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9847 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9848 return Op; 9849 9850 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9851 // perfect shuffle table to emit an optimal matching sequence. 9852 ArrayRef<int> PermMask = SVOp->getMask(); 9853 9854 unsigned PFIndexes[4]; 9855 bool isFourElementShuffle = true; 9856 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9857 unsigned EltNo = 8; // Start out undef. 9858 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9859 if (PermMask[i*4+j] < 0) 9860 continue; // Undef, ignore it. 9861 9862 unsigned ByteSource = PermMask[i*4+j]; 9863 if ((ByteSource & 3) != j) { 9864 isFourElementShuffle = false; 9865 break; 9866 } 9867 9868 if (EltNo == 8) { 9869 EltNo = ByteSource/4; 9870 } else if (EltNo != ByteSource/4) { 9871 isFourElementShuffle = false; 9872 break; 9873 } 9874 } 9875 PFIndexes[i] = EltNo; 9876 } 9877 9878 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9879 // perfect shuffle vector to determine if it is cost effective to do this as 9880 // discrete instructions, or whether we should use a vperm. 9881 // For now, we skip this for little endian until such time as we have a 9882 // little-endian perfect shuffle table. 9883 if (isFourElementShuffle && !isLittleEndian) { 9884 // Compute the index in the perfect shuffle table. 9885 unsigned PFTableIndex = 9886 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9887 9888 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9889 unsigned Cost = (PFEntry >> 30); 9890 9891 // Determining when to avoid vperm is tricky. Many things affect the cost 9892 // of vperm, particularly how many times the perm mask needs to be computed. 9893 // For example, if the perm mask can be hoisted out of a loop or is already 9894 // used (perhaps because there are multiple permutes with the same shuffle 9895 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9896 // the loop requires an extra register. 9897 // 9898 // As a compromise, we only emit discrete instructions if the shuffle can be 9899 // generated in 3 or fewer operations. When we have loop information 9900 // available, if this block is within a loop, we should avoid using vperm 9901 // for 3-operation perms and use a constant pool load instead. 9902 if (Cost < 3) 9903 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9904 } 9905 9906 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9907 // vector that will get spilled to the constant pool. 9908 if (V2.isUndef()) V2 = V1; 9909 9910 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9911 // that it is in input element units, not in bytes. Convert now. 9912 9913 // For little endian, the order of the input vectors is reversed, and 9914 // the permutation mask is complemented with respect to 31. This is 9915 // necessary to produce proper semantics with the big-endian-biased vperm 9916 // instruction. 9917 EVT EltVT = V1.getValueType().getVectorElementType(); 9918 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9919 9920 SmallVector<SDValue, 16> ResultMask; 9921 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9922 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9923 9924 for (unsigned j = 0; j != BytesPerElement; ++j) 9925 if (isLittleEndian) 9926 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9927 dl, MVT::i32)); 9928 else 9929 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9930 MVT::i32)); 9931 } 9932 9933 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9934 if (isLittleEndian) 9935 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9936 V2, V1, VPermMask); 9937 else 9938 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9939 V1, V2, VPermMask); 9940 } 9941 9942 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9943 /// vector comparison. If it is, return true and fill in Opc/isDot with 9944 /// information about the intrinsic. 9945 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9946 bool &isDot, const PPCSubtarget &Subtarget) { 9947 unsigned IntrinsicID = 9948 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9949 CompareOpc = -1; 9950 isDot = false; 9951 switch (IntrinsicID) { 9952 default: 9953 return false; 9954 // Comparison predicates. 9955 case Intrinsic::ppc_altivec_vcmpbfp_p: 9956 CompareOpc = 966; 9957 isDot = true; 9958 break; 9959 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9960 CompareOpc = 198; 9961 isDot = true; 9962 break; 9963 case Intrinsic::ppc_altivec_vcmpequb_p: 9964 CompareOpc = 6; 9965 isDot = true; 9966 break; 9967 case Intrinsic::ppc_altivec_vcmpequh_p: 9968 CompareOpc = 70; 9969 isDot = true; 9970 break; 9971 case Intrinsic::ppc_altivec_vcmpequw_p: 9972 CompareOpc = 134; 9973 isDot = true; 9974 break; 9975 case Intrinsic::ppc_altivec_vcmpequd_p: 9976 if (Subtarget.hasP8Altivec()) { 9977 CompareOpc = 199; 9978 isDot = true; 9979 } else 9980 return false; 9981 break; 9982 case Intrinsic::ppc_altivec_vcmpneb_p: 9983 case Intrinsic::ppc_altivec_vcmpneh_p: 9984 case Intrinsic::ppc_altivec_vcmpnew_p: 9985 case Intrinsic::ppc_altivec_vcmpnezb_p: 9986 case Intrinsic::ppc_altivec_vcmpnezh_p: 9987 case Intrinsic::ppc_altivec_vcmpnezw_p: 9988 if (Subtarget.hasP9Altivec()) { 9989 switch (IntrinsicID) { 9990 default: 9991 llvm_unreachable("Unknown comparison intrinsic."); 9992 case Intrinsic::ppc_altivec_vcmpneb_p: 9993 CompareOpc = 7; 9994 break; 9995 case Intrinsic::ppc_altivec_vcmpneh_p: 9996 CompareOpc = 71; 9997 break; 9998 case Intrinsic::ppc_altivec_vcmpnew_p: 9999 CompareOpc = 135; 10000 break; 10001 case Intrinsic::ppc_altivec_vcmpnezb_p: 10002 CompareOpc = 263; 10003 break; 10004 case Intrinsic::ppc_altivec_vcmpnezh_p: 10005 CompareOpc = 327; 10006 break; 10007 case Intrinsic::ppc_altivec_vcmpnezw_p: 10008 CompareOpc = 391; 10009 break; 10010 } 10011 isDot = true; 10012 } else 10013 return false; 10014 break; 10015 case Intrinsic::ppc_altivec_vcmpgefp_p: 10016 CompareOpc = 454; 10017 isDot = true; 10018 break; 10019 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10020 CompareOpc = 710; 10021 isDot = true; 10022 break; 10023 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10024 CompareOpc = 774; 10025 isDot = true; 10026 break; 10027 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10028 CompareOpc = 838; 10029 isDot = true; 10030 break; 10031 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10032 CompareOpc = 902; 10033 isDot = true; 10034 break; 10035 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10036 if (Subtarget.hasP8Altivec()) { 10037 CompareOpc = 967; 10038 isDot = true; 10039 } else 10040 return false; 10041 break; 10042 case Intrinsic::ppc_altivec_vcmpgtub_p: 10043 CompareOpc = 518; 10044 isDot = true; 10045 break; 10046 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10047 CompareOpc = 582; 10048 isDot = true; 10049 break; 10050 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10051 CompareOpc = 646; 10052 isDot = true; 10053 break; 10054 case Intrinsic::ppc_altivec_vcmpgtud_p: 10055 if (Subtarget.hasP8Altivec()) { 10056 CompareOpc = 711; 10057 isDot = true; 10058 } else 10059 return false; 10060 break; 10061 10062 // VSX predicate comparisons use the same infrastructure 10063 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10064 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10065 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10066 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10067 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10068 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10069 if (Subtarget.hasVSX()) { 10070 switch (IntrinsicID) { 10071 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10072 CompareOpc = 99; 10073 break; 10074 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10075 CompareOpc = 115; 10076 break; 10077 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10078 CompareOpc = 107; 10079 break; 10080 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10081 CompareOpc = 67; 10082 break; 10083 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10084 CompareOpc = 83; 10085 break; 10086 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10087 CompareOpc = 75; 10088 break; 10089 } 10090 isDot = true; 10091 } else 10092 return false; 10093 break; 10094 10095 // Normal Comparisons. 10096 case Intrinsic::ppc_altivec_vcmpbfp: 10097 CompareOpc = 966; 10098 break; 10099 case Intrinsic::ppc_altivec_vcmpeqfp: 10100 CompareOpc = 198; 10101 break; 10102 case Intrinsic::ppc_altivec_vcmpequb: 10103 CompareOpc = 6; 10104 break; 10105 case Intrinsic::ppc_altivec_vcmpequh: 10106 CompareOpc = 70; 10107 break; 10108 case Intrinsic::ppc_altivec_vcmpequw: 10109 CompareOpc = 134; 10110 break; 10111 case Intrinsic::ppc_altivec_vcmpequd: 10112 if (Subtarget.hasP8Altivec()) 10113 CompareOpc = 199; 10114 else 10115 return false; 10116 break; 10117 case Intrinsic::ppc_altivec_vcmpneb: 10118 case Intrinsic::ppc_altivec_vcmpneh: 10119 case Intrinsic::ppc_altivec_vcmpnew: 10120 case Intrinsic::ppc_altivec_vcmpnezb: 10121 case Intrinsic::ppc_altivec_vcmpnezh: 10122 case Intrinsic::ppc_altivec_vcmpnezw: 10123 if (Subtarget.hasP9Altivec()) 10124 switch (IntrinsicID) { 10125 default: 10126 llvm_unreachable("Unknown comparison intrinsic."); 10127 case Intrinsic::ppc_altivec_vcmpneb: 10128 CompareOpc = 7; 10129 break; 10130 case Intrinsic::ppc_altivec_vcmpneh: 10131 CompareOpc = 71; 10132 break; 10133 case Intrinsic::ppc_altivec_vcmpnew: 10134 CompareOpc = 135; 10135 break; 10136 case Intrinsic::ppc_altivec_vcmpnezb: 10137 CompareOpc = 263; 10138 break; 10139 case Intrinsic::ppc_altivec_vcmpnezh: 10140 CompareOpc = 327; 10141 break; 10142 case Intrinsic::ppc_altivec_vcmpnezw: 10143 CompareOpc = 391; 10144 break; 10145 } 10146 else 10147 return false; 10148 break; 10149 case Intrinsic::ppc_altivec_vcmpgefp: 10150 CompareOpc = 454; 10151 break; 10152 case Intrinsic::ppc_altivec_vcmpgtfp: 10153 CompareOpc = 710; 10154 break; 10155 case Intrinsic::ppc_altivec_vcmpgtsb: 10156 CompareOpc = 774; 10157 break; 10158 case Intrinsic::ppc_altivec_vcmpgtsh: 10159 CompareOpc = 838; 10160 break; 10161 case Intrinsic::ppc_altivec_vcmpgtsw: 10162 CompareOpc = 902; 10163 break; 10164 case Intrinsic::ppc_altivec_vcmpgtsd: 10165 if (Subtarget.hasP8Altivec()) 10166 CompareOpc = 967; 10167 else 10168 return false; 10169 break; 10170 case Intrinsic::ppc_altivec_vcmpgtub: 10171 CompareOpc = 518; 10172 break; 10173 case Intrinsic::ppc_altivec_vcmpgtuh: 10174 CompareOpc = 582; 10175 break; 10176 case Intrinsic::ppc_altivec_vcmpgtuw: 10177 CompareOpc = 646; 10178 break; 10179 case Intrinsic::ppc_altivec_vcmpgtud: 10180 if (Subtarget.hasP8Altivec()) 10181 CompareOpc = 711; 10182 else 10183 return false; 10184 break; 10185 } 10186 return true; 10187 } 10188 10189 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10190 /// lower, do it, otherwise return null. 10191 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10192 SelectionDAG &DAG) const { 10193 unsigned IntrinsicID = 10194 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10195 10196 SDLoc dl(Op); 10197 10198 if (IntrinsicID == Intrinsic::thread_pointer) { 10199 // Reads the thread pointer register, used for __builtin_thread_pointer. 10200 if (Subtarget.isPPC64()) 10201 return DAG.getRegister(PPC::X13, MVT::i64); 10202 return DAG.getRegister(PPC::R2, MVT::i32); 10203 } 10204 10205 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10206 // opcode number of the comparison. 10207 int CompareOpc; 10208 bool isDot; 10209 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10210 return SDValue(); // Don't custom lower most intrinsics. 10211 10212 // If this is a non-dot comparison, make the VCMP node and we are done. 10213 if (!isDot) { 10214 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10215 Op.getOperand(1), Op.getOperand(2), 10216 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10217 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10218 } 10219 10220 // Create the PPCISD altivec 'dot' comparison node. 10221 SDValue Ops[] = { 10222 Op.getOperand(2), // LHS 10223 Op.getOperand(3), // RHS 10224 DAG.getConstant(CompareOpc, dl, MVT::i32) 10225 }; 10226 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10227 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10228 10229 // Now that we have the comparison, emit a copy from the CR to a GPR. 10230 // This is flagged to the above dot comparison. 10231 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10232 DAG.getRegister(PPC::CR6, MVT::i32), 10233 CompNode.getValue(1)); 10234 10235 // Unpack the result based on how the target uses it. 10236 unsigned BitNo; // Bit # of CR6. 10237 bool InvertBit; // Invert result? 10238 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10239 default: // Can't happen, don't crash on invalid number though. 10240 case 0: // Return the value of the EQ bit of CR6. 10241 BitNo = 0; InvertBit = false; 10242 break; 10243 case 1: // Return the inverted value of the EQ bit of CR6. 10244 BitNo = 0; InvertBit = true; 10245 break; 10246 case 2: // Return the value of the LT bit of CR6. 10247 BitNo = 2; InvertBit = false; 10248 break; 10249 case 3: // Return the inverted value of the LT bit of CR6. 10250 BitNo = 2; InvertBit = true; 10251 break; 10252 } 10253 10254 // Shift the bit into the low position. 10255 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10256 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10257 // Isolate the bit. 10258 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10259 DAG.getConstant(1, dl, MVT::i32)); 10260 10261 // If we are supposed to, toggle the bit. 10262 if (InvertBit) 10263 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10264 DAG.getConstant(1, dl, MVT::i32)); 10265 return Flags; 10266 } 10267 10268 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10269 SelectionDAG &DAG) const { 10270 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10271 // the beginning of the argument list. 10272 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10273 SDLoc DL(Op); 10274 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10275 case Intrinsic::ppc_cfence: { 10276 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10277 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10278 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10279 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10280 Op.getOperand(ArgStart + 1)), 10281 Op.getOperand(0)), 10282 0); 10283 } 10284 default: 10285 break; 10286 } 10287 return SDValue(); 10288 } 10289 10290 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 10291 // Check for a DIV with the same operands as this REM. 10292 for (auto UI : Op.getOperand(1)->uses()) { 10293 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 10294 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 10295 if (UI->getOperand(0) == Op.getOperand(0) && 10296 UI->getOperand(1) == Op.getOperand(1)) 10297 return SDValue(); 10298 } 10299 return Op; 10300 } 10301 10302 // Lower scalar BSWAP64 to xxbrd. 10303 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10304 SDLoc dl(Op); 10305 // MTVSRDD 10306 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10307 Op.getOperand(0)); 10308 // XXBRD 10309 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10310 // MFVSRD 10311 int VectorIndex = 0; 10312 if (Subtarget.isLittleEndian()) 10313 VectorIndex = 1; 10314 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10315 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10316 return Op; 10317 } 10318 10319 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10320 // compared to a value that is atomically loaded (atomic loads zero-extend). 10321 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10322 SelectionDAG &DAG) const { 10323 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10324 "Expecting an atomic compare-and-swap here."); 10325 SDLoc dl(Op); 10326 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10327 EVT MemVT = AtomicNode->getMemoryVT(); 10328 if (MemVT.getSizeInBits() >= 32) 10329 return Op; 10330 10331 SDValue CmpOp = Op.getOperand(2); 10332 // If this is already correctly zero-extended, leave it alone. 10333 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10334 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10335 return Op; 10336 10337 // Clear the high bits of the compare operand. 10338 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10339 SDValue NewCmpOp = 10340 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10341 DAG.getConstant(MaskVal, dl, MVT::i32)); 10342 10343 // Replace the existing compare operand with the properly zero-extended one. 10344 SmallVector<SDValue, 4> Ops; 10345 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10346 Ops.push_back(AtomicNode->getOperand(i)); 10347 Ops[2] = NewCmpOp; 10348 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10349 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10350 auto NodeTy = 10351 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10352 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10353 } 10354 10355 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10356 SelectionDAG &DAG) const { 10357 SDLoc dl(Op); 10358 // Create a stack slot that is 16-byte aligned. 10359 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10360 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10361 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10362 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10363 10364 // Store the input value into Value#0 of the stack slot. 10365 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10366 MachinePointerInfo()); 10367 // Load it out. 10368 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10369 } 10370 10371 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10372 SelectionDAG &DAG) const { 10373 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10374 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10375 10376 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10377 // We have legal lowering for constant indices but not for variable ones. 10378 if (!C) 10379 return SDValue(); 10380 10381 EVT VT = Op.getValueType(); 10382 SDLoc dl(Op); 10383 SDValue V1 = Op.getOperand(0); 10384 SDValue V2 = Op.getOperand(1); 10385 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10386 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10387 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10388 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10389 unsigned InsertAtElement = C->getZExtValue(); 10390 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10391 if (Subtarget.isLittleEndian()) { 10392 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10393 } 10394 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10395 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10396 } 10397 return Op; 10398 } 10399 10400 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 10401 SelectionDAG &DAG) const { 10402 SDLoc dl(Op); 10403 SDNode *N = Op.getNode(); 10404 10405 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 10406 "Unknown extract_vector_elt type"); 10407 10408 SDValue Value = N->getOperand(0); 10409 10410 // The first part of this is like the store lowering except that we don't 10411 // need to track the chain. 10412 10413 // The values are now known to be -1 (false) or 1 (true). To convert this 10414 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10415 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10416 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10417 10418 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10419 // understand how to form the extending load. 10420 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10421 10422 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10423 10424 // Now convert to an integer and store. 10425 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10426 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10427 Value); 10428 10429 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10430 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10431 MachinePointerInfo PtrInfo = 10432 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10433 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10434 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10435 10436 SDValue StoreChain = DAG.getEntryNode(); 10437 SDValue Ops[] = {StoreChain, 10438 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10439 Value, FIdx}; 10440 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10441 10442 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10443 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10444 10445 // Extract the value requested. 10446 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10447 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10448 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10449 10450 SDValue IntVal = 10451 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 10452 10453 if (!Subtarget.useCRBits()) 10454 return IntVal; 10455 10456 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 10457 } 10458 10459 /// Lowering for QPX v4i1 loads 10460 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10461 SelectionDAG &DAG) const { 10462 SDLoc dl(Op); 10463 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10464 SDValue LoadChain = LN->getChain(); 10465 SDValue BasePtr = LN->getBasePtr(); 10466 10467 if (Op.getValueType() == MVT::v4f64 || 10468 Op.getValueType() == MVT::v4f32) { 10469 EVT MemVT = LN->getMemoryVT(); 10470 unsigned Alignment = LN->getAlignment(); 10471 10472 // If this load is properly aligned, then it is legal. 10473 if (Alignment >= MemVT.getStoreSize()) 10474 return Op; 10475 10476 EVT ScalarVT = Op.getValueType().getScalarType(), 10477 ScalarMemVT = MemVT.getScalarType(); 10478 unsigned Stride = ScalarMemVT.getStoreSize(); 10479 10480 SDValue Vals[4], LoadChains[4]; 10481 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10482 SDValue Load; 10483 if (ScalarVT != ScalarMemVT) 10484 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10485 BasePtr, 10486 LN->getPointerInfo().getWithOffset(Idx * Stride), 10487 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10488 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10489 else 10490 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10491 LN->getPointerInfo().getWithOffset(Idx * Stride), 10492 MinAlign(Alignment, Idx * Stride), 10493 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10494 10495 if (Idx == 0 && LN->isIndexed()) { 10496 assert(LN->getAddressingMode() == ISD::PRE_INC && 10497 "Unknown addressing mode on vector load"); 10498 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10499 LN->getAddressingMode()); 10500 } 10501 10502 Vals[Idx] = Load; 10503 LoadChains[Idx] = Load.getValue(1); 10504 10505 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10506 DAG.getConstant(Stride, dl, 10507 BasePtr.getValueType())); 10508 } 10509 10510 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10511 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10512 10513 if (LN->isIndexed()) { 10514 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10515 return DAG.getMergeValues(RetOps, dl); 10516 } 10517 10518 SDValue RetOps[] = { Value, TF }; 10519 return DAG.getMergeValues(RetOps, dl); 10520 } 10521 10522 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10523 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10524 10525 // To lower v4i1 from a byte array, we load the byte elements of the 10526 // vector and then reuse the BUILD_VECTOR logic. 10527 10528 SDValue VectElmts[4], VectElmtChains[4]; 10529 for (unsigned i = 0; i < 4; ++i) { 10530 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10531 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10532 10533 VectElmts[i] = DAG.getExtLoad( 10534 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10535 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10536 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10537 VectElmtChains[i] = VectElmts[i].getValue(1); 10538 } 10539 10540 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10541 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10542 10543 SDValue RVals[] = { Value, LoadChain }; 10544 return DAG.getMergeValues(RVals, dl); 10545 } 10546 10547 /// Lowering for QPX v4i1 stores 10548 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10549 SelectionDAG &DAG) const { 10550 SDLoc dl(Op); 10551 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10552 SDValue StoreChain = SN->getChain(); 10553 SDValue BasePtr = SN->getBasePtr(); 10554 SDValue Value = SN->getValue(); 10555 10556 if (Value.getValueType() == MVT::v4f64 || 10557 Value.getValueType() == MVT::v4f32) { 10558 EVT MemVT = SN->getMemoryVT(); 10559 unsigned Alignment = SN->getAlignment(); 10560 10561 // If this store is properly aligned, then it is legal. 10562 if (Alignment >= MemVT.getStoreSize()) 10563 return Op; 10564 10565 EVT ScalarVT = Value.getValueType().getScalarType(), 10566 ScalarMemVT = MemVT.getScalarType(); 10567 unsigned Stride = ScalarMemVT.getStoreSize(); 10568 10569 SDValue Stores[4]; 10570 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10571 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10572 DAG.getVectorIdxConstant(Idx, dl)); 10573 SDValue Store; 10574 if (ScalarVT != ScalarMemVT) 10575 Store = 10576 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10577 SN->getPointerInfo().getWithOffset(Idx * Stride), 10578 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10579 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10580 else 10581 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10582 SN->getPointerInfo().getWithOffset(Idx * Stride), 10583 MinAlign(Alignment, Idx * Stride), 10584 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10585 10586 if (Idx == 0 && SN->isIndexed()) { 10587 assert(SN->getAddressingMode() == ISD::PRE_INC && 10588 "Unknown addressing mode on vector store"); 10589 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10590 SN->getAddressingMode()); 10591 } 10592 10593 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10594 DAG.getConstant(Stride, dl, 10595 BasePtr.getValueType())); 10596 Stores[Idx] = Store; 10597 } 10598 10599 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10600 10601 if (SN->isIndexed()) { 10602 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10603 return DAG.getMergeValues(RetOps, dl); 10604 } 10605 10606 return TF; 10607 } 10608 10609 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10610 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10611 10612 // The values are now known to be -1 (false) or 1 (true). To convert this 10613 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10614 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10615 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10616 10617 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10618 // understand how to form the extending load. 10619 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10620 10621 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10622 10623 // Now convert to an integer and store. 10624 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10625 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10626 Value); 10627 10628 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10629 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10630 MachinePointerInfo PtrInfo = 10631 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10632 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10633 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10634 10635 SDValue Ops[] = {StoreChain, 10636 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10637 Value, FIdx}; 10638 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10639 10640 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10641 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10642 10643 // Move data into the byte array. 10644 SDValue Loads[4], LoadChains[4]; 10645 for (unsigned i = 0; i < 4; ++i) { 10646 unsigned Offset = 4*i; 10647 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10648 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10649 10650 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10651 PtrInfo.getWithOffset(Offset)); 10652 LoadChains[i] = Loads[i].getValue(1); 10653 } 10654 10655 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10656 10657 SDValue Stores[4]; 10658 for (unsigned i = 0; i < 4; ++i) { 10659 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10660 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10661 10662 Stores[i] = DAG.getTruncStore( 10663 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10664 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10665 SN->getAAInfo()); 10666 } 10667 10668 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10669 10670 return StoreChain; 10671 } 10672 10673 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10674 SDLoc dl(Op); 10675 if (Op.getValueType() == MVT::v4i32) { 10676 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10677 10678 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10679 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10680 10681 SDValue RHSSwap = // = vrlw RHS, 16 10682 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10683 10684 // Shrinkify inputs to v8i16. 10685 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10686 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10687 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10688 10689 // Low parts multiplied together, generating 32-bit results (we ignore the 10690 // top parts). 10691 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10692 LHS, RHS, DAG, dl, MVT::v4i32); 10693 10694 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10695 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10696 // Shift the high parts up 16 bits. 10697 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10698 Neg16, DAG, dl); 10699 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10700 } else if (Op.getValueType() == MVT::v16i8) { 10701 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10702 bool isLittleEndian = Subtarget.isLittleEndian(); 10703 10704 // Multiply the even 8-bit parts, producing 16-bit sums. 10705 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10706 LHS, RHS, DAG, dl, MVT::v8i16); 10707 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10708 10709 // Multiply the odd 8-bit parts, producing 16-bit sums. 10710 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10711 LHS, RHS, DAG, dl, MVT::v8i16); 10712 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10713 10714 // Merge the results together. Because vmuleub and vmuloub are 10715 // instructions with a big-endian bias, we must reverse the 10716 // element numbering and reverse the meaning of "odd" and "even" 10717 // when generating little endian code. 10718 int Ops[16]; 10719 for (unsigned i = 0; i != 8; ++i) { 10720 if (isLittleEndian) { 10721 Ops[i*2 ] = 2*i; 10722 Ops[i*2+1] = 2*i+16; 10723 } else { 10724 Ops[i*2 ] = 2*i+1; 10725 Ops[i*2+1] = 2*i+1+16; 10726 } 10727 } 10728 if (isLittleEndian) 10729 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10730 else 10731 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10732 } else { 10733 llvm_unreachable("Unknown mul to lower!"); 10734 } 10735 } 10736 10737 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10738 10739 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10740 10741 EVT VT = Op.getValueType(); 10742 assert(VT.isVector() && 10743 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10744 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10745 VT == MVT::v16i8) && 10746 "Unexpected vector element type!"); 10747 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10748 "Current subtarget doesn't support smax v2i64!"); 10749 10750 // For vector abs, it can be lowered to: 10751 // abs x 10752 // ==> 10753 // y = -x 10754 // smax(x, y) 10755 10756 SDLoc dl(Op); 10757 SDValue X = Op.getOperand(0); 10758 SDValue Zero = DAG.getConstant(0, dl, VT); 10759 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10760 10761 // SMAX patch https://reviews.llvm.org/D47332 10762 // hasn't landed yet, so use intrinsic first here. 10763 // TODO: Should use SMAX directly once SMAX patch landed 10764 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10765 if (VT == MVT::v2i64) 10766 BifID = Intrinsic::ppc_altivec_vmaxsd; 10767 else if (VT == MVT::v8i16) 10768 BifID = Intrinsic::ppc_altivec_vmaxsh; 10769 else if (VT == MVT::v16i8) 10770 BifID = Intrinsic::ppc_altivec_vmaxsb; 10771 10772 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10773 } 10774 10775 // Custom lowering for fpext vf32 to v2f64 10776 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10777 10778 assert(Op.getOpcode() == ISD::FP_EXTEND && 10779 "Should only be called for ISD::FP_EXTEND"); 10780 10781 // We only want to custom lower an extend from v2f32 to v2f64. 10782 if (Op.getValueType() != MVT::v2f64 || 10783 Op.getOperand(0).getValueType() != MVT::v2f32) 10784 return SDValue(); 10785 10786 SDLoc dl(Op); 10787 SDValue Op0 = Op.getOperand(0); 10788 10789 switch (Op0.getOpcode()) { 10790 default: 10791 return SDValue(); 10792 case ISD::EXTRACT_SUBVECTOR: { 10793 assert(Op0.getNumOperands() == 2 && 10794 isa<ConstantSDNode>(Op0->getOperand(1)) && 10795 "Node should have 2 operands with second one being a constant!"); 10796 10797 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10798 return SDValue(); 10799 10800 // Custom lower is only done for high or low doubleword. 10801 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10802 if (Idx % 2 != 0) 10803 return SDValue(); 10804 10805 // Since input is v4f32, at this point Idx is either 0 or 2. 10806 // Shift to get the doubleword position we want. 10807 int DWord = Idx >> 1; 10808 10809 // High and low word positions are different on little endian. 10810 if (Subtarget.isLittleEndian()) 10811 DWord ^= 0x1; 10812 10813 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10814 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10815 } 10816 case ISD::FADD: 10817 case ISD::FMUL: 10818 case ISD::FSUB: { 10819 SDValue NewLoad[2]; 10820 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10821 // Ensure both input are loads. 10822 SDValue LdOp = Op0.getOperand(i); 10823 if (LdOp.getOpcode() != ISD::LOAD) 10824 return SDValue(); 10825 // Generate new load node. 10826 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10827 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10828 NewLoad[i] = DAG.getMemIntrinsicNode( 10829 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10830 LD->getMemoryVT(), LD->getMemOperand()); 10831 } 10832 SDValue NewOp = 10833 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10834 NewLoad[1], Op0.getNode()->getFlags()); 10835 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10836 DAG.getConstant(0, dl, MVT::i32)); 10837 } 10838 case ISD::LOAD: { 10839 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10840 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10841 SDValue NewLd = DAG.getMemIntrinsicNode( 10842 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10843 LD->getMemoryVT(), LD->getMemOperand()); 10844 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10845 DAG.getConstant(0, dl, MVT::i32)); 10846 } 10847 } 10848 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10849 } 10850 10851 /// LowerOperation - Provide custom lowering hooks for some operations. 10852 /// 10853 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10854 switch (Op.getOpcode()) { 10855 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10856 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10857 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10858 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10859 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10860 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10861 case ISD::SETCC: return LowerSETCC(Op, DAG); 10862 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10863 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10864 10865 // Variable argument lowering. 10866 case ISD::VASTART: return LowerVASTART(Op, DAG); 10867 case ISD::VAARG: return LowerVAARG(Op, DAG); 10868 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10869 10870 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10871 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10872 case ISD::GET_DYNAMIC_AREA_OFFSET: 10873 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10874 10875 // Exception handling lowering. 10876 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10877 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10878 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10879 10880 case ISD::LOAD: return LowerLOAD(Op, DAG); 10881 case ISD::STORE: return LowerSTORE(Op, DAG); 10882 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10883 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10884 case ISD::FP_TO_UINT: 10885 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10886 case ISD::UINT_TO_FP: 10887 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10888 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10889 10890 // Lower 64-bit shifts. 10891 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10892 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10893 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10894 10895 // Vector-related lowering. 10896 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10897 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10898 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10899 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10900 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10901 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10902 case ISD::MUL: return LowerMUL(Op, DAG); 10903 case ISD::ABS: return LowerABS(Op, DAG); 10904 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10905 10906 // For counter-based loop handling. 10907 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10908 10909 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10910 10911 // Frame & Return address. 10912 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10913 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10914 10915 case ISD::INTRINSIC_VOID: 10916 return LowerINTRINSIC_VOID(Op, DAG); 10917 case ISD::SREM: 10918 case ISD::UREM: 10919 return LowerREM(Op, DAG); 10920 case ISD::BSWAP: 10921 return LowerBSWAP(Op, DAG); 10922 case ISD::ATOMIC_CMP_SWAP: 10923 return LowerATOMIC_CMP_SWAP(Op, DAG); 10924 } 10925 } 10926 10927 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10928 SmallVectorImpl<SDValue>&Results, 10929 SelectionDAG &DAG) const { 10930 SDLoc dl(N); 10931 switch (N->getOpcode()) { 10932 default: 10933 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10934 case ISD::READCYCLECOUNTER: { 10935 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10936 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10937 10938 Results.push_back( 10939 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10940 Results.push_back(RTB.getValue(2)); 10941 break; 10942 } 10943 case ISD::INTRINSIC_W_CHAIN: { 10944 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10945 Intrinsic::loop_decrement) 10946 break; 10947 10948 assert(N->getValueType(0) == MVT::i1 && 10949 "Unexpected result type for CTR decrement intrinsic"); 10950 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10951 N->getValueType(0)); 10952 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10953 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10954 N->getOperand(1)); 10955 10956 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10957 Results.push_back(NewInt.getValue(1)); 10958 break; 10959 } 10960 case ISD::VAARG: { 10961 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10962 return; 10963 10964 EVT VT = N->getValueType(0); 10965 10966 if (VT == MVT::i64) { 10967 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10968 10969 Results.push_back(NewNode); 10970 Results.push_back(NewNode.getValue(1)); 10971 } 10972 return; 10973 } 10974 case ISD::FP_TO_SINT: 10975 case ISD::FP_TO_UINT: 10976 // LowerFP_TO_INT() can only handle f32 and f64. 10977 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10978 return; 10979 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10980 return; 10981 case ISD::TRUNCATE: { 10982 EVT TrgVT = N->getValueType(0); 10983 EVT OpVT = N->getOperand(0).getValueType(); 10984 if (TrgVT.isVector() && 10985 isOperationCustom(N->getOpcode(), TrgVT) && 10986 OpVT.getSizeInBits() <= 128 && 10987 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10988 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10989 return; 10990 } 10991 case ISD::BITCAST: 10992 // Don't handle bitcast here. 10993 return; 10994 } 10995 } 10996 10997 //===----------------------------------------------------------------------===// 10998 // Other Lowering Code 10999 //===----------------------------------------------------------------------===// 11000 11001 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 11002 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11003 Function *Func = Intrinsic::getDeclaration(M, Id); 11004 return Builder.CreateCall(Func, {}); 11005 } 11006 11007 // The mappings for emitLeading/TrailingFence is taken from 11008 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11009 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11010 Instruction *Inst, 11011 AtomicOrdering Ord) const { 11012 if (Ord == AtomicOrdering::SequentiallyConsistent) 11013 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11014 if (isReleaseOrStronger(Ord)) 11015 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11016 return nullptr; 11017 } 11018 11019 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11020 Instruction *Inst, 11021 AtomicOrdering Ord) const { 11022 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11023 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11024 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11025 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11026 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11027 return Builder.CreateCall( 11028 Intrinsic::getDeclaration( 11029 Builder.GetInsertBlock()->getParent()->getParent(), 11030 Intrinsic::ppc_cfence, {Inst->getType()}), 11031 {Inst}); 11032 // FIXME: Can use isync for rmw operation. 11033 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11034 } 11035 return nullptr; 11036 } 11037 11038 MachineBasicBlock * 11039 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11040 unsigned AtomicSize, 11041 unsigned BinOpcode, 11042 unsigned CmpOpcode, 11043 unsigned CmpPred) const { 11044 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11045 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11046 11047 auto LoadMnemonic = PPC::LDARX; 11048 auto StoreMnemonic = PPC::STDCX; 11049 switch (AtomicSize) { 11050 default: 11051 llvm_unreachable("Unexpected size of atomic entity"); 11052 case 1: 11053 LoadMnemonic = PPC::LBARX; 11054 StoreMnemonic = PPC::STBCX; 11055 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11056 break; 11057 case 2: 11058 LoadMnemonic = PPC::LHARX; 11059 StoreMnemonic = PPC::STHCX; 11060 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11061 break; 11062 case 4: 11063 LoadMnemonic = PPC::LWARX; 11064 StoreMnemonic = PPC::STWCX; 11065 break; 11066 case 8: 11067 LoadMnemonic = PPC::LDARX; 11068 StoreMnemonic = PPC::STDCX; 11069 break; 11070 } 11071 11072 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11073 MachineFunction *F = BB->getParent(); 11074 MachineFunction::iterator It = ++BB->getIterator(); 11075 11076 Register dest = MI.getOperand(0).getReg(); 11077 Register ptrA = MI.getOperand(1).getReg(); 11078 Register ptrB = MI.getOperand(2).getReg(); 11079 Register incr = MI.getOperand(3).getReg(); 11080 DebugLoc dl = MI.getDebugLoc(); 11081 11082 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11083 MachineBasicBlock *loop2MBB = 11084 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11085 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11086 F->insert(It, loopMBB); 11087 if (CmpOpcode) 11088 F->insert(It, loop2MBB); 11089 F->insert(It, exitMBB); 11090 exitMBB->splice(exitMBB->begin(), BB, 11091 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11092 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11093 11094 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11095 Register TmpReg = (!BinOpcode) ? incr : 11096 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11097 : &PPC::GPRCRegClass); 11098 11099 // thisMBB: 11100 // ... 11101 // fallthrough --> loopMBB 11102 BB->addSuccessor(loopMBB); 11103 11104 // loopMBB: 11105 // l[wd]arx dest, ptr 11106 // add r0, dest, incr 11107 // st[wd]cx. r0, ptr 11108 // bne- loopMBB 11109 // fallthrough --> exitMBB 11110 11111 // For max/min... 11112 // loopMBB: 11113 // l[wd]arx dest, ptr 11114 // cmpl?[wd] incr, dest 11115 // bgt exitMBB 11116 // loop2MBB: 11117 // st[wd]cx. dest, ptr 11118 // bne- loopMBB 11119 // fallthrough --> exitMBB 11120 11121 BB = loopMBB; 11122 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11123 .addReg(ptrA).addReg(ptrB); 11124 if (BinOpcode) 11125 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11126 if (CmpOpcode) { 11127 // Signed comparisons of byte or halfword values must be sign-extended. 11128 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11129 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11130 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11131 ExtReg).addReg(dest); 11132 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11133 .addReg(incr).addReg(ExtReg); 11134 } else 11135 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11136 .addReg(incr).addReg(dest); 11137 11138 BuildMI(BB, dl, TII->get(PPC::BCC)) 11139 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11140 BB->addSuccessor(loop2MBB); 11141 BB->addSuccessor(exitMBB); 11142 BB = loop2MBB; 11143 } 11144 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11145 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11146 BuildMI(BB, dl, TII->get(PPC::BCC)) 11147 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11148 BB->addSuccessor(loopMBB); 11149 BB->addSuccessor(exitMBB); 11150 11151 // exitMBB: 11152 // ... 11153 BB = exitMBB; 11154 return BB; 11155 } 11156 11157 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11158 MachineInstr &MI, MachineBasicBlock *BB, 11159 bool is8bit, // operation 11160 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11161 // If we support part-word atomic mnemonics, just use them 11162 if (Subtarget.hasPartwordAtomics()) 11163 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11164 CmpPred); 11165 11166 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11167 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11168 // In 64 bit mode we have to use 64 bits for addresses, even though the 11169 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11170 // registers without caring whether they're 32 or 64, but here we're 11171 // doing actual arithmetic on the addresses. 11172 bool is64bit = Subtarget.isPPC64(); 11173 bool isLittleEndian = Subtarget.isLittleEndian(); 11174 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11175 11176 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11177 MachineFunction *F = BB->getParent(); 11178 MachineFunction::iterator It = ++BB->getIterator(); 11179 11180 Register dest = MI.getOperand(0).getReg(); 11181 Register ptrA = MI.getOperand(1).getReg(); 11182 Register ptrB = MI.getOperand(2).getReg(); 11183 Register incr = MI.getOperand(3).getReg(); 11184 DebugLoc dl = MI.getDebugLoc(); 11185 11186 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11187 MachineBasicBlock *loop2MBB = 11188 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11189 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11190 F->insert(It, loopMBB); 11191 if (CmpOpcode) 11192 F->insert(It, loop2MBB); 11193 F->insert(It, exitMBB); 11194 exitMBB->splice(exitMBB->begin(), BB, 11195 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11196 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11197 11198 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11199 const TargetRegisterClass *RC = 11200 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11201 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11202 11203 Register PtrReg = RegInfo.createVirtualRegister(RC); 11204 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11205 Register ShiftReg = 11206 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11207 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11208 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11209 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11210 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11211 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11212 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11213 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11214 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11215 Register Ptr1Reg; 11216 Register TmpReg = 11217 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11218 11219 // thisMBB: 11220 // ... 11221 // fallthrough --> loopMBB 11222 BB->addSuccessor(loopMBB); 11223 11224 // The 4-byte load must be aligned, while a char or short may be 11225 // anywhere in the word. Hence all this nasty bookkeeping code. 11226 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11227 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11228 // xori shift, shift1, 24 [16] 11229 // rlwinm ptr, ptr1, 0, 0, 29 11230 // slw incr2, incr, shift 11231 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11232 // slw mask, mask2, shift 11233 // loopMBB: 11234 // lwarx tmpDest, ptr 11235 // add tmp, tmpDest, incr2 11236 // andc tmp2, tmpDest, mask 11237 // and tmp3, tmp, mask 11238 // or tmp4, tmp3, tmp2 11239 // stwcx. tmp4, ptr 11240 // bne- loopMBB 11241 // fallthrough --> exitMBB 11242 // srw dest, tmpDest, shift 11243 if (ptrA != ZeroReg) { 11244 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11245 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11246 .addReg(ptrA) 11247 .addReg(ptrB); 11248 } else { 11249 Ptr1Reg = ptrB; 11250 } 11251 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11252 // mode. 11253 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11254 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11255 .addImm(3) 11256 .addImm(27) 11257 .addImm(is8bit ? 28 : 27); 11258 if (!isLittleEndian) 11259 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11260 .addReg(Shift1Reg) 11261 .addImm(is8bit ? 24 : 16); 11262 if (is64bit) 11263 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11264 .addReg(Ptr1Reg) 11265 .addImm(0) 11266 .addImm(61); 11267 else 11268 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11269 .addReg(Ptr1Reg) 11270 .addImm(0) 11271 .addImm(0) 11272 .addImm(29); 11273 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11274 if (is8bit) 11275 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11276 else { 11277 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11278 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11279 .addReg(Mask3Reg) 11280 .addImm(65535); 11281 } 11282 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11283 .addReg(Mask2Reg) 11284 .addReg(ShiftReg); 11285 11286 BB = loopMBB; 11287 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11288 .addReg(ZeroReg) 11289 .addReg(PtrReg); 11290 if (BinOpcode) 11291 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11292 .addReg(Incr2Reg) 11293 .addReg(TmpDestReg); 11294 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11295 .addReg(TmpDestReg) 11296 .addReg(MaskReg); 11297 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11298 if (CmpOpcode) { 11299 // For unsigned comparisons, we can directly compare the shifted values. 11300 // For signed comparisons we shift and sign extend. 11301 Register SReg = RegInfo.createVirtualRegister(GPRC); 11302 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11303 .addReg(TmpDestReg) 11304 .addReg(MaskReg); 11305 unsigned ValueReg = SReg; 11306 unsigned CmpReg = Incr2Reg; 11307 if (CmpOpcode == PPC::CMPW) { 11308 ValueReg = RegInfo.createVirtualRegister(GPRC); 11309 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11310 .addReg(SReg) 11311 .addReg(ShiftReg); 11312 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11313 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11314 .addReg(ValueReg); 11315 ValueReg = ValueSReg; 11316 CmpReg = incr; 11317 } 11318 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11319 .addReg(CmpReg) 11320 .addReg(ValueReg); 11321 BuildMI(BB, dl, TII->get(PPC::BCC)) 11322 .addImm(CmpPred) 11323 .addReg(PPC::CR0) 11324 .addMBB(exitMBB); 11325 BB->addSuccessor(loop2MBB); 11326 BB->addSuccessor(exitMBB); 11327 BB = loop2MBB; 11328 } 11329 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11330 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11331 .addReg(Tmp4Reg) 11332 .addReg(ZeroReg) 11333 .addReg(PtrReg); 11334 BuildMI(BB, dl, TII->get(PPC::BCC)) 11335 .addImm(PPC::PRED_NE) 11336 .addReg(PPC::CR0) 11337 .addMBB(loopMBB); 11338 BB->addSuccessor(loopMBB); 11339 BB->addSuccessor(exitMBB); 11340 11341 // exitMBB: 11342 // ... 11343 BB = exitMBB; 11344 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11345 .addReg(TmpDestReg) 11346 .addReg(ShiftReg); 11347 return BB; 11348 } 11349 11350 llvm::MachineBasicBlock * 11351 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11352 MachineBasicBlock *MBB) const { 11353 DebugLoc DL = MI.getDebugLoc(); 11354 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11355 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11356 11357 MachineFunction *MF = MBB->getParent(); 11358 MachineRegisterInfo &MRI = MF->getRegInfo(); 11359 11360 const BasicBlock *BB = MBB->getBasicBlock(); 11361 MachineFunction::iterator I = ++MBB->getIterator(); 11362 11363 Register DstReg = MI.getOperand(0).getReg(); 11364 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11365 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11366 Register mainDstReg = MRI.createVirtualRegister(RC); 11367 Register restoreDstReg = MRI.createVirtualRegister(RC); 11368 11369 MVT PVT = getPointerTy(MF->getDataLayout()); 11370 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11371 "Invalid Pointer Size!"); 11372 // For v = setjmp(buf), we generate 11373 // 11374 // thisMBB: 11375 // SjLjSetup mainMBB 11376 // bl mainMBB 11377 // v_restore = 1 11378 // b sinkMBB 11379 // 11380 // mainMBB: 11381 // buf[LabelOffset] = LR 11382 // v_main = 0 11383 // 11384 // sinkMBB: 11385 // v = phi(main, restore) 11386 // 11387 11388 MachineBasicBlock *thisMBB = MBB; 11389 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11390 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11391 MF->insert(I, mainMBB); 11392 MF->insert(I, sinkMBB); 11393 11394 MachineInstrBuilder MIB; 11395 11396 // Transfer the remainder of BB and its successor edges to sinkMBB. 11397 sinkMBB->splice(sinkMBB->begin(), MBB, 11398 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11399 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11400 11401 // Note that the structure of the jmp_buf used here is not compatible 11402 // with that used by libc, and is not designed to be. Specifically, it 11403 // stores only those 'reserved' registers that LLVM does not otherwise 11404 // understand how to spill. Also, by convention, by the time this 11405 // intrinsic is called, Clang has already stored the frame address in the 11406 // first slot of the buffer and stack address in the third. Following the 11407 // X86 target code, we'll store the jump address in the second slot. We also 11408 // need to save the TOC pointer (R2) to handle jumps between shared 11409 // libraries, and that will be stored in the fourth slot. The thread 11410 // identifier (R13) is not affected. 11411 11412 // thisMBB: 11413 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11414 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11415 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11416 11417 // Prepare IP either in reg. 11418 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11419 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11420 Register BufReg = MI.getOperand(1).getReg(); 11421 11422 if (Subtarget.is64BitELFABI()) { 11423 setUsesTOCBasePtr(*MBB->getParent()); 11424 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11425 .addReg(PPC::X2) 11426 .addImm(TOCOffset) 11427 .addReg(BufReg) 11428 .cloneMemRefs(MI); 11429 } 11430 11431 // Naked functions never have a base pointer, and so we use r1. For all 11432 // other functions, this decision must be delayed until during PEI. 11433 unsigned BaseReg; 11434 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11435 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11436 else 11437 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11438 11439 MIB = BuildMI(*thisMBB, MI, DL, 11440 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11441 .addReg(BaseReg) 11442 .addImm(BPOffset) 11443 .addReg(BufReg) 11444 .cloneMemRefs(MI); 11445 11446 // Setup 11447 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11448 MIB.addRegMask(TRI->getNoPreservedMask()); 11449 11450 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11451 11452 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11453 .addMBB(mainMBB); 11454 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11455 11456 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11457 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11458 11459 // mainMBB: 11460 // mainDstReg = 0 11461 MIB = 11462 BuildMI(mainMBB, DL, 11463 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11464 11465 // Store IP 11466 if (Subtarget.isPPC64()) { 11467 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11468 .addReg(LabelReg) 11469 .addImm(LabelOffset) 11470 .addReg(BufReg); 11471 } else { 11472 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11473 .addReg(LabelReg) 11474 .addImm(LabelOffset) 11475 .addReg(BufReg); 11476 } 11477 MIB.cloneMemRefs(MI); 11478 11479 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11480 mainMBB->addSuccessor(sinkMBB); 11481 11482 // sinkMBB: 11483 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11484 TII->get(PPC::PHI), DstReg) 11485 .addReg(mainDstReg).addMBB(mainMBB) 11486 .addReg(restoreDstReg).addMBB(thisMBB); 11487 11488 MI.eraseFromParent(); 11489 return sinkMBB; 11490 } 11491 11492 MachineBasicBlock * 11493 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11494 MachineBasicBlock *MBB) const { 11495 DebugLoc DL = MI.getDebugLoc(); 11496 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11497 11498 MachineFunction *MF = MBB->getParent(); 11499 MachineRegisterInfo &MRI = MF->getRegInfo(); 11500 11501 MVT PVT = getPointerTy(MF->getDataLayout()); 11502 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11503 "Invalid Pointer Size!"); 11504 11505 const TargetRegisterClass *RC = 11506 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11507 Register Tmp = MRI.createVirtualRegister(RC); 11508 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11509 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11510 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11511 unsigned BP = 11512 (PVT == MVT::i64) 11513 ? PPC::X30 11514 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11515 : PPC::R30); 11516 11517 MachineInstrBuilder MIB; 11518 11519 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11520 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11521 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11522 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11523 11524 Register BufReg = MI.getOperand(0).getReg(); 11525 11526 // Reload FP (the jumped-to function may not have had a 11527 // frame pointer, and if so, then its r31 will be restored 11528 // as necessary). 11529 if (PVT == MVT::i64) { 11530 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11531 .addImm(0) 11532 .addReg(BufReg); 11533 } else { 11534 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11535 .addImm(0) 11536 .addReg(BufReg); 11537 } 11538 MIB.cloneMemRefs(MI); 11539 11540 // Reload IP 11541 if (PVT == MVT::i64) { 11542 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11543 .addImm(LabelOffset) 11544 .addReg(BufReg); 11545 } else { 11546 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11547 .addImm(LabelOffset) 11548 .addReg(BufReg); 11549 } 11550 MIB.cloneMemRefs(MI); 11551 11552 // Reload SP 11553 if (PVT == MVT::i64) { 11554 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11555 .addImm(SPOffset) 11556 .addReg(BufReg); 11557 } else { 11558 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11559 .addImm(SPOffset) 11560 .addReg(BufReg); 11561 } 11562 MIB.cloneMemRefs(MI); 11563 11564 // Reload BP 11565 if (PVT == MVT::i64) { 11566 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11567 .addImm(BPOffset) 11568 .addReg(BufReg); 11569 } else { 11570 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11571 .addImm(BPOffset) 11572 .addReg(BufReg); 11573 } 11574 MIB.cloneMemRefs(MI); 11575 11576 // Reload TOC 11577 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11578 setUsesTOCBasePtr(*MBB->getParent()); 11579 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11580 .addImm(TOCOffset) 11581 .addReg(BufReg) 11582 .cloneMemRefs(MI); 11583 } 11584 11585 // Jump 11586 BuildMI(*MBB, MI, DL, 11587 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11588 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11589 11590 MI.eraseFromParent(); 11591 return MBB; 11592 } 11593 11594 MachineBasicBlock * 11595 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11596 MachineBasicBlock *BB) const { 11597 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11598 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11599 if (Subtarget.is64BitELFABI() && 11600 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11601 !Subtarget.isUsingPCRelativeCalls()) { 11602 // Call lowering should have added an r2 operand to indicate a dependence 11603 // on the TOC base pointer value. It can't however, because there is no 11604 // way to mark the dependence as implicit there, and so the stackmap code 11605 // will confuse it with a regular operand. Instead, add the dependence 11606 // here. 11607 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11608 } 11609 11610 return emitPatchPoint(MI, BB); 11611 } 11612 11613 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11614 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11615 return emitEHSjLjSetJmp(MI, BB); 11616 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11617 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11618 return emitEHSjLjLongJmp(MI, BB); 11619 } 11620 11621 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11622 11623 // To "insert" these instructions we actually have to insert their 11624 // control-flow patterns. 11625 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11626 MachineFunction::iterator It = ++BB->getIterator(); 11627 11628 MachineFunction *F = BB->getParent(); 11629 11630 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11631 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11632 MI.getOpcode() == PPC::SELECT_I8) { 11633 SmallVector<MachineOperand, 2> Cond; 11634 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11635 MI.getOpcode() == PPC::SELECT_CC_I8) 11636 Cond.push_back(MI.getOperand(4)); 11637 else 11638 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11639 Cond.push_back(MI.getOperand(1)); 11640 11641 DebugLoc dl = MI.getDebugLoc(); 11642 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11643 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11644 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11645 MI.getOpcode() == PPC::SELECT_CC_F8 || 11646 MI.getOpcode() == PPC::SELECT_CC_F16 || 11647 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11648 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11649 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11650 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11651 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11652 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11653 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11654 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11655 MI.getOpcode() == PPC::SELECT_CC_SPE || 11656 MI.getOpcode() == PPC::SELECT_F4 || 11657 MI.getOpcode() == PPC::SELECT_F8 || 11658 MI.getOpcode() == PPC::SELECT_F16 || 11659 MI.getOpcode() == PPC::SELECT_QFRC || 11660 MI.getOpcode() == PPC::SELECT_QSRC || 11661 MI.getOpcode() == PPC::SELECT_QBRC || 11662 MI.getOpcode() == PPC::SELECT_SPE || 11663 MI.getOpcode() == PPC::SELECT_SPE4 || 11664 MI.getOpcode() == PPC::SELECT_VRRC || 11665 MI.getOpcode() == PPC::SELECT_VSFRC || 11666 MI.getOpcode() == PPC::SELECT_VSSRC || 11667 MI.getOpcode() == PPC::SELECT_VSRC) { 11668 // The incoming instruction knows the destination vreg to set, the 11669 // condition code register to branch on, the true/false values to 11670 // select between, and a branch opcode to use. 11671 11672 // thisMBB: 11673 // ... 11674 // TrueVal = ... 11675 // cmpTY ccX, r1, r2 11676 // bCC copy1MBB 11677 // fallthrough --> copy0MBB 11678 MachineBasicBlock *thisMBB = BB; 11679 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11680 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11681 DebugLoc dl = MI.getDebugLoc(); 11682 F->insert(It, copy0MBB); 11683 F->insert(It, sinkMBB); 11684 11685 // Transfer the remainder of BB and its successor edges to sinkMBB. 11686 sinkMBB->splice(sinkMBB->begin(), BB, 11687 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11688 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11689 11690 // Next, add the true and fallthrough blocks as its successors. 11691 BB->addSuccessor(copy0MBB); 11692 BB->addSuccessor(sinkMBB); 11693 11694 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11695 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11696 MI.getOpcode() == PPC::SELECT_F16 || 11697 MI.getOpcode() == PPC::SELECT_SPE4 || 11698 MI.getOpcode() == PPC::SELECT_SPE || 11699 MI.getOpcode() == PPC::SELECT_QFRC || 11700 MI.getOpcode() == PPC::SELECT_QSRC || 11701 MI.getOpcode() == PPC::SELECT_QBRC || 11702 MI.getOpcode() == PPC::SELECT_VRRC || 11703 MI.getOpcode() == PPC::SELECT_VSFRC || 11704 MI.getOpcode() == PPC::SELECT_VSSRC || 11705 MI.getOpcode() == PPC::SELECT_VSRC) { 11706 BuildMI(BB, dl, TII->get(PPC::BC)) 11707 .addReg(MI.getOperand(1).getReg()) 11708 .addMBB(sinkMBB); 11709 } else { 11710 unsigned SelectPred = MI.getOperand(4).getImm(); 11711 BuildMI(BB, dl, TII->get(PPC::BCC)) 11712 .addImm(SelectPred) 11713 .addReg(MI.getOperand(1).getReg()) 11714 .addMBB(sinkMBB); 11715 } 11716 11717 // copy0MBB: 11718 // %FalseValue = ... 11719 // # fallthrough to sinkMBB 11720 BB = copy0MBB; 11721 11722 // Update machine-CFG edges 11723 BB->addSuccessor(sinkMBB); 11724 11725 // sinkMBB: 11726 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11727 // ... 11728 BB = sinkMBB; 11729 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11730 .addReg(MI.getOperand(3).getReg()) 11731 .addMBB(copy0MBB) 11732 .addReg(MI.getOperand(2).getReg()) 11733 .addMBB(thisMBB); 11734 } else if (MI.getOpcode() == PPC::ReadTB) { 11735 // To read the 64-bit time-base register on a 32-bit target, we read the 11736 // two halves. Should the counter have wrapped while it was being read, we 11737 // need to try again. 11738 // ... 11739 // readLoop: 11740 // mfspr Rx,TBU # load from TBU 11741 // mfspr Ry,TB # load from TB 11742 // mfspr Rz,TBU # load from TBU 11743 // cmpw crX,Rx,Rz # check if 'old'='new' 11744 // bne readLoop # branch if they're not equal 11745 // ... 11746 11747 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11748 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11749 DebugLoc dl = MI.getDebugLoc(); 11750 F->insert(It, readMBB); 11751 F->insert(It, sinkMBB); 11752 11753 // Transfer the remainder of BB and its successor edges to sinkMBB. 11754 sinkMBB->splice(sinkMBB->begin(), BB, 11755 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11756 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11757 11758 BB->addSuccessor(readMBB); 11759 BB = readMBB; 11760 11761 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11762 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11763 Register LoReg = MI.getOperand(0).getReg(); 11764 Register HiReg = MI.getOperand(1).getReg(); 11765 11766 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11767 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11768 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11769 11770 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11771 11772 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11773 .addReg(HiReg) 11774 .addReg(ReadAgainReg); 11775 BuildMI(BB, dl, TII->get(PPC::BCC)) 11776 .addImm(PPC::PRED_NE) 11777 .addReg(CmpReg) 11778 .addMBB(readMBB); 11779 11780 BB->addSuccessor(readMBB); 11781 BB->addSuccessor(sinkMBB); 11782 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11783 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11784 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11785 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11786 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11787 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11788 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11789 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11790 11791 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11792 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11793 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11794 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11795 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11796 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11797 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11798 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11799 11800 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11801 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11802 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11803 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11804 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11805 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11806 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11807 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11808 11809 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11810 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11811 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11812 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11813 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11814 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11815 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11816 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11817 11818 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11819 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11820 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11821 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11822 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11823 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11824 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11825 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11826 11827 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11828 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11829 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11830 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11831 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11832 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11833 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11834 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11835 11836 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11837 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11838 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11839 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11840 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11841 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11842 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11843 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11844 11845 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11846 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11847 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11848 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11849 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11850 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11851 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11852 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11853 11854 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11855 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11856 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11857 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11858 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11859 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11860 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11861 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11862 11863 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11864 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11865 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11866 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11867 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11868 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11869 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11870 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11871 11872 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11873 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11874 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11875 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11876 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11877 BB = EmitAtomicBinary(MI, BB, 4, 0); 11878 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11879 BB = EmitAtomicBinary(MI, BB, 8, 0); 11880 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11881 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11882 (Subtarget.hasPartwordAtomics() && 11883 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11884 (Subtarget.hasPartwordAtomics() && 11885 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11886 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11887 11888 auto LoadMnemonic = PPC::LDARX; 11889 auto StoreMnemonic = PPC::STDCX; 11890 switch (MI.getOpcode()) { 11891 default: 11892 llvm_unreachable("Compare and swap of unknown size"); 11893 case PPC::ATOMIC_CMP_SWAP_I8: 11894 LoadMnemonic = PPC::LBARX; 11895 StoreMnemonic = PPC::STBCX; 11896 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11897 break; 11898 case PPC::ATOMIC_CMP_SWAP_I16: 11899 LoadMnemonic = PPC::LHARX; 11900 StoreMnemonic = PPC::STHCX; 11901 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11902 break; 11903 case PPC::ATOMIC_CMP_SWAP_I32: 11904 LoadMnemonic = PPC::LWARX; 11905 StoreMnemonic = PPC::STWCX; 11906 break; 11907 case PPC::ATOMIC_CMP_SWAP_I64: 11908 LoadMnemonic = PPC::LDARX; 11909 StoreMnemonic = PPC::STDCX; 11910 break; 11911 } 11912 Register dest = MI.getOperand(0).getReg(); 11913 Register ptrA = MI.getOperand(1).getReg(); 11914 Register ptrB = MI.getOperand(2).getReg(); 11915 Register oldval = MI.getOperand(3).getReg(); 11916 Register newval = MI.getOperand(4).getReg(); 11917 DebugLoc dl = MI.getDebugLoc(); 11918 11919 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11920 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11921 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11922 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11923 F->insert(It, loop1MBB); 11924 F->insert(It, loop2MBB); 11925 F->insert(It, midMBB); 11926 F->insert(It, exitMBB); 11927 exitMBB->splice(exitMBB->begin(), BB, 11928 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11929 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11930 11931 // thisMBB: 11932 // ... 11933 // fallthrough --> loopMBB 11934 BB->addSuccessor(loop1MBB); 11935 11936 // loop1MBB: 11937 // l[bhwd]arx dest, ptr 11938 // cmp[wd] dest, oldval 11939 // bne- midMBB 11940 // loop2MBB: 11941 // st[bhwd]cx. newval, ptr 11942 // bne- loopMBB 11943 // b exitBB 11944 // midMBB: 11945 // st[bhwd]cx. dest, ptr 11946 // exitBB: 11947 BB = loop1MBB; 11948 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11949 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11950 .addReg(oldval) 11951 .addReg(dest); 11952 BuildMI(BB, dl, TII->get(PPC::BCC)) 11953 .addImm(PPC::PRED_NE) 11954 .addReg(PPC::CR0) 11955 .addMBB(midMBB); 11956 BB->addSuccessor(loop2MBB); 11957 BB->addSuccessor(midMBB); 11958 11959 BB = loop2MBB; 11960 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11961 .addReg(newval) 11962 .addReg(ptrA) 11963 .addReg(ptrB); 11964 BuildMI(BB, dl, TII->get(PPC::BCC)) 11965 .addImm(PPC::PRED_NE) 11966 .addReg(PPC::CR0) 11967 .addMBB(loop1MBB); 11968 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11969 BB->addSuccessor(loop1MBB); 11970 BB->addSuccessor(exitMBB); 11971 11972 BB = midMBB; 11973 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11974 .addReg(dest) 11975 .addReg(ptrA) 11976 .addReg(ptrB); 11977 BB->addSuccessor(exitMBB); 11978 11979 // exitMBB: 11980 // ... 11981 BB = exitMBB; 11982 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11983 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11984 // We must use 64-bit registers for addresses when targeting 64-bit, 11985 // since we're actually doing arithmetic on them. Other registers 11986 // can be 32-bit. 11987 bool is64bit = Subtarget.isPPC64(); 11988 bool isLittleEndian = Subtarget.isLittleEndian(); 11989 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11990 11991 Register dest = MI.getOperand(0).getReg(); 11992 Register ptrA = MI.getOperand(1).getReg(); 11993 Register ptrB = MI.getOperand(2).getReg(); 11994 Register oldval = MI.getOperand(3).getReg(); 11995 Register newval = MI.getOperand(4).getReg(); 11996 DebugLoc dl = MI.getDebugLoc(); 11997 11998 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11999 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12000 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12001 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12002 F->insert(It, loop1MBB); 12003 F->insert(It, loop2MBB); 12004 F->insert(It, midMBB); 12005 F->insert(It, exitMBB); 12006 exitMBB->splice(exitMBB->begin(), BB, 12007 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12008 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12009 12010 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12011 const TargetRegisterClass *RC = 12012 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12013 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12014 12015 Register PtrReg = RegInfo.createVirtualRegister(RC); 12016 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12017 Register ShiftReg = 12018 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12019 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12020 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12021 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12022 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12023 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12024 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12025 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12026 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12027 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12028 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12029 Register Ptr1Reg; 12030 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12031 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12032 // thisMBB: 12033 // ... 12034 // fallthrough --> loopMBB 12035 BB->addSuccessor(loop1MBB); 12036 12037 // The 4-byte load must be aligned, while a char or short may be 12038 // anywhere in the word. Hence all this nasty bookkeeping code. 12039 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12040 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12041 // xori shift, shift1, 24 [16] 12042 // rlwinm ptr, ptr1, 0, 0, 29 12043 // slw newval2, newval, shift 12044 // slw oldval2, oldval,shift 12045 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12046 // slw mask, mask2, shift 12047 // and newval3, newval2, mask 12048 // and oldval3, oldval2, mask 12049 // loop1MBB: 12050 // lwarx tmpDest, ptr 12051 // and tmp, tmpDest, mask 12052 // cmpw tmp, oldval3 12053 // bne- midMBB 12054 // loop2MBB: 12055 // andc tmp2, tmpDest, mask 12056 // or tmp4, tmp2, newval3 12057 // stwcx. tmp4, ptr 12058 // bne- loop1MBB 12059 // b exitBB 12060 // midMBB: 12061 // stwcx. tmpDest, ptr 12062 // exitBB: 12063 // srw dest, tmpDest, shift 12064 if (ptrA != ZeroReg) { 12065 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12066 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12067 .addReg(ptrA) 12068 .addReg(ptrB); 12069 } else { 12070 Ptr1Reg = ptrB; 12071 } 12072 12073 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12074 // mode. 12075 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12076 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12077 .addImm(3) 12078 .addImm(27) 12079 .addImm(is8bit ? 28 : 27); 12080 if (!isLittleEndian) 12081 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12082 .addReg(Shift1Reg) 12083 .addImm(is8bit ? 24 : 16); 12084 if (is64bit) 12085 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12086 .addReg(Ptr1Reg) 12087 .addImm(0) 12088 .addImm(61); 12089 else 12090 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12091 .addReg(Ptr1Reg) 12092 .addImm(0) 12093 .addImm(0) 12094 .addImm(29); 12095 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12096 .addReg(newval) 12097 .addReg(ShiftReg); 12098 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12099 .addReg(oldval) 12100 .addReg(ShiftReg); 12101 if (is8bit) 12102 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12103 else { 12104 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12105 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12106 .addReg(Mask3Reg) 12107 .addImm(65535); 12108 } 12109 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12110 .addReg(Mask2Reg) 12111 .addReg(ShiftReg); 12112 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12113 .addReg(NewVal2Reg) 12114 .addReg(MaskReg); 12115 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12116 .addReg(OldVal2Reg) 12117 .addReg(MaskReg); 12118 12119 BB = loop1MBB; 12120 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12121 .addReg(ZeroReg) 12122 .addReg(PtrReg); 12123 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12124 .addReg(TmpDestReg) 12125 .addReg(MaskReg); 12126 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12127 .addReg(TmpReg) 12128 .addReg(OldVal3Reg); 12129 BuildMI(BB, dl, TII->get(PPC::BCC)) 12130 .addImm(PPC::PRED_NE) 12131 .addReg(PPC::CR0) 12132 .addMBB(midMBB); 12133 BB->addSuccessor(loop2MBB); 12134 BB->addSuccessor(midMBB); 12135 12136 BB = loop2MBB; 12137 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12138 .addReg(TmpDestReg) 12139 .addReg(MaskReg); 12140 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12141 .addReg(Tmp2Reg) 12142 .addReg(NewVal3Reg); 12143 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12144 .addReg(Tmp4Reg) 12145 .addReg(ZeroReg) 12146 .addReg(PtrReg); 12147 BuildMI(BB, dl, TII->get(PPC::BCC)) 12148 .addImm(PPC::PRED_NE) 12149 .addReg(PPC::CR0) 12150 .addMBB(loop1MBB); 12151 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12152 BB->addSuccessor(loop1MBB); 12153 BB->addSuccessor(exitMBB); 12154 12155 BB = midMBB; 12156 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12157 .addReg(TmpDestReg) 12158 .addReg(ZeroReg) 12159 .addReg(PtrReg); 12160 BB->addSuccessor(exitMBB); 12161 12162 // exitMBB: 12163 // ... 12164 BB = exitMBB; 12165 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12166 .addReg(TmpReg) 12167 .addReg(ShiftReg); 12168 } else if (MI.getOpcode() == PPC::FADDrtz) { 12169 // This pseudo performs an FADD with rounding mode temporarily forced 12170 // to round-to-zero. We emit this via custom inserter since the FPSCR 12171 // is not modeled at the SelectionDAG level. 12172 Register Dest = MI.getOperand(0).getReg(); 12173 Register Src1 = MI.getOperand(1).getReg(); 12174 Register Src2 = MI.getOperand(2).getReg(); 12175 DebugLoc dl = MI.getDebugLoc(); 12176 12177 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12178 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12179 12180 // Save FPSCR value. 12181 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12182 12183 // Set rounding mode to round-to-zero. 12184 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 12185 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 12186 12187 // Perform addition. 12188 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 12189 12190 // Restore FPSCR value. 12191 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12192 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12193 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12194 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12195 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12196 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12197 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12198 ? PPC::ANDI8_rec 12199 : PPC::ANDI_rec; 12200 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12201 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12202 12203 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12204 Register Dest = RegInfo.createVirtualRegister( 12205 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12206 12207 DebugLoc Dl = MI.getDebugLoc(); 12208 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12209 .addReg(MI.getOperand(1).getReg()) 12210 .addImm(1); 12211 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12212 MI.getOperand(0).getReg()) 12213 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12214 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12215 DebugLoc Dl = MI.getDebugLoc(); 12216 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12217 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12218 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12219 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12220 MI.getOperand(0).getReg()) 12221 .addReg(CRReg); 12222 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12223 DebugLoc Dl = MI.getDebugLoc(); 12224 unsigned Imm = MI.getOperand(1).getImm(); 12225 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12226 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12227 MI.getOperand(0).getReg()) 12228 .addReg(PPC::CR0EQ); 12229 } else if (MI.getOpcode() == PPC::SETRNDi) { 12230 DebugLoc dl = MI.getDebugLoc(); 12231 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12232 12233 // Save FPSCR value. 12234 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12235 12236 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12237 // the following settings: 12238 // 00 Round to nearest 12239 // 01 Round to 0 12240 // 10 Round to +inf 12241 // 11 Round to -inf 12242 12243 // When the operand is immediate, using the two least significant bits of 12244 // the immediate to set the bits 62:63 of FPSCR. 12245 unsigned Mode = MI.getOperand(1).getImm(); 12246 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12247 .addImm(31); 12248 12249 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12250 .addImm(30); 12251 } else if (MI.getOpcode() == PPC::SETRND) { 12252 DebugLoc dl = MI.getDebugLoc(); 12253 12254 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12255 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12256 // If the target doesn't have DirectMove, we should use stack to do the 12257 // conversion, because the target doesn't have the instructions like mtvsrd 12258 // or mfvsrd to do this conversion directly. 12259 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12260 if (Subtarget.hasDirectMove()) { 12261 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12262 .addReg(SrcReg); 12263 } else { 12264 // Use stack to do the register copy. 12265 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12266 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12267 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12268 if (RC == &PPC::F8RCRegClass) { 12269 // Copy register from F8RCRegClass to G8RCRegclass. 12270 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12271 "Unsupported RegClass."); 12272 12273 StoreOp = PPC::STFD; 12274 LoadOp = PPC::LD; 12275 } else { 12276 // Copy register from G8RCRegClass to F8RCRegclass. 12277 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12278 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12279 "Unsupported RegClass."); 12280 } 12281 12282 MachineFrameInfo &MFI = F->getFrameInfo(); 12283 int FrameIdx = MFI.CreateStackObject(8, 8, false); 12284 12285 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12286 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12287 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12288 MFI.getObjectAlign(FrameIdx)); 12289 12290 // Store the SrcReg into the stack. 12291 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12292 .addReg(SrcReg) 12293 .addImm(0) 12294 .addFrameIndex(FrameIdx) 12295 .addMemOperand(MMOStore); 12296 12297 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12298 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12299 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12300 MFI.getObjectAlign(FrameIdx)); 12301 12302 // Load from the stack where SrcReg is stored, and save to DestReg, 12303 // so we have done the RegClass conversion from RegClass::SrcReg to 12304 // RegClass::DestReg. 12305 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12306 .addImm(0) 12307 .addFrameIndex(FrameIdx) 12308 .addMemOperand(MMOLoad); 12309 } 12310 }; 12311 12312 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12313 12314 // Save FPSCR value. 12315 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12316 12317 // When the operand is gprc register, use two least significant bits of the 12318 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12319 // 12320 // copy OldFPSCRTmpReg, OldFPSCRReg 12321 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12322 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12323 // copy NewFPSCRReg, NewFPSCRTmpReg 12324 // mtfsf 255, NewFPSCRReg 12325 MachineOperand SrcOp = MI.getOperand(1); 12326 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12327 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12328 12329 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12330 12331 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12332 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12333 12334 // The first operand of INSERT_SUBREG should be a register which has 12335 // subregisters, we only care about its RegClass, so we should use an 12336 // IMPLICIT_DEF register. 12337 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12338 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12339 .addReg(ImDefReg) 12340 .add(SrcOp) 12341 .addImm(1); 12342 12343 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12344 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12345 .addReg(OldFPSCRTmpReg) 12346 .addReg(ExtSrcReg) 12347 .addImm(0) 12348 .addImm(62); 12349 12350 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12351 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12352 12353 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12354 // bits of FPSCR. 12355 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12356 .addImm(255) 12357 .addReg(NewFPSCRReg) 12358 .addImm(0) 12359 .addImm(0); 12360 } else { 12361 llvm_unreachable("Unexpected instr type to insert"); 12362 } 12363 12364 MI.eraseFromParent(); // The pseudo instruction is gone now. 12365 return BB; 12366 } 12367 12368 //===----------------------------------------------------------------------===// 12369 // Target Optimization Hooks 12370 //===----------------------------------------------------------------------===// 12371 12372 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12373 // For the estimates, convergence is quadratic, so we essentially double the 12374 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12375 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12376 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12377 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12378 if (VT.getScalarType() == MVT::f64) 12379 RefinementSteps++; 12380 return RefinementSteps; 12381 } 12382 12383 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12384 int Enabled, int &RefinementSteps, 12385 bool &UseOneConstNR, 12386 bool Reciprocal) const { 12387 EVT VT = Operand.getValueType(); 12388 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12389 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12390 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12391 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12392 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12393 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12394 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12395 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12396 12397 // The Newton-Raphson computation with a single constant does not provide 12398 // enough accuracy on some CPUs. 12399 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12400 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12401 } 12402 return SDValue(); 12403 } 12404 12405 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12406 int Enabled, 12407 int &RefinementSteps) const { 12408 EVT VT = Operand.getValueType(); 12409 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12410 (VT == MVT::f64 && Subtarget.hasFRE()) || 12411 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12412 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12413 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12414 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12415 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12416 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12417 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12418 } 12419 return SDValue(); 12420 } 12421 12422 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12423 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12424 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12425 // enabled for division), this functionality is redundant with the default 12426 // combiner logic (once the division -> reciprocal/multiply transformation 12427 // has taken place). As a result, this matters more for older cores than for 12428 // newer ones. 12429 12430 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12431 // reciprocal if there are two or more FDIVs (for embedded cores with only 12432 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12433 switch (Subtarget.getCPUDirective()) { 12434 default: 12435 return 3; 12436 case PPC::DIR_440: 12437 case PPC::DIR_A2: 12438 case PPC::DIR_E500: 12439 case PPC::DIR_E500mc: 12440 case PPC::DIR_E5500: 12441 return 2; 12442 } 12443 } 12444 12445 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12446 // collapsed, and so we need to look through chains of them. 12447 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12448 int64_t& Offset, SelectionDAG &DAG) { 12449 if (DAG.isBaseWithConstantOffset(Loc)) { 12450 Base = Loc.getOperand(0); 12451 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12452 12453 // The base might itself be a base plus an offset, and if so, accumulate 12454 // that as well. 12455 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12456 } 12457 } 12458 12459 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12460 unsigned Bytes, int Dist, 12461 SelectionDAG &DAG) { 12462 if (VT.getSizeInBits() / 8 != Bytes) 12463 return false; 12464 12465 SDValue BaseLoc = Base->getBasePtr(); 12466 if (Loc.getOpcode() == ISD::FrameIndex) { 12467 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12468 return false; 12469 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12470 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12471 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12472 int FS = MFI.getObjectSize(FI); 12473 int BFS = MFI.getObjectSize(BFI); 12474 if (FS != BFS || FS != (int)Bytes) return false; 12475 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12476 } 12477 12478 SDValue Base1 = Loc, Base2 = BaseLoc; 12479 int64_t Offset1 = 0, Offset2 = 0; 12480 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12481 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12482 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12483 return true; 12484 12485 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12486 const GlobalValue *GV1 = nullptr; 12487 const GlobalValue *GV2 = nullptr; 12488 Offset1 = 0; 12489 Offset2 = 0; 12490 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12491 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12492 if (isGA1 && isGA2 && GV1 == GV2) 12493 return Offset1 == (Offset2 + Dist*Bytes); 12494 return false; 12495 } 12496 12497 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12498 // not enforce equality of the chain operands. 12499 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12500 unsigned Bytes, int Dist, 12501 SelectionDAG &DAG) { 12502 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12503 EVT VT = LS->getMemoryVT(); 12504 SDValue Loc = LS->getBasePtr(); 12505 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12506 } 12507 12508 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12509 EVT VT; 12510 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12511 default: return false; 12512 case Intrinsic::ppc_qpx_qvlfd: 12513 case Intrinsic::ppc_qpx_qvlfda: 12514 VT = MVT::v4f64; 12515 break; 12516 case Intrinsic::ppc_qpx_qvlfs: 12517 case Intrinsic::ppc_qpx_qvlfsa: 12518 VT = MVT::v4f32; 12519 break; 12520 case Intrinsic::ppc_qpx_qvlfcd: 12521 case Intrinsic::ppc_qpx_qvlfcda: 12522 VT = MVT::v2f64; 12523 break; 12524 case Intrinsic::ppc_qpx_qvlfcs: 12525 case Intrinsic::ppc_qpx_qvlfcsa: 12526 VT = MVT::v2f32; 12527 break; 12528 case Intrinsic::ppc_qpx_qvlfiwa: 12529 case Intrinsic::ppc_qpx_qvlfiwz: 12530 case Intrinsic::ppc_altivec_lvx: 12531 case Intrinsic::ppc_altivec_lvxl: 12532 case Intrinsic::ppc_vsx_lxvw4x: 12533 case Intrinsic::ppc_vsx_lxvw4x_be: 12534 VT = MVT::v4i32; 12535 break; 12536 case Intrinsic::ppc_vsx_lxvd2x: 12537 case Intrinsic::ppc_vsx_lxvd2x_be: 12538 VT = MVT::v2f64; 12539 break; 12540 case Intrinsic::ppc_altivec_lvebx: 12541 VT = MVT::i8; 12542 break; 12543 case Intrinsic::ppc_altivec_lvehx: 12544 VT = MVT::i16; 12545 break; 12546 case Intrinsic::ppc_altivec_lvewx: 12547 VT = MVT::i32; 12548 break; 12549 } 12550 12551 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12552 } 12553 12554 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12555 EVT VT; 12556 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12557 default: return false; 12558 case Intrinsic::ppc_qpx_qvstfd: 12559 case Intrinsic::ppc_qpx_qvstfda: 12560 VT = MVT::v4f64; 12561 break; 12562 case Intrinsic::ppc_qpx_qvstfs: 12563 case Intrinsic::ppc_qpx_qvstfsa: 12564 VT = MVT::v4f32; 12565 break; 12566 case Intrinsic::ppc_qpx_qvstfcd: 12567 case Intrinsic::ppc_qpx_qvstfcda: 12568 VT = MVT::v2f64; 12569 break; 12570 case Intrinsic::ppc_qpx_qvstfcs: 12571 case Intrinsic::ppc_qpx_qvstfcsa: 12572 VT = MVT::v2f32; 12573 break; 12574 case Intrinsic::ppc_qpx_qvstfiw: 12575 case Intrinsic::ppc_qpx_qvstfiwa: 12576 case Intrinsic::ppc_altivec_stvx: 12577 case Intrinsic::ppc_altivec_stvxl: 12578 case Intrinsic::ppc_vsx_stxvw4x: 12579 VT = MVT::v4i32; 12580 break; 12581 case Intrinsic::ppc_vsx_stxvd2x: 12582 VT = MVT::v2f64; 12583 break; 12584 case Intrinsic::ppc_vsx_stxvw4x_be: 12585 VT = MVT::v4i32; 12586 break; 12587 case Intrinsic::ppc_vsx_stxvd2x_be: 12588 VT = MVT::v2f64; 12589 break; 12590 case Intrinsic::ppc_altivec_stvebx: 12591 VT = MVT::i8; 12592 break; 12593 case Intrinsic::ppc_altivec_stvehx: 12594 VT = MVT::i16; 12595 break; 12596 case Intrinsic::ppc_altivec_stvewx: 12597 VT = MVT::i32; 12598 break; 12599 } 12600 12601 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12602 } 12603 12604 return false; 12605 } 12606 12607 // Return true is there is a nearyby consecutive load to the one provided 12608 // (regardless of alignment). We search up and down the chain, looking though 12609 // token factors and other loads (but nothing else). As a result, a true result 12610 // indicates that it is safe to create a new consecutive load adjacent to the 12611 // load provided. 12612 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12613 SDValue Chain = LD->getChain(); 12614 EVT VT = LD->getMemoryVT(); 12615 12616 SmallSet<SDNode *, 16> LoadRoots; 12617 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12618 SmallSet<SDNode *, 16> Visited; 12619 12620 // First, search up the chain, branching to follow all token-factor operands. 12621 // If we find a consecutive load, then we're done, otherwise, record all 12622 // nodes just above the top-level loads and token factors. 12623 while (!Queue.empty()) { 12624 SDNode *ChainNext = Queue.pop_back_val(); 12625 if (!Visited.insert(ChainNext).second) 12626 continue; 12627 12628 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12629 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12630 return true; 12631 12632 if (!Visited.count(ChainLD->getChain().getNode())) 12633 Queue.push_back(ChainLD->getChain().getNode()); 12634 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12635 for (const SDUse &O : ChainNext->ops()) 12636 if (!Visited.count(O.getNode())) 12637 Queue.push_back(O.getNode()); 12638 } else 12639 LoadRoots.insert(ChainNext); 12640 } 12641 12642 // Second, search down the chain, starting from the top-level nodes recorded 12643 // in the first phase. These top-level nodes are the nodes just above all 12644 // loads and token factors. Starting with their uses, recursively look though 12645 // all loads (just the chain uses) and token factors to find a consecutive 12646 // load. 12647 Visited.clear(); 12648 Queue.clear(); 12649 12650 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12651 IE = LoadRoots.end(); I != IE; ++I) { 12652 Queue.push_back(*I); 12653 12654 while (!Queue.empty()) { 12655 SDNode *LoadRoot = Queue.pop_back_val(); 12656 if (!Visited.insert(LoadRoot).second) 12657 continue; 12658 12659 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12660 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12661 return true; 12662 12663 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12664 UE = LoadRoot->use_end(); UI != UE; ++UI) 12665 if (((isa<MemSDNode>(*UI) && 12666 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12667 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12668 Queue.push_back(*UI); 12669 } 12670 } 12671 12672 return false; 12673 } 12674 12675 /// This function is called when we have proved that a SETCC node can be replaced 12676 /// by subtraction (and other supporting instructions) so that the result of 12677 /// comparison is kept in a GPR instead of CR. This function is purely for 12678 /// codegen purposes and has some flags to guide the codegen process. 12679 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12680 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12681 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12682 12683 // Zero extend the operands to the largest legal integer. Originally, they 12684 // must be of a strictly smaller size. 12685 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12686 DAG.getConstant(Size, DL, MVT::i32)); 12687 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12688 DAG.getConstant(Size, DL, MVT::i32)); 12689 12690 // Swap if needed. Depends on the condition code. 12691 if (Swap) 12692 std::swap(Op0, Op1); 12693 12694 // Subtract extended integers. 12695 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12696 12697 // Move the sign bit to the least significant position and zero out the rest. 12698 // Now the least significant bit carries the result of original comparison. 12699 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12700 DAG.getConstant(Size - 1, DL, MVT::i32)); 12701 auto Final = Shifted; 12702 12703 // Complement the result if needed. Based on the condition code. 12704 if (Complement) 12705 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12706 DAG.getConstant(1, DL, MVT::i64)); 12707 12708 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12709 } 12710 12711 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12712 DAGCombinerInfo &DCI) const { 12713 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12714 12715 SelectionDAG &DAG = DCI.DAG; 12716 SDLoc DL(N); 12717 12718 // Size of integers being compared has a critical role in the following 12719 // analysis, so we prefer to do this when all types are legal. 12720 if (!DCI.isAfterLegalizeDAG()) 12721 return SDValue(); 12722 12723 // If all users of SETCC extend its value to a legal integer type 12724 // then we replace SETCC with a subtraction 12725 for (SDNode::use_iterator UI = N->use_begin(), 12726 UE = N->use_end(); UI != UE; ++UI) { 12727 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12728 return SDValue(); 12729 } 12730 12731 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12732 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12733 12734 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12735 12736 if (OpSize < Size) { 12737 switch (CC) { 12738 default: break; 12739 case ISD::SETULT: 12740 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12741 case ISD::SETULE: 12742 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12743 case ISD::SETUGT: 12744 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12745 case ISD::SETUGE: 12746 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12747 } 12748 } 12749 12750 return SDValue(); 12751 } 12752 12753 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12754 DAGCombinerInfo &DCI) const { 12755 SelectionDAG &DAG = DCI.DAG; 12756 SDLoc dl(N); 12757 12758 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12759 // If we're tracking CR bits, we need to be careful that we don't have: 12760 // trunc(binary-ops(zext(x), zext(y))) 12761 // or 12762 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12763 // such that we're unnecessarily moving things into GPRs when it would be 12764 // better to keep them in CR bits. 12765 12766 // Note that trunc here can be an actual i1 trunc, or can be the effective 12767 // truncation that comes from a setcc or select_cc. 12768 if (N->getOpcode() == ISD::TRUNCATE && 12769 N->getValueType(0) != MVT::i1) 12770 return SDValue(); 12771 12772 if (N->getOperand(0).getValueType() != MVT::i32 && 12773 N->getOperand(0).getValueType() != MVT::i64) 12774 return SDValue(); 12775 12776 if (N->getOpcode() == ISD::SETCC || 12777 N->getOpcode() == ISD::SELECT_CC) { 12778 // If we're looking at a comparison, then we need to make sure that the 12779 // high bits (all except for the first) don't matter the result. 12780 ISD::CondCode CC = 12781 cast<CondCodeSDNode>(N->getOperand( 12782 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12783 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12784 12785 if (ISD::isSignedIntSetCC(CC)) { 12786 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12787 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12788 return SDValue(); 12789 } else if (ISD::isUnsignedIntSetCC(CC)) { 12790 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12791 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12792 !DAG.MaskedValueIsZero(N->getOperand(1), 12793 APInt::getHighBitsSet(OpBits, OpBits-1))) 12794 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12795 : SDValue()); 12796 } else { 12797 // This is neither a signed nor an unsigned comparison, just make sure 12798 // that the high bits are equal. 12799 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12800 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12801 12802 // We don't really care about what is known about the first bit (if 12803 // anything), so clear it in all masks prior to comparing them. 12804 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12805 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12806 12807 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12808 return SDValue(); 12809 } 12810 } 12811 12812 // We now know that the higher-order bits are irrelevant, we just need to 12813 // make sure that all of the intermediate operations are bit operations, and 12814 // all inputs are extensions. 12815 if (N->getOperand(0).getOpcode() != ISD::AND && 12816 N->getOperand(0).getOpcode() != ISD::OR && 12817 N->getOperand(0).getOpcode() != ISD::XOR && 12818 N->getOperand(0).getOpcode() != ISD::SELECT && 12819 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12820 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12821 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12822 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12823 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12824 return SDValue(); 12825 12826 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12827 N->getOperand(1).getOpcode() != ISD::AND && 12828 N->getOperand(1).getOpcode() != ISD::OR && 12829 N->getOperand(1).getOpcode() != ISD::XOR && 12830 N->getOperand(1).getOpcode() != ISD::SELECT && 12831 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12832 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12833 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12834 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12835 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12836 return SDValue(); 12837 12838 SmallVector<SDValue, 4> Inputs; 12839 SmallVector<SDValue, 8> BinOps, PromOps; 12840 SmallPtrSet<SDNode *, 16> Visited; 12841 12842 for (unsigned i = 0; i < 2; ++i) { 12843 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12844 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12845 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12846 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12847 isa<ConstantSDNode>(N->getOperand(i))) 12848 Inputs.push_back(N->getOperand(i)); 12849 else 12850 BinOps.push_back(N->getOperand(i)); 12851 12852 if (N->getOpcode() == ISD::TRUNCATE) 12853 break; 12854 } 12855 12856 // Visit all inputs, collect all binary operations (and, or, xor and 12857 // select) that are all fed by extensions. 12858 while (!BinOps.empty()) { 12859 SDValue BinOp = BinOps.back(); 12860 BinOps.pop_back(); 12861 12862 if (!Visited.insert(BinOp.getNode()).second) 12863 continue; 12864 12865 PromOps.push_back(BinOp); 12866 12867 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12868 // The condition of the select is not promoted. 12869 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12870 continue; 12871 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12872 continue; 12873 12874 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12875 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12876 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12877 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12878 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12879 Inputs.push_back(BinOp.getOperand(i)); 12880 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12881 BinOp.getOperand(i).getOpcode() == ISD::OR || 12882 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12883 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12884 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12885 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12886 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12887 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12888 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12889 BinOps.push_back(BinOp.getOperand(i)); 12890 } else { 12891 // We have an input that is not an extension or another binary 12892 // operation; we'll abort this transformation. 12893 return SDValue(); 12894 } 12895 } 12896 } 12897 12898 // Make sure that this is a self-contained cluster of operations (which 12899 // is not quite the same thing as saying that everything has only one 12900 // use). 12901 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12902 if (isa<ConstantSDNode>(Inputs[i])) 12903 continue; 12904 12905 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12906 UE = Inputs[i].getNode()->use_end(); 12907 UI != UE; ++UI) { 12908 SDNode *User = *UI; 12909 if (User != N && !Visited.count(User)) 12910 return SDValue(); 12911 12912 // Make sure that we're not going to promote the non-output-value 12913 // operand(s) or SELECT or SELECT_CC. 12914 // FIXME: Although we could sometimes handle this, and it does occur in 12915 // practice that one of the condition inputs to the select is also one of 12916 // the outputs, we currently can't deal with this. 12917 if (User->getOpcode() == ISD::SELECT) { 12918 if (User->getOperand(0) == Inputs[i]) 12919 return SDValue(); 12920 } else if (User->getOpcode() == ISD::SELECT_CC) { 12921 if (User->getOperand(0) == Inputs[i] || 12922 User->getOperand(1) == Inputs[i]) 12923 return SDValue(); 12924 } 12925 } 12926 } 12927 12928 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12929 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12930 UE = PromOps[i].getNode()->use_end(); 12931 UI != UE; ++UI) { 12932 SDNode *User = *UI; 12933 if (User != N && !Visited.count(User)) 12934 return SDValue(); 12935 12936 // Make sure that we're not going to promote the non-output-value 12937 // operand(s) or SELECT or SELECT_CC. 12938 // FIXME: Although we could sometimes handle this, and it does occur in 12939 // practice that one of the condition inputs to the select is also one of 12940 // the outputs, we currently can't deal with this. 12941 if (User->getOpcode() == ISD::SELECT) { 12942 if (User->getOperand(0) == PromOps[i]) 12943 return SDValue(); 12944 } else if (User->getOpcode() == ISD::SELECT_CC) { 12945 if (User->getOperand(0) == PromOps[i] || 12946 User->getOperand(1) == PromOps[i]) 12947 return SDValue(); 12948 } 12949 } 12950 } 12951 12952 // Replace all inputs with the extension operand. 12953 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12954 // Constants may have users outside the cluster of to-be-promoted nodes, 12955 // and so we need to replace those as we do the promotions. 12956 if (isa<ConstantSDNode>(Inputs[i])) 12957 continue; 12958 else 12959 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12960 } 12961 12962 std::list<HandleSDNode> PromOpHandles; 12963 for (auto &PromOp : PromOps) 12964 PromOpHandles.emplace_back(PromOp); 12965 12966 // Replace all operations (these are all the same, but have a different 12967 // (i1) return type). DAG.getNode will validate that the types of 12968 // a binary operator match, so go through the list in reverse so that 12969 // we've likely promoted both operands first. Any intermediate truncations or 12970 // extensions disappear. 12971 while (!PromOpHandles.empty()) { 12972 SDValue PromOp = PromOpHandles.back().getValue(); 12973 PromOpHandles.pop_back(); 12974 12975 if (PromOp.getOpcode() == ISD::TRUNCATE || 12976 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12977 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12978 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12979 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12980 PromOp.getOperand(0).getValueType() != MVT::i1) { 12981 // The operand is not yet ready (see comment below). 12982 PromOpHandles.emplace_front(PromOp); 12983 continue; 12984 } 12985 12986 SDValue RepValue = PromOp.getOperand(0); 12987 if (isa<ConstantSDNode>(RepValue)) 12988 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12989 12990 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12991 continue; 12992 } 12993 12994 unsigned C; 12995 switch (PromOp.getOpcode()) { 12996 default: C = 0; break; 12997 case ISD::SELECT: C = 1; break; 12998 case ISD::SELECT_CC: C = 2; break; 12999 } 13000 13001 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13002 PromOp.getOperand(C).getValueType() != MVT::i1) || 13003 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13004 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13005 // The to-be-promoted operands of this node have not yet been 13006 // promoted (this should be rare because we're going through the 13007 // list backward, but if one of the operands has several users in 13008 // this cluster of to-be-promoted nodes, it is possible). 13009 PromOpHandles.emplace_front(PromOp); 13010 continue; 13011 } 13012 13013 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13014 PromOp.getNode()->op_end()); 13015 13016 // If there are any constant inputs, make sure they're replaced now. 13017 for (unsigned i = 0; i < 2; ++i) 13018 if (isa<ConstantSDNode>(Ops[C+i])) 13019 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13020 13021 DAG.ReplaceAllUsesOfValueWith(PromOp, 13022 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13023 } 13024 13025 // Now we're left with the initial truncation itself. 13026 if (N->getOpcode() == ISD::TRUNCATE) 13027 return N->getOperand(0); 13028 13029 // Otherwise, this is a comparison. The operands to be compared have just 13030 // changed type (to i1), but everything else is the same. 13031 return SDValue(N, 0); 13032 } 13033 13034 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13035 DAGCombinerInfo &DCI) const { 13036 SelectionDAG &DAG = DCI.DAG; 13037 SDLoc dl(N); 13038 13039 // If we're tracking CR bits, we need to be careful that we don't have: 13040 // zext(binary-ops(trunc(x), trunc(y))) 13041 // or 13042 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13043 // such that we're unnecessarily moving things into CR bits that can more 13044 // efficiently stay in GPRs. Note that if we're not certain that the high 13045 // bits are set as required by the final extension, we still may need to do 13046 // some masking to get the proper behavior. 13047 13048 // This same functionality is important on PPC64 when dealing with 13049 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13050 // the return values of functions. Because it is so similar, it is handled 13051 // here as well. 13052 13053 if (N->getValueType(0) != MVT::i32 && 13054 N->getValueType(0) != MVT::i64) 13055 return SDValue(); 13056 13057 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13058 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13059 return SDValue(); 13060 13061 if (N->getOperand(0).getOpcode() != ISD::AND && 13062 N->getOperand(0).getOpcode() != ISD::OR && 13063 N->getOperand(0).getOpcode() != ISD::XOR && 13064 N->getOperand(0).getOpcode() != ISD::SELECT && 13065 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13066 return SDValue(); 13067 13068 SmallVector<SDValue, 4> Inputs; 13069 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13070 SmallPtrSet<SDNode *, 16> Visited; 13071 13072 // Visit all inputs, collect all binary operations (and, or, xor and 13073 // select) that are all fed by truncations. 13074 while (!BinOps.empty()) { 13075 SDValue BinOp = BinOps.back(); 13076 BinOps.pop_back(); 13077 13078 if (!Visited.insert(BinOp.getNode()).second) 13079 continue; 13080 13081 PromOps.push_back(BinOp); 13082 13083 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13084 // The condition of the select is not promoted. 13085 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13086 continue; 13087 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13088 continue; 13089 13090 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13091 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13092 Inputs.push_back(BinOp.getOperand(i)); 13093 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13094 BinOp.getOperand(i).getOpcode() == ISD::OR || 13095 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13096 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13097 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13098 BinOps.push_back(BinOp.getOperand(i)); 13099 } else { 13100 // We have an input that is not a truncation or another binary 13101 // operation; we'll abort this transformation. 13102 return SDValue(); 13103 } 13104 } 13105 } 13106 13107 // The operands of a select that must be truncated when the select is 13108 // promoted because the operand is actually part of the to-be-promoted set. 13109 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13110 13111 // Make sure that this is a self-contained cluster of operations (which 13112 // is not quite the same thing as saying that everything has only one 13113 // use). 13114 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13115 if (isa<ConstantSDNode>(Inputs[i])) 13116 continue; 13117 13118 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13119 UE = Inputs[i].getNode()->use_end(); 13120 UI != UE; ++UI) { 13121 SDNode *User = *UI; 13122 if (User != N && !Visited.count(User)) 13123 return SDValue(); 13124 13125 // If we're going to promote the non-output-value operand(s) or SELECT or 13126 // SELECT_CC, record them for truncation. 13127 if (User->getOpcode() == ISD::SELECT) { 13128 if (User->getOperand(0) == Inputs[i]) 13129 SelectTruncOp[0].insert(std::make_pair(User, 13130 User->getOperand(0).getValueType())); 13131 } else if (User->getOpcode() == ISD::SELECT_CC) { 13132 if (User->getOperand(0) == Inputs[i]) 13133 SelectTruncOp[0].insert(std::make_pair(User, 13134 User->getOperand(0).getValueType())); 13135 if (User->getOperand(1) == Inputs[i]) 13136 SelectTruncOp[1].insert(std::make_pair(User, 13137 User->getOperand(1).getValueType())); 13138 } 13139 } 13140 } 13141 13142 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13143 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13144 UE = PromOps[i].getNode()->use_end(); 13145 UI != UE; ++UI) { 13146 SDNode *User = *UI; 13147 if (User != N && !Visited.count(User)) 13148 return SDValue(); 13149 13150 // If we're going to promote the non-output-value operand(s) or SELECT or 13151 // SELECT_CC, record them for truncation. 13152 if (User->getOpcode() == ISD::SELECT) { 13153 if (User->getOperand(0) == PromOps[i]) 13154 SelectTruncOp[0].insert(std::make_pair(User, 13155 User->getOperand(0).getValueType())); 13156 } else if (User->getOpcode() == ISD::SELECT_CC) { 13157 if (User->getOperand(0) == PromOps[i]) 13158 SelectTruncOp[0].insert(std::make_pair(User, 13159 User->getOperand(0).getValueType())); 13160 if (User->getOperand(1) == PromOps[i]) 13161 SelectTruncOp[1].insert(std::make_pair(User, 13162 User->getOperand(1).getValueType())); 13163 } 13164 } 13165 } 13166 13167 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13168 bool ReallyNeedsExt = false; 13169 if (N->getOpcode() != ISD::ANY_EXTEND) { 13170 // If all of the inputs are not already sign/zero extended, then 13171 // we'll still need to do that at the end. 13172 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13173 if (isa<ConstantSDNode>(Inputs[i])) 13174 continue; 13175 13176 unsigned OpBits = 13177 Inputs[i].getOperand(0).getValueSizeInBits(); 13178 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13179 13180 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13181 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13182 APInt::getHighBitsSet(OpBits, 13183 OpBits-PromBits))) || 13184 (N->getOpcode() == ISD::SIGN_EXTEND && 13185 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13186 (OpBits-(PromBits-1)))) { 13187 ReallyNeedsExt = true; 13188 break; 13189 } 13190 } 13191 } 13192 13193 // Replace all inputs, either with the truncation operand, or a 13194 // truncation or extension to the final output type. 13195 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13196 // Constant inputs need to be replaced with the to-be-promoted nodes that 13197 // use them because they might have users outside of the cluster of 13198 // promoted nodes. 13199 if (isa<ConstantSDNode>(Inputs[i])) 13200 continue; 13201 13202 SDValue InSrc = Inputs[i].getOperand(0); 13203 if (Inputs[i].getValueType() == N->getValueType(0)) 13204 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13205 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13206 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13207 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13208 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13209 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13210 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13211 else 13212 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13213 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13214 } 13215 13216 std::list<HandleSDNode> PromOpHandles; 13217 for (auto &PromOp : PromOps) 13218 PromOpHandles.emplace_back(PromOp); 13219 13220 // Replace all operations (these are all the same, but have a different 13221 // (promoted) return type). DAG.getNode will validate that the types of 13222 // a binary operator match, so go through the list in reverse so that 13223 // we've likely promoted both operands first. 13224 while (!PromOpHandles.empty()) { 13225 SDValue PromOp = PromOpHandles.back().getValue(); 13226 PromOpHandles.pop_back(); 13227 13228 unsigned C; 13229 switch (PromOp.getOpcode()) { 13230 default: C = 0; break; 13231 case ISD::SELECT: C = 1; break; 13232 case ISD::SELECT_CC: C = 2; break; 13233 } 13234 13235 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13236 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13237 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13238 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13239 // The to-be-promoted operands of this node have not yet been 13240 // promoted (this should be rare because we're going through the 13241 // list backward, but if one of the operands has several users in 13242 // this cluster of to-be-promoted nodes, it is possible). 13243 PromOpHandles.emplace_front(PromOp); 13244 continue; 13245 } 13246 13247 // For SELECT and SELECT_CC nodes, we do a similar check for any 13248 // to-be-promoted comparison inputs. 13249 if (PromOp.getOpcode() == ISD::SELECT || 13250 PromOp.getOpcode() == ISD::SELECT_CC) { 13251 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13252 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13253 (SelectTruncOp[1].count(PromOp.getNode()) && 13254 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13255 PromOpHandles.emplace_front(PromOp); 13256 continue; 13257 } 13258 } 13259 13260 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13261 PromOp.getNode()->op_end()); 13262 13263 // If this node has constant inputs, then they'll need to be promoted here. 13264 for (unsigned i = 0; i < 2; ++i) { 13265 if (!isa<ConstantSDNode>(Ops[C+i])) 13266 continue; 13267 if (Ops[C+i].getValueType() == N->getValueType(0)) 13268 continue; 13269 13270 if (N->getOpcode() == ISD::SIGN_EXTEND) 13271 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13272 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13273 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13274 else 13275 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13276 } 13277 13278 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13279 // truncate them again to the original value type. 13280 if (PromOp.getOpcode() == ISD::SELECT || 13281 PromOp.getOpcode() == ISD::SELECT_CC) { 13282 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13283 if (SI0 != SelectTruncOp[0].end()) 13284 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13285 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13286 if (SI1 != SelectTruncOp[1].end()) 13287 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13288 } 13289 13290 DAG.ReplaceAllUsesOfValueWith(PromOp, 13291 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13292 } 13293 13294 // Now we're left with the initial extension itself. 13295 if (!ReallyNeedsExt) 13296 return N->getOperand(0); 13297 13298 // To zero extend, just mask off everything except for the first bit (in the 13299 // i1 case). 13300 if (N->getOpcode() == ISD::ZERO_EXTEND) 13301 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13302 DAG.getConstant(APInt::getLowBitsSet( 13303 N->getValueSizeInBits(0), PromBits), 13304 dl, N->getValueType(0))); 13305 13306 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13307 "Invalid extension type"); 13308 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13309 SDValue ShiftCst = 13310 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13311 return DAG.getNode( 13312 ISD::SRA, dl, N->getValueType(0), 13313 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13314 ShiftCst); 13315 } 13316 13317 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13318 DAGCombinerInfo &DCI) const { 13319 assert(N->getOpcode() == ISD::SETCC && 13320 "Should be called with a SETCC node"); 13321 13322 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13323 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13324 SDValue LHS = N->getOperand(0); 13325 SDValue RHS = N->getOperand(1); 13326 13327 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13328 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13329 LHS.hasOneUse()) 13330 std::swap(LHS, RHS); 13331 13332 // x == 0-y --> x+y == 0 13333 // x != 0-y --> x+y != 0 13334 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13335 RHS.hasOneUse()) { 13336 SDLoc DL(N); 13337 SelectionDAG &DAG = DCI.DAG; 13338 EVT VT = N->getValueType(0); 13339 EVT OpVT = LHS.getValueType(); 13340 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13341 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13342 } 13343 } 13344 13345 return DAGCombineTruncBoolExt(N, DCI); 13346 } 13347 13348 // Is this an extending load from an f32 to an f64? 13349 static bool isFPExtLoad(SDValue Op) { 13350 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13351 return LD->getExtensionType() == ISD::EXTLOAD && 13352 Op.getValueType() == MVT::f64; 13353 return false; 13354 } 13355 13356 /// Reduces the number of fp-to-int conversion when building a vector. 13357 /// 13358 /// If this vector is built out of floating to integer conversions, 13359 /// transform it to a vector built out of floating point values followed by a 13360 /// single floating to integer conversion of the vector. 13361 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13362 /// becomes (fptosi (build_vector ($A, $B, ...))) 13363 SDValue PPCTargetLowering:: 13364 combineElementTruncationToVectorTruncation(SDNode *N, 13365 DAGCombinerInfo &DCI) const { 13366 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13367 "Should be called with a BUILD_VECTOR node"); 13368 13369 SelectionDAG &DAG = DCI.DAG; 13370 SDLoc dl(N); 13371 13372 SDValue FirstInput = N->getOperand(0); 13373 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13374 "The input operand must be an fp-to-int conversion."); 13375 13376 // This combine happens after legalization so the fp_to_[su]i nodes are 13377 // already converted to PPCSISD nodes. 13378 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13379 if (FirstConversion == PPCISD::FCTIDZ || 13380 FirstConversion == PPCISD::FCTIDUZ || 13381 FirstConversion == PPCISD::FCTIWZ || 13382 FirstConversion == PPCISD::FCTIWUZ) { 13383 bool IsSplat = true; 13384 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13385 FirstConversion == PPCISD::FCTIWUZ; 13386 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13387 SmallVector<SDValue, 4> Ops; 13388 EVT TargetVT = N->getValueType(0); 13389 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13390 SDValue NextOp = N->getOperand(i); 13391 if (NextOp.getOpcode() != PPCISD::MFVSR) 13392 return SDValue(); 13393 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13394 if (NextConversion != FirstConversion) 13395 return SDValue(); 13396 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13397 // This is not valid if the input was originally double precision. It is 13398 // also not profitable to do unless this is an extending load in which 13399 // case doing this combine will allow us to combine consecutive loads. 13400 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13401 return SDValue(); 13402 if (N->getOperand(i) != FirstInput) 13403 IsSplat = false; 13404 } 13405 13406 // If this is a splat, we leave it as-is since there will be only a single 13407 // fp-to-int conversion followed by a splat of the integer. This is better 13408 // for 32-bit and smaller ints and neutral for 64-bit ints. 13409 if (IsSplat) 13410 return SDValue(); 13411 13412 // Now that we know we have the right type of node, get its operands 13413 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13414 SDValue In = N->getOperand(i).getOperand(0); 13415 if (Is32Bit) { 13416 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13417 // here, we know that all inputs are extending loads so this is safe). 13418 if (In.isUndef()) 13419 Ops.push_back(DAG.getUNDEF(SrcVT)); 13420 else { 13421 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13422 MVT::f32, In.getOperand(0), 13423 DAG.getIntPtrConstant(1, dl)); 13424 Ops.push_back(Trunc); 13425 } 13426 } else 13427 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13428 } 13429 13430 unsigned Opcode; 13431 if (FirstConversion == PPCISD::FCTIDZ || 13432 FirstConversion == PPCISD::FCTIWZ) 13433 Opcode = ISD::FP_TO_SINT; 13434 else 13435 Opcode = ISD::FP_TO_UINT; 13436 13437 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13438 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13439 return DAG.getNode(Opcode, dl, TargetVT, BV); 13440 } 13441 return SDValue(); 13442 } 13443 13444 /// Reduce the number of loads when building a vector. 13445 /// 13446 /// Building a vector out of multiple loads can be converted to a load 13447 /// of the vector type if the loads are consecutive. If the loads are 13448 /// consecutive but in descending order, a shuffle is added at the end 13449 /// to reorder the vector. 13450 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13451 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13452 "Should be called with a BUILD_VECTOR node"); 13453 13454 SDLoc dl(N); 13455 13456 // Return early for non byte-sized type, as they can't be consecutive. 13457 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13458 return SDValue(); 13459 13460 bool InputsAreConsecutiveLoads = true; 13461 bool InputsAreReverseConsecutive = true; 13462 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13463 SDValue FirstInput = N->getOperand(0); 13464 bool IsRoundOfExtLoad = false; 13465 13466 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13467 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13468 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13469 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13470 } 13471 // Not a build vector of (possibly fp_rounded) loads. 13472 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13473 N->getNumOperands() == 1) 13474 return SDValue(); 13475 13476 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13477 // If any inputs are fp_round(extload), they all must be. 13478 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13479 return SDValue(); 13480 13481 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13482 N->getOperand(i); 13483 if (NextInput.getOpcode() != ISD::LOAD) 13484 return SDValue(); 13485 13486 SDValue PreviousInput = 13487 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13488 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13489 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13490 13491 // If any inputs are fp_round(extload), they all must be. 13492 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13493 return SDValue(); 13494 13495 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13496 InputsAreConsecutiveLoads = false; 13497 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13498 InputsAreReverseConsecutive = false; 13499 13500 // Exit early if the loads are neither consecutive nor reverse consecutive. 13501 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13502 return SDValue(); 13503 } 13504 13505 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13506 "The loads cannot be both consecutive and reverse consecutive."); 13507 13508 SDValue FirstLoadOp = 13509 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13510 SDValue LastLoadOp = 13511 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13512 N->getOperand(N->getNumOperands()-1); 13513 13514 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13515 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13516 if (InputsAreConsecutiveLoads) { 13517 assert(LD1 && "Input needs to be a LoadSDNode."); 13518 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13519 LD1->getBasePtr(), LD1->getPointerInfo(), 13520 LD1->getAlignment()); 13521 } 13522 if (InputsAreReverseConsecutive) { 13523 assert(LDL && "Input needs to be a LoadSDNode."); 13524 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13525 LDL->getBasePtr(), LDL->getPointerInfo(), 13526 LDL->getAlignment()); 13527 SmallVector<int, 16> Ops; 13528 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13529 Ops.push_back(i); 13530 13531 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13532 DAG.getUNDEF(N->getValueType(0)), Ops); 13533 } 13534 return SDValue(); 13535 } 13536 13537 // This function adds the required vector_shuffle needed to get 13538 // the elements of the vector extract in the correct position 13539 // as specified by the CorrectElems encoding. 13540 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13541 SDValue Input, uint64_t Elems, 13542 uint64_t CorrectElems) { 13543 SDLoc dl(N); 13544 13545 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13546 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13547 13548 // Knowing the element indices being extracted from the original 13549 // vector and the order in which they're being inserted, just put 13550 // them at element indices required for the instruction. 13551 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13552 if (DAG.getDataLayout().isLittleEndian()) 13553 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13554 else 13555 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13556 CorrectElems = CorrectElems >> 8; 13557 Elems = Elems >> 8; 13558 } 13559 13560 SDValue Shuffle = 13561 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13562 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13563 13564 EVT VT = N->getValueType(0); 13565 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13566 13567 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13568 Input.getValueType().getVectorElementType(), 13569 VT.getVectorNumElements()); 13570 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13571 DAG.getValueType(ExtVT)); 13572 } 13573 13574 // Look for build vector patterns where input operands come from sign 13575 // extended vector_extract elements of specific indices. If the correct indices 13576 // aren't used, add a vector shuffle to fix up the indices and create 13577 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13578 // during instruction selection. 13579 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13580 // This array encodes the indices that the vector sign extend instructions 13581 // extract from when extending from one type to another for both BE and LE. 13582 // The right nibble of each byte corresponds to the LE incides. 13583 // and the left nibble of each byte corresponds to the BE incides. 13584 // For example: 0x3074B8FC byte->word 13585 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13586 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13587 // For example: 0x000070F8 byte->double word 13588 // For LE: the allowed indices are: 0x0,0x8 13589 // For BE: the allowed indices are: 0x7,0xF 13590 uint64_t TargetElems[] = { 13591 0x3074B8FC, // b->w 13592 0x000070F8, // b->d 13593 0x10325476, // h->w 13594 0x00003074, // h->d 13595 0x00001032, // w->d 13596 }; 13597 13598 uint64_t Elems = 0; 13599 int Index; 13600 SDValue Input; 13601 13602 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13603 if (!Op) 13604 return false; 13605 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13606 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13607 return false; 13608 13609 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13610 // of the right width. 13611 SDValue Extract = Op.getOperand(0); 13612 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13613 Extract = Extract.getOperand(0); 13614 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13615 return false; 13616 13617 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13618 if (!ExtOp) 13619 return false; 13620 13621 Index = ExtOp->getZExtValue(); 13622 if (Input && Input != Extract.getOperand(0)) 13623 return false; 13624 13625 if (!Input) 13626 Input = Extract.getOperand(0); 13627 13628 Elems = Elems << 8; 13629 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13630 Elems |= Index; 13631 13632 return true; 13633 }; 13634 13635 // If the build vector operands aren't sign extended vector extracts, 13636 // of the same input vector, then return. 13637 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13638 if (!isSExtOfVecExtract(N->getOperand(i))) { 13639 return SDValue(); 13640 } 13641 } 13642 13643 // If the vector extract indicies are not correct, add the appropriate 13644 // vector_shuffle. 13645 int TgtElemArrayIdx; 13646 int InputSize = Input.getValueType().getScalarSizeInBits(); 13647 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13648 if (InputSize + OutputSize == 40) 13649 TgtElemArrayIdx = 0; 13650 else if (InputSize + OutputSize == 72) 13651 TgtElemArrayIdx = 1; 13652 else if (InputSize + OutputSize == 48) 13653 TgtElemArrayIdx = 2; 13654 else if (InputSize + OutputSize == 80) 13655 TgtElemArrayIdx = 3; 13656 else if (InputSize + OutputSize == 96) 13657 TgtElemArrayIdx = 4; 13658 else 13659 return SDValue(); 13660 13661 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13662 CorrectElems = DAG.getDataLayout().isLittleEndian() 13663 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13664 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13665 if (Elems != CorrectElems) { 13666 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13667 } 13668 13669 // Regular lowering will catch cases where a shuffle is not needed. 13670 return SDValue(); 13671 } 13672 13673 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13674 DAGCombinerInfo &DCI) const { 13675 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13676 "Should be called with a BUILD_VECTOR node"); 13677 13678 SelectionDAG &DAG = DCI.DAG; 13679 SDLoc dl(N); 13680 13681 if (!Subtarget.hasVSX()) 13682 return SDValue(); 13683 13684 // The target independent DAG combiner will leave a build_vector of 13685 // float-to-int conversions intact. We can generate MUCH better code for 13686 // a float-to-int conversion of a vector of floats. 13687 SDValue FirstInput = N->getOperand(0); 13688 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13689 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13690 if (Reduced) 13691 return Reduced; 13692 } 13693 13694 // If we're building a vector out of consecutive loads, just load that 13695 // vector type. 13696 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13697 if (Reduced) 13698 return Reduced; 13699 13700 // If we're building a vector out of extended elements from another vector 13701 // we have P9 vector integer extend instructions. The code assumes legal 13702 // input types (i.e. it can't handle things like v4i16) so do not run before 13703 // legalization. 13704 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13705 Reduced = combineBVOfVecSExt(N, DAG); 13706 if (Reduced) 13707 return Reduced; 13708 } 13709 13710 13711 if (N->getValueType(0) != MVT::v2f64) 13712 return SDValue(); 13713 13714 // Looking for: 13715 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13716 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13717 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13718 return SDValue(); 13719 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13720 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13721 return SDValue(); 13722 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13723 return SDValue(); 13724 13725 SDValue Ext1 = FirstInput.getOperand(0); 13726 SDValue Ext2 = N->getOperand(1).getOperand(0); 13727 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13728 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13729 return SDValue(); 13730 13731 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13732 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13733 if (!Ext1Op || !Ext2Op) 13734 return SDValue(); 13735 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13736 Ext1.getOperand(0) != Ext2.getOperand(0)) 13737 return SDValue(); 13738 13739 int FirstElem = Ext1Op->getZExtValue(); 13740 int SecondElem = Ext2Op->getZExtValue(); 13741 int SubvecIdx; 13742 if (FirstElem == 0 && SecondElem == 1) 13743 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13744 else if (FirstElem == 2 && SecondElem == 3) 13745 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13746 else 13747 return SDValue(); 13748 13749 SDValue SrcVec = Ext1.getOperand(0); 13750 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13751 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13752 return DAG.getNode(NodeType, dl, MVT::v2f64, 13753 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13754 } 13755 13756 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13757 DAGCombinerInfo &DCI) const { 13758 assert((N->getOpcode() == ISD::SINT_TO_FP || 13759 N->getOpcode() == ISD::UINT_TO_FP) && 13760 "Need an int -> FP conversion node here"); 13761 13762 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13763 return SDValue(); 13764 13765 SelectionDAG &DAG = DCI.DAG; 13766 SDLoc dl(N); 13767 SDValue Op(N, 0); 13768 13769 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13770 // from the hardware. 13771 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13772 return SDValue(); 13773 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13774 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13775 return SDValue(); 13776 13777 SDValue FirstOperand(Op.getOperand(0)); 13778 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13779 (FirstOperand.getValueType() == MVT::i8 || 13780 FirstOperand.getValueType() == MVT::i16); 13781 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13782 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13783 bool DstDouble = Op.getValueType() == MVT::f64; 13784 unsigned ConvOp = Signed ? 13785 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13786 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13787 SDValue WidthConst = 13788 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13789 dl, false); 13790 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13791 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13792 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13793 DAG.getVTList(MVT::f64, MVT::Other), 13794 Ops, MVT::i8, LDN->getMemOperand()); 13795 13796 // For signed conversion, we need to sign-extend the value in the VSR 13797 if (Signed) { 13798 SDValue ExtOps[] = { Ld, WidthConst }; 13799 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13800 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13801 } else 13802 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13803 } 13804 13805 13806 // For i32 intermediate values, unfortunately, the conversion functions 13807 // leave the upper 32 bits of the value are undefined. Within the set of 13808 // scalar instructions, we have no method for zero- or sign-extending the 13809 // value. Thus, we cannot handle i32 intermediate values here. 13810 if (Op.getOperand(0).getValueType() == MVT::i32) 13811 return SDValue(); 13812 13813 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13814 "UINT_TO_FP is supported only with FPCVT"); 13815 13816 // If we have FCFIDS, then use it when converting to single-precision. 13817 // Otherwise, convert to double-precision and then round. 13818 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13819 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13820 : PPCISD::FCFIDS) 13821 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13822 : PPCISD::FCFID); 13823 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13824 ? MVT::f32 13825 : MVT::f64; 13826 13827 // If we're converting from a float, to an int, and back to a float again, 13828 // then we don't need the store/load pair at all. 13829 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13830 Subtarget.hasFPCVT()) || 13831 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13832 SDValue Src = Op.getOperand(0).getOperand(0); 13833 if (Src.getValueType() == MVT::f32) { 13834 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13835 DCI.AddToWorklist(Src.getNode()); 13836 } else if (Src.getValueType() != MVT::f64) { 13837 // Make sure that we don't pick up a ppc_fp128 source value. 13838 return SDValue(); 13839 } 13840 13841 unsigned FCTOp = 13842 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13843 PPCISD::FCTIDUZ; 13844 13845 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13846 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13847 13848 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13849 FP = DAG.getNode(ISD::FP_ROUND, dl, 13850 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13851 DCI.AddToWorklist(FP.getNode()); 13852 } 13853 13854 return FP; 13855 } 13856 13857 return SDValue(); 13858 } 13859 13860 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13861 // builtins) into loads with swaps. 13862 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13863 DAGCombinerInfo &DCI) const { 13864 SelectionDAG &DAG = DCI.DAG; 13865 SDLoc dl(N); 13866 SDValue Chain; 13867 SDValue Base; 13868 MachineMemOperand *MMO; 13869 13870 switch (N->getOpcode()) { 13871 default: 13872 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13873 case ISD::LOAD: { 13874 LoadSDNode *LD = cast<LoadSDNode>(N); 13875 Chain = LD->getChain(); 13876 Base = LD->getBasePtr(); 13877 MMO = LD->getMemOperand(); 13878 // If the MMO suggests this isn't a load of a full vector, leave 13879 // things alone. For a built-in, we have to make the change for 13880 // correctness, so if there is a size problem that will be a bug. 13881 if (MMO->getSize() < 16) 13882 return SDValue(); 13883 break; 13884 } 13885 case ISD::INTRINSIC_W_CHAIN: { 13886 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13887 Chain = Intrin->getChain(); 13888 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13889 // us what we want. Get operand 2 instead. 13890 Base = Intrin->getOperand(2); 13891 MMO = Intrin->getMemOperand(); 13892 break; 13893 } 13894 } 13895 13896 MVT VecTy = N->getValueType(0).getSimpleVT(); 13897 13898 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13899 // aligned and the type is a vector with elements up to 4 bytes 13900 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13901 VecTy.getScalarSizeInBits() <= 32) { 13902 return SDValue(); 13903 } 13904 13905 SDValue LoadOps[] = { Chain, Base }; 13906 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13907 DAG.getVTList(MVT::v2f64, MVT::Other), 13908 LoadOps, MVT::v2f64, MMO); 13909 13910 DCI.AddToWorklist(Load.getNode()); 13911 Chain = Load.getValue(1); 13912 SDValue Swap = DAG.getNode( 13913 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13914 DCI.AddToWorklist(Swap.getNode()); 13915 13916 // Add a bitcast if the resulting load type doesn't match v2f64. 13917 if (VecTy != MVT::v2f64) { 13918 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13919 DCI.AddToWorklist(N.getNode()); 13920 // Package {bitcast value, swap's chain} to match Load's shape. 13921 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13922 N, Swap.getValue(1)); 13923 } 13924 13925 return Swap; 13926 } 13927 13928 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13929 // builtins) into stores with swaps. 13930 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13931 DAGCombinerInfo &DCI) const { 13932 SelectionDAG &DAG = DCI.DAG; 13933 SDLoc dl(N); 13934 SDValue Chain; 13935 SDValue Base; 13936 unsigned SrcOpnd; 13937 MachineMemOperand *MMO; 13938 13939 switch (N->getOpcode()) { 13940 default: 13941 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13942 case ISD::STORE: { 13943 StoreSDNode *ST = cast<StoreSDNode>(N); 13944 Chain = ST->getChain(); 13945 Base = ST->getBasePtr(); 13946 MMO = ST->getMemOperand(); 13947 SrcOpnd = 1; 13948 // If the MMO suggests this isn't a store of a full vector, leave 13949 // things alone. For a built-in, we have to make the change for 13950 // correctness, so if there is a size problem that will be a bug. 13951 if (MMO->getSize() < 16) 13952 return SDValue(); 13953 break; 13954 } 13955 case ISD::INTRINSIC_VOID: { 13956 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13957 Chain = Intrin->getChain(); 13958 // Intrin->getBasePtr() oddly does not get what we want. 13959 Base = Intrin->getOperand(3); 13960 MMO = Intrin->getMemOperand(); 13961 SrcOpnd = 2; 13962 break; 13963 } 13964 } 13965 13966 SDValue Src = N->getOperand(SrcOpnd); 13967 MVT VecTy = Src.getValueType().getSimpleVT(); 13968 13969 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13970 // aligned and the type is a vector with elements up to 4 bytes 13971 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13972 VecTy.getScalarSizeInBits() <= 32) { 13973 return SDValue(); 13974 } 13975 13976 // All stores are done as v2f64 and possible bit cast. 13977 if (VecTy != MVT::v2f64) { 13978 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13979 DCI.AddToWorklist(Src.getNode()); 13980 } 13981 13982 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13983 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13984 DCI.AddToWorklist(Swap.getNode()); 13985 Chain = Swap.getValue(1); 13986 SDValue StoreOps[] = { Chain, Swap, Base }; 13987 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13988 DAG.getVTList(MVT::Other), 13989 StoreOps, VecTy, MMO); 13990 DCI.AddToWorklist(Store.getNode()); 13991 return Store; 13992 } 13993 13994 // Handle DAG combine for STORE (FP_TO_INT F). 13995 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13996 DAGCombinerInfo &DCI) const { 13997 13998 SelectionDAG &DAG = DCI.DAG; 13999 SDLoc dl(N); 14000 unsigned Opcode = N->getOperand(1).getOpcode(); 14001 14002 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14003 && "Not a FP_TO_INT Instruction!"); 14004 14005 SDValue Val = N->getOperand(1).getOperand(0); 14006 EVT Op1VT = N->getOperand(1).getValueType(); 14007 EVT ResVT = Val.getValueType(); 14008 14009 // Floating point types smaller than 32 bits are not legal on Power. 14010 if (ResVT.getScalarSizeInBits() < 32) 14011 return SDValue(); 14012 14013 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14014 bool ValidTypeForStoreFltAsInt = 14015 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14016 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14017 14018 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14019 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14020 return SDValue(); 14021 14022 // Extend f32 values to f64 14023 if (ResVT.getScalarSizeInBits() == 32) { 14024 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14025 DCI.AddToWorklist(Val.getNode()); 14026 } 14027 14028 // Set signed or unsigned conversion opcode. 14029 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14030 PPCISD::FP_TO_SINT_IN_VSR : 14031 PPCISD::FP_TO_UINT_IN_VSR; 14032 14033 Val = DAG.getNode(ConvOpcode, 14034 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14035 DCI.AddToWorklist(Val.getNode()); 14036 14037 // Set number of bytes being converted. 14038 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14039 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14040 DAG.getIntPtrConstant(ByteSize, dl, false), 14041 DAG.getValueType(Op1VT) }; 14042 14043 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14044 DAG.getVTList(MVT::Other), Ops, 14045 cast<StoreSDNode>(N)->getMemoryVT(), 14046 cast<StoreSDNode>(N)->getMemOperand()); 14047 14048 DCI.AddToWorklist(Val.getNode()); 14049 return Val; 14050 } 14051 14052 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14053 LSBaseSDNode *LSBase, 14054 DAGCombinerInfo &DCI) const { 14055 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14056 "Not a reverse memop pattern!"); 14057 14058 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14059 auto Mask = SVN->getMask(); 14060 int i = 0; 14061 auto I = Mask.rbegin(); 14062 auto E = Mask.rend(); 14063 14064 for (; I != E; ++I) { 14065 if (*I != i) 14066 return false; 14067 i++; 14068 } 14069 return true; 14070 }; 14071 14072 SelectionDAG &DAG = DCI.DAG; 14073 EVT VT = SVN->getValueType(0); 14074 14075 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14076 return SDValue(); 14077 14078 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14079 // See comment in PPCVSXSwapRemoval.cpp. 14080 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14081 if (!Subtarget.hasP9Vector()) 14082 return SDValue(); 14083 14084 if(!IsElementReverse(SVN)) 14085 return SDValue(); 14086 14087 if (LSBase->getOpcode() == ISD::LOAD) { 14088 SDLoc dl(SVN); 14089 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14090 return DAG.getMemIntrinsicNode( 14091 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14092 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14093 } 14094 14095 if (LSBase->getOpcode() == ISD::STORE) { 14096 SDLoc dl(LSBase); 14097 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14098 LSBase->getBasePtr()}; 14099 return DAG.getMemIntrinsicNode( 14100 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14101 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14102 } 14103 14104 llvm_unreachable("Expected a load or store node here"); 14105 } 14106 14107 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14108 DAGCombinerInfo &DCI) const { 14109 SelectionDAG &DAG = DCI.DAG; 14110 SDLoc dl(N); 14111 switch (N->getOpcode()) { 14112 default: break; 14113 case ISD::ADD: 14114 return combineADD(N, DCI); 14115 case ISD::SHL: 14116 return combineSHL(N, DCI); 14117 case ISD::SRA: 14118 return combineSRA(N, DCI); 14119 case ISD::SRL: 14120 return combineSRL(N, DCI); 14121 case ISD::MUL: 14122 return combineMUL(N, DCI); 14123 case PPCISD::SHL: 14124 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14125 return N->getOperand(0); 14126 break; 14127 case PPCISD::SRL: 14128 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14129 return N->getOperand(0); 14130 break; 14131 case PPCISD::SRA: 14132 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14133 if (C->isNullValue() || // 0 >>s V -> 0. 14134 C->isAllOnesValue()) // -1 >>s V -> -1. 14135 return N->getOperand(0); 14136 } 14137 break; 14138 case ISD::SIGN_EXTEND: 14139 case ISD::ZERO_EXTEND: 14140 case ISD::ANY_EXTEND: 14141 return DAGCombineExtBoolTrunc(N, DCI); 14142 case ISD::TRUNCATE: 14143 return combineTRUNCATE(N, DCI); 14144 case ISD::SETCC: 14145 if (SDValue CSCC = combineSetCC(N, DCI)) 14146 return CSCC; 14147 LLVM_FALLTHROUGH; 14148 case ISD::SELECT_CC: 14149 return DAGCombineTruncBoolExt(N, DCI); 14150 case ISD::SINT_TO_FP: 14151 case ISD::UINT_TO_FP: 14152 return combineFPToIntToFP(N, DCI); 14153 case ISD::VECTOR_SHUFFLE: 14154 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14155 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14156 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14157 } 14158 break; 14159 case ISD::STORE: { 14160 14161 EVT Op1VT = N->getOperand(1).getValueType(); 14162 unsigned Opcode = N->getOperand(1).getOpcode(); 14163 14164 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14165 SDValue Val= combineStoreFPToInt(N, DCI); 14166 if (Val) 14167 return Val; 14168 } 14169 14170 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14171 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14172 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14173 if (Val) 14174 return Val; 14175 } 14176 14177 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14178 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14179 N->getOperand(1).getNode()->hasOneUse() && 14180 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14181 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14182 14183 // STBRX can only handle simple types and it makes no sense to store less 14184 // two bytes in byte-reversed order. 14185 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14186 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14187 break; 14188 14189 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14190 // Do an any-extend to 32-bits if this is a half-word input. 14191 if (BSwapOp.getValueType() == MVT::i16) 14192 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14193 14194 // If the type of BSWAP operand is wider than stored memory width 14195 // it need to be shifted to the right side before STBRX. 14196 if (Op1VT.bitsGT(mVT)) { 14197 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14198 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14199 DAG.getConstant(Shift, dl, MVT::i32)); 14200 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14201 if (Op1VT == MVT::i64) 14202 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14203 } 14204 14205 SDValue Ops[] = { 14206 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14207 }; 14208 return 14209 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14210 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14211 cast<StoreSDNode>(N)->getMemOperand()); 14212 } 14213 14214 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14215 // So it can increase the chance of CSE constant construction. 14216 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14217 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14218 // Need to sign-extended to 64-bits to handle negative values. 14219 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14220 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14221 MemVT.getSizeInBits()); 14222 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14223 14224 // DAG.getTruncStore() can't be used here because it doesn't accept 14225 // the general (base + offset) addressing mode. 14226 // So we use UpdateNodeOperands and setTruncatingStore instead. 14227 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14228 N->getOperand(3)); 14229 cast<StoreSDNode>(N)->setTruncatingStore(true); 14230 return SDValue(N, 0); 14231 } 14232 14233 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14234 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14235 if (Op1VT.isSimple()) { 14236 MVT StoreVT = Op1VT.getSimpleVT(); 14237 if (Subtarget.needsSwapsForVSXMemOps() && 14238 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14239 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14240 return expandVSXStoreForLE(N, DCI); 14241 } 14242 break; 14243 } 14244 case ISD::LOAD: { 14245 LoadSDNode *LD = cast<LoadSDNode>(N); 14246 EVT VT = LD->getValueType(0); 14247 14248 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14249 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14250 if (VT.isSimple()) { 14251 MVT LoadVT = VT.getSimpleVT(); 14252 if (Subtarget.needsSwapsForVSXMemOps() && 14253 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14254 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14255 return expandVSXLoadForLE(N, DCI); 14256 } 14257 14258 // We sometimes end up with a 64-bit integer load, from which we extract 14259 // two single-precision floating-point numbers. This happens with 14260 // std::complex<float>, and other similar structures, because of the way we 14261 // canonicalize structure copies. However, if we lack direct moves, 14262 // then the final bitcasts from the extracted integer values to the 14263 // floating-point numbers turn into store/load pairs. Even with direct moves, 14264 // just loading the two floating-point numbers is likely better. 14265 auto ReplaceTwoFloatLoad = [&]() { 14266 if (VT != MVT::i64) 14267 return false; 14268 14269 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14270 LD->isVolatile()) 14271 return false; 14272 14273 // We're looking for a sequence like this: 14274 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14275 // t16: i64 = srl t13, Constant:i32<32> 14276 // t17: i32 = truncate t16 14277 // t18: f32 = bitcast t17 14278 // t19: i32 = truncate t13 14279 // t20: f32 = bitcast t19 14280 14281 if (!LD->hasNUsesOfValue(2, 0)) 14282 return false; 14283 14284 auto UI = LD->use_begin(); 14285 while (UI.getUse().getResNo() != 0) ++UI; 14286 SDNode *Trunc = *UI++; 14287 while (UI.getUse().getResNo() != 0) ++UI; 14288 SDNode *RightShift = *UI; 14289 if (Trunc->getOpcode() != ISD::TRUNCATE) 14290 std::swap(Trunc, RightShift); 14291 14292 if (Trunc->getOpcode() != ISD::TRUNCATE || 14293 Trunc->getValueType(0) != MVT::i32 || 14294 !Trunc->hasOneUse()) 14295 return false; 14296 if (RightShift->getOpcode() != ISD::SRL || 14297 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14298 RightShift->getConstantOperandVal(1) != 32 || 14299 !RightShift->hasOneUse()) 14300 return false; 14301 14302 SDNode *Trunc2 = *RightShift->use_begin(); 14303 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14304 Trunc2->getValueType(0) != MVT::i32 || 14305 !Trunc2->hasOneUse()) 14306 return false; 14307 14308 SDNode *Bitcast = *Trunc->use_begin(); 14309 SDNode *Bitcast2 = *Trunc2->use_begin(); 14310 14311 if (Bitcast->getOpcode() != ISD::BITCAST || 14312 Bitcast->getValueType(0) != MVT::f32) 14313 return false; 14314 if (Bitcast2->getOpcode() != ISD::BITCAST || 14315 Bitcast2->getValueType(0) != MVT::f32) 14316 return false; 14317 14318 if (Subtarget.isLittleEndian()) 14319 std::swap(Bitcast, Bitcast2); 14320 14321 // Bitcast has the second float (in memory-layout order) and Bitcast2 14322 // has the first one. 14323 14324 SDValue BasePtr = LD->getBasePtr(); 14325 if (LD->isIndexed()) { 14326 assert(LD->getAddressingMode() == ISD::PRE_INC && 14327 "Non-pre-inc AM on PPC?"); 14328 BasePtr = 14329 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14330 LD->getOffset()); 14331 } 14332 14333 auto MMOFlags = 14334 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14335 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14336 LD->getPointerInfo(), LD->getAlignment(), 14337 MMOFlags, LD->getAAInfo()); 14338 SDValue AddPtr = 14339 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14340 BasePtr, DAG.getIntPtrConstant(4, dl)); 14341 SDValue FloatLoad2 = DAG.getLoad( 14342 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14343 LD->getPointerInfo().getWithOffset(4), 14344 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14345 14346 if (LD->isIndexed()) { 14347 // Note that DAGCombine should re-form any pre-increment load(s) from 14348 // what is produced here if that makes sense. 14349 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14350 } 14351 14352 DCI.CombineTo(Bitcast2, FloatLoad); 14353 DCI.CombineTo(Bitcast, FloatLoad2); 14354 14355 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14356 SDValue(FloatLoad2.getNode(), 1)); 14357 return true; 14358 }; 14359 14360 if (ReplaceTwoFloatLoad()) 14361 return SDValue(N, 0); 14362 14363 EVT MemVT = LD->getMemoryVT(); 14364 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14365 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 14366 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 14367 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 14368 if (LD->isUnindexed() && VT.isVector() && 14369 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14370 // P8 and later hardware should just use LOAD. 14371 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 14372 VT == MVT::v4i32 || VT == MVT::v4f32)) || 14373 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 14374 LD->getAlignment() >= ScalarABIAlignment)) && 14375 LD->getAlignment() < ABIAlignment) { 14376 // This is a type-legal unaligned Altivec or QPX load. 14377 SDValue Chain = LD->getChain(); 14378 SDValue Ptr = LD->getBasePtr(); 14379 bool isLittleEndian = Subtarget.isLittleEndian(); 14380 14381 // This implements the loading of unaligned vectors as described in 14382 // the venerable Apple Velocity Engine overview. Specifically: 14383 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14384 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14385 // 14386 // The general idea is to expand a sequence of one or more unaligned 14387 // loads into an alignment-based permutation-control instruction (lvsl 14388 // or lvsr), a series of regular vector loads (which always truncate 14389 // their input address to an aligned address), and a series of 14390 // permutations. The results of these permutations are the requested 14391 // loaded values. The trick is that the last "extra" load is not taken 14392 // from the address you might suspect (sizeof(vector) bytes after the 14393 // last requested load), but rather sizeof(vector) - 1 bytes after the 14394 // last requested vector. The point of this is to avoid a page fault if 14395 // the base address happened to be aligned. This works because if the 14396 // base address is aligned, then adding less than a full vector length 14397 // will cause the last vector in the sequence to be (re)loaded. 14398 // Otherwise, the next vector will be fetched as you might suspect was 14399 // necessary. 14400 14401 // We might be able to reuse the permutation generation from 14402 // a different base address offset from this one by an aligned amount. 14403 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14404 // optimization later. 14405 Intrinsic::ID Intr, IntrLD, IntrPerm; 14406 MVT PermCntlTy, PermTy, LDTy; 14407 if (Subtarget.hasAltivec()) { 14408 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 14409 Intrinsic::ppc_altivec_lvsl; 14410 IntrLD = Intrinsic::ppc_altivec_lvx; 14411 IntrPerm = Intrinsic::ppc_altivec_vperm; 14412 PermCntlTy = MVT::v16i8; 14413 PermTy = MVT::v4i32; 14414 LDTy = MVT::v4i32; 14415 } else { 14416 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 14417 Intrinsic::ppc_qpx_qvlpcls; 14418 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 14419 Intrinsic::ppc_qpx_qvlfs; 14420 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 14421 PermCntlTy = MVT::v4f64; 14422 PermTy = MVT::v4f64; 14423 LDTy = MemVT.getSimpleVT(); 14424 } 14425 14426 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14427 14428 // Create the new MMO for the new base load. It is like the original MMO, 14429 // but represents an area in memory almost twice the vector size centered 14430 // on the original address. If the address is unaligned, we might start 14431 // reading up to (sizeof(vector)-1) bytes below the address of the 14432 // original unaligned load. 14433 MachineFunction &MF = DAG.getMachineFunction(); 14434 MachineMemOperand *BaseMMO = 14435 MF.getMachineMemOperand(LD->getMemOperand(), 14436 -(long)MemVT.getStoreSize()+1, 14437 2*MemVT.getStoreSize()-1); 14438 14439 // Create the new base load. 14440 SDValue LDXIntID = 14441 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14442 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14443 SDValue BaseLoad = 14444 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14445 DAG.getVTList(PermTy, MVT::Other), 14446 BaseLoadOps, LDTy, BaseMMO); 14447 14448 // Note that the value of IncOffset (which is provided to the next 14449 // load's pointer info offset value, and thus used to calculate the 14450 // alignment), and the value of IncValue (which is actually used to 14451 // increment the pointer value) are different! This is because we 14452 // require the next load to appear to be aligned, even though it 14453 // is actually offset from the base pointer by a lesser amount. 14454 int IncOffset = VT.getSizeInBits() / 8; 14455 int IncValue = IncOffset; 14456 14457 // Walk (both up and down) the chain looking for another load at the real 14458 // (aligned) offset (the alignment of the other load does not matter in 14459 // this case). If found, then do not use the offset reduction trick, as 14460 // that will prevent the loads from being later combined (as they would 14461 // otherwise be duplicates). 14462 if (!findConsecutiveLoad(LD, DAG)) 14463 --IncValue; 14464 14465 SDValue Increment = 14466 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14467 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14468 14469 MachineMemOperand *ExtraMMO = 14470 MF.getMachineMemOperand(LD->getMemOperand(), 14471 1, 2*MemVT.getStoreSize()-1); 14472 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14473 SDValue ExtraLoad = 14474 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14475 DAG.getVTList(PermTy, MVT::Other), 14476 ExtraLoadOps, LDTy, ExtraMMO); 14477 14478 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14479 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14480 14481 // Because vperm has a big-endian bias, we must reverse the order 14482 // of the input vectors and complement the permute control vector 14483 // when generating little endian code. We have already handled the 14484 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14485 // and ExtraLoad here. 14486 SDValue Perm; 14487 if (isLittleEndian) 14488 Perm = BuildIntrinsicOp(IntrPerm, 14489 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14490 else 14491 Perm = BuildIntrinsicOp(IntrPerm, 14492 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14493 14494 if (VT != PermTy) 14495 Perm = Subtarget.hasAltivec() ? 14496 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14497 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14498 DAG.getTargetConstant(1, dl, MVT::i64)); 14499 // second argument is 1 because this rounding 14500 // is always exact. 14501 14502 // The output of the permutation is our loaded result, the TokenFactor is 14503 // our new chain. 14504 DCI.CombineTo(N, Perm, TF); 14505 return SDValue(N, 0); 14506 } 14507 } 14508 break; 14509 case ISD::INTRINSIC_WO_CHAIN: { 14510 bool isLittleEndian = Subtarget.isLittleEndian(); 14511 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14512 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14513 : Intrinsic::ppc_altivec_lvsl); 14514 if ((IID == Intr || 14515 IID == Intrinsic::ppc_qpx_qvlpcld || 14516 IID == Intrinsic::ppc_qpx_qvlpcls) && 14517 N->getOperand(1)->getOpcode() == ISD::ADD) { 14518 SDValue Add = N->getOperand(1); 14519 14520 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14521 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14522 14523 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14524 APInt::getAllOnesValue(Bits /* alignment */) 14525 .zext(Add.getScalarValueSizeInBits()))) { 14526 SDNode *BasePtr = Add->getOperand(0).getNode(); 14527 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14528 UE = BasePtr->use_end(); 14529 UI != UE; ++UI) { 14530 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14531 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14532 // We've found another LVSL/LVSR, and this address is an aligned 14533 // multiple of that one. The results will be the same, so use the 14534 // one we've just found instead. 14535 14536 return SDValue(*UI, 0); 14537 } 14538 } 14539 } 14540 14541 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14542 SDNode *BasePtr = Add->getOperand(0).getNode(); 14543 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14544 UE = BasePtr->use_end(); UI != UE; ++UI) { 14545 if (UI->getOpcode() == ISD::ADD && 14546 isa<ConstantSDNode>(UI->getOperand(1)) && 14547 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14548 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14549 (1ULL << Bits) == 0) { 14550 SDNode *OtherAdd = *UI; 14551 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14552 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14553 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14554 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14555 return SDValue(*VI, 0); 14556 } 14557 } 14558 } 14559 } 14560 } 14561 } 14562 14563 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14564 // Expose the vabsduw/h/b opportunity for down stream 14565 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14566 (IID == Intrinsic::ppc_altivec_vmaxsw || 14567 IID == Intrinsic::ppc_altivec_vmaxsh || 14568 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14569 SDValue V1 = N->getOperand(1); 14570 SDValue V2 = N->getOperand(2); 14571 if ((V1.getSimpleValueType() == MVT::v4i32 || 14572 V1.getSimpleValueType() == MVT::v8i16 || 14573 V1.getSimpleValueType() == MVT::v16i8) && 14574 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14575 // (0-a, a) 14576 if (V1.getOpcode() == ISD::SUB && 14577 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14578 V1.getOperand(1) == V2) { 14579 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14580 } 14581 // (a, 0-a) 14582 if (V2.getOpcode() == ISD::SUB && 14583 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14584 V2.getOperand(1) == V1) { 14585 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14586 } 14587 // (x-y, y-x) 14588 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14589 V1.getOperand(0) == V2.getOperand(1) && 14590 V1.getOperand(1) == V2.getOperand(0)) { 14591 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14592 } 14593 } 14594 } 14595 } 14596 14597 break; 14598 case ISD::INTRINSIC_W_CHAIN: 14599 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14600 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14601 if (Subtarget.needsSwapsForVSXMemOps()) { 14602 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14603 default: 14604 break; 14605 case Intrinsic::ppc_vsx_lxvw4x: 14606 case Intrinsic::ppc_vsx_lxvd2x: 14607 return expandVSXLoadForLE(N, DCI); 14608 } 14609 } 14610 break; 14611 case ISD::INTRINSIC_VOID: 14612 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14613 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14614 if (Subtarget.needsSwapsForVSXMemOps()) { 14615 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14616 default: 14617 break; 14618 case Intrinsic::ppc_vsx_stxvw4x: 14619 case Intrinsic::ppc_vsx_stxvd2x: 14620 return expandVSXStoreForLE(N, DCI); 14621 } 14622 } 14623 break; 14624 case ISD::BSWAP: 14625 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14626 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14627 N->getOperand(0).hasOneUse() && 14628 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14629 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14630 N->getValueType(0) == MVT::i64))) { 14631 SDValue Load = N->getOperand(0); 14632 LoadSDNode *LD = cast<LoadSDNode>(Load); 14633 // Create the byte-swapping load. 14634 SDValue Ops[] = { 14635 LD->getChain(), // Chain 14636 LD->getBasePtr(), // Ptr 14637 DAG.getValueType(N->getValueType(0)) // VT 14638 }; 14639 SDValue BSLoad = 14640 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14641 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14642 MVT::i64 : MVT::i32, MVT::Other), 14643 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14644 14645 // If this is an i16 load, insert the truncate. 14646 SDValue ResVal = BSLoad; 14647 if (N->getValueType(0) == MVT::i16) 14648 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14649 14650 // First, combine the bswap away. This makes the value produced by the 14651 // load dead. 14652 DCI.CombineTo(N, ResVal); 14653 14654 // Next, combine the load away, we give it a bogus result value but a real 14655 // chain result. The result value is dead because the bswap is dead. 14656 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14657 14658 // Return N so it doesn't get rechecked! 14659 return SDValue(N, 0); 14660 } 14661 break; 14662 case PPCISD::VCMP: 14663 // If a VCMPo node already exists with exactly the same operands as this 14664 // node, use its result instead of this node (VCMPo computes both a CR6 and 14665 // a normal output). 14666 // 14667 if (!N->getOperand(0).hasOneUse() && 14668 !N->getOperand(1).hasOneUse() && 14669 !N->getOperand(2).hasOneUse()) { 14670 14671 // Scan all of the users of the LHS, looking for VCMPo's that match. 14672 SDNode *VCMPoNode = nullptr; 14673 14674 SDNode *LHSN = N->getOperand(0).getNode(); 14675 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14676 UI != E; ++UI) 14677 if (UI->getOpcode() == PPCISD::VCMPo && 14678 UI->getOperand(1) == N->getOperand(1) && 14679 UI->getOperand(2) == N->getOperand(2) && 14680 UI->getOperand(0) == N->getOperand(0)) { 14681 VCMPoNode = *UI; 14682 break; 14683 } 14684 14685 // If there is no VCMPo node, or if the flag value has a single use, don't 14686 // transform this. 14687 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14688 break; 14689 14690 // Look at the (necessarily single) use of the flag value. If it has a 14691 // chain, this transformation is more complex. Note that multiple things 14692 // could use the value result, which we should ignore. 14693 SDNode *FlagUser = nullptr; 14694 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14695 FlagUser == nullptr; ++UI) { 14696 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14697 SDNode *User = *UI; 14698 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14699 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14700 FlagUser = User; 14701 break; 14702 } 14703 } 14704 } 14705 14706 // If the user is a MFOCRF instruction, we know this is safe. 14707 // Otherwise we give up for right now. 14708 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14709 return SDValue(VCMPoNode, 0); 14710 } 14711 break; 14712 case ISD::BRCOND: { 14713 SDValue Cond = N->getOperand(1); 14714 SDValue Target = N->getOperand(2); 14715 14716 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14717 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14718 Intrinsic::loop_decrement) { 14719 14720 // We now need to make the intrinsic dead (it cannot be instruction 14721 // selected). 14722 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14723 assert(Cond.getNode()->hasOneUse() && 14724 "Counter decrement has more than one use"); 14725 14726 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14727 N->getOperand(0), Target); 14728 } 14729 } 14730 break; 14731 case ISD::BR_CC: { 14732 // If this is a branch on an altivec predicate comparison, lower this so 14733 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14734 // lowering is done pre-legalize, because the legalizer lowers the predicate 14735 // compare down to code that is difficult to reassemble. 14736 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14737 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14738 14739 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14740 // value. If so, pass-through the AND to get to the intrinsic. 14741 if (LHS.getOpcode() == ISD::AND && 14742 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14743 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14744 Intrinsic::loop_decrement && 14745 isa<ConstantSDNode>(LHS.getOperand(1)) && 14746 !isNullConstant(LHS.getOperand(1))) 14747 LHS = LHS.getOperand(0); 14748 14749 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14750 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14751 Intrinsic::loop_decrement && 14752 isa<ConstantSDNode>(RHS)) { 14753 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14754 "Counter decrement comparison is not EQ or NE"); 14755 14756 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14757 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14758 (CC == ISD::SETNE && !Val); 14759 14760 // We now need to make the intrinsic dead (it cannot be instruction 14761 // selected). 14762 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14763 assert(LHS.getNode()->hasOneUse() && 14764 "Counter decrement has more than one use"); 14765 14766 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14767 N->getOperand(0), N->getOperand(4)); 14768 } 14769 14770 int CompareOpc; 14771 bool isDot; 14772 14773 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14774 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14775 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14776 assert(isDot && "Can't compare against a vector result!"); 14777 14778 // If this is a comparison against something other than 0/1, then we know 14779 // that the condition is never/always true. 14780 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14781 if (Val != 0 && Val != 1) { 14782 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14783 return N->getOperand(0); 14784 // Always !=, turn it into an unconditional branch. 14785 return DAG.getNode(ISD::BR, dl, MVT::Other, 14786 N->getOperand(0), N->getOperand(4)); 14787 } 14788 14789 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14790 14791 // Create the PPCISD altivec 'dot' comparison node. 14792 SDValue Ops[] = { 14793 LHS.getOperand(2), // LHS of compare 14794 LHS.getOperand(3), // RHS of compare 14795 DAG.getConstant(CompareOpc, dl, MVT::i32) 14796 }; 14797 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14798 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14799 14800 // Unpack the result based on how the target uses it. 14801 PPC::Predicate CompOpc; 14802 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14803 default: // Can't happen, don't crash on invalid number though. 14804 case 0: // Branch on the value of the EQ bit of CR6. 14805 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14806 break; 14807 case 1: // Branch on the inverted value of the EQ bit of CR6. 14808 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14809 break; 14810 case 2: // Branch on the value of the LT bit of CR6. 14811 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14812 break; 14813 case 3: // Branch on the inverted value of the LT bit of CR6. 14814 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14815 break; 14816 } 14817 14818 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14819 DAG.getConstant(CompOpc, dl, MVT::i32), 14820 DAG.getRegister(PPC::CR6, MVT::i32), 14821 N->getOperand(4), CompNode.getValue(1)); 14822 } 14823 break; 14824 } 14825 case ISD::BUILD_VECTOR: 14826 return DAGCombineBuildVector(N, DCI); 14827 case ISD::ABS: 14828 return combineABS(N, DCI); 14829 case ISD::VSELECT: 14830 return combineVSelect(N, DCI); 14831 } 14832 14833 return SDValue(); 14834 } 14835 14836 SDValue 14837 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14838 SelectionDAG &DAG, 14839 SmallVectorImpl<SDNode *> &Created) const { 14840 // fold (sdiv X, pow2) 14841 EVT VT = N->getValueType(0); 14842 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14843 return SDValue(); 14844 if ((VT != MVT::i32 && VT != MVT::i64) || 14845 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14846 return SDValue(); 14847 14848 SDLoc DL(N); 14849 SDValue N0 = N->getOperand(0); 14850 14851 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14852 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14853 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14854 14855 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14856 Created.push_back(Op.getNode()); 14857 14858 if (IsNegPow2) { 14859 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14860 Created.push_back(Op.getNode()); 14861 } 14862 14863 return Op; 14864 } 14865 14866 //===----------------------------------------------------------------------===// 14867 // Inline Assembly Support 14868 //===----------------------------------------------------------------------===// 14869 14870 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14871 KnownBits &Known, 14872 const APInt &DemandedElts, 14873 const SelectionDAG &DAG, 14874 unsigned Depth) const { 14875 Known.resetAll(); 14876 switch (Op.getOpcode()) { 14877 default: break; 14878 case PPCISD::LBRX: { 14879 // lhbrx is known to have the top bits cleared out. 14880 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14881 Known.Zero = 0xFFFF0000; 14882 break; 14883 } 14884 case ISD::INTRINSIC_WO_CHAIN: { 14885 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14886 default: break; 14887 case Intrinsic::ppc_altivec_vcmpbfp_p: 14888 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14889 case Intrinsic::ppc_altivec_vcmpequb_p: 14890 case Intrinsic::ppc_altivec_vcmpequh_p: 14891 case Intrinsic::ppc_altivec_vcmpequw_p: 14892 case Intrinsic::ppc_altivec_vcmpequd_p: 14893 case Intrinsic::ppc_altivec_vcmpgefp_p: 14894 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14895 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14896 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14897 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14898 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14899 case Intrinsic::ppc_altivec_vcmpgtub_p: 14900 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14901 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14902 case Intrinsic::ppc_altivec_vcmpgtud_p: 14903 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14904 break; 14905 } 14906 } 14907 } 14908 } 14909 14910 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14911 switch (Subtarget.getCPUDirective()) { 14912 default: break; 14913 case PPC::DIR_970: 14914 case PPC::DIR_PWR4: 14915 case PPC::DIR_PWR5: 14916 case PPC::DIR_PWR5X: 14917 case PPC::DIR_PWR6: 14918 case PPC::DIR_PWR6X: 14919 case PPC::DIR_PWR7: 14920 case PPC::DIR_PWR8: 14921 case PPC::DIR_PWR9: 14922 case PPC::DIR_PWR_FUTURE: { 14923 if (!ML) 14924 break; 14925 14926 if (!DisableInnermostLoopAlign32) { 14927 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14928 // so that we can decrease cache misses and branch-prediction misses. 14929 // Actual alignment of the loop will depend on the hotness check and other 14930 // logic in alignBlocks. 14931 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14932 return Align(32); 14933 } 14934 14935 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14936 14937 // For small loops (between 5 and 8 instructions), align to a 32-byte 14938 // boundary so that the entire loop fits in one instruction-cache line. 14939 uint64_t LoopSize = 0; 14940 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14941 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14942 LoopSize += TII->getInstSizeInBytes(*J); 14943 if (LoopSize > 32) 14944 break; 14945 } 14946 14947 if (LoopSize > 16 && LoopSize <= 32) 14948 return Align(32); 14949 14950 break; 14951 } 14952 } 14953 14954 return TargetLowering::getPrefLoopAlignment(ML); 14955 } 14956 14957 /// getConstraintType - Given a constraint, return the type of 14958 /// constraint it is for this target. 14959 PPCTargetLowering::ConstraintType 14960 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14961 if (Constraint.size() == 1) { 14962 switch (Constraint[0]) { 14963 default: break; 14964 case 'b': 14965 case 'r': 14966 case 'f': 14967 case 'd': 14968 case 'v': 14969 case 'y': 14970 return C_RegisterClass; 14971 case 'Z': 14972 // FIXME: While Z does indicate a memory constraint, it specifically 14973 // indicates an r+r address (used in conjunction with the 'y' modifier 14974 // in the replacement string). Currently, we're forcing the base 14975 // register to be r0 in the asm printer (which is interpreted as zero) 14976 // and forming the complete address in the second register. This is 14977 // suboptimal. 14978 return C_Memory; 14979 } 14980 } else if (Constraint == "wc") { // individual CR bits. 14981 return C_RegisterClass; 14982 } else if (Constraint == "wa" || Constraint == "wd" || 14983 Constraint == "wf" || Constraint == "ws" || 14984 Constraint == "wi" || Constraint == "ww") { 14985 return C_RegisterClass; // VSX registers. 14986 } 14987 return TargetLowering::getConstraintType(Constraint); 14988 } 14989 14990 /// Examine constraint type and operand type and determine a weight value. 14991 /// This object must already have been set up with the operand type 14992 /// and the current alternative constraint selected. 14993 TargetLowering::ConstraintWeight 14994 PPCTargetLowering::getSingleConstraintMatchWeight( 14995 AsmOperandInfo &info, const char *constraint) const { 14996 ConstraintWeight weight = CW_Invalid; 14997 Value *CallOperandVal = info.CallOperandVal; 14998 // If we don't have a value, we can't do a match, 14999 // but allow it at the lowest weight. 15000 if (!CallOperandVal) 15001 return CW_Default; 15002 Type *type = CallOperandVal->getType(); 15003 15004 // Look at the constraint type. 15005 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15006 return CW_Register; // an individual CR bit. 15007 else if ((StringRef(constraint) == "wa" || 15008 StringRef(constraint) == "wd" || 15009 StringRef(constraint) == "wf") && 15010 type->isVectorTy()) 15011 return CW_Register; 15012 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15013 return CW_Register; // just hold 64-bit integers data. 15014 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15015 return CW_Register; 15016 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15017 return CW_Register; 15018 15019 switch (*constraint) { 15020 default: 15021 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15022 break; 15023 case 'b': 15024 if (type->isIntegerTy()) 15025 weight = CW_Register; 15026 break; 15027 case 'f': 15028 if (type->isFloatTy()) 15029 weight = CW_Register; 15030 break; 15031 case 'd': 15032 if (type->isDoubleTy()) 15033 weight = CW_Register; 15034 break; 15035 case 'v': 15036 if (type->isVectorTy()) 15037 weight = CW_Register; 15038 break; 15039 case 'y': 15040 weight = CW_Register; 15041 break; 15042 case 'Z': 15043 weight = CW_Memory; 15044 break; 15045 } 15046 return weight; 15047 } 15048 15049 std::pair<unsigned, const TargetRegisterClass *> 15050 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15051 StringRef Constraint, 15052 MVT VT) const { 15053 if (Constraint.size() == 1) { 15054 // GCC RS6000 Constraint Letters 15055 switch (Constraint[0]) { 15056 case 'b': // R1-R31 15057 if (VT == MVT::i64 && Subtarget.isPPC64()) 15058 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15059 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15060 case 'r': // R0-R31 15061 if (VT == MVT::i64 && Subtarget.isPPC64()) 15062 return std::make_pair(0U, &PPC::G8RCRegClass); 15063 return std::make_pair(0U, &PPC::GPRCRegClass); 15064 // 'd' and 'f' constraints are both defined to be "the floating point 15065 // registers", where one is for 32-bit and the other for 64-bit. We don't 15066 // really care overly much here so just give them all the same reg classes. 15067 case 'd': 15068 case 'f': 15069 if (Subtarget.hasSPE()) { 15070 if (VT == MVT::f32 || VT == MVT::i32) 15071 return std::make_pair(0U, &PPC::GPRCRegClass); 15072 if (VT == MVT::f64 || VT == MVT::i64) 15073 return std::make_pair(0U, &PPC::SPERCRegClass); 15074 } else { 15075 if (VT == MVT::f32 || VT == MVT::i32) 15076 return std::make_pair(0U, &PPC::F4RCRegClass); 15077 if (VT == MVT::f64 || VT == MVT::i64) 15078 return std::make_pair(0U, &PPC::F8RCRegClass); 15079 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15080 return std::make_pair(0U, &PPC::QFRCRegClass); 15081 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15082 return std::make_pair(0U, &PPC::QSRCRegClass); 15083 } 15084 break; 15085 case 'v': 15086 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15087 return std::make_pair(0U, &PPC::QFRCRegClass); 15088 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15089 return std::make_pair(0U, &PPC::QSRCRegClass); 15090 if (Subtarget.hasAltivec()) 15091 return std::make_pair(0U, &PPC::VRRCRegClass); 15092 break; 15093 case 'y': // crrc 15094 return std::make_pair(0U, &PPC::CRRCRegClass); 15095 } 15096 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15097 // An individual CR bit. 15098 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15099 } else if ((Constraint == "wa" || Constraint == "wd" || 15100 Constraint == "wf" || Constraint == "wi") && 15101 Subtarget.hasVSX()) { 15102 return std::make_pair(0U, &PPC::VSRCRegClass); 15103 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15104 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15105 return std::make_pair(0U, &PPC::VSSRCRegClass); 15106 else 15107 return std::make_pair(0U, &PPC::VSFRCRegClass); 15108 } 15109 15110 // If we name a VSX register, we can't defer to the base class because it 15111 // will not recognize the correct register (their names will be VSL{0-31} 15112 // and V{0-31} so they won't match). So we match them here. 15113 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15114 int VSNum = atoi(Constraint.data() + 3); 15115 assert(VSNum >= 0 && VSNum <= 63 && 15116 "Attempted to access a vsr out of range"); 15117 if (VSNum < 32) 15118 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15119 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15120 } 15121 std::pair<unsigned, const TargetRegisterClass *> R = 15122 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15123 15124 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15125 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15126 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15127 // register. 15128 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15129 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15130 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15131 PPC::GPRCRegClass.contains(R.first)) 15132 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15133 PPC::sub_32, &PPC::G8RCRegClass), 15134 &PPC::G8RCRegClass); 15135 15136 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15137 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15138 R.first = PPC::CR0; 15139 R.second = &PPC::CRRCRegClass; 15140 } 15141 15142 return R; 15143 } 15144 15145 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15146 /// vector. If it is invalid, don't add anything to Ops. 15147 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15148 std::string &Constraint, 15149 std::vector<SDValue>&Ops, 15150 SelectionDAG &DAG) const { 15151 SDValue Result; 15152 15153 // Only support length 1 constraints. 15154 if (Constraint.length() > 1) return; 15155 15156 char Letter = Constraint[0]; 15157 switch (Letter) { 15158 default: break; 15159 case 'I': 15160 case 'J': 15161 case 'K': 15162 case 'L': 15163 case 'M': 15164 case 'N': 15165 case 'O': 15166 case 'P': { 15167 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15168 if (!CST) return; // Must be an immediate to match. 15169 SDLoc dl(Op); 15170 int64_t Value = CST->getSExtValue(); 15171 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15172 // numbers are printed as such. 15173 switch (Letter) { 15174 default: llvm_unreachable("Unknown constraint letter!"); 15175 case 'I': // "I" is a signed 16-bit constant. 15176 if (isInt<16>(Value)) 15177 Result = DAG.getTargetConstant(Value, dl, TCVT); 15178 break; 15179 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15180 if (isShiftedUInt<16, 16>(Value)) 15181 Result = DAG.getTargetConstant(Value, dl, TCVT); 15182 break; 15183 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15184 if (isShiftedInt<16, 16>(Value)) 15185 Result = DAG.getTargetConstant(Value, dl, TCVT); 15186 break; 15187 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15188 if (isUInt<16>(Value)) 15189 Result = DAG.getTargetConstant(Value, dl, TCVT); 15190 break; 15191 case 'M': // "M" is a constant that is greater than 31. 15192 if (Value > 31) 15193 Result = DAG.getTargetConstant(Value, dl, TCVT); 15194 break; 15195 case 'N': // "N" is a positive constant that is an exact power of two. 15196 if (Value > 0 && isPowerOf2_64(Value)) 15197 Result = DAG.getTargetConstant(Value, dl, TCVT); 15198 break; 15199 case 'O': // "O" is the constant zero. 15200 if (Value == 0) 15201 Result = DAG.getTargetConstant(Value, dl, TCVT); 15202 break; 15203 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15204 if (isInt<16>(-Value)) 15205 Result = DAG.getTargetConstant(Value, dl, TCVT); 15206 break; 15207 } 15208 break; 15209 } 15210 } 15211 15212 if (Result.getNode()) { 15213 Ops.push_back(Result); 15214 return; 15215 } 15216 15217 // Handle standard constraint letters. 15218 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15219 } 15220 15221 // isLegalAddressingMode - Return true if the addressing mode represented 15222 // by AM is legal for this target, for a load/store of the specified type. 15223 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15224 const AddrMode &AM, Type *Ty, 15225 unsigned AS, Instruction *I) const { 15226 // PPC does not allow r+i addressing modes for vectors! 15227 if (Ty->isVectorTy() && AM.BaseOffs != 0) 15228 return false; 15229 15230 // PPC allows a sign-extended 16-bit immediate field. 15231 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15232 return false; 15233 15234 // No global is ever allowed as a base. 15235 if (AM.BaseGV) 15236 return false; 15237 15238 // PPC only support r+r, 15239 switch (AM.Scale) { 15240 case 0: // "r+i" or just "i", depending on HasBaseReg. 15241 break; 15242 case 1: 15243 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15244 return false; 15245 // Otherwise we have r+r or r+i. 15246 break; 15247 case 2: 15248 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15249 return false; 15250 // Allow 2*r as r+r. 15251 break; 15252 default: 15253 // No other scales are supported. 15254 return false; 15255 } 15256 15257 return true; 15258 } 15259 15260 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15261 SelectionDAG &DAG) const { 15262 MachineFunction &MF = DAG.getMachineFunction(); 15263 MachineFrameInfo &MFI = MF.getFrameInfo(); 15264 MFI.setReturnAddressIsTaken(true); 15265 15266 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15267 return SDValue(); 15268 15269 SDLoc dl(Op); 15270 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15271 15272 // Make sure the function does not optimize away the store of the RA to 15273 // the stack. 15274 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15275 FuncInfo->setLRStoreRequired(); 15276 bool isPPC64 = Subtarget.isPPC64(); 15277 auto PtrVT = getPointerTy(MF.getDataLayout()); 15278 15279 if (Depth > 0) { 15280 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15281 SDValue Offset = 15282 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15283 isPPC64 ? MVT::i64 : MVT::i32); 15284 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15285 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15286 MachinePointerInfo()); 15287 } 15288 15289 // Just load the return address off the stack. 15290 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15291 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15292 MachinePointerInfo()); 15293 } 15294 15295 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15296 SelectionDAG &DAG) const { 15297 SDLoc dl(Op); 15298 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15299 15300 MachineFunction &MF = DAG.getMachineFunction(); 15301 MachineFrameInfo &MFI = MF.getFrameInfo(); 15302 MFI.setFrameAddressIsTaken(true); 15303 15304 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15305 bool isPPC64 = PtrVT == MVT::i64; 15306 15307 // Naked functions never have a frame pointer, and so we use r1. For all 15308 // other functions, this decision must be delayed until during PEI. 15309 unsigned FrameReg; 15310 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15311 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15312 else 15313 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15314 15315 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15316 PtrVT); 15317 while (Depth--) 15318 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15319 FrameAddr, MachinePointerInfo()); 15320 return FrameAddr; 15321 } 15322 15323 // FIXME? Maybe this could be a TableGen attribute on some registers and 15324 // this table could be generated automatically from RegInfo. 15325 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15326 const MachineFunction &MF) const { 15327 bool isPPC64 = Subtarget.isPPC64(); 15328 15329 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15330 if (!is64Bit && VT != LLT::scalar(32)) 15331 report_fatal_error("Invalid register global variable type"); 15332 15333 Register Reg = StringSwitch<Register>(RegName) 15334 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15335 .Case("r2", isPPC64 ? Register() : PPC::R2) 15336 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15337 .Default(Register()); 15338 15339 if (Reg) 15340 return Reg; 15341 report_fatal_error("Invalid register name global variable"); 15342 } 15343 15344 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15345 // 32-bit SVR4 ABI access everything as got-indirect. 15346 if (Subtarget.is32BitELFABI()) 15347 return true; 15348 15349 // AIX accesses everything indirectly through the TOC, which is similar to 15350 // the GOT. 15351 if (Subtarget.isAIXABI()) 15352 return true; 15353 15354 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15355 // If it is small or large code model, module locals are accessed 15356 // indirectly by loading their address from .toc/.got. 15357 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15358 return true; 15359 15360 // JumpTable and BlockAddress are accessed as got-indirect. 15361 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15362 return true; 15363 15364 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15365 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15366 15367 return false; 15368 } 15369 15370 bool 15371 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15372 // The PowerPC target isn't yet aware of offsets. 15373 return false; 15374 } 15375 15376 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15377 const CallInst &I, 15378 MachineFunction &MF, 15379 unsigned Intrinsic) const { 15380 switch (Intrinsic) { 15381 case Intrinsic::ppc_qpx_qvlfd: 15382 case Intrinsic::ppc_qpx_qvlfs: 15383 case Intrinsic::ppc_qpx_qvlfcd: 15384 case Intrinsic::ppc_qpx_qvlfcs: 15385 case Intrinsic::ppc_qpx_qvlfiwa: 15386 case Intrinsic::ppc_qpx_qvlfiwz: 15387 case Intrinsic::ppc_altivec_lvx: 15388 case Intrinsic::ppc_altivec_lvxl: 15389 case Intrinsic::ppc_altivec_lvebx: 15390 case Intrinsic::ppc_altivec_lvehx: 15391 case Intrinsic::ppc_altivec_lvewx: 15392 case Intrinsic::ppc_vsx_lxvd2x: 15393 case Intrinsic::ppc_vsx_lxvw4x: { 15394 EVT VT; 15395 switch (Intrinsic) { 15396 case Intrinsic::ppc_altivec_lvebx: 15397 VT = MVT::i8; 15398 break; 15399 case Intrinsic::ppc_altivec_lvehx: 15400 VT = MVT::i16; 15401 break; 15402 case Intrinsic::ppc_altivec_lvewx: 15403 VT = MVT::i32; 15404 break; 15405 case Intrinsic::ppc_vsx_lxvd2x: 15406 VT = MVT::v2f64; 15407 break; 15408 case Intrinsic::ppc_qpx_qvlfd: 15409 VT = MVT::v4f64; 15410 break; 15411 case Intrinsic::ppc_qpx_qvlfs: 15412 VT = MVT::v4f32; 15413 break; 15414 case Intrinsic::ppc_qpx_qvlfcd: 15415 VT = MVT::v2f64; 15416 break; 15417 case Intrinsic::ppc_qpx_qvlfcs: 15418 VT = MVT::v2f32; 15419 break; 15420 default: 15421 VT = MVT::v4i32; 15422 break; 15423 } 15424 15425 Info.opc = ISD::INTRINSIC_W_CHAIN; 15426 Info.memVT = VT; 15427 Info.ptrVal = I.getArgOperand(0); 15428 Info.offset = -VT.getStoreSize()+1; 15429 Info.size = 2*VT.getStoreSize()-1; 15430 Info.align = Align(1); 15431 Info.flags = MachineMemOperand::MOLoad; 15432 return true; 15433 } 15434 case Intrinsic::ppc_qpx_qvlfda: 15435 case Intrinsic::ppc_qpx_qvlfsa: 15436 case Intrinsic::ppc_qpx_qvlfcda: 15437 case Intrinsic::ppc_qpx_qvlfcsa: 15438 case Intrinsic::ppc_qpx_qvlfiwaa: 15439 case Intrinsic::ppc_qpx_qvlfiwza: { 15440 EVT VT; 15441 switch (Intrinsic) { 15442 case Intrinsic::ppc_qpx_qvlfda: 15443 VT = MVT::v4f64; 15444 break; 15445 case Intrinsic::ppc_qpx_qvlfsa: 15446 VT = MVT::v4f32; 15447 break; 15448 case Intrinsic::ppc_qpx_qvlfcda: 15449 VT = MVT::v2f64; 15450 break; 15451 case Intrinsic::ppc_qpx_qvlfcsa: 15452 VT = MVT::v2f32; 15453 break; 15454 default: 15455 VT = MVT::v4i32; 15456 break; 15457 } 15458 15459 Info.opc = ISD::INTRINSIC_W_CHAIN; 15460 Info.memVT = VT; 15461 Info.ptrVal = I.getArgOperand(0); 15462 Info.offset = 0; 15463 Info.size = VT.getStoreSize(); 15464 Info.align = Align(1); 15465 Info.flags = MachineMemOperand::MOLoad; 15466 return true; 15467 } 15468 case Intrinsic::ppc_qpx_qvstfd: 15469 case Intrinsic::ppc_qpx_qvstfs: 15470 case Intrinsic::ppc_qpx_qvstfcd: 15471 case Intrinsic::ppc_qpx_qvstfcs: 15472 case Intrinsic::ppc_qpx_qvstfiw: 15473 case Intrinsic::ppc_altivec_stvx: 15474 case Intrinsic::ppc_altivec_stvxl: 15475 case Intrinsic::ppc_altivec_stvebx: 15476 case Intrinsic::ppc_altivec_stvehx: 15477 case Intrinsic::ppc_altivec_stvewx: 15478 case Intrinsic::ppc_vsx_stxvd2x: 15479 case Intrinsic::ppc_vsx_stxvw4x: { 15480 EVT VT; 15481 switch (Intrinsic) { 15482 case Intrinsic::ppc_altivec_stvebx: 15483 VT = MVT::i8; 15484 break; 15485 case Intrinsic::ppc_altivec_stvehx: 15486 VT = MVT::i16; 15487 break; 15488 case Intrinsic::ppc_altivec_stvewx: 15489 VT = MVT::i32; 15490 break; 15491 case Intrinsic::ppc_vsx_stxvd2x: 15492 VT = MVT::v2f64; 15493 break; 15494 case Intrinsic::ppc_qpx_qvstfd: 15495 VT = MVT::v4f64; 15496 break; 15497 case Intrinsic::ppc_qpx_qvstfs: 15498 VT = MVT::v4f32; 15499 break; 15500 case Intrinsic::ppc_qpx_qvstfcd: 15501 VT = MVT::v2f64; 15502 break; 15503 case Intrinsic::ppc_qpx_qvstfcs: 15504 VT = MVT::v2f32; 15505 break; 15506 default: 15507 VT = MVT::v4i32; 15508 break; 15509 } 15510 15511 Info.opc = ISD::INTRINSIC_VOID; 15512 Info.memVT = VT; 15513 Info.ptrVal = I.getArgOperand(1); 15514 Info.offset = -VT.getStoreSize()+1; 15515 Info.size = 2*VT.getStoreSize()-1; 15516 Info.align = Align(1); 15517 Info.flags = MachineMemOperand::MOStore; 15518 return true; 15519 } 15520 case Intrinsic::ppc_qpx_qvstfda: 15521 case Intrinsic::ppc_qpx_qvstfsa: 15522 case Intrinsic::ppc_qpx_qvstfcda: 15523 case Intrinsic::ppc_qpx_qvstfcsa: 15524 case Intrinsic::ppc_qpx_qvstfiwa: { 15525 EVT VT; 15526 switch (Intrinsic) { 15527 case Intrinsic::ppc_qpx_qvstfda: 15528 VT = MVT::v4f64; 15529 break; 15530 case Intrinsic::ppc_qpx_qvstfsa: 15531 VT = MVT::v4f32; 15532 break; 15533 case Intrinsic::ppc_qpx_qvstfcda: 15534 VT = MVT::v2f64; 15535 break; 15536 case Intrinsic::ppc_qpx_qvstfcsa: 15537 VT = MVT::v2f32; 15538 break; 15539 default: 15540 VT = MVT::v4i32; 15541 break; 15542 } 15543 15544 Info.opc = ISD::INTRINSIC_VOID; 15545 Info.memVT = VT; 15546 Info.ptrVal = I.getArgOperand(1); 15547 Info.offset = 0; 15548 Info.size = VT.getStoreSize(); 15549 Info.align = Align(1); 15550 Info.flags = MachineMemOperand::MOStore; 15551 return true; 15552 } 15553 default: 15554 break; 15555 } 15556 15557 return false; 15558 } 15559 15560 /// It returns EVT::Other if the type should be determined using generic 15561 /// target-independent logic. 15562 EVT PPCTargetLowering::getOptimalMemOpType( 15563 const MemOp &Op, const AttributeList &FuncAttributes) const { 15564 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15565 // When expanding a memset, require at least two QPX instructions to cover 15566 // the cost of loading the value to be stored from the constant pool. 15567 if (Subtarget.hasQPX() && Op.size() >= 32 && 15568 (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) && 15569 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15570 return MVT::v4f64; 15571 } 15572 15573 // We should use Altivec/VSX loads and stores when available. For unaligned 15574 // addresses, unaligned VSX loads are only fast starting with the P8. 15575 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15576 (Op.isAligned(Align(16)) || 15577 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15578 return MVT::v4i32; 15579 } 15580 15581 if (Subtarget.isPPC64()) { 15582 return MVT::i64; 15583 } 15584 15585 return MVT::i32; 15586 } 15587 15588 /// Returns true if it is beneficial to convert a load of a constant 15589 /// to just the constant itself. 15590 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15591 Type *Ty) const { 15592 assert(Ty->isIntegerTy()); 15593 15594 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15595 return !(BitSize == 0 || BitSize > 64); 15596 } 15597 15598 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15599 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15600 return false; 15601 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15602 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15603 return NumBits1 == 64 && NumBits2 == 32; 15604 } 15605 15606 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15607 if (!VT1.isInteger() || !VT2.isInteger()) 15608 return false; 15609 unsigned NumBits1 = VT1.getSizeInBits(); 15610 unsigned NumBits2 = VT2.getSizeInBits(); 15611 return NumBits1 == 64 && NumBits2 == 32; 15612 } 15613 15614 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15615 // Generally speaking, zexts are not free, but they are free when they can be 15616 // folded with other operations. 15617 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15618 EVT MemVT = LD->getMemoryVT(); 15619 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15620 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15621 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15622 LD->getExtensionType() == ISD::ZEXTLOAD)) 15623 return true; 15624 } 15625 15626 // FIXME: Add other cases... 15627 // - 32-bit shifts with a zext to i64 15628 // - zext after ctlz, bswap, etc. 15629 // - zext after and by a constant mask 15630 15631 return TargetLowering::isZExtFree(Val, VT2); 15632 } 15633 15634 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15635 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15636 "invalid fpext types"); 15637 // Extending to float128 is not free. 15638 if (DestVT == MVT::f128) 15639 return false; 15640 return true; 15641 } 15642 15643 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15644 return isInt<16>(Imm) || isUInt<16>(Imm); 15645 } 15646 15647 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15648 return isInt<16>(Imm) || isUInt<16>(Imm); 15649 } 15650 15651 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15652 unsigned, 15653 unsigned, 15654 MachineMemOperand::Flags, 15655 bool *Fast) const { 15656 if (DisablePPCUnaligned) 15657 return false; 15658 15659 // PowerPC supports unaligned memory access for simple non-vector types. 15660 // Although accessing unaligned addresses is not as efficient as accessing 15661 // aligned addresses, it is generally more efficient than manual expansion, 15662 // and generally only traps for software emulation when crossing page 15663 // boundaries. 15664 15665 if (!VT.isSimple()) 15666 return false; 15667 15668 if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess()) 15669 return false; 15670 15671 if (VT.getSimpleVT().isVector()) { 15672 if (Subtarget.hasVSX()) { 15673 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15674 VT != MVT::v4f32 && VT != MVT::v4i32) 15675 return false; 15676 } else { 15677 return false; 15678 } 15679 } 15680 15681 if (VT == MVT::ppcf128) 15682 return false; 15683 15684 if (Fast) 15685 *Fast = true; 15686 15687 return true; 15688 } 15689 15690 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15691 EVT VT) const { 15692 return isFMAFasterThanFMulAndFAdd( 15693 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15694 } 15695 15696 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15697 Type *Ty) const { 15698 switch (Ty->getScalarType()->getTypeID()) { 15699 case Type::FloatTyID: 15700 case Type::DoubleTyID: 15701 return true; 15702 case Type::FP128TyID: 15703 return EnableQuadPrecision && Subtarget.hasP9Vector(); 15704 default: 15705 return false; 15706 } 15707 } 15708 15709 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist. 15710 // FIXME: add more patterns which are profitable to hoist. 15711 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15712 if (I->getOpcode() != Instruction::FMul) 15713 return true; 15714 15715 if (!I->hasOneUse()) 15716 return true; 15717 15718 Instruction *User = I->user_back(); 15719 assert(User && "A single use instruction with no uses."); 15720 15721 if (User->getOpcode() != Instruction::FSub && 15722 User->getOpcode() != Instruction::FAdd) 15723 return true; 15724 15725 const TargetOptions &Options = getTargetMachine().Options; 15726 const Function *F = I->getFunction(); 15727 const DataLayout &DL = F->getParent()->getDataLayout(); 15728 Type *Ty = User->getOperand(0)->getType(); 15729 15730 return !( 15731 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15732 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15733 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15734 } 15735 15736 const MCPhysReg * 15737 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15738 // LR is a callee-save register, but we must treat it as clobbered by any call 15739 // site. Hence we include LR in the scratch registers, which are in turn added 15740 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15741 // to CTR, which is used by any indirect call. 15742 static const MCPhysReg ScratchRegs[] = { 15743 PPC::X12, PPC::LR8, PPC::CTR8, 0 15744 }; 15745 15746 return ScratchRegs; 15747 } 15748 15749 Register PPCTargetLowering::getExceptionPointerRegister( 15750 const Constant *PersonalityFn) const { 15751 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15752 } 15753 15754 Register PPCTargetLowering::getExceptionSelectorRegister( 15755 const Constant *PersonalityFn) const { 15756 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15757 } 15758 15759 bool 15760 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15761 EVT VT , unsigned DefinedValues) const { 15762 if (VT == MVT::v2i64) 15763 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15764 15765 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15766 return true; 15767 15768 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15769 } 15770 15771 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15772 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15773 return TargetLowering::getSchedulingPreference(N); 15774 15775 return Sched::ILP; 15776 } 15777 15778 // Create a fast isel object. 15779 FastISel * 15780 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15781 const TargetLibraryInfo *LibInfo) const { 15782 return PPC::createFastISel(FuncInfo, LibInfo); 15783 } 15784 15785 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15786 if (!Subtarget.isPPC64()) return; 15787 15788 // Update IsSplitCSR in PPCFunctionInfo 15789 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 15790 PFI->setIsSplitCSR(true); 15791 } 15792 15793 void PPCTargetLowering::insertCopiesSplitCSR( 15794 MachineBasicBlock *Entry, 15795 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15796 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 15797 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15798 if (!IStart) 15799 return; 15800 15801 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 15802 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15803 MachineBasicBlock::iterator MBBI = Entry->begin(); 15804 for (const MCPhysReg *I = IStart; *I; ++I) { 15805 const TargetRegisterClass *RC = nullptr; 15806 if (PPC::G8RCRegClass.contains(*I)) 15807 RC = &PPC::G8RCRegClass; 15808 else if (PPC::F8RCRegClass.contains(*I)) 15809 RC = &PPC::F8RCRegClass; 15810 else if (PPC::CRRCRegClass.contains(*I)) 15811 RC = &PPC::CRRCRegClass; 15812 else if (PPC::VRRCRegClass.contains(*I)) 15813 RC = &PPC::VRRCRegClass; 15814 else 15815 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15816 15817 Register NewVR = MRI->createVirtualRegister(RC); 15818 // Create copy from CSR to a virtual register. 15819 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15820 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15821 // nounwind. If we want to generalize this later, we may need to emit 15822 // CFI pseudo-instructions. 15823 assert(Entry->getParent()->getFunction().hasFnAttribute( 15824 Attribute::NoUnwind) && 15825 "Function should be nounwind in insertCopiesSplitCSR!"); 15826 Entry->addLiveIn(*I); 15827 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15828 .addReg(*I); 15829 15830 // Insert the copy-back instructions right before the terminator. 15831 for (auto *Exit : Exits) 15832 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15833 TII->get(TargetOpcode::COPY), *I) 15834 .addReg(NewVR); 15835 } 15836 } 15837 15838 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15839 bool PPCTargetLowering::useLoadStackGuardNode() const { 15840 if (!Subtarget.isTargetLinux()) 15841 return TargetLowering::useLoadStackGuardNode(); 15842 return true; 15843 } 15844 15845 // Override to disable global variable loading on Linux. 15846 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15847 if (!Subtarget.isTargetLinux()) 15848 return TargetLowering::insertSSPDeclarations(M); 15849 } 15850 15851 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15852 bool ForCodeSize) const { 15853 if (!VT.isSimple() || !Subtarget.hasVSX()) 15854 return false; 15855 15856 switch(VT.getSimpleVT().SimpleTy) { 15857 default: 15858 // For FP types that are currently not supported by PPC backend, return 15859 // false. Examples: f16, f80. 15860 return false; 15861 case MVT::f32: 15862 case MVT::f64: 15863 case MVT::ppcf128: 15864 return Imm.isPosZero(); 15865 } 15866 } 15867 15868 // For vector shift operation op, fold 15869 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15870 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15871 SelectionDAG &DAG) { 15872 SDValue N0 = N->getOperand(0); 15873 SDValue N1 = N->getOperand(1); 15874 EVT VT = N0.getValueType(); 15875 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15876 unsigned Opcode = N->getOpcode(); 15877 unsigned TargetOpcode; 15878 15879 switch (Opcode) { 15880 default: 15881 llvm_unreachable("Unexpected shift operation"); 15882 case ISD::SHL: 15883 TargetOpcode = PPCISD::SHL; 15884 break; 15885 case ISD::SRL: 15886 TargetOpcode = PPCISD::SRL; 15887 break; 15888 case ISD::SRA: 15889 TargetOpcode = PPCISD::SRA; 15890 break; 15891 } 15892 15893 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15894 N1->getOpcode() == ISD::AND) 15895 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15896 if (Mask->getZExtValue() == OpSizeInBits - 1) 15897 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15898 15899 return SDValue(); 15900 } 15901 15902 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15903 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15904 return Value; 15905 15906 SDValue N0 = N->getOperand(0); 15907 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15908 if (!Subtarget.isISA3_0() || 15909 N0.getOpcode() != ISD::SIGN_EXTEND || 15910 N0.getOperand(0).getValueType() != MVT::i32 || 15911 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15912 return SDValue(); 15913 15914 // We can't save an operation here if the value is already extended, and 15915 // the existing shift is easier to combine. 15916 SDValue ExtsSrc = N0.getOperand(0); 15917 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15918 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15919 return SDValue(); 15920 15921 SDLoc DL(N0); 15922 SDValue ShiftBy = SDValue(CN1, 0); 15923 // We want the shift amount to be i32 on the extswli, but the shift could 15924 // have an i64. 15925 if (ShiftBy.getValueType() == MVT::i64) 15926 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15927 15928 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15929 ShiftBy); 15930 } 15931 15932 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15933 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15934 return Value; 15935 15936 return SDValue(); 15937 } 15938 15939 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15940 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15941 return Value; 15942 15943 return SDValue(); 15944 } 15945 15946 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15947 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15948 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15949 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15950 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15951 const PPCSubtarget &Subtarget) { 15952 if (!Subtarget.isPPC64()) 15953 return SDValue(); 15954 15955 SDValue LHS = N->getOperand(0); 15956 SDValue RHS = N->getOperand(1); 15957 15958 auto isZextOfCompareWithConstant = [](SDValue Op) { 15959 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15960 Op.getValueType() != MVT::i64) 15961 return false; 15962 15963 SDValue Cmp = Op.getOperand(0); 15964 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15965 Cmp.getOperand(0).getValueType() != MVT::i64) 15966 return false; 15967 15968 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15969 int64_t NegConstant = 0 - Constant->getSExtValue(); 15970 // Due to the limitations of the addi instruction, 15971 // -C is required to be [-32768, 32767]. 15972 return isInt<16>(NegConstant); 15973 } 15974 15975 return false; 15976 }; 15977 15978 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15979 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15980 15981 // If there is a pattern, canonicalize a zext operand to the RHS. 15982 if (LHSHasPattern && !RHSHasPattern) 15983 std::swap(LHS, RHS); 15984 else if (!LHSHasPattern && !RHSHasPattern) 15985 return SDValue(); 15986 15987 SDLoc DL(N); 15988 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15989 SDValue Cmp = RHS.getOperand(0); 15990 SDValue Z = Cmp.getOperand(0); 15991 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15992 15993 assert(Constant && "Constant Should not be a null pointer."); 15994 int64_t NegConstant = 0 - Constant->getSExtValue(); 15995 15996 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15997 default: break; 15998 case ISD::SETNE: { 15999 // when C == 0 16000 // --> addze X, (addic Z, -1).carry 16001 // / 16002 // add X, (zext(setne Z, C))-- 16003 // \ when -32768 <= -C <= 32767 && C != 0 16004 // --> addze X, (addic (addi Z, -C), -1).carry 16005 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16006 DAG.getConstant(NegConstant, DL, MVT::i64)); 16007 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16008 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16009 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16010 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16011 SDValue(Addc.getNode(), 1)); 16012 } 16013 case ISD::SETEQ: { 16014 // when C == 0 16015 // --> addze X, (subfic Z, 0).carry 16016 // / 16017 // add X, (zext(sete Z, C))-- 16018 // \ when -32768 <= -C <= 32767 && C != 0 16019 // --> addze X, (subfic (addi Z, -C), 0).carry 16020 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16021 DAG.getConstant(NegConstant, DL, MVT::i64)); 16022 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16023 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16024 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16025 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16026 SDValue(Subc.getNode(), 1)); 16027 } 16028 } 16029 16030 return SDValue(); 16031 } 16032 16033 // Transform 16034 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16035 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16036 // In this case both C1 and C2 must be known constants. 16037 // C1+C2 must fit into a 34 bit signed integer. 16038 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16039 const PPCSubtarget &Subtarget) { 16040 if (!Subtarget.isUsingPCRelativeCalls()) 16041 return SDValue(); 16042 16043 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16044 // If we find that node try to cast the Global Address and the Constant. 16045 SDValue LHS = N->getOperand(0); 16046 SDValue RHS = N->getOperand(1); 16047 16048 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16049 std::swap(LHS, RHS); 16050 16051 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16052 return SDValue(); 16053 16054 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16055 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16056 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16057 16058 // Check that both casts succeeded. 16059 if (!GSDN || !ConstNode) 16060 return SDValue(); 16061 16062 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16063 SDLoc DL(GSDN); 16064 16065 // The signed int offset needs to fit in 34 bits. 16066 if (!isInt<34>(NewOffset)) 16067 return SDValue(); 16068 16069 // The new global address is a copy of the old global address except 16070 // that it has the updated Offset. 16071 SDValue GA = 16072 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16073 NewOffset, GSDN->getTargetFlags()); 16074 SDValue MatPCRel = 16075 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16076 return MatPCRel; 16077 } 16078 16079 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16080 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16081 return Value; 16082 16083 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16084 return Value; 16085 16086 return SDValue(); 16087 } 16088 16089 // Detect TRUNCATE operations on bitcasts of float128 values. 16090 // What we are looking for here is the situtation where we extract a subset 16091 // of bits from a 128 bit float. 16092 // This can be of two forms: 16093 // 1) BITCAST of f128 feeding TRUNCATE 16094 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16095 // The reason this is required is because we do not have a legal i128 type 16096 // and so we want to prevent having to store the f128 and then reload part 16097 // of it. 16098 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16099 DAGCombinerInfo &DCI) const { 16100 // If we are using CRBits then try that first. 16101 if (Subtarget.useCRBits()) { 16102 // Check if CRBits did anything and return that if it did. 16103 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16104 return CRTruncValue; 16105 } 16106 16107 SDLoc dl(N); 16108 SDValue Op0 = N->getOperand(0); 16109 16110 // Looking for a truncate of i128 to i64. 16111 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16112 return SDValue(); 16113 16114 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16115 16116 // SRL feeding TRUNCATE. 16117 if (Op0.getOpcode() == ISD::SRL) { 16118 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16119 // The right shift has to be by 64 bits. 16120 if (!ConstNode || ConstNode->getZExtValue() != 64) 16121 return SDValue(); 16122 16123 // Switch the element number to extract. 16124 EltToExtract = EltToExtract ? 0 : 1; 16125 // Update Op0 past the SRL. 16126 Op0 = Op0.getOperand(0); 16127 } 16128 16129 // BITCAST feeding a TRUNCATE possibly via SRL. 16130 if (Op0.getOpcode() == ISD::BITCAST && 16131 Op0.getValueType() == MVT::i128 && 16132 Op0.getOperand(0).getValueType() == MVT::f128) { 16133 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16134 return DCI.DAG.getNode( 16135 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16136 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16137 } 16138 return SDValue(); 16139 } 16140 16141 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16142 SelectionDAG &DAG = DCI.DAG; 16143 16144 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16145 if (!ConstOpOrElement) 16146 return SDValue(); 16147 16148 // An imul is usually smaller than the alternative sequence for legal type. 16149 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16150 isOperationLegal(ISD::MUL, N->getValueType(0))) 16151 return SDValue(); 16152 16153 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16154 switch (this->Subtarget.getCPUDirective()) { 16155 default: 16156 // TODO: enhance the condition for subtarget before pwr8 16157 return false; 16158 case PPC::DIR_PWR8: 16159 // type mul add shl 16160 // scalar 4 1 1 16161 // vector 7 2 2 16162 return true; 16163 case PPC::DIR_PWR9: 16164 case PPC::DIR_PWR_FUTURE: 16165 // type mul add shl 16166 // scalar 5 2 2 16167 // vector 7 2 2 16168 16169 // The cycle RATIO of related operations are showed as a table above. 16170 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16171 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16172 // are 4, it is always profitable; but for 3 instrs patterns 16173 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16174 // So we should only do it for vector type. 16175 return IsAddOne && IsNeg ? VT.isVector() : true; 16176 } 16177 }; 16178 16179 EVT VT = N->getValueType(0); 16180 SDLoc DL(N); 16181 16182 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16183 bool IsNeg = MulAmt.isNegative(); 16184 APInt MulAmtAbs = MulAmt.abs(); 16185 16186 if ((MulAmtAbs - 1).isPowerOf2()) { 16187 // (mul x, 2^N + 1) => (add (shl x, N), x) 16188 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16189 16190 if (!IsProfitable(IsNeg, true, VT)) 16191 return SDValue(); 16192 16193 SDValue Op0 = N->getOperand(0); 16194 SDValue Op1 = 16195 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16196 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16197 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16198 16199 if (!IsNeg) 16200 return Res; 16201 16202 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16203 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16204 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16205 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16206 16207 if (!IsProfitable(IsNeg, false, VT)) 16208 return SDValue(); 16209 16210 SDValue Op0 = N->getOperand(0); 16211 SDValue Op1 = 16212 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16213 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16214 16215 if (!IsNeg) 16216 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16217 else 16218 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16219 16220 } else { 16221 return SDValue(); 16222 } 16223 } 16224 16225 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16226 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16227 if (!Subtarget.is64BitELFABI()) 16228 return false; 16229 16230 // If not a tail call then no need to proceed. 16231 if (!CI->isTailCall()) 16232 return false; 16233 16234 // If sibling calls have been disabled and tail-calls aren't guaranteed 16235 // there is no reason to duplicate. 16236 auto &TM = getTargetMachine(); 16237 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16238 return false; 16239 16240 // Can't tail call a function called indirectly, or if it has variadic args. 16241 const Function *Callee = CI->getCalledFunction(); 16242 if (!Callee || Callee->isVarArg()) 16243 return false; 16244 16245 // Make sure the callee and caller calling conventions are eligible for tco. 16246 const Function *Caller = CI->getParent()->getParent(); 16247 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16248 CI->getCallingConv())) 16249 return false; 16250 16251 // If the function is local then we have a good chance at tail-calling it 16252 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16253 } 16254 16255 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16256 if (!Subtarget.hasVSX()) 16257 return false; 16258 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16259 return true; 16260 return VT == MVT::f32 || VT == MVT::f64 || 16261 VT == MVT::v4f32 || VT == MVT::v2f64; 16262 } 16263 16264 bool PPCTargetLowering:: 16265 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16266 const Value *Mask = AndI.getOperand(1); 16267 // If the mask is suitable for andi. or andis. we should sink the and. 16268 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16269 // Can't handle constants wider than 64-bits. 16270 if (CI->getBitWidth() > 64) 16271 return false; 16272 int64_t ConstVal = CI->getZExtValue(); 16273 return isUInt<16>(ConstVal) || 16274 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16275 } 16276 16277 // For non-constant masks, we can always use the record-form and. 16278 return true; 16279 } 16280 16281 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16282 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16283 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16284 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16285 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16286 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16287 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16288 assert(Subtarget.hasP9Altivec() && 16289 "Only combine this when P9 altivec supported!"); 16290 EVT VT = N->getValueType(0); 16291 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16292 return SDValue(); 16293 16294 SelectionDAG &DAG = DCI.DAG; 16295 SDLoc dl(N); 16296 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16297 // Even for signed integers, if it's known to be positive (as signed 16298 // integer) due to zero-extended inputs. 16299 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16300 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16301 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16302 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16303 (SubOpcd1 == ISD::ZERO_EXTEND || 16304 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16305 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16306 N->getOperand(0)->getOperand(0), 16307 N->getOperand(0)->getOperand(1), 16308 DAG.getTargetConstant(0, dl, MVT::i32)); 16309 } 16310 16311 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16312 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16313 N->getOperand(0).hasOneUse()) { 16314 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16315 N->getOperand(0)->getOperand(0), 16316 N->getOperand(0)->getOperand(1), 16317 DAG.getTargetConstant(1, dl, MVT::i32)); 16318 } 16319 } 16320 16321 return SDValue(); 16322 } 16323 16324 // For type v4i32/v8ii16/v16i8, transform 16325 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16326 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16327 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16328 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16329 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16330 DAGCombinerInfo &DCI) const { 16331 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16332 assert(Subtarget.hasP9Altivec() && 16333 "Only combine this when P9 altivec supported!"); 16334 16335 SelectionDAG &DAG = DCI.DAG; 16336 SDLoc dl(N); 16337 SDValue Cond = N->getOperand(0); 16338 SDValue TrueOpnd = N->getOperand(1); 16339 SDValue FalseOpnd = N->getOperand(2); 16340 EVT VT = N->getOperand(1).getValueType(); 16341 16342 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16343 FalseOpnd.getOpcode() != ISD::SUB) 16344 return SDValue(); 16345 16346 // ABSD only available for type v4i32/v8i16/v16i8 16347 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16348 return SDValue(); 16349 16350 // At least to save one more dependent computation 16351 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16352 return SDValue(); 16353 16354 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16355 16356 // Can only handle unsigned comparison here 16357 switch (CC) { 16358 default: 16359 return SDValue(); 16360 case ISD::SETUGT: 16361 case ISD::SETUGE: 16362 break; 16363 case ISD::SETULT: 16364 case ISD::SETULE: 16365 std::swap(TrueOpnd, FalseOpnd); 16366 break; 16367 } 16368 16369 SDValue CmpOpnd1 = Cond.getOperand(0); 16370 SDValue CmpOpnd2 = Cond.getOperand(1); 16371 16372 // SETCC CmpOpnd1 CmpOpnd2 cond 16373 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16374 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16375 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16376 TrueOpnd.getOperand(1) == CmpOpnd2 && 16377 FalseOpnd.getOperand(0) == CmpOpnd2 && 16378 FalseOpnd.getOperand(1) == CmpOpnd1) { 16379 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16380 CmpOpnd1, CmpOpnd2, 16381 DAG.getTargetConstant(0, dl, MVT::i32)); 16382 } 16383 16384 return SDValue(); 16385 } 16386