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 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM"); 129 130 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 131 132 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 133 134 // FIXME: Remove this once the bug has been fixed! 135 extern cl::opt<bool> ANDIGlueBug; 136 137 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 138 const PPCSubtarget &STI) 139 : TargetLowering(TM), Subtarget(STI) { 140 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 141 // arguments are at least 4/8 bytes aligned. 142 bool isPPC64 = Subtarget.isPPC64(); 143 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 144 145 // Set up the register classes. 146 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 147 if (!useSoftFloat()) { 148 if (hasSPE()) { 149 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 150 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 151 } else { 152 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 153 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 154 } 155 } 156 157 // Match BITREVERSE to customized fast code sequence in the td file. 158 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 159 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 160 161 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 162 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 163 164 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 165 for (MVT VT : MVT::integer_valuetypes()) { 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 167 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 168 } 169 170 if (Subtarget.isISA3_0()) { 171 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 172 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 173 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 174 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 175 } else { 176 // No extending loads from f16 or HW conversions back and forth. 177 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 178 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 179 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 180 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 181 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 182 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 183 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 184 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 185 } 186 187 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 188 189 // PowerPC has pre-inc load and store's. 190 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 191 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 192 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 193 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 194 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 195 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 196 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 197 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 198 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 199 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 200 if (!Subtarget.hasSPE()) { 201 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 202 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 204 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 205 } 206 207 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 208 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 209 for (MVT VT : ScalarIntVTs) { 210 setOperationAction(ISD::ADDC, VT, Legal); 211 setOperationAction(ISD::ADDE, VT, Legal); 212 setOperationAction(ISD::SUBC, VT, Legal); 213 setOperationAction(ISD::SUBE, VT, Legal); 214 } 215 216 if (Subtarget.useCRBits()) { 217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 218 219 if (isPPC64 || Subtarget.hasFPCVT()) { 220 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 221 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 222 isPPC64 ? MVT::i64 : MVT::i32); 223 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 224 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 225 isPPC64 ? MVT::i64 : MVT::i32); 226 } else { 227 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 228 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 229 } 230 231 // PowerPC does not support direct load/store of condition registers. 232 setOperationAction(ISD::LOAD, MVT::i1, Custom); 233 setOperationAction(ISD::STORE, MVT::i1, Custom); 234 235 // FIXME: Remove this once the ANDI glue bug is fixed: 236 if (ANDIGlueBug) 237 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 238 239 for (MVT VT : MVT::integer_valuetypes()) { 240 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 241 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 242 setTruncStoreAction(VT, MVT::i1, Expand); 243 } 244 245 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 246 } 247 248 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 249 // PPC (the libcall is not available). 250 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 251 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 252 253 // We do not currently implement these libm ops for PowerPC. 254 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 255 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 256 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 257 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 258 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 259 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 260 261 // PowerPC has no SREM/UREM instructions unless we are on P9 262 // On P9 we may use a hardware instruction to compute the remainder. 263 // The instructions are not legalized directly because in the cases where the 264 // result of both the remainder and the division is required it is more 265 // efficient to compute the remainder from the result of the division rather 266 // than use the remainder instruction. 267 if (Subtarget.isISA3_0()) { 268 setOperationAction(ISD::SREM, MVT::i32, Custom); 269 setOperationAction(ISD::UREM, MVT::i32, Custom); 270 setOperationAction(ISD::SREM, MVT::i64, Custom); 271 setOperationAction(ISD::UREM, MVT::i64, Custom); 272 } else { 273 setOperationAction(ISD::SREM, MVT::i32, Expand); 274 setOperationAction(ISD::UREM, MVT::i32, Expand); 275 setOperationAction(ISD::SREM, MVT::i64, Expand); 276 setOperationAction(ISD::UREM, MVT::i64, Expand); 277 } 278 279 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 280 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 281 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 282 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 283 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 284 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 285 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 286 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 287 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 288 289 // Handle constrained floating-point operations of scalar. 290 // TODO: Handle SPE specific operation. 291 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 292 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 293 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 294 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 295 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 296 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 297 298 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 299 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 300 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 301 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 302 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 303 if (Subtarget.hasVSX()) 304 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal); 305 306 if (Subtarget.hasFSQRT()) { 307 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 308 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 309 } 310 311 if (Subtarget.hasFPRND()) { 312 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 313 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 314 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 315 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 316 317 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 318 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 319 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 320 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 321 } 322 323 // We don't support sin/cos/sqrt/fmod/pow 324 setOperationAction(ISD::FSIN , MVT::f64, Expand); 325 setOperationAction(ISD::FCOS , MVT::f64, Expand); 326 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 327 setOperationAction(ISD::FREM , MVT::f64, Expand); 328 setOperationAction(ISD::FPOW , MVT::f64, Expand); 329 setOperationAction(ISD::FSIN , MVT::f32, Expand); 330 setOperationAction(ISD::FCOS , MVT::f32, Expand); 331 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 332 setOperationAction(ISD::FREM , MVT::f32, Expand); 333 setOperationAction(ISD::FPOW , MVT::f32, Expand); 334 if (Subtarget.hasSPE()) { 335 setOperationAction(ISD::FMA , MVT::f64, Expand); 336 setOperationAction(ISD::FMA , MVT::f32, Expand); 337 } else { 338 setOperationAction(ISD::FMA , MVT::f64, Legal); 339 setOperationAction(ISD::FMA , MVT::f32, Legal); 340 } 341 342 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 343 344 // If we're enabling GP optimizations, use hardware square root 345 if (!Subtarget.hasFSQRT() && 346 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 347 Subtarget.hasFRE())) 348 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 349 350 if (!Subtarget.hasFSQRT() && 351 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 352 Subtarget.hasFRES())) 353 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 354 355 if (Subtarget.hasFCPSGN()) { 356 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 357 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 358 } else { 359 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 360 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 361 } 362 363 if (Subtarget.hasFPRND()) { 364 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 365 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 366 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 367 setOperationAction(ISD::FROUND, MVT::f64, Legal); 368 369 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 370 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 371 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 372 setOperationAction(ISD::FROUND, MVT::f32, Legal); 373 } 374 375 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 376 // to speed up scalar BSWAP64. 377 // CTPOP or CTTZ were introduced in P8/P9 respectively 378 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 379 if (Subtarget.hasP9Vector()) 380 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 381 else 382 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 383 if (Subtarget.isISA3_0()) { 384 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 385 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 386 } else { 387 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 388 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 389 } 390 391 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 392 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 393 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 394 } else { 395 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 396 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 397 } 398 399 // PowerPC does not have ROTR 400 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 401 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 402 403 if (!Subtarget.useCRBits()) { 404 // PowerPC does not have Select 405 setOperationAction(ISD::SELECT, MVT::i32, Expand); 406 setOperationAction(ISD::SELECT, MVT::i64, Expand); 407 setOperationAction(ISD::SELECT, MVT::f32, Expand); 408 setOperationAction(ISD::SELECT, MVT::f64, Expand); 409 } 410 411 // PowerPC wants to turn select_cc of FP into fsel when possible. 412 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 413 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 414 415 // PowerPC wants to optimize integer setcc a bit 416 if (!Subtarget.useCRBits()) 417 setOperationAction(ISD::SETCC, MVT::i32, Custom); 418 419 // PowerPC does not have BRCOND which requires SetCC 420 if (!Subtarget.useCRBits()) 421 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 422 423 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 424 425 if (Subtarget.hasSPE()) { 426 // SPE has built-in conversions 427 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 428 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 429 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 430 } else { 431 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 432 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 433 434 // PowerPC does not have [U|S]INT_TO_FP 435 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 436 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 437 } 438 439 if (Subtarget.hasDirectMove() && isPPC64) { 440 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 441 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 442 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 443 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 444 if (TM.Options.UnsafeFPMath) { 445 setOperationAction(ISD::LRINT, MVT::f64, Legal); 446 setOperationAction(ISD::LRINT, MVT::f32, Legal); 447 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 448 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 449 setOperationAction(ISD::LROUND, MVT::f64, Legal); 450 setOperationAction(ISD::LROUND, MVT::f32, Legal); 451 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 452 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 453 } 454 } else { 455 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 456 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 457 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 458 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 459 } 460 461 // We cannot sextinreg(i1). Expand to shifts. 462 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 463 464 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 465 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 466 // support continuation, user-level threading, and etc.. As a result, no 467 // other SjLj exception interfaces are implemented and please don't build 468 // your own exception handling based on them. 469 // LLVM/Clang supports zero-cost DWARF exception handling. 470 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 471 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 472 473 // We want to legalize GlobalAddress and ConstantPool nodes into the 474 // appropriate instructions to materialize the address. 475 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 476 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 477 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 478 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 479 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 480 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 481 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 482 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 483 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 484 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 485 486 // TRAP is legal. 487 setOperationAction(ISD::TRAP, MVT::Other, Legal); 488 489 // TRAMPOLINE is custom lowered. 490 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 491 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 492 493 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 494 setOperationAction(ISD::VASTART , MVT::Other, Custom); 495 496 if (Subtarget.is64BitELFABI()) { 497 // VAARG always uses double-word chunks, so promote anything smaller. 498 setOperationAction(ISD::VAARG, MVT::i1, Promote); 499 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 500 setOperationAction(ISD::VAARG, MVT::i8, Promote); 501 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 502 setOperationAction(ISD::VAARG, MVT::i16, Promote); 503 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 504 setOperationAction(ISD::VAARG, MVT::i32, Promote); 505 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 506 setOperationAction(ISD::VAARG, MVT::Other, Expand); 507 } else if (Subtarget.is32BitELFABI()) { 508 // VAARG is custom lowered with the 32-bit SVR4 ABI. 509 setOperationAction(ISD::VAARG, MVT::Other, Custom); 510 setOperationAction(ISD::VAARG, MVT::i64, Custom); 511 } else 512 setOperationAction(ISD::VAARG, MVT::Other, Expand); 513 514 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 515 if (Subtarget.is32BitELFABI()) 516 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 517 else 518 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 519 520 // Use the default implementation. 521 setOperationAction(ISD::VAEND , MVT::Other, Expand); 522 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 523 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 524 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 525 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 526 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 527 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 528 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 529 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 530 531 // We want to custom lower some of our intrinsics. 532 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 533 534 // To handle counter-based loop conditions. 535 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 536 537 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 538 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 539 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 540 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 541 542 // Comparisons that require checking two conditions. 543 if (Subtarget.hasSPE()) { 544 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 545 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 546 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 547 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 548 } 549 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 550 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 551 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 552 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 553 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 554 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 555 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 556 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 557 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 558 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 559 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 560 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 561 562 if (Subtarget.has64BitSupport()) { 563 // They also have instructions for converting between i64 and fp. 564 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 565 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 566 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 567 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 568 // This is just the low 32 bits of a (signed) fp->i64 conversion. 569 // We cannot do this with Promote because i64 is not a legal type. 570 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 571 572 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 573 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 574 } else { 575 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 576 if (Subtarget.hasSPE()) 577 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 578 else 579 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 580 } 581 582 // With the instructions enabled under FPCVT, we can do everything. 583 if (Subtarget.hasFPCVT()) { 584 if (Subtarget.has64BitSupport()) { 585 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 586 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 587 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 588 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 589 } 590 591 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 592 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 593 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 594 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 595 } 596 597 if (Subtarget.use64BitRegs()) { 598 // 64-bit PowerPC implementations can support i64 types directly 599 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 600 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 601 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 602 // 64-bit PowerPC wants to expand i128 shifts itself. 603 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 604 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 605 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 606 } else { 607 // 32-bit PowerPC wants to expand i64 shifts itself. 608 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 609 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 610 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 611 } 612 613 if (Subtarget.hasVSX()) { 614 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 615 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 616 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 617 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 618 } 619 620 if (Subtarget.hasAltivec()) { 621 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 622 setOperationAction(ISD::SADDSAT, VT, Legal); 623 setOperationAction(ISD::SSUBSAT, VT, Legal); 624 setOperationAction(ISD::UADDSAT, VT, Legal); 625 setOperationAction(ISD::USUBSAT, VT, Legal); 626 } 627 // First set operation action for all vector types to expand. Then we 628 // will selectively turn on ones that can be effectively codegen'd. 629 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 630 // add/sub are legal for all supported vector VT's. 631 setOperationAction(ISD::ADD, VT, Legal); 632 setOperationAction(ISD::SUB, VT, Legal); 633 634 // For v2i64, these are only valid with P8Vector. This is corrected after 635 // the loop. 636 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 637 setOperationAction(ISD::SMAX, VT, Legal); 638 setOperationAction(ISD::SMIN, VT, Legal); 639 setOperationAction(ISD::UMAX, VT, Legal); 640 setOperationAction(ISD::UMIN, VT, Legal); 641 } 642 else { 643 setOperationAction(ISD::SMAX, VT, Expand); 644 setOperationAction(ISD::SMIN, VT, Expand); 645 setOperationAction(ISD::UMAX, VT, Expand); 646 setOperationAction(ISD::UMIN, VT, Expand); 647 } 648 649 if (Subtarget.hasVSX()) { 650 setOperationAction(ISD::FMAXNUM, VT, Legal); 651 setOperationAction(ISD::FMINNUM, VT, Legal); 652 } 653 654 // Vector instructions introduced in P8 655 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 656 setOperationAction(ISD::CTPOP, VT, Legal); 657 setOperationAction(ISD::CTLZ, VT, Legal); 658 } 659 else { 660 setOperationAction(ISD::CTPOP, VT, Expand); 661 setOperationAction(ISD::CTLZ, VT, Expand); 662 } 663 664 // Vector instructions introduced in P9 665 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 666 setOperationAction(ISD::CTTZ, VT, Legal); 667 else 668 setOperationAction(ISD::CTTZ, VT, Expand); 669 670 // We promote all shuffles to v16i8. 671 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 672 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 673 674 // We promote all non-typed operations to v4i32. 675 setOperationAction(ISD::AND , VT, Promote); 676 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 677 setOperationAction(ISD::OR , VT, Promote); 678 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 679 setOperationAction(ISD::XOR , VT, Promote); 680 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 681 setOperationAction(ISD::LOAD , VT, Promote); 682 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 683 setOperationAction(ISD::SELECT, VT, Promote); 684 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 685 setOperationAction(ISD::VSELECT, VT, Legal); 686 setOperationAction(ISD::SELECT_CC, VT, Promote); 687 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 688 setOperationAction(ISD::STORE, VT, Promote); 689 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 690 691 // No other operations are legal. 692 setOperationAction(ISD::MUL , VT, Expand); 693 setOperationAction(ISD::SDIV, VT, Expand); 694 setOperationAction(ISD::SREM, VT, Expand); 695 setOperationAction(ISD::UDIV, VT, Expand); 696 setOperationAction(ISD::UREM, VT, Expand); 697 setOperationAction(ISD::FDIV, VT, Expand); 698 setOperationAction(ISD::FREM, VT, Expand); 699 setOperationAction(ISD::FNEG, VT, Expand); 700 setOperationAction(ISD::FSQRT, VT, Expand); 701 setOperationAction(ISD::FLOG, VT, Expand); 702 setOperationAction(ISD::FLOG10, VT, Expand); 703 setOperationAction(ISD::FLOG2, VT, Expand); 704 setOperationAction(ISD::FEXP, VT, Expand); 705 setOperationAction(ISD::FEXP2, VT, Expand); 706 setOperationAction(ISD::FSIN, VT, Expand); 707 setOperationAction(ISD::FCOS, VT, Expand); 708 setOperationAction(ISD::FABS, VT, Expand); 709 setOperationAction(ISD::FFLOOR, VT, Expand); 710 setOperationAction(ISD::FCEIL, VT, Expand); 711 setOperationAction(ISD::FTRUNC, VT, Expand); 712 setOperationAction(ISD::FRINT, VT, Expand); 713 setOperationAction(ISD::FNEARBYINT, VT, Expand); 714 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 715 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 716 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 717 setOperationAction(ISD::MULHU, VT, Expand); 718 setOperationAction(ISD::MULHS, VT, Expand); 719 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 720 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 721 setOperationAction(ISD::UDIVREM, VT, Expand); 722 setOperationAction(ISD::SDIVREM, VT, Expand); 723 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 724 setOperationAction(ISD::FPOW, VT, Expand); 725 setOperationAction(ISD::BSWAP, VT, Expand); 726 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 727 setOperationAction(ISD::ROTL, VT, Expand); 728 setOperationAction(ISD::ROTR, VT, Expand); 729 730 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 731 setTruncStoreAction(VT, InnerVT, Expand); 732 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 733 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 734 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 735 } 736 } 737 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 738 if (!Subtarget.hasP8Vector()) { 739 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 740 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 741 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 742 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 743 } 744 745 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 746 setOperationAction(ISD::ABS, VT, Custom); 747 748 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 749 // with merges, splats, etc. 750 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 751 752 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 753 // are cheap, so handle them before they get expanded to scalar. 754 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 755 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 756 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 757 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 758 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 759 760 setOperationAction(ISD::AND , MVT::v4i32, Legal); 761 setOperationAction(ISD::OR , MVT::v4i32, Legal); 762 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 763 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 764 setOperationAction(ISD::SELECT, MVT::v4i32, 765 Subtarget.useCRBits() ? Legal : Expand); 766 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 767 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 768 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 769 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 770 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 771 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 772 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 773 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 774 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 775 776 // Without hasP8Altivec set, v2i64 SMAX isn't available. 777 // But ABS custom lowering requires SMAX support. 778 if (!Subtarget.hasP8Altivec()) 779 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 780 781 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 782 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 783 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 784 if (Subtarget.hasAltivec()) 785 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 786 setOperationAction(ISD::ROTL, VT, Legal); 787 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 788 if (Subtarget.hasP8Altivec()) 789 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 790 791 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 792 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 793 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 794 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 795 796 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 797 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 798 799 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 800 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 801 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 802 } 803 804 if (Subtarget.hasP8Altivec()) 805 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 806 else 807 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 808 809 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 810 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 811 812 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 813 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 814 815 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 816 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 817 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 818 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 819 820 // Altivec does not contain unordered floating-point compare instructions 821 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 822 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 823 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 824 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 825 826 if (Subtarget.hasVSX()) { 827 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 828 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 829 if (Subtarget.hasP8Vector()) { 830 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 831 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 832 } 833 if (Subtarget.hasDirectMove() && isPPC64) { 834 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 835 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 836 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 837 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 838 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 839 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 840 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 841 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 842 } 843 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 844 845 // The nearbyint variants are not allowed to raise the inexact exception 846 // so we can only code-gen them with unsafe math. 847 if (TM.Options.UnsafeFPMath) { 848 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 849 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 850 } 851 852 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 853 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 854 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 855 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 856 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 857 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 858 setOperationAction(ISD::FROUND, MVT::f64, Legal); 859 setOperationAction(ISD::FRINT, MVT::f64, Legal); 860 861 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 862 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 863 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 864 setOperationAction(ISD::FROUND, MVT::f32, Legal); 865 setOperationAction(ISD::FRINT, MVT::f32, Legal); 866 867 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 868 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 869 870 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 871 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 872 873 // Share the Altivec comparison restrictions. 874 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 875 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 876 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 877 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 878 879 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 880 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 881 882 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 883 884 if (Subtarget.hasP8Vector()) 885 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 886 887 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 888 889 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 890 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 891 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 892 893 if (Subtarget.hasP8Altivec()) { 894 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 895 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 896 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 897 898 // 128 bit shifts can be accomplished via 3 instructions for SHL and 899 // SRL, but not for SRA because of the instructions available: 900 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 901 // doing 902 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 903 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 904 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 905 906 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 907 } 908 else { 909 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 910 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 911 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 912 913 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 914 915 // VSX v2i64 only supports non-arithmetic operations. 916 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 917 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 918 } 919 920 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 921 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 922 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 923 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 924 925 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 926 927 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 928 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 929 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 930 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 931 932 // Custom handling for partial vectors of integers converted to 933 // floating point. We already have optimal handling for v2i32 through 934 // the DAG combine, so those aren't necessary. 935 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 936 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 937 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 938 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 939 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 940 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 941 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 942 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 943 944 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 945 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 946 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 947 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 948 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 949 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 950 951 if (Subtarget.hasDirectMove()) 952 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 953 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 954 955 // Handle constrained floating-point operations of vector. 956 // The predictor is `hasVSX` because altivec instruction has 957 // no exception but VSX vector instruction has. 958 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 959 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 960 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 961 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 962 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 963 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 964 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 965 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 966 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal); 967 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 968 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 969 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 970 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 971 972 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 973 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 974 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 975 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 976 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 977 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 978 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 979 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 980 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal); 981 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 982 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 983 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 984 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 985 986 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 987 } 988 989 if (Subtarget.hasP8Altivec()) { 990 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 991 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 992 } 993 994 if (Subtarget.hasP9Vector()) { 995 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 997 998 // 128 bit shifts can be accomplished via 3 instructions for SHL and 999 // SRL, but not for SRA because of the instructions available: 1000 // VS{RL} and VS{RL}O. 1001 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1002 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1003 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1004 1005 if (EnableQuadPrecision) { 1006 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1007 setOperationAction(ISD::FADD, MVT::f128, Legal); 1008 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1009 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1010 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1011 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1012 // No extending loads to f128 on PPC. 1013 for (MVT FPT : MVT::fp_valuetypes()) 1014 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1015 setOperationAction(ISD::FMA, MVT::f128, Legal); 1016 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1017 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1018 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1019 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1020 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1021 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1022 1023 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1024 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1025 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1026 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1027 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1028 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1029 1030 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1031 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1032 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1033 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1034 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1035 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1036 // No implementation for these ops for PowerPC. 1037 setOperationAction(ISD::FSIN , MVT::f128, Expand); 1038 setOperationAction(ISD::FCOS , MVT::f128, Expand); 1039 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1040 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1041 setOperationAction(ISD::FREM, MVT::f128, Expand); 1042 1043 // Handle constrained floating-point operations of fp128 1044 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1045 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1046 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1047 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1048 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1049 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1050 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1051 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1052 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1053 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1054 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1055 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1056 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1057 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1058 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1059 } 1060 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1061 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1062 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1063 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1064 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1065 } 1066 1067 if (Subtarget.hasP9Altivec()) { 1068 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1069 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1070 1071 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1072 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1073 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1074 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1075 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1076 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1077 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1078 } 1079 } 1080 1081 if (Subtarget.hasQPX()) { 1082 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1083 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1084 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1085 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 1086 1087 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 1088 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 1089 1090 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 1091 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 1092 1093 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 1094 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 1095 1096 if (!Subtarget.useCRBits()) 1097 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 1098 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1099 1100 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 1101 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 1102 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 1103 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 1104 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 1105 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1106 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1107 1108 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1109 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1110 1111 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1112 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1113 1114 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1115 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1116 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1117 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1118 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1119 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1120 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1121 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1122 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1123 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1124 1125 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1126 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1127 1128 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1129 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1130 1131 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1132 1133 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1134 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1135 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1136 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1137 1138 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1139 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1140 1141 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1142 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1143 1144 if (!Subtarget.useCRBits()) 1145 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1146 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1147 1148 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1149 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1150 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1151 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1152 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1153 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1154 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1155 1156 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1157 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1158 1159 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1160 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1161 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1162 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1163 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1164 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1165 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1166 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1167 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1168 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1169 1170 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1171 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1172 1173 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1174 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1175 1176 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1177 1178 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1179 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1180 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1181 1182 if (!Subtarget.useCRBits()) 1183 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1184 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1185 1186 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1187 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1188 1189 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1190 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1191 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1192 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1193 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1194 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1195 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1196 1197 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1198 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1199 1200 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1201 1202 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1203 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1204 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1205 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1206 1207 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1208 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1209 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1210 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1211 1212 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1213 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1214 1215 // These need to set FE_INEXACT, and so cannot be vectorized here. 1216 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1217 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1218 1219 if (TM.Options.UnsafeFPMath) { 1220 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1221 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1222 1223 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1224 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1225 } else { 1226 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1227 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1228 1229 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1230 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1231 } 1232 1233 // TODO: Handle constrained floating-point operations of v4f64 1234 } 1235 1236 if (Subtarget.has64BitSupport()) 1237 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1238 1239 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1240 1241 if (!isPPC64) { 1242 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1243 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1244 } 1245 1246 setBooleanContents(ZeroOrOneBooleanContent); 1247 1248 if (Subtarget.hasAltivec()) { 1249 // Altivec instructions set fields to all zeros or all ones. 1250 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1251 } 1252 1253 if (!isPPC64) { 1254 // These libcalls are not available in 32-bit. 1255 setLibcallName(RTLIB::SHL_I128, nullptr); 1256 setLibcallName(RTLIB::SRL_I128, nullptr); 1257 setLibcallName(RTLIB::SRA_I128, nullptr); 1258 } 1259 1260 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1261 1262 // We have target-specific dag combine patterns for the following nodes: 1263 setTargetDAGCombine(ISD::ADD); 1264 setTargetDAGCombine(ISD::SHL); 1265 setTargetDAGCombine(ISD::SRA); 1266 setTargetDAGCombine(ISD::SRL); 1267 setTargetDAGCombine(ISD::MUL); 1268 setTargetDAGCombine(ISD::FMA); 1269 setTargetDAGCombine(ISD::SINT_TO_FP); 1270 setTargetDAGCombine(ISD::BUILD_VECTOR); 1271 if (Subtarget.hasFPCVT()) 1272 setTargetDAGCombine(ISD::UINT_TO_FP); 1273 setTargetDAGCombine(ISD::LOAD); 1274 setTargetDAGCombine(ISD::STORE); 1275 setTargetDAGCombine(ISD::BR_CC); 1276 if (Subtarget.useCRBits()) 1277 setTargetDAGCombine(ISD::BRCOND); 1278 setTargetDAGCombine(ISD::BSWAP); 1279 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1280 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1281 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1282 1283 setTargetDAGCombine(ISD::SIGN_EXTEND); 1284 setTargetDAGCombine(ISD::ZERO_EXTEND); 1285 setTargetDAGCombine(ISD::ANY_EXTEND); 1286 1287 setTargetDAGCombine(ISD::TRUNCATE); 1288 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1289 1290 1291 if (Subtarget.useCRBits()) { 1292 setTargetDAGCombine(ISD::TRUNCATE); 1293 setTargetDAGCombine(ISD::SETCC); 1294 setTargetDAGCombine(ISD::SELECT_CC); 1295 } 1296 1297 // Use reciprocal estimates. 1298 if (TM.Options.UnsafeFPMath) { 1299 setTargetDAGCombine(ISD::FDIV); 1300 setTargetDAGCombine(ISD::FSQRT); 1301 } 1302 1303 if (Subtarget.hasP9Altivec()) { 1304 setTargetDAGCombine(ISD::ABS); 1305 setTargetDAGCombine(ISD::VSELECT); 1306 } 1307 1308 if (EnableQuadPrecision) { 1309 setLibcallName(RTLIB::LOG_F128, "logf128"); 1310 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1311 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1312 setLibcallName(RTLIB::EXP_F128, "expf128"); 1313 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1314 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1315 setLibcallName(RTLIB::COS_F128, "cosf128"); 1316 setLibcallName(RTLIB::POW_F128, "powf128"); 1317 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1318 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1319 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1320 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1321 } 1322 1323 // With 32 condition bits, we don't need to sink (and duplicate) compares 1324 // aggressively in CodeGenPrep. 1325 if (Subtarget.useCRBits()) { 1326 setHasMultipleConditionRegisters(); 1327 setJumpIsExpensive(); 1328 } 1329 1330 setMinFunctionAlignment(Align(4)); 1331 1332 switch (Subtarget.getCPUDirective()) { 1333 default: break; 1334 case PPC::DIR_970: 1335 case PPC::DIR_A2: 1336 case PPC::DIR_E500: 1337 case PPC::DIR_E500mc: 1338 case PPC::DIR_E5500: 1339 case PPC::DIR_PWR4: 1340 case PPC::DIR_PWR5: 1341 case PPC::DIR_PWR5X: 1342 case PPC::DIR_PWR6: 1343 case PPC::DIR_PWR6X: 1344 case PPC::DIR_PWR7: 1345 case PPC::DIR_PWR8: 1346 case PPC::DIR_PWR9: 1347 case PPC::DIR_PWR10: 1348 case PPC::DIR_PWR_FUTURE: 1349 setPrefLoopAlignment(Align(16)); 1350 setPrefFunctionAlignment(Align(16)); 1351 break; 1352 } 1353 1354 if (Subtarget.enableMachineScheduler()) 1355 setSchedulingPreference(Sched::Source); 1356 else 1357 setSchedulingPreference(Sched::Hybrid); 1358 1359 computeRegisterProperties(STI.getRegisterInfo()); 1360 1361 // The Freescale cores do better with aggressive inlining of memcpy and 1362 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1363 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1364 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1365 MaxStoresPerMemset = 32; 1366 MaxStoresPerMemsetOptSize = 16; 1367 MaxStoresPerMemcpy = 32; 1368 MaxStoresPerMemcpyOptSize = 8; 1369 MaxStoresPerMemmove = 32; 1370 MaxStoresPerMemmoveOptSize = 8; 1371 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1372 // The A2 also benefits from (very) aggressive inlining of memcpy and 1373 // friends. The overhead of a the function call, even when warm, can be 1374 // over one hundred cycles. 1375 MaxStoresPerMemset = 128; 1376 MaxStoresPerMemcpy = 128; 1377 MaxStoresPerMemmove = 128; 1378 MaxLoadsPerMemcmp = 128; 1379 } else { 1380 MaxLoadsPerMemcmp = 8; 1381 MaxLoadsPerMemcmpOptSize = 4; 1382 } 1383 1384 // Let the subtarget (CPU) decide if a predictable select is more expensive 1385 // than the corresponding branch. This information is used in CGP to decide 1386 // when to convert selects into branches. 1387 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1388 } 1389 1390 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1391 /// the desired ByVal argument alignment. 1392 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1393 if (MaxAlign == MaxMaxAlign) 1394 return; 1395 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1396 if (MaxMaxAlign >= 32 && 1397 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1398 MaxAlign = Align(32); 1399 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1400 MaxAlign < 16) 1401 MaxAlign = Align(16); 1402 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1403 Align EltAlign; 1404 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1405 if (EltAlign > MaxAlign) 1406 MaxAlign = EltAlign; 1407 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1408 for (auto *EltTy : STy->elements()) { 1409 Align EltAlign; 1410 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1411 if (EltAlign > MaxAlign) 1412 MaxAlign = EltAlign; 1413 if (MaxAlign == MaxMaxAlign) 1414 break; 1415 } 1416 } 1417 } 1418 1419 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1420 /// function arguments in the caller parameter area. 1421 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1422 const DataLayout &DL) const { 1423 // 16byte and wider vectors are passed on 16byte boundary. 1424 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1425 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1426 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1427 getMaxByValAlign(Ty, Alignment, Subtarget.hasQPX() ? Align(32) : Align(16)); 1428 return Alignment.value(); 1429 } 1430 1431 bool PPCTargetLowering::useSoftFloat() const { 1432 return Subtarget.useSoftFloat(); 1433 } 1434 1435 bool PPCTargetLowering::hasSPE() const { 1436 return Subtarget.hasSPE(); 1437 } 1438 1439 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1440 return VT.isScalarInteger(); 1441 } 1442 1443 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1444 /// type is cheaper than a multiply followed by a shift. 1445 /// This is true for words and doublewords on 64-bit PowerPC. 1446 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1447 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1448 isOperationLegal(ISD::MULHU, Type))) 1449 return true; 1450 return TargetLowering::isMulhCheaperThanMulShift(Type); 1451 } 1452 1453 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1454 switch ((PPCISD::NodeType)Opcode) { 1455 case PPCISD::FIRST_NUMBER: break; 1456 case PPCISD::FSEL: return "PPCISD::FSEL"; 1457 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1458 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1459 case PPCISD::FCFID: return "PPCISD::FCFID"; 1460 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1461 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1462 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1463 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1464 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1465 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1466 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1467 case PPCISD::FP_TO_UINT_IN_VSR: 1468 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1469 case PPCISD::FP_TO_SINT_IN_VSR: 1470 return "PPCISD::FP_TO_SINT_IN_VSR"; 1471 case PPCISD::FRE: return "PPCISD::FRE"; 1472 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1473 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1474 case PPCISD::VPERM: return "PPCISD::VPERM"; 1475 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1476 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1477 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1478 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1479 case PPCISD::CMPB: return "PPCISD::CMPB"; 1480 case PPCISD::Hi: return "PPCISD::Hi"; 1481 case PPCISD::Lo: return "PPCISD::Lo"; 1482 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1483 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1484 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1485 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1486 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1487 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1488 case PPCISD::SRL: return "PPCISD::SRL"; 1489 case PPCISD::SRA: return "PPCISD::SRA"; 1490 case PPCISD::SHL: return "PPCISD::SHL"; 1491 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1492 case PPCISD::CALL: return "PPCISD::CALL"; 1493 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1494 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1495 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1496 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1497 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1498 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1499 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1500 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1501 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1502 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1503 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1504 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1505 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1506 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1507 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1508 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1509 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1510 case PPCISD::ANDI_rec_1_EQ_BIT: 1511 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1512 case PPCISD::ANDI_rec_1_GT_BIT: 1513 return "PPCISD::ANDI_rec_1_GT_BIT"; 1514 case PPCISD::VCMP: return "PPCISD::VCMP"; 1515 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1516 case PPCISD::LBRX: return "PPCISD::LBRX"; 1517 case PPCISD::STBRX: return "PPCISD::STBRX"; 1518 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1519 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1520 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1521 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1522 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1523 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1524 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1525 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1526 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1527 case PPCISD::ST_VSR_SCAL_INT: 1528 return "PPCISD::ST_VSR_SCAL_INT"; 1529 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1530 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1531 case PPCISD::BDZ: return "PPCISD::BDZ"; 1532 case PPCISD::MFFS: return "PPCISD::MFFS"; 1533 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1534 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1535 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1536 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1537 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1538 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1539 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1540 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1541 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1542 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1543 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1544 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1545 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1546 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1547 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1548 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1549 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1550 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1551 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1552 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1553 case PPCISD::SC: return "PPCISD::SC"; 1554 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1555 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1556 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1557 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1558 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1559 case PPCISD::VABSD: return "PPCISD::VABSD"; 1560 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1561 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1562 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1563 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1564 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1565 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1566 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1567 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1568 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1569 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1570 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1571 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1572 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1573 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1574 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1575 } 1576 return nullptr; 1577 } 1578 1579 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1580 EVT VT) const { 1581 if (!VT.isVector()) 1582 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1583 1584 if (Subtarget.hasQPX()) 1585 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1586 1587 return VT.changeVectorElementTypeToInteger(); 1588 } 1589 1590 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1591 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1592 return true; 1593 } 1594 1595 //===----------------------------------------------------------------------===// 1596 // Node matching predicates, for use by the tblgen matching code. 1597 //===----------------------------------------------------------------------===// 1598 1599 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1600 static bool isFloatingPointZero(SDValue Op) { 1601 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1602 return CFP->getValueAPF().isZero(); 1603 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1604 // Maybe this has already been legalized into the constant pool? 1605 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1606 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1607 return CFP->getValueAPF().isZero(); 1608 } 1609 return false; 1610 } 1611 1612 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1613 /// true if Op is undef or if it matches the specified value. 1614 static bool isConstantOrUndef(int Op, int Val) { 1615 return Op < 0 || Op == Val; 1616 } 1617 1618 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1619 /// VPKUHUM instruction. 1620 /// The ShuffleKind distinguishes between big-endian operations with 1621 /// two different inputs (0), either-endian operations with two identical 1622 /// inputs (1), and little-endian operations with two different inputs (2). 1623 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1624 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1625 SelectionDAG &DAG) { 1626 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1627 if (ShuffleKind == 0) { 1628 if (IsLE) 1629 return false; 1630 for (unsigned i = 0; i != 16; ++i) 1631 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1632 return false; 1633 } else if (ShuffleKind == 2) { 1634 if (!IsLE) 1635 return false; 1636 for (unsigned i = 0; i != 16; ++i) 1637 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1638 return false; 1639 } else if (ShuffleKind == 1) { 1640 unsigned j = IsLE ? 0 : 1; 1641 for (unsigned i = 0; i != 8; ++i) 1642 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1643 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1644 return false; 1645 } 1646 return true; 1647 } 1648 1649 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1650 /// VPKUWUM instruction. 1651 /// The ShuffleKind distinguishes between big-endian operations with 1652 /// two different inputs (0), either-endian operations with two identical 1653 /// inputs (1), and little-endian operations with two different inputs (2). 1654 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1655 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1656 SelectionDAG &DAG) { 1657 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1658 if (ShuffleKind == 0) { 1659 if (IsLE) 1660 return false; 1661 for (unsigned i = 0; i != 16; i += 2) 1662 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1663 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1664 return false; 1665 } else if (ShuffleKind == 2) { 1666 if (!IsLE) 1667 return false; 1668 for (unsigned i = 0; i != 16; i += 2) 1669 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1670 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1671 return false; 1672 } else if (ShuffleKind == 1) { 1673 unsigned j = IsLE ? 0 : 2; 1674 for (unsigned i = 0; i != 8; i += 2) 1675 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1676 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1677 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1678 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1679 return false; 1680 } 1681 return true; 1682 } 1683 1684 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1685 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1686 /// current subtarget. 1687 /// 1688 /// The ShuffleKind distinguishes between big-endian operations with 1689 /// two different inputs (0), either-endian operations with two identical 1690 /// inputs (1), and little-endian operations with two different inputs (2). 1691 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1692 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1693 SelectionDAG &DAG) { 1694 const PPCSubtarget& Subtarget = 1695 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1696 if (!Subtarget.hasP8Vector()) 1697 return false; 1698 1699 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1700 if (ShuffleKind == 0) { 1701 if (IsLE) 1702 return false; 1703 for (unsigned i = 0; i != 16; i += 4) 1704 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1705 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1706 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1707 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1708 return false; 1709 } else if (ShuffleKind == 2) { 1710 if (!IsLE) 1711 return false; 1712 for (unsigned i = 0; i != 16; i += 4) 1713 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1714 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1715 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1716 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1717 return false; 1718 } else if (ShuffleKind == 1) { 1719 unsigned j = IsLE ? 0 : 4; 1720 for (unsigned i = 0; i != 8; i += 4) 1721 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1722 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1723 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1724 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1725 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1726 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1727 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1728 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1729 return false; 1730 } 1731 return true; 1732 } 1733 1734 /// isVMerge - Common function, used to match vmrg* shuffles. 1735 /// 1736 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1737 unsigned LHSStart, unsigned RHSStart) { 1738 if (N->getValueType(0) != MVT::v16i8) 1739 return false; 1740 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1741 "Unsupported merge size!"); 1742 1743 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1744 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1745 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1746 LHSStart+j+i*UnitSize) || 1747 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1748 RHSStart+j+i*UnitSize)) 1749 return false; 1750 } 1751 return true; 1752 } 1753 1754 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1755 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1756 /// The ShuffleKind distinguishes between big-endian merges with two 1757 /// different inputs (0), either-endian merges with two identical inputs (1), 1758 /// and little-endian merges with two different inputs (2). For the latter, 1759 /// the input operands are swapped (see PPCInstrAltivec.td). 1760 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1761 unsigned ShuffleKind, SelectionDAG &DAG) { 1762 if (DAG.getDataLayout().isLittleEndian()) { 1763 if (ShuffleKind == 1) // unary 1764 return isVMerge(N, UnitSize, 0, 0); 1765 else if (ShuffleKind == 2) // swapped 1766 return isVMerge(N, UnitSize, 0, 16); 1767 else 1768 return false; 1769 } else { 1770 if (ShuffleKind == 1) // unary 1771 return isVMerge(N, UnitSize, 8, 8); 1772 else if (ShuffleKind == 0) // normal 1773 return isVMerge(N, UnitSize, 8, 24); 1774 else 1775 return false; 1776 } 1777 } 1778 1779 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1780 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1781 /// The ShuffleKind distinguishes between big-endian merges with two 1782 /// different inputs (0), either-endian merges with two identical inputs (1), 1783 /// and little-endian merges with two different inputs (2). For the latter, 1784 /// the input operands are swapped (see PPCInstrAltivec.td). 1785 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1786 unsigned ShuffleKind, SelectionDAG &DAG) { 1787 if (DAG.getDataLayout().isLittleEndian()) { 1788 if (ShuffleKind == 1) // unary 1789 return isVMerge(N, UnitSize, 8, 8); 1790 else if (ShuffleKind == 2) // swapped 1791 return isVMerge(N, UnitSize, 8, 24); 1792 else 1793 return false; 1794 } else { 1795 if (ShuffleKind == 1) // unary 1796 return isVMerge(N, UnitSize, 0, 0); 1797 else if (ShuffleKind == 0) // normal 1798 return isVMerge(N, UnitSize, 0, 16); 1799 else 1800 return false; 1801 } 1802 } 1803 1804 /** 1805 * Common function used to match vmrgew and vmrgow shuffles 1806 * 1807 * The indexOffset determines whether to look for even or odd words in 1808 * the shuffle mask. This is based on the of the endianness of the target 1809 * machine. 1810 * - Little Endian: 1811 * - Use offset of 0 to check for odd elements 1812 * - Use offset of 4 to check for even elements 1813 * - Big Endian: 1814 * - Use offset of 0 to check for even elements 1815 * - Use offset of 4 to check for odd elements 1816 * A detailed description of the vector element ordering for little endian and 1817 * big endian can be found at 1818 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1819 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1820 * compiler differences mean to you 1821 * 1822 * The mask to the shuffle vector instruction specifies the indices of the 1823 * elements from the two input vectors to place in the result. The elements are 1824 * numbered in array-access order, starting with the first vector. These vectors 1825 * are always of type v16i8, thus each vector will contain 16 elements of size 1826 * 8. More info on the shuffle vector can be found in the 1827 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1828 * Language Reference. 1829 * 1830 * The RHSStartValue indicates whether the same input vectors are used (unary) 1831 * or two different input vectors are used, based on the following: 1832 * - If the instruction uses the same vector for both inputs, the range of the 1833 * indices will be 0 to 15. In this case, the RHSStart value passed should 1834 * be 0. 1835 * - If the instruction has two different vectors then the range of the 1836 * indices will be 0 to 31. In this case, the RHSStart value passed should 1837 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1838 * to 31 specify elements in the second vector). 1839 * 1840 * \param[in] N The shuffle vector SD Node to analyze 1841 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1842 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1843 * vector to the shuffle_vector instruction 1844 * \return true iff this shuffle vector represents an even or odd word merge 1845 */ 1846 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1847 unsigned RHSStartValue) { 1848 if (N->getValueType(0) != MVT::v16i8) 1849 return false; 1850 1851 for (unsigned i = 0; i < 2; ++i) 1852 for (unsigned j = 0; j < 4; ++j) 1853 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1854 i*RHSStartValue+j+IndexOffset) || 1855 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1856 i*RHSStartValue+j+IndexOffset+8)) 1857 return false; 1858 return true; 1859 } 1860 1861 /** 1862 * Determine if the specified shuffle mask is suitable for the vmrgew or 1863 * vmrgow instructions. 1864 * 1865 * \param[in] N The shuffle vector SD Node to analyze 1866 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1867 * \param[in] ShuffleKind Identify the type of merge: 1868 * - 0 = big-endian merge with two different inputs; 1869 * - 1 = either-endian merge with two identical inputs; 1870 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1871 * little-endian merges). 1872 * \param[in] DAG The current SelectionDAG 1873 * \return true iff this shuffle mask 1874 */ 1875 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1876 unsigned ShuffleKind, SelectionDAG &DAG) { 1877 if (DAG.getDataLayout().isLittleEndian()) { 1878 unsigned indexOffset = CheckEven ? 4 : 0; 1879 if (ShuffleKind == 1) // Unary 1880 return isVMerge(N, indexOffset, 0); 1881 else if (ShuffleKind == 2) // swapped 1882 return isVMerge(N, indexOffset, 16); 1883 else 1884 return false; 1885 } 1886 else { 1887 unsigned indexOffset = CheckEven ? 0 : 4; 1888 if (ShuffleKind == 1) // Unary 1889 return isVMerge(N, indexOffset, 0); 1890 else if (ShuffleKind == 0) // Normal 1891 return isVMerge(N, indexOffset, 16); 1892 else 1893 return false; 1894 } 1895 return false; 1896 } 1897 1898 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1899 /// amount, otherwise return -1. 1900 /// The ShuffleKind distinguishes between big-endian operations with two 1901 /// different inputs (0), either-endian operations with two identical inputs 1902 /// (1), and little-endian operations with two different inputs (2). For the 1903 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1904 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1905 SelectionDAG &DAG) { 1906 if (N->getValueType(0) != MVT::v16i8) 1907 return -1; 1908 1909 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1910 1911 // Find the first non-undef value in the shuffle mask. 1912 unsigned i; 1913 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1914 /*search*/; 1915 1916 if (i == 16) return -1; // all undef. 1917 1918 // Otherwise, check to see if the rest of the elements are consecutively 1919 // numbered from this value. 1920 unsigned ShiftAmt = SVOp->getMaskElt(i); 1921 if (ShiftAmt < i) return -1; 1922 1923 ShiftAmt -= i; 1924 bool isLE = DAG.getDataLayout().isLittleEndian(); 1925 1926 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1927 // Check the rest of the elements to see if they are consecutive. 1928 for (++i; i != 16; ++i) 1929 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1930 return -1; 1931 } else if (ShuffleKind == 1) { 1932 // Check the rest of the elements to see if they are consecutive. 1933 for (++i; i != 16; ++i) 1934 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1935 return -1; 1936 } else 1937 return -1; 1938 1939 if (isLE) 1940 ShiftAmt = 16 - ShiftAmt; 1941 1942 return ShiftAmt; 1943 } 1944 1945 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1946 /// specifies a splat of a single element that is suitable for input to 1947 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1948 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1949 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1950 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1951 1952 // The consecutive indices need to specify an element, not part of two 1953 // different elements. So abandon ship early if this isn't the case. 1954 if (N->getMaskElt(0) % EltSize != 0) 1955 return false; 1956 1957 // This is a splat operation if each element of the permute is the same, and 1958 // if the value doesn't reference the second vector. 1959 unsigned ElementBase = N->getMaskElt(0); 1960 1961 // FIXME: Handle UNDEF elements too! 1962 if (ElementBase >= 16) 1963 return false; 1964 1965 // Check that the indices are consecutive, in the case of a multi-byte element 1966 // splatted with a v16i8 mask. 1967 for (unsigned i = 1; i != EltSize; ++i) 1968 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1969 return false; 1970 1971 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1972 if (N->getMaskElt(i) < 0) continue; 1973 for (unsigned j = 0; j != EltSize; ++j) 1974 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1975 return false; 1976 } 1977 return true; 1978 } 1979 1980 /// Check that the mask is shuffling N byte elements. Within each N byte 1981 /// element of the mask, the indices could be either in increasing or 1982 /// decreasing order as long as they are consecutive. 1983 /// \param[in] N the shuffle vector SD Node to analyze 1984 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1985 /// Word/DoubleWord/QuadWord). 1986 /// \param[in] StepLen the delta indices number among the N byte element, if 1987 /// the mask is in increasing/decreasing order then it is 1/-1. 1988 /// \return true iff the mask is shuffling N byte elements. 1989 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1990 int StepLen) { 1991 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1992 "Unexpected element width."); 1993 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1994 1995 unsigned NumOfElem = 16 / Width; 1996 unsigned MaskVal[16]; // Width is never greater than 16 1997 for (unsigned i = 0; i < NumOfElem; ++i) { 1998 MaskVal[0] = N->getMaskElt(i * Width); 1999 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2000 return false; 2001 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2002 return false; 2003 } 2004 2005 for (unsigned int j = 1; j < Width; ++j) { 2006 MaskVal[j] = N->getMaskElt(i * Width + j); 2007 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2008 return false; 2009 } 2010 } 2011 } 2012 2013 return true; 2014 } 2015 2016 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2017 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2018 if (!isNByteElemShuffleMask(N, 4, 1)) 2019 return false; 2020 2021 // Now we look at mask elements 0,4,8,12 2022 unsigned M0 = N->getMaskElt(0) / 4; 2023 unsigned M1 = N->getMaskElt(4) / 4; 2024 unsigned M2 = N->getMaskElt(8) / 4; 2025 unsigned M3 = N->getMaskElt(12) / 4; 2026 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2027 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2028 2029 // Below, let H and L be arbitrary elements of the shuffle mask 2030 // where H is in the range [4,7] and L is in the range [0,3]. 2031 // H, 1, 2, 3 or L, 5, 6, 7 2032 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2033 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2034 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2035 InsertAtByte = IsLE ? 12 : 0; 2036 Swap = M0 < 4; 2037 return true; 2038 } 2039 // 0, H, 2, 3 or 4, L, 6, 7 2040 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2041 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2042 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2043 InsertAtByte = IsLE ? 8 : 4; 2044 Swap = M1 < 4; 2045 return true; 2046 } 2047 // 0, 1, H, 3 or 4, 5, L, 7 2048 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2049 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2050 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2051 InsertAtByte = IsLE ? 4 : 8; 2052 Swap = M2 < 4; 2053 return true; 2054 } 2055 // 0, 1, 2, H or 4, 5, 6, L 2056 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2057 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2058 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2059 InsertAtByte = IsLE ? 0 : 12; 2060 Swap = M3 < 4; 2061 return true; 2062 } 2063 2064 // If both vector operands for the shuffle are the same vector, the mask will 2065 // contain only elements from the first one and the second one will be undef. 2066 if (N->getOperand(1).isUndef()) { 2067 ShiftElts = 0; 2068 Swap = true; 2069 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2070 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2071 InsertAtByte = IsLE ? 12 : 0; 2072 return true; 2073 } 2074 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2075 InsertAtByte = IsLE ? 8 : 4; 2076 return true; 2077 } 2078 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2079 InsertAtByte = IsLE ? 4 : 8; 2080 return true; 2081 } 2082 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2083 InsertAtByte = IsLE ? 0 : 12; 2084 return true; 2085 } 2086 } 2087 2088 return false; 2089 } 2090 2091 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2092 bool &Swap, bool IsLE) { 2093 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2094 // Ensure each byte index of the word is consecutive. 2095 if (!isNByteElemShuffleMask(N, 4, 1)) 2096 return false; 2097 2098 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2099 unsigned M0 = N->getMaskElt(0) / 4; 2100 unsigned M1 = N->getMaskElt(4) / 4; 2101 unsigned M2 = N->getMaskElt(8) / 4; 2102 unsigned M3 = N->getMaskElt(12) / 4; 2103 2104 // If both vector operands for the shuffle are the same vector, the mask will 2105 // contain only elements from the first one and the second one will be undef. 2106 if (N->getOperand(1).isUndef()) { 2107 assert(M0 < 4 && "Indexing into an undef vector?"); 2108 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2109 return false; 2110 2111 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2112 Swap = false; 2113 return true; 2114 } 2115 2116 // Ensure each word index of the ShuffleVector Mask is consecutive. 2117 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2118 return false; 2119 2120 if (IsLE) { 2121 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2122 // Input vectors don't need to be swapped if the leading element 2123 // of the result is one of the 3 left elements of the second vector 2124 // (or if there is no shift to be done at all). 2125 Swap = false; 2126 ShiftElts = (8 - M0) % 8; 2127 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2128 // Input vectors need to be swapped if the leading element 2129 // of the result is one of the 3 left elements of the first vector 2130 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2131 Swap = true; 2132 ShiftElts = (4 - M0) % 4; 2133 } 2134 2135 return true; 2136 } else { // BE 2137 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2138 // Input vectors don't need to be swapped if the leading element 2139 // of the result is one of the 4 elements of the first vector. 2140 Swap = false; 2141 ShiftElts = M0; 2142 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2143 // Input vectors need to be swapped if the leading element 2144 // of the result is one of the 4 elements of the right vector. 2145 Swap = true; 2146 ShiftElts = M0 - 4; 2147 } 2148 2149 return true; 2150 } 2151 } 2152 2153 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2154 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2155 2156 if (!isNByteElemShuffleMask(N, Width, -1)) 2157 return false; 2158 2159 for (int i = 0; i < 16; i += Width) 2160 if (N->getMaskElt(i) != i + Width - 1) 2161 return false; 2162 2163 return true; 2164 } 2165 2166 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2167 return isXXBRShuffleMaskHelper(N, 2); 2168 } 2169 2170 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2171 return isXXBRShuffleMaskHelper(N, 4); 2172 } 2173 2174 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2175 return isXXBRShuffleMaskHelper(N, 8); 2176 } 2177 2178 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2179 return isXXBRShuffleMaskHelper(N, 16); 2180 } 2181 2182 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2183 /// if the inputs to the instruction should be swapped and set \p DM to the 2184 /// value for the immediate. 2185 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2186 /// AND element 0 of the result comes from the first input (LE) or second input 2187 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2188 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2189 /// mask. 2190 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2191 bool &Swap, bool IsLE) { 2192 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2193 2194 // Ensure each byte index of the double word is consecutive. 2195 if (!isNByteElemShuffleMask(N, 8, 1)) 2196 return false; 2197 2198 unsigned M0 = N->getMaskElt(0) / 8; 2199 unsigned M1 = N->getMaskElt(8) / 8; 2200 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2201 2202 // If both vector operands for the shuffle are the same vector, the mask will 2203 // contain only elements from the first one and the second one will be undef. 2204 if (N->getOperand(1).isUndef()) { 2205 if ((M0 | M1) < 2) { 2206 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2207 Swap = false; 2208 return true; 2209 } else 2210 return false; 2211 } 2212 2213 if (IsLE) { 2214 if (M0 > 1 && M1 < 2) { 2215 Swap = false; 2216 } else if (M0 < 2 && M1 > 1) { 2217 M0 = (M0 + 2) % 4; 2218 M1 = (M1 + 2) % 4; 2219 Swap = true; 2220 } else 2221 return false; 2222 2223 // Note: if control flow comes here that means Swap is already set above 2224 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2225 return true; 2226 } else { // BE 2227 if (M0 < 2 && M1 > 1) { 2228 Swap = false; 2229 } else if (M0 > 1 && M1 < 2) { 2230 M0 = (M0 + 2) % 4; 2231 M1 = (M1 + 2) % 4; 2232 Swap = true; 2233 } else 2234 return false; 2235 2236 // Note: if control flow comes here that means Swap is already set above 2237 DM = (M0 << 1) + (M1 & 1); 2238 return true; 2239 } 2240 } 2241 2242 2243 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2244 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2245 /// elements are counted from the left of the vector register). 2246 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2247 SelectionDAG &DAG) { 2248 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2249 assert(isSplatShuffleMask(SVOp, EltSize)); 2250 if (DAG.getDataLayout().isLittleEndian()) 2251 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2252 else 2253 return SVOp->getMaskElt(0) / EltSize; 2254 } 2255 2256 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2257 /// by using a vspltis[bhw] instruction of the specified element size, return 2258 /// the constant being splatted. The ByteSize field indicates the number of 2259 /// bytes of each element [124] -> [bhw]. 2260 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2261 SDValue OpVal(nullptr, 0); 2262 2263 // If ByteSize of the splat is bigger than the element size of the 2264 // build_vector, then we have a case where we are checking for a splat where 2265 // multiple elements of the buildvector are folded together into a single 2266 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2267 unsigned EltSize = 16/N->getNumOperands(); 2268 if (EltSize < ByteSize) { 2269 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2270 SDValue UniquedVals[4]; 2271 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2272 2273 // See if all of the elements in the buildvector agree across. 2274 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2275 if (N->getOperand(i).isUndef()) continue; 2276 // If the element isn't a constant, bail fully out. 2277 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2278 2279 if (!UniquedVals[i&(Multiple-1)].getNode()) 2280 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2281 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2282 return SDValue(); // no match. 2283 } 2284 2285 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2286 // either constant or undef values that are identical for each chunk. See 2287 // if these chunks can form into a larger vspltis*. 2288 2289 // Check to see if all of the leading entries are either 0 or -1. If 2290 // neither, then this won't fit into the immediate field. 2291 bool LeadingZero = true; 2292 bool LeadingOnes = true; 2293 for (unsigned i = 0; i != Multiple-1; ++i) { 2294 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2295 2296 LeadingZero &= isNullConstant(UniquedVals[i]); 2297 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2298 } 2299 // Finally, check the least significant entry. 2300 if (LeadingZero) { 2301 if (!UniquedVals[Multiple-1].getNode()) 2302 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2303 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2304 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2305 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2306 } 2307 if (LeadingOnes) { 2308 if (!UniquedVals[Multiple-1].getNode()) 2309 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2310 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2311 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2312 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2313 } 2314 2315 return SDValue(); 2316 } 2317 2318 // Check to see if this buildvec has a single non-undef value in its elements. 2319 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2320 if (N->getOperand(i).isUndef()) continue; 2321 if (!OpVal.getNode()) 2322 OpVal = N->getOperand(i); 2323 else if (OpVal != N->getOperand(i)) 2324 return SDValue(); 2325 } 2326 2327 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2328 2329 unsigned ValSizeInBytes = EltSize; 2330 uint64_t Value = 0; 2331 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2332 Value = CN->getZExtValue(); 2333 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2334 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2335 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2336 } 2337 2338 // If the splat value is larger than the element value, then we can never do 2339 // this splat. The only case that we could fit the replicated bits into our 2340 // immediate field for would be zero, and we prefer to use vxor for it. 2341 if (ValSizeInBytes < ByteSize) return SDValue(); 2342 2343 // If the element value is larger than the splat value, check if it consists 2344 // of a repeated bit pattern of size ByteSize. 2345 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2346 return SDValue(); 2347 2348 // Properly sign extend the value. 2349 int MaskVal = SignExtend32(Value, ByteSize * 8); 2350 2351 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2352 if (MaskVal == 0) return SDValue(); 2353 2354 // Finally, if this value fits in a 5 bit sext field, return it 2355 if (SignExtend32<5>(MaskVal) == MaskVal) 2356 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2357 return SDValue(); 2358 } 2359 2360 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2361 /// amount, otherwise return -1. 2362 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2363 EVT VT = N->getValueType(0); 2364 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2365 return -1; 2366 2367 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2368 2369 // Find the first non-undef value in the shuffle mask. 2370 unsigned i; 2371 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2372 /*search*/; 2373 2374 if (i == 4) return -1; // all undef. 2375 2376 // Otherwise, check to see if the rest of the elements are consecutively 2377 // numbered from this value. 2378 unsigned ShiftAmt = SVOp->getMaskElt(i); 2379 if (ShiftAmt < i) return -1; 2380 ShiftAmt -= i; 2381 2382 // Check the rest of the elements to see if they are consecutive. 2383 for (++i; i != 4; ++i) 2384 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2385 return -1; 2386 2387 return ShiftAmt; 2388 } 2389 2390 //===----------------------------------------------------------------------===// 2391 // Addressing Mode Selection 2392 //===----------------------------------------------------------------------===// 2393 2394 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2395 /// or 64-bit immediate, and if the value can be accurately represented as a 2396 /// sign extension from a 16-bit value. If so, this returns true and the 2397 /// immediate. 2398 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2399 if (!isa<ConstantSDNode>(N)) 2400 return false; 2401 2402 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2403 if (N->getValueType(0) == MVT::i32) 2404 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2405 else 2406 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2407 } 2408 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2409 return isIntS16Immediate(Op.getNode(), Imm); 2410 } 2411 2412 2413 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2414 /// be represented as an indexed [r+r] operation. 2415 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2416 SDValue &Index, 2417 SelectionDAG &DAG) const { 2418 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2419 UI != E; ++UI) { 2420 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2421 if (Memop->getMemoryVT() == MVT::f64) { 2422 Base = N.getOperand(0); 2423 Index = N.getOperand(1); 2424 return true; 2425 } 2426 } 2427 } 2428 return false; 2429 } 2430 2431 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2432 /// can be represented as an indexed [r+r] operation. Returns false if it 2433 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2434 /// non-zero and N can be represented by a base register plus a signed 16-bit 2435 /// displacement, make a more precise judgement by checking (displacement % \p 2436 /// EncodingAlignment). 2437 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2438 SDValue &Index, SelectionDAG &DAG, 2439 unsigned EncodingAlignment) const { 2440 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2441 // a [pc+imm]. 2442 if (SelectAddressPCRel(N, Base)) 2443 return false; 2444 2445 int16_t imm = 0; 2446 if (N.getOpcode() == ISD::ADD) { 2447 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2448 // SPE load/store can only handle 8-bit offsets. 2449 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2450 return true; 2451 if (isIntS16Immediate(N.getOperand(1), imm) && 2452 (!EncodingAlignment || !(imm % EncodingAlignment))) 2453 return false; // r+i 2454 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2455 return false; // r+i 2456 2457 Base = N.getOperand(0); 2458 Index = N.getOperand(1); 2459 return true; 2460 } else if (N.getOpcode() == ISD::OR) { 2461 if (isIntS16Immediate(N.getOperand(1), imm) && 2462 (!EncodingAlignment || !(imm % EncodingAlignment))) 2463 return false; // r+i can fold it if we can. 2464 2465 // If this is an or of disjoint bitfields, we can codegen this as an add 2466 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2467 // disjoint. 2468 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2469 2470 if (LHSKnown.Zero.getBoolValue()) { 2471 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2472 // If all of the bits are known zero on the LHS or RHS, the add won't 2473 // carry. 2474 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2475 Base = N.getOperand(0); 2476 Index = N.getOperand(1); 2477 return true; 2478 } 2479 } 2480 } 2481 2482 return false; 2483 } 2484 2485 // If we happen to be doing an i64 load or store into a stack slot that has 2486 // less than a 4-byte alignment, then the frame-index elimination may need to 2487 // use an indexed load or store instruction (because the offset may not be a 2488 // multiple of 4). The extra register needed to hold the offset comes from the 2489 // register scavenger, and it is possible that the scavenger will need to use 2490 // an emergency spill slot. As a result, we need to make sure that a spill slot 2491 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2492 // stack slot. 2493 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2494 // FIXME: This does not handle the LWA case. 2495 if (VT != MVT::i64) 2496 return; 2497 2498 // NOTE: We'll exclude negative FIs here, which come from argument 2499 // lowering, because there are no known test cases triggering this problem 2500 // using packed structures (or similar). We can remove this exclusion if 2501 // we find such a test case. The reason why this is so test-case driven is 2502 // because this entire 'fixup' is only to prevent crashes (from the 2503 // register scavenger) on not-really-valid inputs. For example, if we have: 2504 // %a = alloca i1 2505 // %b = bitcast i1* %a to i64* 2506 // store i64* a, i64 b 2507 // then the store should really be marked as 'align 1', but is not. If it 2508 // were marked as 'align 1' then the indexed form would have been 2509 // instruction-selected initially, and the problem this 'fixup' is preventing 2510 // won't happen regardless. 2511 if (FrameIdx < 0) 2512 return; 2513 2514 MachineFunction &MF = DAG.getMachineFunction(); 2515 MachineFrameInfo &MFI = MF.getFrameInfo(); 2516 2517 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2518 return; 2519 2520 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2521 FuncInfo->setHasNonRISpills(); 2522 } 2523 2524 /// Returns true if the address N can be represented by a base register plus 2525 /// a signed 16-bit displacement [r+imm], and if it is not better 2526 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2527 /// displacements that are multiples of that value. 2528 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2529 SDValue &Base, 2530 SelectionDAG &DAG, 2531 unsigned EncodingAlignment) const { 2532 // FIXME dl should come from parent load or store, not from address 2533 SDLoc dl(N); 2534 2535 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2536 // a [pc+imm]. 2537 if (SelectAddressPCRel(N, Base)) 2538 return false; 2539 2540 // If this can be more profitably realized as r+r, fail. 2541 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2542 return false; 2543 2544 if (N.getOpcode() == ISD::ADD) { 2545 int16_t imm = 0; 2546 if (isIntS16Immediate(N.getOperand(1), imm) && 2547 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2548 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2549 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2550 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2551 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2552 } else { 2553 Base = N.getOperand(0); 2554 } 2555 return true; // [r+i] 2556 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2557 // Match LOAD (ADD (X, Lo(G))). 2558 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2559 && "Cannot handle constant offsets yet!"); 2560 Disp = N.getOperand(1).getOperand(0); // The global address. 2561 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2562 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2563 Disp.getOpcode() == ISD::TargetConstantPool || 2564 Disp.getOpcode() == ISD::TargetJumpTable); 2565 Base = N.getOperand(0); 2566 return true; // [&g+r] 2567 } 2568 } else if (N.getOpcode() == ISD::OR) { 2569 int16_t imm = 0; 2570 if (isIntS16Immediate(N.getOperand(1), imm) && 2571 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2572 // If this is an or of disjoint bitfields, we can codegen this as an add 2573 // (for better address arithmetic) if the LHS and RHS of the OR are 2574 // provably disjoint. 2575 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2576 2577 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2578 // If all of the bits are known zero on the LHS or RHS, the add won't 2579 // carry. 2580 if (FrameIndexSDNode *FI = 2581 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2582 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2583 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2584 } else { 2585 Base = N.getOperand(0); 2586 } 2587 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2588 return true; 2589 } 2590 } 2591 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2592 // Loading from a constant address. 2593 2594 // If this address fits entirely in a 16-bit sext immediate field, codegen 2595 // this as "d, 0" 2596 int16_t Imm; 2597 if (isIntS16Immediate(CN, Imm) && 2598 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2599 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2600 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2601 CN->getValueType(0)); 2602 return true; 2603 } 2604 2605 // Handle 32-bit sext immediates with LIS + addr mode. 2606 if ((CN->getValueType(0) == MVT::i32 || 2607 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2608 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2609 int Addr = (int)CN->getZExtValue(); 2610 2611 // Otherwise, break this down into an LIS + disp. 2612 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2613 2614 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2615 MVT::i32); 2616 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2617 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2618 return true; 2619 } 2620 } 2621 2622 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2623 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2624 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2625 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2626 } else 2627 Base = N; 2628 return true; // [r+0] 2629 } 2630 2631 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2632 /// represented as an indexed [r+r] operation. 2633 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2634 SDValue &Index, 2635 SelectionDAG &DAG) const { 2636 // Check to see if we can easily represent this as an [r+r] address. This 2637 // will fail if it thinks that the address is more profitably represented as 2638 // reg+imm, e.g. where imm = 0. 2639 if (SelectAddressRegReg(N, Base, Index, DAG)) 2640 return true; 2641 2642 // If the address is the result of an add, we will utilize the fact that the 2643 // address calculation includes an implicit add. However, we can reduce 2644 // register pressure if we do not materialize a constant just for use as the 2645 // index register. We only get rid of the add if it is not an add of a 2646 // value and a 16-bit signed constant and both have a single use. 2647 int16_t imm = 0; 2648 if (N.getOpcode() == ISD::ADD && 2649 (!isIntS16Immediate(N.getOperand(1), imm) || 2650 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2651 Base = N.getOperand(0); 2652 Index = N.getOperand(1); 2653 return true; 2654 } 2655 2656 // Otherwise, do it the hard way, using R0 as the base register. 2657 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2658 N.getValueType()); 2659 Index = N; 2660 return true; 2661 } 2662 2663 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2664 Ty *PCRelCand = dyn_cast<Ty>(N); 2665 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2666 } 2667 2668 /// Returns true if this address is a PC Relative address. 2669 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2670 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2671 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2672 // This is a materialize PC Relative node. Always select this as PC Relative. 2673 Base = N; 2674 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2675 return true; 2676 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2677 isValidPCRelNode<GlobalAddressSDNode>(N) || 2678 isValidPCRelNode<JumpTableSDNode>(N) || 2679 isValidPCRelNode<BlockAddressSDNode>(N)) 2680 return true; 2681 return false; 2682 } 2683 2684 /// Returns true if we should use a direct load into vector instruction 2685 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2686 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2687 2688 // If there are any other uses other than scalar to vector, then we should 2689 // keep it as a scalar load -> direct move pattern to prevent multiple 2690 // loads. 2691 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2692 if (!LD) 2693 return false; 2694 2695 EVT MemVT = LD->getMemoryVT(); 2696 if (!MemVT.isSimple()) 2697 return false; 2698 switch(MemVT.getSimpleVT().SimpleTy) { 2699 case MVT::i64: 2700 break; 2701 case MVT::i32: 2702 if (!ST.hasP8Vector()) 2703 return false; 2704 break; 2705 case MVT::i16: 2706 case MVT::i8: 2707 if (!ST.hasP9Vector()) 2708 return false; 2709 break; 2710 default: 2711 return false; 2712 } 2713 2714 SDValue LoadedVal(N, 0); 2715 if (!LoadedVal.hasOneUse()) 2716 return false; 2717 2718 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2719 UI != UE; ++UI) 2720 if (UI.getUse().get().getResNo() == 0 && 2721 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2722 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2723 return false; 2724 2725 return true; 2726 } 2727 2728 /// getPreIndexedAddressParts - returns true by value, base pointer and 2729 /// offset pointer and addressing mode by reference if the node's address 2730 /// can be legally represented as pre-indexed load / store address. 2731 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2732 SDValue &Offset, 2733 ISD::MemIndexedMode &AM, 2734 SelectionDAG &DAG) const { 2735 if (DisablePPCPreinc) return false; 2736 2737 bool isLoad = true; 2738 SDValue Ptr; 2739 EVT VT; 2740 unsigned Alignment; 2741 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2742 Ptr = LD->getBasePtr(); 2743 VT = LD->getMemoryVT(); 2744 Alignment = LD->getAlignment(); 2745 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2746 Ptr = ST->getBasePtr(); 2747 VT = ST->getMemoryVT(); 2748 Alignment = ST->getAlignment(); 2749 isLoad = false; 2750 } else 2751 return false; 2752 2753 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2754 // instructions because we can fold these into a more efficient instruction 2755 // instead, (such as LXSD). 2756 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2757 return false; 2758 } 2759 2760 // PowerPC doesn't have preinc load/store instructions for vectors (except 2761 // for QPX, which does have preinc r+r forms). 2762 if (VT.isVector()) { 2763 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2764 return false; 2765 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2766 AM = ISD::PRE_INC; 2767 return true; 2768 } 2769 } 2770 2771 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2772 // Common code will reject creating a pre-inc form if the base pointer 2773 // is a frame index, or if N is a store and the base pointer is either 2774 // the same as or a predecessor of the value being stored. Check for 2775 // those situations here, and try with swapped Base/Offset instead. 2776 bool Swap = false; 2777 2778 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2779 Swap = true; 2780 else if (!isLoad) { 2781 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2782 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2783 Swap = true; 2784 } 2785 2786 if (Swap) 2787 std::swap(Base, Offset); 2788 2789 AM = ISD::PRE_INC; 2790 return true; 2791 } 2792 2793 // LDU/STU can only handle immediates that are a multiple of 4. 2794 if (VT != MVT::i64) { 2795 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2796 return false; 2797 } else { 2798 // LDU/STU need an address with at least 4-byte alignment. 2799 if (Alignment < 4) 2800 return false; 2801 2802 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2803 return false; 2804 } 2805 2806 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2807 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2808 // sext i32 to i64 when addr mode is r+i. 2809 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2810 LD->getExtensionType() == ISD::SEXTLOAD && 2811 isa<ConstantSDNode>(Offset)) 2812 return false; 2813 } 2814 2815 AM = ISD::PRE_INC; 2816 return true; 2817 } 2818 2819 //===----------------------------------------------------------------------===// 2820 // LowerOperation implementation 2821 //===----------------------------------------------------------------------===// 2822 2823 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2824 /// and LoOpFlags to the target MO flags. 2825 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2826 unsigned &HiOpFlags, unsigned &LoOpFlags, 2827 const GlobalValue *GV = nullptr) { 2828 HiOpFlags = PPCII::MO_HA; 2829 LoOpFlags = PPCII::MO_LO; 2830 2831 // Don't use the pic base if not in PIC relocation model. 2832 if (IsPIC) { 2833 HiOpFlags |= PPCII::MO_PIC_FLAG; 2834 LoOpFlags |= PPCII::MO_PIC_FLAG; 2835 } 2836 } 2837 2838 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2839 SelectionDAG &DAG) { 2840 SDLoc DL(HiPart); 2841 EVT PtrVT = HiPart.getValueType(); 2842 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2843 2844 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2845 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2846 2847 // With PIC, the first instruction is actually "GR+hi(&G)". 2848 if (isPIC) 2849 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2850 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2851 2852 // Generate non-pic code that has direct accesses to the constant pool. 2853 // The address of the global is just (hi(&g)+lo(&g)). 2854 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2855 } 2856 2857 static void setUsesTOCBasePtr(MachineFunction &MF) { 2858 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2859 FuncInfo->setUsesTOCBasePtr(); 2860 } 2861 2862 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2863 setUsesTOCBasePtr(DAG.getMachineFunction()); 2864 } 2865 2866 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2867 SDValue GA) const { 2868 const bool Is64Bit = Subtarget.isPPC64(); 2869 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2870 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2871 : Subtarget.isAIXABI() 2872 ? DAG.getRegister(PPC::R2, VT) 2873 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2874 SDValue Ops[] = { GA, Reg }; 2875 return DAG.getMemIntrinsicNode( 2876 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2877 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2878 MachineMemOperand::MOLoad); 2879 } 2880 2881 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2882 SelectionDAG &DAG) const { 2883 EVT PtrVT = Op.getValueType(); 2884 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2885 const Constant *C = CP->getConstVal(); 2886 2887 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2888 // The actual address of the GlobalValue is stored in the TOC. 2889 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2890 if (Subtarget.isUsingPCRelativeCalls()) { 2891 SDLoc DL(CP); 2892 EVT Ty = getPointerTy(DAG.getDataLayout()); 2893 SDValue ConstPool = DAG.getTargetConstantPool( 2894 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2895 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2896 } 2897 setUsesTOCBasePtr(DAG); 2898 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2899 return getTOCEntry(DAG, SDLoc(CP), GA); 2900 } 2901 2902 unsigned MOHiFlag, MOLoFlag; 2903 bool IsPIC = isPositionIndependent(); 2904 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2905 2906 if (IsPIC && Subtarget.isSVR4ABI()) { 2907 SDValue GA = 2908 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2909 return getTOCEntry(DAG, SDLoc(CP), GA); 2910 } 2911 2912 SDValue CPIHi = 2913 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2914 SDValue CPILo = 2915 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2916 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2917 } 2918 2919 // For 64-bit PowerPC, prefer the more compact relative encodings. 2920 // This trades 32 bits per jump table entry for one or two instructions 2921 // on the jump site. 2922 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2923 if (isJumpTableRelative()) 2924 return MachineJumpTableInfo::EK_LabelDifference32; 2925 2926 return TargetLowering::getJumpTableEncoding(); 2927 } 2928 2929 bool PPCTargetLowering::isJumpTableRelative() const { 2930 if (UseAbsoluteJumpTables) 2931 return false; 2932 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2933 return true; 2934 return TargetLowering::isJumpTableRelative(); 2935 } 2936 2937 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2938 SelectionDAG &DAG) const { 2939 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2940 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2941 2942 switch (getTargetMachine().getCodeModel()) { 2943 case CodeModel::Small: 2944 case CodeModel::Medium: 2945 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2946 default: 2947 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2948 getPointerTy(DAG.getDataLayout())); 2949 } 2950 } 2951 2952 const MCExpr * 2953 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2954 unsigned JTI, 2955 MCContext &Ctx) const { 2956 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2957 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2958 2959 switch (getTargetMachine().getCodeModel()) { 2960 case CodeModel::Small: 2961 case CodeModel::Medium: 2962 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2963 default: 2964 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2965 } 2966 } 2967 2968 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2969 EVT PtrVT = Op.getValueType(); 2970 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2971 2972 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2973 if (Subtarget.isUsingPCRelativeCalls()) { 2974 SDLoc DL(JT); 2975 EVT Ty = getPointerTy(DAG.getDataLayout()); 2976 SDValue GA = 2977 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2978 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2979 return MatAddr; 2980 } 2981 2982 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2983 // The actual address of the GlobalValue is stored in the TOC. 2984 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2985 setUsesTOCBasePtr(DAG); 2986 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2987 return getTOCEntry(DAG, SDLoc(JT), GA); 2988 } 2989 2990 unsigned MOHiFlag, MOLoFlag; 2991 bool IsPIC = isPositionIndependent(); 2992 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2993 2994 if (IsPIC && Subtarget.isSVR4ABI()) { 2995 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2996 PPCII::MO_PIC_FLAG); 2997 return getTOCEntry(DAG, SDLoc(GA), GA); 2998 } 2999 3000 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3001 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3002 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3003 } 3004 3005 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3006 SelectionDAG &DAG) const { 3007 EVT PtrVT = Op.getValueType(); 3008 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3009 const BlockAddress *BA = BASDN->getBlockAddress(); 3010 3011 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3012 if (Subtarget.isUsingPCRelativeCalls()) { 3013 SDLoc DL(BASDN); 3014 EVT Ty = getPointerTy(DAG.getDataLayout()); 3015 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3016 PPCII::MO_PCREL_FLAG); 3017 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3018 return MatAddr; 3019 } 3020 3021 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3022 // The actual BlockAddress is stored in the TOC. 3023 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3024 setUsesTOCBasePtr(DAG); 3025 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3026 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3027 } 3028 3029 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3030 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3031 return getTOCEntry( 3032 DAG, SDLoc(BASDN), 3033 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3034 3035 unsigned MOHiFlag, MOLoFlag; 3036 bool IsPIC = isPositionIndependent(); 3037 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3038 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3039 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3040 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3041 } 3042 3043 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3044 SelectionDAG &DAG) const { 3045 // FIXME: TLS addresses currently use medium model code sequences, 3046 // which is the most useful form. Eventually support for small and 3047 // large models could be added if users need it, at the cost of 3048 // additional complexity. 3049 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3050 if (DAG.getTarget().useEmulatedTLS()) 3051 return LowerToTLSEmulatedModel(GA, DAG); 3052 3053 SDLoc dl(GA); 3054 const GlobalValue *GV = GA->getGlobal(); 3055 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3056 bool is64bit = Subtarget.isPPC64(); 3057 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3058 PICLevel::Level picLevel = M->getPICLevel(); 3059 3060 const TargetMachine &TM = getTargetMachine(); 3061 TLSModel::Model Model = TM.getTLSModel(GV); 3062 3063 if (Model == TLSModel::LocalExec) { 3064 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3065 PPCII::MO_TPREL_HA); 3066 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3067 PPCII::MO_TPREL_LO); 3068 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3069 : DAG.getRegister(PPC::R2, MVT::i32); 3070 3071 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3072 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3073 } 3074 3075 if (Model == TLSModel::InitialExec) { 3076 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3077 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3078 PPCII::MO_TLS); 3079 SDValue GOTPtr; 3080 if (is64bit) { 3081 setUsesTOCBasePtr(DAG); 3082 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3083 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 3084 PtrVT, GOTReg, TGA); 3085 } else { 3086 if (!TM.isPositionIndependent()) 3087 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3088 else if (picLevel == PICLevel::SmallPIC) 3089 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3090 else 3091 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3092 } 3093 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 3094 PtrVT, TGA, GOTPtr); 3095 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3096 } 3097 3098 if (Model == TLSModel::GeneralDynamic) { 3099 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3100 SDValue GOTPtr; 3101 if (is64bit) { 3102 setUsesTOCBasePtr(DAG); 3103 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3104 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3105 GOTReg, TGA); 3106 } else { 3107 if (picLevel == PICLevel::SmallPIC) 3108 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3109 else 3110 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3111 } 3112 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3113 GOTPtr, TGA, TGA); 3114 } 3115 3116 if (Model == TLSModel::LocalDynamic) { 3117 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3118 SDValue GOTPtr; 3119 if (is64bit) { 3120 setUsesTOCBasePtr(DAG); 3121 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3122 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3123 GOTReg, TGA); 3124 } else { 3125 if (picLevel == PICLevel::SmallPIC) 3126 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3127 else 3128 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3129 } 3130 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3131 PtrVT, GOTPtr, TGA, TGA); 3132 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3133 PtrVT, TLSAddr, TGA); 3134 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3135 } 3136 3137 llvm_unreachable("Unknown TLS model!"); 3138 } 3139 3140 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3141 SelectionDAG &DAG) const { 3142 EVT PtrVT = Op.getValueType(); 3143 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3144 SDLoc DL(GSDN); 3145 const GlobalValue *GV = GSDN->getGlobal(); 3146 3147 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3148 // The actual address of the GlobalValue is stored in the TOC. 3149 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3150 if (Subtarget.isUsingPCRelativeCalls()) { 3151 EVT Ty = getPointerTy(DAG.getDataLayout()); 3152 if (isAccessedAsGotIndirect(Op)) { 3153 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3154 PPCII::MO_PCREL_FLAG | 3155 PPCII::MO_GOT_FLAG); 3156 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3157 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3158 MachinePointerInfo()); 3159 return Load; 3160 } else { 3161 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3162 PPCII::MO_PCREL_FLAG); 3163 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3164 } 3165 } 3166 setUsesTOCBasePtr(DAG); 3167 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3168 return getTOCEntry(DAG, DL, GA); 3169 } 3170 3171 unsigned MOHiFlag, MOLoFlag; 3172 bool IsPIC = isPositionIndependent(); 3173 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3174 3175 if (IsPIC && Subtarget.isSVR4ABI()) { 3176 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3177 GSDN->getOffset(), 3178 PPCII::MO_PIC_FLAG); 3179 return getTOCEntry(DAG, DL, GA); 3180 } 3181 3182 SDValue GAHi = 3183 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3184 SDValue GALo = 3185 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3186 3187 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3188 } 3189 3190 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3191 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3192 SDLoc dl(Op); 3193 3194 if (Op.getValueType() == MVT::v2i64) { 3195 // When the operands themselves are v2i64 values, we need to do something 3196 // special because VSX has no underlying comparison operations for these. 3197 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3198 // Equality can be handled by casting to the legal type for Altivec 3199 // comparisons, everything else needs to be expanded. 3200 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3201 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3202 DAG.getSetCC(dl, MVT::v4i32, 3203 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3204 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3205 CC)); 3206 } 3207 3208 return SDValue(); 3209 } 3210 3211 // We handle most of these in the usual way. 3212 return Op; 3213 } 3214 3215 // If we're comparing for equality to zero, expose the fact that this is 3216 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3217 // fold the new nodes. 3218 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3219 return V; 3220 3221 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3222 // Leave comparisons against 0 and -1 alone for now, since they're usually 3223 // optimized. FIXME: revisit this when we can custom lower all setcc 3224 // optimizations. 3225 if (C->isAllOnesValue() || C->isNullValue()) 3226 return SDValue(); 3227 } 3228 3229 // If we have an integer seteq/setne, turn it into a compare against zero 3230 // by xor'ing the rhs with the lhs, which is faster than setting a 3231 // condition register, reading it back out, and masking the correct bit. The 3232 // normal approach here uses sub to do this instead of xor. Using xor exposes 3233 // the result to other bit-twiddling opportunities. 3234 EVT LHSVT = Op.getOperand(0).getValueType(); 3235 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3236 EVT VT = Op.getValueType(); 3237 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3238 Op.getOperand(1)); 3239 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3240 } 3241 return SDValue(); 3242 } 3243 3244 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3245 SDNode *Node = Op.getNode(); 3246 EVT VT = Node->getValueType(0); 3247 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3248 SDValue InChain = Node->getOperand(0); 3249 SDValue VAListPtr = Node->getOperand(1); 3250 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3251 SDLoc dl(Node); 3252 3253 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3254 3255 // gpr_index 3256 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3257 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3258 InChain = GprIndex.getValue(1); 3259 3260 if (VT == MVT::i64) { 3261 // Check if GprIndex is even 3262 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3263 DAG.getConstant(1, dl, MVT::i32)); 3264 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3265 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3266 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3267 DAG.getConstant(1, dl, MVT::i32)); 3268 // Align GprIndex to be even if it isn't 3269 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3270 GprIndex); 3271 } 3272 3273 // fpr index is 1 byte after gpr 3274 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3275 DAG.getConstant(1, dl, MVT::i32)); 3276 3277 // fpr 3278 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3279 FprPtr, MachinePointerInfo(SV), MVT::i8); 3280 InChain = FprIndex.getValue(1); 3281 3282 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3283 DAG.getConstant(8, dl, MVT::i32)); 3284 3285 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3286 DAG.getConstant(4, dl, MVT::i32)); 3287 3288 // areas 3289 SDValue OverflowArea = 3290 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3291 InChain = OverflowArea.getValue(1); 3292 3293 SDValue RegSaveArea = 3294 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3295 InChain = RegSaveArea.getValue(1); 3296 3297 // select overflow_area if index > 8 3298 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3299 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3300 3301 // adjustment constant gpr_index * 4/8 3302 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3303 VT.isInteger() ? GprIndex : FprIndex, 3304 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3305 MVT::i32)); 3306 3307 // OurReg = RegSaveArea + RegConstant 3308 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3309 RegConstant); 3310 3311 // Floating types are 32 bytes into RegSaveArea 3312 if (VT.isFloatingPoint()) 3313 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3314 DAG.getConstant(32, dl, MVT::i32)); 3315 3316 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3317 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3318 VT.isInteger() ? GprIndex : FprIndex, 3319 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3320 MVT::i32)); 3321 3322 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3323 VT.isInteger() ? VAListPtr : FprPtr, 3324 MachinePointerInfo(SV), MVT::i8); 3325 3326 // determine if we should load from reg_save_area or overflow_area 3327 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3328 3329 // increase overflow_area by 4/8 if gpr/fpr > 8 3330 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3331 DAG.getConstant(VT.isInteger() ? 4 : 8, 3332 dl, MVT::i32)); 3333 3334 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3335 OverflowAreaPlusN); 3336 3337 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3338 MachinePointerInfo(), MVT::i32); 3339 3340 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3341 } 3342 3343 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3344 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3345 3346 // We have to copy the entire va_list struct: 3347 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3348 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3349 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3350 false, true, false, MachinePointerInfo(), 3351 MachinePointerInfo()); 3352 } 3353 3354 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3355 SelectionDAG &DAG) const { 3356 if (Subtarget.isAIXABI()) 3357 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3358 3359 return Op.getOperand(0); 3360 } 3361 3362 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3363 SelectionDAG &DAG) const { 3364 if (Subtarget.isAIXABI()) 3365 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3366 3367 SDValue Chain = Op.getOperand(0); 3368 SDValue Trmp = Op.getOperand(1); // trampoline 3369 SDValue FPtr = Op.getOperand(2); // nested function 3370 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3371 SDLoc dl(Op); 3372 3373 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3374 bool isPPC64 = (PtrVT == MVT::i64); 3375 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3376 3377 TargetLowering::ArgListTy Args; 3378 TargetLowering::ArgListEntry Entry; 3379 3380 Entry.Ty = IntPtrTy; 3381 Entry.Node = Trmp; Args.push_back(Entry); 3382 3383 // TrampSize == (isPPC64 ? 48 : 40); 3384 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3385 isPPC64 ? MVT::i64 : MVT::i32); 3386 Args.push_back(Entry); 3387 3388 Entry.Node = FPtr; Args.push_back(Entry); 3389 Entry.Node = Nest; Args.push_back(Entry); 3390 3391 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3392 TargetLowering::CallLoweringInfo CLI(DAG); 3393 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3394 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3395 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3396 3397 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3398 return CallResult.second; 3399 } 3400 3401 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3402 MachineFunction &MF = DAG.getMachineFunction(); 3403 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3404 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3405 3406 SDLoc dl(Op); 3407 3408 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3409 // vastart just stores the address of the VarArgsFrameIndex slot into the 3410 // memory location argument. 3411 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3412 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3413 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3414 MachinePointerInfo(SV)); 3415 } 3416 3417 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3418 // We suppose the given va_list is already allocated. 3419 // 3420 // typedef struct { 3421 // char gpr; /* index into the array of 8 GPRs 3422 // * stored in the register save area 3423 // * gpr=0 corresponds to r3, 3424 // * gpr=1 to r4, etc. 3425 // */ 3426 // char fpr; /* index into the array of 8 FPRs 3427 // * stored in the register save area 3428 // * fpr=0 corresponds to f1, 3429 // * fpr=1 to f2, etc. 3430 // */ 3431 // char *overflow_arg_area; 3432 // /* location on stack that holds 3433 // * the next overflow argument 3434 // */ 3435 // char *reg_save_area; 3436 // /* where r3:r10 and f1:f8 (if saved) 3437 // * are stored 3438 // */ 3439 // } va_list[1]; 3440 3441 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3442 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3443 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3444 PtrVT); 3445 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3446 PtrVT); 3447 3448 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3449 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3450 3451 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3452 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3453 3454 uint64_t FPROffset = 1; 3455 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3456 3457 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3458 3459 // Store first byte : number of int regs 3460 SDValue firstStore = 3461 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3462 MachinePointerInfo(SV), MVT::i8); 3463 uint64_t nextOffset = FPROffset; 3464 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3465 ConstFPROffset); 3466 3467 // Store second byte : number of float regs 3468 SDValue secondStore = 3469 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3470 MachinePointerInfo(SV, nextOffset), MVT::i8); 3471 nextOffset += StackOffset; 3472 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3473 3474 // Store second word : arguments given on stack 3475 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3476 MachinePointerInfo(SV, nextOffset)); 3477 nextOffset += FrameOffset; 3478 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3479 3480 // Store third word : arguments given in registers 3481 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3482 MachinePointerInfo(SV, nextOffset)); 3483 } 3484 3485 /// FPR - The set of FP registers that should be allocated for arguments 3486 /// on Darwin and AIX. 3487 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3488 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3489 PPC::F11, PPC::F12, PPC::F13}; 3490 3491 /// QFPR - The set of QPX registers that should be allocated for arguments. 3492 static const MCPhysReg QFPR[] = { 3493 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3494 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3495 3496 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3497 /// the stack. 3498 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3499 unsigned PtrByteSize) { 3500 unsigned ArgSize = ArgVT.getStoreSize(); 3501 if (Flags.isByVal()) 3502 ArgSize = Flags.getByValSize(); 3503 3504 // Round up to multiples of the pointer size, except for array members, 3505 // which are always packed. 3506 if (!Flags.isInConsecutiveRegs()) 3507 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3508 3509 return ArgSize; 3510 } 3511 3512 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3513 /// on the stack. 3514 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3515 ISD::ArgFlagsTy Flags, 3516 unsigned PtrByteSize) { 3517 Align Alignment(PtrByteSize); 3518 3519 // Altivec parameters are padded to a 16 byte boundary. 3520 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3521 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3522 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3523 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3524 Alignment = Align(16); 3525 // QPX vector types stored in double-precision are padded to a 32 byte 3526 // boundary. 3527 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3528 Alignment = Align(32); 3529 3530 // ByVal parameters are aligned as requested. 3531 if (Flags.isByVal()) { 3532 auto BVAlign = Flags.getNonZeroByValAlign(); 3533 if (BVAlign > PtrByteSize) { 3534 if (BVAlign.value() % PtrByteSize != 0) 3535 llvm_unreachable( 3536 "ByVal alignment is not a multiple of the pointer size"); 3537 3538 Alignment = BVAlign; 3539 } 3540 } 3541 3542 // Array members are always packed to their original alignment. 3543 if (Flags.isInConsecutiveRegs()) { 3544 // If the array member was split into multiple registers, the first 3545 // needs to be aligned to the size of the full type. (Except for 3546 // ppcf128, which is only aligned as its f64 components.) 3547 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3548 Alignment = Align(OrigVT.getStoreSize()); 3549 else 3550 Alignment = Align(ArgVT.getStoreSize()); 3551 } 3552 3553 return Alignment; 3554 } 3555 3556 /// CalculateStackSlotUsed - Return whether this argument will use its 3557 /// stack slot (instead of being passed in registers). ArgOffset, 3558 /// AvailableFPRs, and AvailableVRs must hold the current argument 3559 /// position, and will be updated to account for this argument. 3560 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3561 ISD::ArgFlagsTy Flags, 3562 unsigned PtrByteSize, 3563 unsigned LinkageSize, 3564 unsigned ParamAreaSize, 3565 unsigned &ArgOffset, 3566 unsigned &AvailableFPRs, 3567 unsigned &AvailableVRs, bool HasQPX) { 3568 bool UseMemory = false; 3569 3570 // Respect alignment of argument on the stack. 3571 Align Alignment = 3572 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3573 ArgOffset = alignTo(ArgOffset, Alignment); 3574 // If there's no space left in the argument save area, we must 3575 // use memory (this check also catches zero-sized arguments). 3576 if (ArgOffset >= LinkageSize + ParamAreaSize) 3577 UseMemory = true; 3578 3579 // Allocate argument on the stack. 3580 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3581 if (Flags.isInConsecutiveRegsLast()) 3582 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3583 // If we overran the argument save area, we must use memory 3584 // (this check catches arguments passed partially in memory) 3585 if (ArgOffset > LinkageSize + ParamAreaSize) 3586 UseMemory = true; 3587 3588 // However, if the argument is actually passed in an FPR or a VR, 3589 // we don't use memory after all. 3590 if (!Flags.isByVal()) { 3591 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3592 // QPX registers overlap with the scalar FP registers. 3593 (HasQPX && (ArgVT == MVT::v4f32 || 3594 ArgVT == MVT::v4f64 || 3595 ArgVT == MVT::v4i1))) 3596 if (AvailableFPRs > 0) { 3597 --AvailableFPRs; 3598 return false; 3599 } 3600 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3601 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3602 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3603 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3604 if (AvailableVRs > 0) { 3605 --AvailableVRs; 3606 return false; 3607 } 3608 } 3609 3610 return UseMemory; 3611 } 3612 3613 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3614 /// ensure minimum alignment required for target. 3615 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3616 unsigned NumBytes) { 3617 return alignTo(NumBytes, Lowering->getStackAlign()); 3618 } 3619 3620 SDValue PPCTargetLowering::LowerFormalArguments( 3621 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3622 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3623 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3624 if (Subtarget.isAIXABI()) 3625 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3626 InVals); 3627 if (Subtarget.is64BitELFABI()) 3628 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3629 InVals); 3630 if (Subtarget.is32BitELFABI()) 3631 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3632 InVals); 3633 3634 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3635 InVals); 3636 } 3637 3638 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3639 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3640 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3641 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3642 3643 // 32-bit SVR4 ABI Stack Frame Layout: 3644 // +-----------------------------------+ 3645 // +--> | Back chain | 3646 // | +-----------------------------------+ 3647 // | | Floating-point register save area | 3648 // | +-----------------------------------+ 3649 // | | General register save area | 3650 // | +-----------------------------------+ 3651 // | | CR save word | 3652 // | +-----------------------------------+ 3653 // | | VRSAVE save word | 3654 // | +-----------------------------------+ 3655 // | | Alignment padding | 3656 // | +-----------------------------------+ 3657 // | | Vector register save area | 3658 // | +-----------------------------------+ 3659 // | | Local variable space | 3660 // | +-----------------------------------+ 3661 // | | Parameter list area | 3662 // | +-----------------------------------+ 3663 // | | LR save word | 3664 // | +-----------------------------------+ 3665 // SP--> +--- | Back chain | 3666 // +-----------------------------------+ 3667 // 3668 // Specifications: 3669 // System V Application Binary Interface PowerPC Processor Supplement 3670 // AltiVec Technology Programming Interface Manual 3671 3672 MachineFunction &MF = DAG.getMachineFunction(); 3673 MachineFrameInfo &MFI = MF.getFrameInfo(); 3674 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3675 3676 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3677 // Potential tail calls could cause overwriting of argument stack slots. 3678 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3679 (CallConv == CallingConv::Fast)); 3680 const Align PtrAlign(4); 3681 3682 // Assign locations to all of the incoming arguments. 3683 SmallVector<CCValAssign, 16> ArgLocs; 3684 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3685 *DAG.getContext()); 3686 3687 // Reserve space for the linkage area on the stack. 3688 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3689 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3690 if (useSoftFloat()) 3691 CCInfo.PreAnalyzeFormalArguments(Ins); 3692 3693 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3694 CCInfo.clearWasPPCF128(); 3695 3696 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3697 CCValAssign &VA = ArgLocs[i]; 3698 3699 // Arguments stored in registers. 3700 if (VA.isRegLoc()) { 3701 const TargetRegisterClass *RC; 3702 EVT ValVT = VA.getValVT(); 3703 3704 switch (ValVT.getSimpleVT().SimpleTy) { 3705 default: 3706 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3707 case MVT::i1: 3708 case MVT::i32: 3709 RC = &PPC::GPRCRegClass; 3710 break; 3711 case MVT::f32: 3712 if (Subtarget.hasP8Vector()) 3713 RC = &PPC::VSSRCRegClass; 3714 else if (Subtarget.hasSPE()) 3715 RC = &PPC::GPRCRegClass; 3716 else 3717 RC = &PPC::F4RCRegClass; 3718 break; 3719 case MVT::f64: 3720 if (Subtarget.hasVSX()) 3721 RC = &PPC::VSFRCRegClass; 3722 else if (Subtarget.hasSPE()) 3723 // SPE passes doubles in GPR pairs. 3724 RC = &PPC::GPRCRegClass; 3725 else 3726 RC = &PPC::F8RCRegClass; 3727 break; 3728 case MVT::v16i8: 3729 case MVT::v8i16: 3730 case MVT::v4i32: 3731 RC = &PPC::VRRCRegClass; 3732 break; 3733 case MVT::v4f32: 3734 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3735 break; 3736 case MVT::v2f64: 3737 case MVT::v2i64: 3738 RC = &PPC::VRRCRegClass; 3739 break; 3740 case MVT::v4f64: 3741 RC = &PPC::QFRCRegClass; 3742 break; 3743 case MVT::v4i1: 3744 RC = &PPC::QBRCRegClass; 3745 break; 3746 } 3747 3748 SDValue ArgValue; 3749 // Transform the arguments stored in physical registers into 3750 // virtual ones. 3751 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3752 assert(i + 1 < e && "No second half of double precision argument"); 3753 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3754 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3755 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3756 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3757 if (!Subtarget.isLittleEndian()) 3758 std::swap (ArgValueLo, ArgValueHi); 3759 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3760 ArgValueHi); 3761 } else { 3762 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3763 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3764 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3765 if (ValVT == MVT::i1) 3766 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3767 } 3768 3769 InVals.push_back(ArgValue); 3770 } else { 3771 // Argument stored in memory. 3772 assert(VA.isMemLoc()); 3773 3774 // Get the extended size of the argument type in stack 3775 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3776 // Get the actual size of the argument type 3777 unsigned ObjSize = VA.getValVT().getStoreSize(); 3778 unsigned ArgOffset = VA.getLocMemOffset(); 3779 // Stack objects in PPC32 are right justified. 3780 ArgOffset += ArgSize - ObjSize; 3781 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3782 3783 // Create load nodes to retrieve arguments from the stack. 3784 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3785 InVals.push_back( 3786 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3787 } 3788 } 3789 3790 // Assign locations to all of the incoming aggregate by value arguments. 3791 // Aggregates passed by value are stored in the local variable space of the 3792 // caller's stack frame, right above the parameter list area. 3793 SmallVector<CCValAssign, 16> ByValArgLocs; 3794 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3795 ByValArgLocs, *DAG.getContext()); 3796 3797 // Reserve stack space for the allocations in CCInfo. 3798 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3799 3800 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3801 3802 // Area that is at least reserved in the caller of this function. 3803 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3804 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3805 3806 // Set the size that is at least reserved in caller of this function. Tail 3807 // call optimized function's reserved stack space needs to be aligned so that 3808 // taking the difference between two stack areas will result in an aligned 3809 // stack. 3810 MinReservedArea = 3811 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3812 FuncInfo->setMinReservedArea(MinReservedArea); 3813 3814 SmallVector<SDValue, 8> MemOps; 3815 3816 // If the function takes variable number of arguments, make a frame index for 3817 // the start of the first vararg value... for expansion of llvm.va_start. 3818 if (isVarArg) { 3819 static const MCPhysReg GPArgRegs[] = { 3820 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3821 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3822 }; 3823 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3824 3825 static const MCPhysReg FPArgRegs[] = { 3826 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3827 PPC::F8 3828 }; 3829 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3830 3831 if (useSoftFloat() || hasSPE()) 3832 NumFPArgRegs = 0; 3833 3834 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3835 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3836 3837 // Make room for NumGPArgRegs and NumFPArgRegs. 3838 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3839 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3840 3841 FuncInfo->setVarArgsStackOffset( 3842 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3843 CCInfo.getNextStackOffset(), true)); 3844 3845 FuncInfo->setVarArgsFrameIndex( 3846 MFI.CreateStackObject(Depth, Align(8), false)); 3847 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3848 3849 // The fixed integer arguments of a variadic function are stored to the 3850 // VarArgsFrameIndex on the stack so that they may be loaded by 3851 // dereferencing the result of va_next. 3852 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3853 // Get an existing live-in vreg, or add a new one. 3854 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3855 if (!VReg) 3856 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3857 3858 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3859 SDValue Store = 3860 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3861 MemOps.push_back(Store); 3862 // Increment the address by four for the next argument to store 3863 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3864 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3865 } 3866 3867 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3868 // is set. 3869 // The double arguments are stored to the VarArgsFrameIndex 3870 // on the stack. 3871 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3872 // Get an existing live-in vreg, or add a new one. 3873 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3874 if (!VReg) 3875 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3876 3877 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3878 SDValue Store = 3879 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3880 MemOps.push_back(Store); 3881 // Increment the address by eight for the next argument to store 3882 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3883 PtrVT); 3884 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3885 } 3886 } 3887 3888 if (!MemOps.empty()) 3889 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3890 3891 return Chain; 3892 } 3893 3894 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3895 // value to MVT::i64 and then truncate to the correct register size. 3896 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3897 EVT ObjectVT, SelectionDAG &DAG, 3898 SDValue ArgVal, 3899 const SDLoc &dl) const { 3900 if (Flags.isSExt()) 3901 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3902 DAG.getValueType(ObjectVT)); 3903 else if (Flags.isZExt()) 3904 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3905 DAG.getValueType(ObjectVT)); 3906 3907 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3908 } 3909 3910 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3911 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3912 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3913 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3914 // TODO: add description of PPC stack frame format, or at least some docs. 3915 // 3916 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3917 bool isLittleEndian = Subtarget.isLittleEndian(); 3918 MachineFunction &MF = DAG.getMachineFunction(); 3919 MachineFrameInfo &MFI = MF.getFrameInfo(); 3920 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3921 3922 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3923 "fastcc not supported on varargs functions"); 3924 3925 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3926 // Potential tail calls could cause overwriting of argument stack slots. 3927 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3928 (CallConv == CallingConv::Fast)); 3929 unsigned PtrByteSize = 8; 3930 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3931 3932 static const MCPhysReg GPR[] = { 3933 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3934 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3935 }; 3936 static const MCPhysReg VR[] = { 3937 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3938 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3939 }; 3940 3941 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3942 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3943 const unsigned Num_VR_Regs = array_lengthof(VR); 3944 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3945 3946 // Do a first pass over the arguments to determine whether the ABI 3947 // guarantees that our caller has allocated the parameter save area 3948 // on its stack frame. In the ELFv1 ABI, this is always the case; 3949 // in the ELFv2 ABI, it is true if this is a vararg function or if 3950 // any parameter is located in a stack slot. 3951 3952 bool HasParameterArea = !isELFv2ABI || isVarArg; 3953 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3954 unsigned NumBytes = LinkageSize; 3955 unsigned AvailableFPRs = Num_FPR_Regs; 3956 unsigned AvailableVRs = Num_VR_Regs; 3957 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3958 if (Ins[i].Flags.isNest()) 3959 continue; 3960 3961 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3962 PtrByteSize, LinkageSize, ParamAreaSize, 3963 NumBytes, AvailableFPRs, AvailableVRs, 3964 Subtarget.hasQPX())) 3965 HasParameterArea = true; 3966 } 3967 3968 // Add DAG nodes to load the arguments or copy them out of registers. On 3969 // entry to a function on PPC, the arguments start after the linkage area, 3970 // although the first ones are often in registers. 3971 3972 unsigned ArgOffset = LinkageSize; 3973 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3974 unsigned &QFPR_idx = FPR_idx; 3975 SmallVector<SDValue, 8> MemOps; 3976 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3977 unsigned CurArgIdx = 0; 3978 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3979 SDValue ArgVal; 3980 bool needsLoad = false; 3981 EVT ObjectVT = Ins[ArgNo].VT; 3982 EVT OrigVT = Ins[ArgNo].ArgVT; 3983 unsigned ObjSize = ObjectVT.getStoreSize(); 3984 unsigned ArgSize = ObjSize; 3985 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3986 if (Ins[ArgNo].isOrigArg()) { 3987 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3988 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3989 } 3990 // We re-align the argument offset for each argument, except when using the 3991 // fast calling convention, when we need to make sure we do that only when 3992 // we'll actually use a stack slot. 3993 unsigned CurArgOffset; 3994 Align Alignment; 3995 auto ComputeArgOffset = [&]() { 3996 /* Respect alignment of argument on the stack. */ 3997 Alignment = 3998 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3999 ArgOffset = alignTo(ArgOffset, Alignment); 4000 CurArgOffset = ArgOffset; 4001 }; 4002 4003 if (CallConv != CallingConv::Fast) { 4004 ComputeArgOffset(); 4005 4006 /* Compute GPR index associated with argument offset. */ 4007 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4008 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4009 } 4010 4011 // FIXME the codegen can be much improved in some cases. 4012 // We do not have to keep everything in memory. 4013 if (Flags.isByVal()) { 4014 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4015 4016 if (CallConv == CallingConv::Fast) 4017 ComputeArgOffset(); 4018 4019 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4020 ObjSize = Flags.getByValSize(); 4021 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4022 // Empty aggregate parameters do not take up registers. Examples: 4023 // struct { } a; 4024 // union { } b; 4025 // int c[0]; 4026 // etc. However, we have to provide a place-holder in InVals, so 4027 // pretend we have an 8-byte item at the current address for that 4028 // purpose. 4029 if (!ObjSize) { 4030 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4031 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4032 InVals.push_back(FIN); 4033 continue; 4034 } 4035 4036 // Create a stack object covering all stack doublewords occupied 4037 // by the argument. If the argument is (fully or partially) on 4038 // the stack, or if the argument is fully in registers but the 4039 // caller has allocated the parameter save anyway, we can refer 4040 // directly to the caller's stack frame. Otherwise, create a 4041 // local copy in our own frame. 4042 int FI; 4043 if (HasParameterArea || 4044 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4045 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4046 else 4047 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4048 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4049 4050 // Handle aggregates smaller than 8 bytes. 4051 if (ObjSize < PtrByteSize) { 4052 // The value of the object is its address, which differs from the 4053 // address of the enclosing doubleword on big-endian systems. 4054 SDValue Arg = FIN; 4055 if (!isLittleEndian) { 4056 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4057 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4058 } 4059 InVals.push_back(Arg); 4060 4061 if (GPR_idx != Num_GPR_Regs) { 4062 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4063 FuncInfo->addLiveInAttr(VReg, Flags); 4064 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4065 SDValue Store; 4066 4067 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4068 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4069 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4070 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4071 MachinePointerInfo(&*FuncArg), ObjType); 4072 } else { 4073 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4074 // store the whole register as-is to the parameter save area 4075 // slot. 4076 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4077 MachinePointerInfo(&*FuncArg)); 4078 } 4079 4080 MemOps.push_back(Store); 4081 } 4082 // Whether we copied from a register or not, advance the offset 4083 // into the parameter save area by a full doubleword. 4084 ArgOffset += PtrByteSize; 4085 continue; 4086 } 4087 4088 // The value of the object is its address, which is the address of 4089 // its first stack doubleword. 4090 InVals.push_back(FIN); 4091 4092 // Store whatever pieces of the object are in registers to memory. 4093 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4094 if (GPR_idx == Num_GPR_Regs) 4095 break; 4096 4097 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4098 FuncInfo->addLiveInAttr(VReg, Flags); 4099 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4100 SDValue Addr = FIN; 4101 if (j) { 4102 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4103 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4104 } 4105 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4106 MachinePointerInfo(&*FuncArg, j)); 4107 MemOps.push_back(Store); 4108 ++GPR_idx; 4109 } 4110 ArgOffset += ArgSize; 4111 continue; 4112 } 4113 4114 switch (ObjectVT.getSimpleVT().SimpleTy) { 4115 default: llvm_unreachable("Unhandled argument type!"); 4116 case MVT::i1: 4117 case MVT::i32: 4118 case MVT::i64: 4119 if (Flags.isNest()) { 4120 // The 'nest' parameter, if any, is passed in R11. 4121 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4122 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4123 4124 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4125 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4126 4127 break; 4128 } 4129 4130 // These can be scalar arguments or elements of an integer array type 4131 // passed directly. Clang may use those instead of "byval" aggregate 4132 // types to avoid forcing arguments to memory unnecessarily. 4133 if (GPR_idx != Num_GPR_Regs) { 4134 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4135 FuncInfo->addLiveInAttr(VReg, Flags); 4136 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4137 4138 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4139 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4140 // value to MVT::i64 and then truncate to the correct register size. 4141 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4142 } else { 4143 if (CallConv == CallingConv::Fast) 4144 ComputeArgOffset(); 4145 4146 needsLoad = true; 4147 ArgSize = PtrByteSize; 4148 } 4149 if (CallConv != CallingConv::Fast || needsLoad) 4150 ArgOffset += 8; 4151 break; 4152 4153 case MVT::f32: 4154 case MVT::f64: 4155 // These can be scalar arguments or elements of a float array type 4156 // passed directly. The latter are used to implement ELFv2 homogenous 4157 // float aggregates. 4158 if (FPR_idx != Num_FPR_Regs) { 4159 unsigned VReg; 4160 4161 if (ObjectVT == MVT::f32) 4162 VReg = MF.addLiveIn(FPR[FPR_idx], 4163 Subtarget.hasP8Vector() 4164 ? &PPC::VSSRCRegClass 4165 : &PPC::F4RCRegClass); 4166 else 4167 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4168 ? &PPC::VSFRCRegClass 4169 : &PPC::F8RCRegClass); 4170 4171 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4172 ++FPR_idx; 4173 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4174 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4175 // once we support fp <-> gpr moves. 4176 4177 // This can only ever happen in the presence of f32 array types, 4178 // since otherwise we never run out of FPRs before running out 4179 // of GPRs. 4180 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4181 FuncInfo->addLiveInAttr(VReg, Flags); 4182 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4183 4184 if (ObjectVT == MVT::f32) { 4185 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4186 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4187 DAG.getConstant(32, dl, MVT::i32)); 4188 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4189 } 4190 4191 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4192 } else { 4193 if (CallConv == CallingConv::Fast) 4194 ComputeArgOffset(); 4195 4196 needsLoad = true; 4197 } 4198 4199 // When passing an array of floats, the array occupies consecutive 4200 // space in the argument area; only round up to the next doubleword 4201 // at the end of the array. Otherwise, each float takes 8 bytes. 4202 if (CallConv != CallingConv::Fast || needsLoad) { 4203 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4204 ArgOffset += ArgSize; 4205 if (Flags.isInConsecutiveRegsLast()) 4206 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4207 } 4208 break; 4209 case MVT::v4f32: 4210 case MVT::v4i32: 4211 case MVT::v8i16: 4212 case MVT::v16i8: 4213 case MVT::v2f64: 4214 case MVT::v2i64: 4215 case MVT::v1i128: 4216 case MVT::f128: 4217 if (!Subtarget.hasQPX()) { 4218 // These can be scalar arguments or elements of a vector array type 4219 // passed directly. The latter are used to implement ELFv2 homogenous 4220 // vector aggregates. 4221 if (VR_idx != Num_VR_Regs) { 4222 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4223 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4224 ++VR_idx; 4225 } else { 4226 if (CallConv == CallingConv::Fast) 4227 ComputeArgOffset(); 4228 needsLoad = true; 4229 } 4230 if (CallConv != CallingConv::Fast || needsLoad) 4231 ArgOffset += 16; 4232 break; 4233 } // not QPX 4234 4235 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4236 "Invalid QPX parameter type"); 4237 LLVM_FALLTHROUGH; 4238 4239 case MVT::v4f64: 4240 case MVT::v4i1: 4241 // QPX vectors are treated like their scalar floating-point subregisters 4242 // (except that they're larger). 4243 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4244 if (QFPR_idx != Num_QFPR_Regs) { 4245 const TargetRegisterClass *RC; 4246 switch (ObjectVT.getSimpleVT().SimpleTy) { 4247 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4248 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4249 default: RC = &PPC::QBRCRegClass; break; 4250 } 4251 4252 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4253 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4254 ++QFPR_idx; 4255 } else { 4256 if (CallConv == CallingConv::Fast) 4257 ComputeArgOffset(); 4258 needsLoad = true; 4259 } 4260 if (CallConv != CallingConv::Fast || needsLoad) 4261 ArgOffset += Sz; 4262 break; 4263 } 4264 4265 // We need to load the argument to a virtual register if we determined 4266 // above that we ran out of physical registers of the appropriate type. 4267 if (needsLoad) { 4268 if (ObjSize < ArgSize && !isLittleEndian) 4269 CurArgOffset += ArgSize - ObjSize; 4270 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4271 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4272 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4273 } 4274 4275 InVals.push_back(ArgVal); 4276 } 4277 4278 // Area that is at least reserved in the caller of this function. 4279 unsigned MinReservedArea; 4280 if (HasParameterArea) 4281 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4282 else 4283 MinReservedArea = LinkageSize; 4284 4285 // Set the size that is at least reserved in caller of this function. Tail 4286 // call optimized functions' reserved stack space needs to be aligned so that 4287 // taking the difference between two stack areas will result in an aligned 4288 // stack. 4289 MinReservedArea = 4290 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4291 FuncInfo->setMinReservedArea(MinReservedArea); 4292 4293 // If the function takes variable number of arguments, make a frame index for 4294 // the start of the first vararg value... for expansion of llvm.va_start. 4295 if (isVarArg) { 4296 int Depth = ArgOffset; 4297 4298 FuncInfo->setVarArgsFrameIndex( 4299 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4300 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4301 4302 // If this function is vararg, store any remaining integer argument regs 4303 // to their spots on the stack so that they may be loaded by dereferencing 4304 // the result of va_next. 4305 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4306 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4307 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4308 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4309 SDValue Store = 4310 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4311 MemOps.push_back(Store); 4312 // Increment the address by four for the next argument to store 4313 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4314 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4315 } 4316 } 4317 4318 if (!MemOps.empty()) 4319 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4320 4321 return Chain; 4322 } 4323 4324 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4325 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4326 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4327 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4328 // TODO: add description of PPC stack frame format, or at least some docs. 4329 // 4330 MachineFunction &MF = DAG.getMachineFunction(); 4331 MachineFrameInfo &MFI = MF.getFrameInfo(); 4332 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4333 4334 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4335 bool isPPC64 = PtrVT == MVT::i64; 4336 // Potential tail calls could cause overwriting of argument stack slots. 4337 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4338 (CallConv == CallingConv::Fast)); 4339 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4340 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4341 unsigned ArgOffset = LinkageSize; 4342 // Area that is at least reserved in caller of this function. 4343 unsigned MinReservedArea = ArgOffset; 4344 4345 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4346 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4347 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4348 }; 4349 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4350 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4351 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4352 }; 4353 static const MCPhysReg VR[] = { 4354 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4355 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4356 }; 4357 4358 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4359 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4360 const unsigned Num_VR_Regs = array_lengthof( VR); 4361 4362 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4363 4364 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4365 4366 // In 32-bit non-varargs functions, the stack space for vectors is after the 4367 // stack space for non-vectors. We do not use this space unless we have 4368 // too many vectors to fit in registers, something that only occurs in 4369 // constructed examples:), but we have to walk the arglist to figure 4370 // that out...for the pathological case, compute VecArgOffset as the 4371 // start of the vector parameter area. Computing VecArgOffset is the 4372 // entire point of the following loop. 4373 unsigned VecArgOffset = ArgOffset; 4374 if (!isVarArg && !isPPC64) { 4375 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4376 ++ArgNo) { 4377 EVT ObjectVT = Ins[ArgNo].VT; 4378 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4379 4380 if (Flags.isByVal()) { 4381 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4382 unsigned ObjSize = Flags.getByValSize(); 4383 unsigned ArgSize = 4384 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4385 VecArgOffset += ArgSize; 4386 continue; 4387 } 4388 4389 switch(ObjectVT.getSimpleVT().SimpleTy) { 4390 default: llvm_unreachable("Unhandled argument type!"); 4391 case MVT::i1: 4392 case MVT::i32: 4393 case MVT::f32: 4394 VecArgOffset += 4; 4395 break; 4396 case MVT::i64: // PPC64 4397 case MVT::f64: 4398 // FIXME: We are guaranteed to be !isPPC64 at this point. 4399 // Does MVT::i64 apply? 4400 VecArgOffset += 8; 4401 break; 4402 case MVT::v4f32: 4403 case MVT::v4i32: 4404 case MVT::v8i16: 4405 case MVT::v16i8: 4406 // Nothing to do, we're only looking at Nonvector args here. 4407 break; 4408 } 4409 } 4410 } 4411 // We've found where the vector parameter area in memory is. Skip the 4412 // first 12 parameters; these don't use that memory. 4413 VecArgOffset = ((VecArgOffset+15)/16)*16; 4414 VecArgOffset += 12*16; 4415 4416 // Add DAG nodes to load the arguments or copy them out of registers. On 4417 // entry to a function on PPC, the arguments start after the linkage area, 4418 // although the first ones are often in registers. 4419 4420 SmallVector<SDValue, 8> MemOps; 4421 unsigned nAltivecParamsAtEnd = 0; 4422 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4423 unsigned CurArgIdx = 0; 4424 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4425 SDValue ArgVal; 4426 bool needsLoad = false; 4427 EVT ObjectVT = Ins[ArgNo].VT; 4428 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4429 unsigned ArgSize = ObjSize; 4430 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4431 if (Ins[ArgNo].isOrigArg()) { 4432 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4433 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4434 } 4435 unsigned CurArgOffset = ArgOffset; 4436 4437 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4438 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4439 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4440 if (isVarArg || isPPC64) { 4441 MinReservedArea = ((MinReservedArea+15)/16)*16; 4442 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4443 Flags, 4444 PtrByteSize); 4445 } else nAltivecParamsAtEnd++; 4446 } else 4447 // Calculate min reserved area. 4448 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4449 Flags, 4450 PtrByteSize); 4451 4452 // FIXME the codegen can be much improved in some cases. 4453 // We do not have to keep everything in memory. 4454 if (Flags.isByVal()) { 4455 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4456 4457 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4458 ObjSize = Flags.getByValSize(); 4459 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4460 // Objects of size 1 and 2 are right justified, everything else is 4461 // left justified. This means the memory address is adjusted forwards. 4462 if (ObjSize==1 || ObjSize==2) { 4463 CurArgOffset = CurArgOffset + (4 - ObjSize); 4464 } 4465 // The value of the object is its address. 4466 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4467 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4468 InVals.push_back(FIN); 4469 if (ObjSize==1 || ObjSize==2) { 4470 if (GPR_idx != Num_GPR_Regs) { 4471 unsigned VReg; 4472 if (isPPC64) 4473 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4474 else 4475 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4476 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4477 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4478 SDValue Store = 4479 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4480 MachinePointerInfo(&*FuncArg), ObjType); 4481 MemOps.push_back(Store); 4482 ++GPR_idx; 4483 } 4484 4485 ArgOffset += PtrByteSize; 4486 4487 continue; 4488 } 4489 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4490 // Store whatever pieces of the object are in registers 4491 // to memory. ArgOffset will be the address of the beginning 4492 // of the object. 4493 if (GPR_idx != Num_GPR_Regs) { 4494 unsigned VReg; 4495 if (isPPC64) 4496 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4497 else 4498 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4499 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4500 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4501 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4502 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4503 MachinePointerInfo(&*FuncArg, j)); 4504 MemOps.push_back(Store); 4505 ++GPR_idx; 4506 ArgOffset += PtrByteSize; 4507 } else { 4508 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4509 break; 4510 } 4511 } 4512 continue; 4513 } 4514 4515 switch (ObjectVT.getSimpleVT().SimpleTy) { 4516 default: llvm_unreachable("Unhandled argument type!"); 4517 case MVT::i1: 4518 case MVT::i32: 4519 if (!isPPC64) { 4520 if (GPR_idx != Num_GPR_Regs) { 4521 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4522 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4523 4524 if (ObjectVT == MVT::i1) 4525 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4526 4527 ++GPR_idx; 4528 } else { 4529 needsLoad = true; 4530 ArgSize = PtrByteSize; 4531 } 4532 // All int arguments reserve stack space in the Darwin ABI. 4533 ArgOffset += PtrByteSize; 4534 break; 4535 } 4536 LLVM_FALLTHROUGH; 4537 case MVT::i64: // PPC64 4538 if (GPR_idx != Num_GPR_Regs) { 4539 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4540 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4541 4542 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4543 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4544 // value to MVT::i64 and then truncate to the correct register size. 4545 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4546 4547 ++GPR_idx; 4548 } else { 4549 needsLoad = true; 4550 ArgSize = PtrByteSize; 4551 } 4552 // All int arguments reserve stack space in the Darwin ABI. 4553 ArgOffset += 8; 4554 break; 4555 4556 case MVT::f32: 4557 case MVT::f64: 4558 // Every 4 bytes of argument space consumes one of the GPRs available for 4559 // argument passing. 4560 if (GPR_idx != Num_GPR_Regs) { 4561 ++GPR_idx; 4562 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4563 ++GPR_idx; 4564 } 4565 if (FPR_idx != Num_FPR_Regs) { 4566 unsigned VReg; 4567 4568 if (ObjectVT == MVT::f32) 4569 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4570 else 4571 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4572 4573 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4574 ++FPR_idx; 4575 } else { 4576 needsLoad = true; 4577 } 4578 4579 // All FP arguments reserve stack space in the Darwin ABI. 4580 ArgOffset += isPPC64 ? 8 : ObjSize; 4581 break; 4582 case MVT::v4f32: 4583 case MVT::v4i32: 4584 case MVT::v8i16: 4585 case MVT::v16i8: 4586 // Note that vector arguments in registers don't reserve stack space, 4587 // except in varargs functions. 4588 if (VR_idx != Num_VR_Regs) { 4589 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4590 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4591 if (isVarArg) { 4592 while ((ArgOffset % 16) != 0) { 4593 ArgOffset += PtrByteSize; 4594 if (GPR_idx != Num_GPR_Regs) 4595 GPR_idx++; 4596 } 4597 ArgOffset += 16; 4598 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4599 } 4600 ++VR_idx; 4601 } else { 4602 if (!isVarArg && !isPPC64) { 4603 // Vectors go after all the nonvectors. 4604 CurArgOffset = VecArgOffset; 4605 VecArgOffset += 16; 4606 } else { 4607 // Vectors are aligned. 4608 ArgOffset = ((ArgOffset+15)/16)*16; 4609 CurArgOffset = ArgOffset; 4610 ArgOffset += 16; 4611 } 4612 needsLoad = true; 4613 } 4614 break; 4615 } 4616 4617 // We need to load the argument to a virtual register if we determined above 4618 // that we ran out of physical registers of the appropriate type. 4619 if (needsLoad) { 4620 int FI = MFI.CreateFixedObject(ObjSize, 4621 CurArgOffset + (ArgSize - ObjSize), 4622 isImmutable); 4623 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4624 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4625 } 4626 4627 InVals.push_back(ArgVal); 4628 } 4629 4630 // Allow for Altivec parameters at the end, if needed. 4631 if (nAltivecParamsAtEnd) { 4632 MinReservedArea = ((MinReservedArea+15)/16)*16; 4633 MinReservedArea += 16*nAltivecParamsAtEnd; 4634 } 4635 4636 // Area that is at least reserved in the caller of this function. 4637 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4638 4639 // Set the size that is at least reserved in caller of this function. Tail 4640 // call optimized functions' reserved stack space needs to be aligned so that 4641 // taking the difference between two stack areas will result in an aligned 4642 // stack. 4643 MinReservedArea = 4644 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4645 FuncInfo->setMinReservedArea(MinReservedArea); 4646 4647 // If the function takes variable number of arguments, make a frame index for 4648 // the start of the first vararg value... for expansion of llvm.va_start. 4649 if (isVarArg) { 4650 int Depth = ArgOffset; 4651 4652 FuncInfo->setVarArgsFrameIndex( 4653 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4654 Depth, true)); 4655 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4656 4657 // If this function is vararg, store any remaining integer argument regs 4658 // to their spots on the stack so that they may be loaded by dereferencing 4659 // the result of va_next. 4660 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4661 unsigned VReg; 4662 4663 if (isPPC64) 4664 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4665 else 4666 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4667 4668 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4669 SDValue Store = 4670 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4671 MemOps.push_back(Store); 4672 // Increment the address by four for the next argument to store 4673 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4674 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4675 } 4676 } 4677 4678 if (!MemOps.empty()) 4679 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4680 4681 return Chain; 4682 } 4683 4684 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4685 /// adjusted to accommodate the arguments for the tailcall. 4686 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4687 unsigned ParamSize) { 4688 4689 if (!isTailCall) return 0; 4690 4691 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4692 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4693 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4694 // Remember only if the new adjustment is bigger. 4695 if (SPDiff < FI->getTailCallSPDelta()) 4696 FI->setTailCallSPDelta(SPDiff); 4697 4698 return SPDiff; 4699 } 4700 4701 static bool isFunctionGlobalAddress(SDValue Callee); 4702 4703 static bool 4704 callsShareTOCBase(const Function *Caller, SDValue Callee, 4705 const TargetMachine &TM) { 4706 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4707 // don't have enough information to determine if the caller and calle share 4708 // the same TOC base, so we have to pessimistically assume they don't for 4709 // correctness. 4710 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4711 if (!G) 4712 return false; 4713 4714 const GlobalValue *GV = G->getGlobal(); 4715 // The medium and large code models are expected to provide a sufficiently 4716 // large TOC to provide all data addressing needs of a module with a 4717 // single TOC. Since each module will be addressed with a single TOC then we 4718 // only need to check that caller and callee don't cross dso boundaries. 4719 if (CodeModel::Medium == TM.getCodeModel() || 4720 CodeModel::Large == TM.getCodeModel()) 4721 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4722 4723 // Otherwise we need to ensure callee and caller are in the same section, 4724 // since the linker may allocate multiple TOCs, and we don't know which 4725 // sections will belong to the same TOC base. 4726 4727 if (!GV->isStrongDefinitionForLinker()) 4728 return false; 4729 4730 // Any explicitly-specified sections and section prefixes must also match. 4731 // Also, if we're using -ffunction-sections, then each function is always in 4732 // a different section (the same is true for COMDAT functions). 4733 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4734 GV->getSection() != Caller->getSection()) 4735 return false; 4736 if (const auto *F = dyn_cast<Function>(GV)) { 4737 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4738 return false; 4739 } 4740 4741 // If the callee might be interposed, then we can't assume the ultimate call 4742 // target will be in the same section. Even in cases where we can assume that 4743 // interposition won't happen, in any case where the linker might insert a 4744 // stub to allow for interposition, we must generate code as though 4745 // interposition might occur. To understand why this matters, consider a 4746 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4747 // in the same section, but a is in a different module (i.e. has a different 4748 // TOC base pointer). If the linker allows for interposition between b and c, 4749 // then it will generate a stub for the call edge between b and c which will 4750 // save the TOC pointer into the designated stack slot allocated by b. If we 4751 // return true here, and therefore allow a tail call between b and c, that 4752 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4753 // pointer into the stack slot allocated by a (where the a -> b stub saved 4754 // a's TOC base pointer). If we're not considering a tail call, but rather, 4755 // whether a nop is needed after the call instruction in b, because the linker 4756 // will insert a stub, it might complain about a missing nop if we omit it 4757 // (although many don't complain in this case). 4758 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4759 return false; 4760 4761 return true; 4762 } 4763 4764 static bool 4765 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4766 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4767 assert(Subtarget.is64BitELFABI()); 4768 4769 const unsigned PtrByteSize = 8; 4770 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4771 4772 static const MCPhysReg GPR[] = { 4773 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4774 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4775 }; 4776 static const MCPhysReg VR[] = { 4777 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4778 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4779 }; 4780 4781 const unsigned NumGPRs = array_lengthof(GPR); 4782 const unsigned NumFPRs = 13; 4783 const unsigned NumVRs = array_lengthof(VR); 4784 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4785 4786 unsigned NumBytes = LinkageSize; 4787 unsigned AvailableFPRs = NumFPRs; 4788 unsigned AvailableVRs = NumVRs; 4789 4790 for (const ISD::OutputArg& Param : Outs) { 4791 if (Param.Flags.isNest()) continue; 4792 4793 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4794 PtrByteSize, LinkageSize, ParamAreaSize, 4795 NumBytes, AvailableFPRs, AvailableVRs, 4796 Subtarget.hasQPX())) 4797 return true; 4798 } 4799 return false; 4800 } 4801 4802 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4803 if (CB.arg_size() != CallerFn->arg_size()) 4804 return false; 4805 4806 auto CalleeArgIter = CB.arg_begin(); 4807 auto CalleeArgEnd = CB.arg_end(); 4808 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4809 4810 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4811 const Value* CalleeArg = *CalleeArgIter; 4812 const Value* CallerArg = &(*CallerArgIter); 4813 if (CalleeArg == CallerArg) 4814 continue; 4815 4816 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4817 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4818 // } 4819 // 1st argument of callee is undef and has the same type as caller. 4820 if (CalleeArg->getType() == CallerArg->getType() && 4821 isa<UndefValue>(CalleeArg)) 4822 continue; 4823 4824 return false; 4825 } 4826 4827 return true; 4828 } 4829 4830 // Returns true if TCO is possible between the callers and callees 4831 // calling conventions. 4832 static bool 4833 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4834 CallingConv::ID CalleeCC) { 4835 // Tail calls are possible with fastcc and ccc. 4836 auto isTailCallableCC = [] (CallingConv::ID CC){ 4837 return CC == CallingConv::C || CC == CallingConv::Fast; 4838 }; 4839 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4840 return false; 4841 4842 // We can safely tail call both fastcc and ccc callees from a c calling 4843 // convention caller. If the caller is fastcc, we may have less stack space 4844 // than a non-fastcc caller with the same signature so disable tail-calls in 4845 // that case. 4846 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4847 } 4848 4849 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4850 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4851 const SmallVectorImpl<ISD::OutputArg> &Outs, 4852 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4853 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4854 4855 if (DisableSCO && !TailCallOpt) return false; 4856 4857 // Variadic argument functions are not supported. 4858 if (isVarArg) return false; 4859 4860 auto &Caller = DAG.getMachineFunction().getFunction(); 4861 // Check that the calling conventions are compatible for tco. 4862 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4863 return false; 4864 4865 // Caller contains any byval parameter is not supported. 4866 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4867 return false; 4868 4869 // Callee contains any byval parameter is not supported, too. 4870 // Note: This is a quick work around, because in some cases, e.g. 4871 // caller's stack size > callee's stack size, we are still able to apply 4872 // sibling call optimization. For example, gcc is able to do SCO for caller1 4873 // in the following example, but not for caller2. 4874 // struct test { 4875 // long int a; 4876 // char ary[56]; 4877 // } gTest; 4878 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4879 // b->a = v.a; 4880 // return 0; 4881 // } 4882 // void caller1(struct test a, struct test c, struct test *b) { 4883 // callee(gTest, b); } 4884 // void caller2(struct test *b) { callee(gTest, b); } 4885 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4886 return false; 4887 4888 // If callee and caller use different calling conventions, we cannot pass 4889 // parameters on stack since offsets for the parameter area may be different. 4890 if (Caller.getCallingConv() != CalleeCC && 4891 needStackSlotPassParameters(Subtarget, Outs)) 4892 return false; 4893 4894 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4895 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4896 // callee potentially have different TOC bases then we cannot tail call since 4897 // we need to restore the TOC pointer after the call. 4898 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4899 // We cannot guarantee this for indirect calls or calls to external functions. 4900 // When PC-Relative addressing is used, the concept of the TOC is no longer 4901 // applicable so this check is not required. 4902 // Check first for indirect calls. 4903 if (!Subtarget.isUsingPCRelativeCalls() && 4904 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4905 return false; 4906 4907 // Check if we share the TOC base. 4908 if (!Subtarget.isUsingPCRelativeCalls() && 4909 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4910 return false; 4911 4912 // TCO allows altering callee ABI, so we don't have to check further. 4913 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4914 return true; 4915 4916 if (DisableSCO) return false; 4917 4918 // If callee use the same argument list that caller is using, then we can 4919 // apply SCO on this case. If it is not, then we need to check if callee needs 4920 // stack for passing arguments. 4921 // PC Relative tail calls may not have a CallBase. 4922 // If there is no CallBase we cannot verify if we have the same argument 4923 // list so assume that we don't have the same argument list. 4924 if (CB && !hasSameArgumentList(&Caller, *CB) && 4925 needStackSlotPassParameters(Subtarget, Outs)) 4926 return false; 4927 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4928 return false; 4929 4930 return true; 4931 } 4932 4933 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4934 /// for tail call optimization. Targets which want to do tail call 4935 /// optimization should implement this function. 4936 bool 4937 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4938 CallingConv::ID CalleeCC, 4939 bool isVarArg, 4940 const SmallVectorImpl<ISD::InputArg> &Ins, 4941 SelectionDAG& DAG) const { 4942 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4943 return false; 4944 4945 // Variable argument functions are not supported. 4946 if (isVarArg) 4947 return false; 4948 4949 MachineFunction &MF = DAG.getMachineFunction(); 4950 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4951 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4952 // Functions containing by val parameters are not supported. 4953 for (unsigned i = 0; i != Ins.size(); i++) { 4954 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4955 if (Flags.isByVal()) return false; 4956 } 4957 4958 // Non-PIC/GOT tail calls are supported. 4959 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4960 return true; 4961 4962 // At the moment we can only do local tail calls (in same module, hidden 4963 // or protected) if we are generating PIC. 4964 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4965 return G->getGlobal()->hasHiddenVisibility() 4966 || G->getGlobal()->hasProtectedVisibility(); 4967 } 4968 4969 return false; 4970 } 4971 4972 /// isCallCompatibleAddress - Return the immediate to use if the specified 4973 /// 32-bit value is representable in the immediate field of a BxA instruction. 4974 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4975 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4976 if (!C) return nullptr; 4977 4978 int Addr = C->getZExtValue(); 4979 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4980 SignExtend32<26>(Addr) != Addr) 4981 return nullptr; // Top 6 bits have to be sext of immediate. 4982 4983 return DAG 4984 .getConstant( 4985 (int)C->getZExtValue() >> 2, SDLoc(Op), 4986 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4987 .getNode(); 4988 } 4989 4990 namespace { 4991 4992 struct TailCallArgumentInfo { 4993 SDValue Arg; 4994 SDValue FrameIdxOp; 4995 int FrameIdx = 0; 4996 4997 TailCallArgumentInfo() = default; 4998 }; 4999 5000 } // end anonymous namespace 5001 5002 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 5003 static void StoreTailCallArgumentsToStackSlot( 5004 SelectionDAG &DAG, SDValue Chain, 5005 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 5006 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 5007 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 5008 SDValue Arg = TailCallArgs[i].Arg; 5009 SDValue FIN = TailCallArgs[i].FrameIdxOp; 5010 int FI = TailCallArgs[i].FrameIdx; 5011 // Store relative to framepointer. 5012 MemOpChains.push_back(DAG.getStore( 5013 Chain, dl, Arg, FIN, 5014 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 5015 } 5016 } 5017 5018 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 5019 /// the appropriate stack slot for the tail call optimized function call. 5020 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 5021 SDValue OldRetAddr, SDValue OldFP, 5022 int SPDiff, const SDLoc &dl) { 5023 if (SPDiff) { 5024 // Calculate the new stack slot for the return address. 5025 MachineFunction &MF = DAG.getMachineFunction(); 5026 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 5027 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 5028 bool isPPC64 = Subtarget.isPPC64(); 5029 int SlotSize = isPPC64 ? 8 : 4; 5030 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 5031 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 5032 NewRetAddrLoc, true); 5033 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5034 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 5035 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 5036 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 5037 } 5038 return Chain; 5039 } 5040 5041 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 5042 /// the position of the argument. 5043 static void 5044 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 5045 SDValue Arg, int SPDiff, unsigned ArgOffset, 5046 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 5047 int Offset = ArgOffset + SPDiff; 5048 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 5049 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5050 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5051 SDValue FIN = DAG.getFrameIndex(FI, VT); 5052 TailCallArgumentInfo Info; 5053 Info.Arg = Arg; 5054 Info.FrameIdxOp = FIN; 5055 Info.FrameIdx = FI; 5056 TailCallArguments.push_back(Info); 5057 } 5058 5059 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5060 /// stack slot. Returns the chain as result and the loaded frame pointers in 5061 /// LROpOut/FPOpout. Used when tail calling. 5062 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5063 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5064 SDValue &FPOpOut, const SDLoc &dl) const { 5065 if (SPDiff) { 5066 // Load the LR and FP stack slot for later adjusting. 5067 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5068 LROpOut = getReturnAddrFrameIndex(DAG); 5069 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5070 Chain = SDValue(LROpOut.getNode(), 1); 5071 } 5072 return Chain; 5073 } 5074 5075 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5076 /// by "Src" to address "Dst" of size "Size". Alignment information is 5077 /// specified by the specific parameter attribute. The copy will be passed as 5078 /// a byval function parameter. 5079 /// Sometimes what we are copying is the end of a larger object, the part that 5080 /// does not fit in registers. 5081 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5082 SDValue Chain, ISD::ArgFlagsTy Flags, 5083 SelectionDAG &DAG, const SDLoc &dl) { 5084 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5085 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5086 Flags.getNonZeroByValAlign(), false, false, false, 5087 MachinePointerInfo(), MachinePointerInfo()); 5088 } 5089 5090 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5091 /// tail calls. 5092 static void LowerMemOpCallTo( 5093 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5094 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5095 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5096 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5097 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5098 if (!isTailCall) { 5099 if (isVector) { 5100 SDValue StackPtr; 5101 if (isPPC64) 5102 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5103 else 5104 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5105 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5106 DAG.getConstant(ArgOffset, dl, PtrVT)); 5107 } 5108 MemOpChains.push_back( 5109 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5110 // Calculate and remember argument location. 5111 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5112 TailCallArguments); 5113 } 5114 5115 static void 5116 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5117 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5118 SDValue FPOp, 5119 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5120 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5121 // might overwrite each other in case of tail call optimization. 5122 SmallVector<SDValue, 8> MemOpChains2; 5123 // Do not flag preceding copytoreg stuff together with the following stuff. 5124 InFlag = SDValue(); 5125 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5126 MemOpChains2, dl); 5127 if (!MemOpChains2.empty()) 5128 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5129 5130 // Store the return address to the appropriate stack slot. 5131 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5132 5133 // Emit callseq_end just before tailcall node. 5134 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5135 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5136 InFlag = Chain.getValue(1); 5137 } 5138 5139 // Is this global address that of a function that can be called by name? (as 5140 // opposed to something that must hold a descriptor for an indirect call). 5141 static bool isFunctionGlobalAddress(SDValue Callee) { 5142 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5143 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5144 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5145 return false; 5146 5147 return G->getGlobal()->getValueType()->isFunctionTy(); 5148 } 5149 5150 return false; 5151 } 5152 5153 SDValue PPCTargetLowering::LowerCallResult( 5154 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5155 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5156 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5157 SmallVector<CCValAssign, 16> RVLocs; 5158 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5159 *DAG.getContext()); 5160 5161 CCRetInfo.AnalyzeCallResult( 5162 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5163 ? RetCC_PPC_Cold 5164 : RetCC_PPC); 5165 5166 // Copy all of the result registers out of their specified physreg. 5167 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5168 CCValAssign &VA = RVLocs[i]; 5169 assert(VA.isRegLoc() && "Can only return in registers!"); 5170 5171 SDValue Val; 5172 5173 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5174 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5175 InFlag); 5176 Chain = Lo.getValue(1); 5177 InFlag = Lo.getValue(2); 5178 VA = RVLocs[++i]; // skip ahead to next loc 5179 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5180 InFlag); 5181 Chain = Hi.getValue(1); 5182 InFlag = Hi.getValue(2); 5183 if (!Subtarget.isLittleEndian()) 5184 std::swap (Lo, Hi); 5185 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5186 } else { 5187 Val = DAG.getCopyFromReg(Chain, dl, 5188 VA.getLocReg(), VA.getLocVT(), InFlag); 5189 Chain = Val.getValue(1); 5190 InFlag = Val.getValue(2); 5191 } 5192 5193 switch (VA.getLocInfo()) { 5194 default: llvm_unreachable("Unknown loc info!"); 5195 case CCValAssign::Full: break; 5196 case CCValAssign::AExt: 5197 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5198 break; 5199 case CCValAssign::ZExt: 5200 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5201 DAG.getValueType(VA.getValVT())); 5202 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5203 break; 5204 case CCValAssign::SExt: 5205 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5206 DAG.getValueType(VA.getValVT())); 5207 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5208 break; 5209 } 5210 5211 InVals.push_back(Val); 5212 } 5213 5214 return Chain; 5215 } 5216 5217 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5218 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5219 // PatchPoint calls are not indirect. 5220 if (isPatchPoint) 5221 return false; 5222 5223 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5224 return false; 5225 5226 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5227 // becuase the immediate function pointer points to a descriptor instead of 5228 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5229 // pointer immediate points to the global entry point, while the BLA would 5230 // need to jump to the local entry point (see rL211174). 5231 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5232 isBLACompatibleAddress(Callee, DAG)) 5233 return false; 5234 5235 return true; 5236 } 5237 5238 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5239 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5240 return Subtarget.isAIXABI() || 5241 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5242 } 5243 5244 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5245 const Function &Caller, 5246 const SDValue &Callee, 5247 const PPCSubtarget &Subtarget, 5248 const TargetMachine &TM) { 5249 if (CFlags.IsTailCall) 5250 return PPCISD::TC_RETURN; 5251 5252 // This is a call through a function pointer. 5253 if (CFlags.IsIndirect) { 5254 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5255 // indirect calls. The save of the caller's TOC pointer to the stack will be 5256 // inserted into the DAG as part of call lowering. The restore of the TOC 5257 // pointer is modeled by using a pseudo instruction for the call opcode that 5258 // represents the 2 instruction sequence of an indirect branch and link, 5259 // immediately followed by a load of the TOC pointer from the the stack save 5260 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5261 // as it is not saved or used. 5262 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5263 : PPCISD::BCTRL; 5264 } 5265 5266 if (Subtarget.isUsingPCRelativeCalls()) { 5267 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5268 return PPCISD::CALL_NOTOC; 5269 } 5270 5271 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5272 // immediately following the call instruction if the caller and callee may 5273 // have different TOC bases. At link time if the linker determines the calls 5274 // may not share a TOC base, the call is redirected to a trampoline inserted 5275 // by the linker. The trampoline will (among other things) save the callers 5276 // TOC pointer at an ABI designated offset in the linkage area and the linker 5277 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5278 // into gpr2. 5279 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5280 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5281 : PPCISD::CALL_NOP; 5282 5283 return PPCISD::CALL; 5284 } 5285 5286 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5287 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5288 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5289 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5290 return SDValue(Dest, 0); 5291 5292 // Returns true if the callee is local, and false otherwise. 5293 auto isLocalCallee = [&]() { 5294 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5295 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5296 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5297 5298 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5299 !dyn_cast_or_null<GlobalIFunc>(GV); 5300 }; 5301 5302 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5303 // a static relocation model causes some versions of GNU LD (2.17.50, at 5304 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5305 // built with secure-PLT. 5306 bool UsePlt = 5307 Subtarget.is32BitELFABI() && !isLocalCallee() && 5308 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5309 5310 // On AIX, direct function calls reference the symbol for the function's 5311 // entry point, which is named by prepending a "." before the function's 5312 // C-linkage name. 5313 const auto getAIXFuncEntryPointSymbolSDNode = 5314 [&](StringRef FuncName, bool IsDeclaration, 5315 const XCOFF::StorageClass &SC) { 5316 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5317 5318 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5319 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5320 5321 if (IsDeclaration && !S->hasRepresentedCsectSet()) { 5322 // On AIX, an undefined symbol needs to be associated with a 5323 // MCSectionXCOFF to get the correct storage mapping class. 5324 // In this case, XCOFF::XMC_PR. 5325 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5326 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5327 SectionKind::getMetadata()); 5328 S->setRepresentedCsect(Sec); 5329 } 5330 5331 MVT PtrVT = 5332 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5333 return DAG.getMCSymbol(S, PtrVT); 5334 }; 5335 5336 if (isFunctionGlobalAddress(Callee)) { 5337 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5338 const GlobalValue *GV = G->getGlobal(); 5339 5340 if (!Subtarget.isAIXABI()) 5341 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5342 UsePlt ? PPCII::MO_PLT : 0); 5343 5344 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5345 const GlobalObject *GO = cast<GlobalObject>(GV); 5346 const XCOFF::StorageClass SC = 5347 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5348 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5349 SC); 5350 } 5351 5352 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5353 const char *SymName = S->getSymbol(); 5354 if (!Subtarget.isAIXABI()) 5355 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5356 UsePlt ? PPCII::MO_PLT : 0); 5357 5358 // If there exists a user-declared function whose name is the same as the 5359 // ExternalSymbol's, then we pick up the user-declared version. 5360 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5361 if (const Function *F = 5362 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5363 const XCOFF::StorageClass SC = 5364 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5365 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5366 SC); 5367 } 5368 5369 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5370 } 5371 5372 // No transformation needed. 5373 assert(Callee.getNode() && "What no callee?"); 5374 return Callee; 5375 } 5376 5377 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5378 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5379 "Expected a CALLSEQ_STARTSDNode."); 5380 5381 // The last operand is the chain, except when the node has glue. If the node 5382 // has glue, then the last operand is the glue, and the chain is the second 5383 // last operand. 5384 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5385 if (LastValue.getValueType() != MVT::Glue) 5386 return LastValue; 5387 5388 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5389 } 5390 5391 // Creates the node that moves a functions address into the count register 5392 // to prepare for an indirect call instruction. 5393 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5394 SDValue &Glue, SDValue &Chain, 5395 const SDLoc &dl) { 5396 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5397 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5398 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5399 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5400 // The glue is the second value produced. 5401 Glue = Chain.getValue(1); 5402 } 5403 5404 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5405 SDValue &Glue, SDValue &Chain, 5406 SDValue CallSeqStart, 5407 const CallBase *CB, const SDLoc &dl, 5408 bool hasNest, 5409 const PPCSubtarget &Subtarget) { 5410 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5411 // entry point, but to the function descriptor (the function entry point 5412 // address is part of the function descriptor though). 5413 // The function descriptor is a three doubleword structure with the 5414 // following fields: function entry point, TOC base address and 5415 // environment pointer. 5416 // Thus for a call through a function pointer, the following actions need 5417 // to be performed: 5418 // 1. Save the TOC of the caller in the TOC save area of its stack 5419 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5420 // 2. Load the address of the function entry point from the function 5421 // descriptor. 5422 // 3. Load the TOC of the callee from the function descriptor into r2. 5423 // 4. Load the environment pointer from the function descriptor into 5424 // r11. 5425 // 5. Branch to the function entry point address. 5426 // 6. On return of the callee, the TOC of the caller needs to be 5427 // restored (this is done in FinishCall()). 5428 // 5429 // The loads are scheduled at the beginning of the call sequence, and the 5430 // register copies are flagged together to ensure that no other 5431 // operations can be scheduled in between. E.g. without flagging the 5432 // copies together, a TOC access in the caller could be scheduled between 5433 // the assignment of the callee TOC and the branch to the callee, which leads 5434 // to incorrect code. 5435 5436 // Start by loading the function address from the descriptor. 5437 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5438 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5439 ? (MachineMemOperand::MODereferenceable | 5440 MachineMemOperand::MOInvariant) 5441 : MachineMemOperand::MONone; 5442 5443 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5444 5445 // Registers used in building the DAG. 5446 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5447 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5448 5449 // Offsets of descriptor members. 5450 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5451 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5452 5453 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5454 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5455 5456 // One load for the functions entry point address. 5457 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5458 Alignment, MMOFlags); 5459 5460 // One for loading the TOC anchor for the module that contains the called 5461 // function. 5462 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5463 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5464 SDValue TOCPtr = 5465 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5466 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5467 5468 // One for loading the environment pointer. 5469 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5470 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5471 SDValue LoadEnvPtr = 5472 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5473 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5474 5475 5476 // Then copy the newly loaded TOC anchor to the TOC pointer. 5477 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5478 Chain = TOCVal.getValue(0); 5479 Glue = TOCVal.getValue(1); 5480 5481 // If the function call has an explicit 'nest' parameter, it takes the 5482 // place of the environment pointer. 5483 assert((!hasNest || !Subtarget.isAIXABI()) && 5484 "Nest parameter is not supported on AIX."); 5485 if (!hasNest) { 5486 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5487 Chain = EnvVal.getValue(0); 5488 Glue = EnvVal.getValue(1); 5489 } 5490 5491 // The rest of the indirect call sequence is the same as the non-descriptor 5492 // DAG. 5493 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5494 } 5495 5496 static void 5497 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5498 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5499 SelectionDAG &DAG, 5500 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5501 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5502 const PPCSubtarget &Subtarget) { 5503 const bool IsPPC64 = Subtarget.isPPC64(); 5504 // MVT for a general purpose register. 5505 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5506 5507 // First operand is always the chain. 5508 Ops.push_back(Chain); 5509 5510 // If it's a direct call pass the callee as the second operand. 5511 if (!CFlags.IsIndirect) 5512 Ops.push_back(Callee); 5513 else { 5514 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5515 5516 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5517 // on the stack (this would have been done in `LowerCall_64SVR4` or 5518 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5519 // represents both the indirect branch and a load that restores the TOC 5520 // pointer from the linkage area. The operand for the TOC restore is an add 5521 // of the TOC save offset to the stack pointer. This must be the second 5522 // operand: after the chain input but before any other variadic arguments. 5523 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5524 // saved or used. 5525 if (isTOCSaveRestoreRequired(Subtarget)) { 5526 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5527 5528 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5529 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5530 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5531 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5532 Ops.push_back(AddTOC); 5533 } 5534 5535 // Add the register used for the environment pointer. 5536 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5537 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5538 RegVT)); 5539 5540 5541 // Add CTR register as callee so a bctr can be emitted later. 5542 if (CFlags.IsTailCall) 5543 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5544 } 5545 5546 // If this is a tail call add stack pointer delta. 5547 if (CFlags.IsTailCall) 5548 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5549 5550 // Add argument registers to the end of the list so that they are known live 5551 // into the call. 5552 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5553 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5554 RegsToPass[i].second.getValueType())); 5555 5556 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5557 // no way to mark dependencies as implicit here. 5558 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5559 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5560 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5561 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5562 5563 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5564 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5565 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5566 5567 // Add a register mask operand representing the call-preserved registers. 5568 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5569 const uint32_t *Mask = 5570 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5571 assert(Mask && "Missing call preserved mask for calling convention"); 5572 Ops.push_back(DAG.getRegisterMask(Mask)); 5573 5574 // If the glue is valid, it is the last operand. 5575 if (Glue.getNode()) 5576 Ops.push_back(Glue); 5577 } 5578 5579 SDValue PPCTargetLowering::FinishCall( 5580 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5581 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5582 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5583 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5584 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5585 5586 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5587 Subtarget.isAIXABI()) 5588 setUsesTOCBasePtr(DAG); 5589 5590 unsigned CallOpc = 5591 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5592 Subtarget, DAG.getTarget()); 5593 5594 if (!CFlags.IsIndirect) 5595 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5596 else if (Subtarget.usesFunctionDescriptors()) 5597 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5598 dl, CFlags.HasNest, Subtarget); 5599 else 5600 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5601 5602 // Build the operand list for the call instruction. 5603 SmallVector<SDValue, 8> Ops; 5604 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5605 SPDiff, Subtarget); 5606 5607 // Emit tail call. 5608 if (CFlags.IsTailCall) { 5609 // Indirect tail call when using PC Relative calls do not have the same 5610 // constraints. 5611 assert(((Callee.getOpcode() == ISD::Register && 5612 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5613 Callee.getOpcode() == ISD::TargetExternalSymbol || 5614 Callee.getOpcode() == ISD::TargetGlobalAddress || 5615 isa<ConstantSDNode>(Callee) || 5616 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5617 "Expecting a global address, external symbol, absolute value, " 5618 "register or an indirect tail call when PC Relative calls are " 5619 "used."); 5620 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5621 assert(CallOpc == PPCISD::TC_RETURN && 5622 "Unexpected call opcode for a tail call."); 5623 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5624 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5625 } 5626 5627 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5628 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5629 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5630 Glue = Chain.getValue(1); 5631 5632 // When performing tail call optimization the callee pops its arguments off 5633 // the stack. Account for this here so these bytes can be pushed back on in 5634 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5635 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5636 getTargetMachine().Options.GuaranteedTailCallOpt) 5637 ? NumBytes 5638 : 0; 5639 5640 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5641 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5642 Glue, dl); 5643 Glue = Chain.getValue(1); 5644 5645 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5646 DAG, InVals); 5647 } 5648 5649 SDValue 5650 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5651 SmallVectorImpl<SDValue> &InVals) const { 5652 SelectionDAG &DAG = CLI.DAG; 5653 SDLoc &dl = CLI.DL; 5654 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5655 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5656 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5657 SDValue Chain = CLI.Chain; 5658 SDValue Callee = CLI.Callee; 5659 bool &isTailCall = CLI.IsTailCall; 5660 CallingConv::ID CallConv = CLI.CallConv; 5661 bool isVarArg = CLI.IsVarArg; 5662 bool isPatchPoint = CLI.IsPatchPoint; 5663 const CallBase *CB = CLI.CB; 5664 5665 if (isTailCall) { 5666 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5667 isTailCall = false; 5668 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5669 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5670 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5671 else 5672 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5673 Ins, DAG); 5674 if (isTailCall) { 5675 ++NumTailCalls; 5676 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5677 ++NumSiblingCalls; 5678 5679 // PC Relative calls no longer guarantee that the callee is a Global 5680 // Address Node. The callee could be an indirect tail call in which 5681 // case the SDValue for the callee could be a load (to load the address 5682 // of a function pointer) or it may be a register copy (to move the 5683 // address of the callee from a function parameter into a virtual 5684 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5685 assert((Subtarget.isUsingPCRelativeCalls() || 5686 isa<GlobalAddressSDNode>(Callee)) && 5687 "Callee should be an llvm::Function object."); 5688 5689 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5690 << "\nTCO callee: "); 5691 LLVM_DEBUG(Callee.dump()); 5692 } 5693 } 5694 5695 if (!isTailCall && CB && CB->isMustTailCall()) 5696 report_fatal_error("failed to perform tail call elimination on a call " 5697 "site marked musttail"); 5698 5699 // When long calls (i.e. indirect calls) are always used, calls are always 5700 // made via function pointer. If we have a function name, first translate it 5701 // into a pointer. 5702 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5703 !isTailCall) 5704 Callee = LowerGlobalAddress(Callee, DAG); 5705 5706 CallFlags CFlags( 5707 CallConv, isTailCall, isVarArg, isPatchPoint, 5708 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5709 // hasNest 5710 Subtarget.is64BitELFABI() && 5711 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5712 CLI.NoMerge); 5713 5714 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5715 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5716 InVals, CB); 5717 5718 if (Subtarget.isSVR4ABI()) 5719 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5720 InVals, CB); 5721 5722 if (Subtarget.isAIXABI()) 5723 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5724 InVals, CB); 5725 5726 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5727 InVals, CB); 5728 } 5729 5730 SDValue PPCTargetLowering::LowerCall_32SVR4( 5731 SDValue Chain, SDValue Callee, CallFlags CFlags, 5732 const SmallVectorImpl<ISD::OutputArg> &Outs, 5733 const SmallVectorImpl<SDValue> &OutVals, 5734 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5735 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5736 const CallBase *CB) const { 5737 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5738 // of the 32-bit SVR4 ABI stack frame layout. 5739 5740 const CallingConv::ID CallConv = CFlags.CallConv; 5741 const bool IsVarArg = CFlags.IsVarArg; 5742 const bool IsTailCall = CFlags.IsTailCall; 5743 5744 assert((CallConv == CallingConv::C || 5745 CallConv == CallingConv::Cold || 5746 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5747 5748 const Align PtrAlign(4); 5749 5750 MachineFunction &MF = DAG.getMachineFunction(); 5751 5752 // Mark this function as potentially containing a function that contains a 5753 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5754 // and restoring the callers stack pointer in this functions epilog. This is 5755 // done because by tail calling the called function might overwrite the value 5756 // in this function's (MF) stack pointer stack slot 0(SP). 5757 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5758 CallConv == CallingConv::Fast) 5759 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5760 5761 // Count how many bytes are to be pushed on the stack, including the linkage 5762 // area, parameter list area and the part of the local variable space which 5763 // contains copies of aggregates which are passed by value. 5764 5765 // Assign locations to all of the outgoing arguments. 5766 SmallVector<CCValAssign, 16> ArgLocs; 5767 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5768 5769 // Reserve space for the linkage area on the stack. 5770 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5771 PtrAlign); 5772 if (useSoftFloat()) 5773 CCInfo.PreAnalyzeCallOperands(Outs); 5774 5775 if (IsVarArg) { 5776 // Handle fixed and variable vector arguments differently. 5777 // Fixed vector arguments go into registers as long as registers are 5778 // available. Variable vector arguments always go into memory. 5779 unsigned NumArgs = Outs.size(); 5780 5781 for (unsigned i = 0; i != NumArgs; ++i) { 5782 MVT ArgVT = Outs[i].VT; 5783 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5784 bool Result; 5785 5786 if (Outs[i].IsFixed) { 5787 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5788 CCInfo); 5789 } else { 5790 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5791 ArgFlags, CCInfo); 5792 } 5793 5794 if (Result) { 5795 #ifndef NDEBUG 5796 errs() << "Call operand #" << i << " has unhandled type " 5797 << EVT(ArgVT).getEVTString() << "\n"; 5798 #endif 5799 llvm_unreachable(nullptr); 5800 } 5801 } 5802 } else { 5803 // All arguments are treated the same. 5804 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5805 } 5806 CCInfo.clearWasPPCF128(); 5807 5808 // Assign locations to all of the outgoing aggregate by value arguments. 5809 SmallVector<CCValAssign, 16> ByValArgLocs; 5810 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5811 5812 // Reserve stack space for the allocations in CCInfo. 5813 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5814 5815 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5816 5817 // Size of the linkage area, parameter list area and the part of the local 5818 // space variable where copies of aggregates which are passed by value are 5819 // stored. 5820 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5821 5822 // Calculate by how many bytes the stack has to be adjusted in case of tail 5823 // call optimization. 5824 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5825 5826 // Adjust the stack pointer for the new arguments... 5827 // These operations are automatically eliminated by the prolog/epilog pass 5828 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5829 SDValue CallSeqStart = Chain; 5830 5831 // Load the return address and frame pointer so it can be moved somewhere else 5832 // later. 5833 SDValue LROp, FPOp; 5834 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5835 5836 // Set up a copy of the stack pointer for use loading and storing any 5837 // arguments that may not fit in the registers available for argument 5838 // passing. 5839 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5840 5841 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5842 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5843 SmallVector<SDValue, 8> MemOpChains; 5844 5845 bool seenFloatArg = false; 5846 // Walk the register/memloc assignments, inserting copies/loads. 5847 // i - Tracks the index into the list of registers allocated for the call 5848 // RealArgIdx - Tracks the index into the list of actual function arguments 5849 // j - Tracks the index into the list of byval arguments 5850 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5851 i != e; 5852 ++i, ++RealArgIdx) { 5853 CCValAssign &VA = ArgLocs[i]; 5854 SDValue Arg = OutVals[RealArgIdx]; 5855 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5856 5857 if (Flags.isByVal()) { 5858 // Argument is an aggregate which is passed by value, thus we need to 5859 // create a copy of it in the local variable space of the current stack 5860 // frame (which is the stack frame of the caller) and pass the address of 5861 // this copy to the callee. 5862 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5863 CCValAssign &ByValVA = ByValArgLocs[j++]; 5864 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5865 5866 // Memory reserved in the local variable space of the callers stack frame. 5867 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5868 5869 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5870 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5871 StackPtr, PtrOff); 5872 5873 // Create a copy of the argument in the local area of the current 5874 // stack frame. 5875 SDValue MemcpyCall = 5876 CreateCopyOfByValArgument(Arg, PtrOff, 5877 CallSeqStart.getNode()->getOperand(0), 5878 Flags, DAG, dl); 5879 5880 // This must go outside the CALLSEQ_START..END. 5881 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5882 SDLoc(MemcpyCall)); 5883 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5884 NewCallSeqStart.getNode()); 5885 Chain = CallSeqStart = NewCallSeqStart; 5886 5887 // Pass the address of the aggregate copy on the stack either in a 5888 // physical register or in the parameter list area of the current stack 5889 // frame to the callee. 5890 Arg = PtrOff; 5891 } 5892 5893 // When useCRBits() is true, there can be i1 arguments. 5894 // It is because getRegisterType(MVT::i1) => MVT::i1, 5895 // and for other integer types getRegisterType() => MVT::i32. 5896 // Extend i1 and ensure callee will get i32. 5897 if (Arg.getValueType() == MVT::i1) 5898 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5899 dl, MVT::i32, Arg); 5900 5901 if (VA.isRegLoc()) { 5902 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5903 // Put argument in a physical register. 5904 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5905 bool IsLE = Subtarget.isLittleEndian(); 5906 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5907 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5908 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5909 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5910 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5911 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5912 SVal.getValue(0))); 5913 } else 5914 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5915 } else { 5916 // Put argument in the parameter list area of the current stack frame. 5917 assert(VA.isMemLoc()); 5918 unsigned LocMemOffset = VA.getLocMemOffset(); 5919 5920 if (!IsTailCall) { 5921 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5922 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5923 StackPtr, PtrOff); 5924 5925 MemOpChains.push_back( 5926 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5927 } else { 5928 // Calculate and remember argument location. 5929 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5930 TailCallArguments); 5931 } 5932 } 5933 } 5934 5935 if (!MemOpChains.empty()) 5936 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5937 5938 // Build a sequence of copy-to-reg nodes chained together with token chain 5939 // and flag operands which copy the outgoing args into the appropriate regs. 5940 SDValue InFlag; 5941 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5942 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5943 RegsToPass[i].second, InFlag); 5944 InFlag = Chain.getValue(1); 5945 } 5946 5947 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5948 // registers. 5949 if (IsVarArg) { 5950 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5951 SDValue Ops[] = { Chain, InFlag }; 5952 5953 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5954 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5955 5956 InFlag = Chain.getValue(1); 5957 } 5958 5959 if (IsTailCall) 5960 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5961 TailCallArguments); 5962 5963 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5964 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5965 } 5966 5967 // Copy an argument into memory, being careful to do this outside the 5968 // call sequence for the call to which the argument belongs. 5969 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5970 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5971 SelectionDAG &DAG, const SDLoc &dl) const { 5972 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5973 CallSeqStart.getNode()->getOperand(0), 5974 Flags, DAG, dl); 5975 // The MEMCPY must go outside the CALLSEQ_START..END. 5976 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5977 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5978 SDLoc(MemcpyCall)); 5979 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5980 NewCallSeqStart.getNode()); 5981 return NewCallSeqStart; 5982 } 5983 5984 SDValue PPCTargetLowering::LowerCall_64SVR4( 5985 SDValue Chain, SDValue Callee, CallFlags CFlags, 5986 const SmallVectorImpl<ISD::OutputArg> &Outs, 5987 const SmallVectorImpl<SDValue> &OutVals, 5988 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5989 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5990 const CallBase *CB) const { 5991 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5992 bool isLittleEndian = Subtarget.isLittleEndian(); 5993 unsigned NumOps = Outs.size(); 5994 bool IsSibCall = false; 5995 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5996 5997 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5998 unsigned PtrByteSize = 8; 5999 6000 MachineFunction &MF = DAG.getMachineFunction(); 6001 6002 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 6003 IsSibCall = true; 6004 6005 // Mark this function as potentially containing a function that contains a 6006 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6007 // and restoring the callers stack pointer in this functions epilog. This is 6008 // done because by tail calling the called function might overwrite the value 6009 // in this function's (MF) stack pointer stack slot 0(SP). 6010 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6011 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6012 6013 assert(!(IsFastCall && CFlags.IsVarArg) && 6014 "fastcc not supported on varargs functions"); 6015 6016 // Count how many bytes are to be pushed on the stack, including the linkage 6017 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 6018 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 6019 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 6020 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6021 unsigned NumBytes = LinkageSize; 6022 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6023 unsigned &QFPR_idx = FPR_idx; 6024 6025 static const MCPhysReg GPR[] = { 6026 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6027 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6028 }; 6029 static const MCPhysReg VR[] = { 6030 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6031 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6032 }; 6033 6034 const unsigned NumGPRs = array_lengthof(GPR); 6035 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 6036 const unsigned NumVRs = array_lengthof(VR); 6037 const unsigned NumQFPRs = NumFPRs; 6038 6039 // On ELFv2, we can avoid allocating the parameter area if all the arguments 6040 // can be passed to the callee in registers. 6041 // For the fast calling convention, there is another check below. 6042 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 6043 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 6044 if (!HasParameterArea) { 6045 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 6046 unsigned AvailableFPRs = NumFPRs; 6047 unsigned AvailableVRs = NumVRs; 6048 unsigned NumBytesTmp = NumBytes; 6049 for (unsigned i = 0; i != NumOps; ++i) { 6050 if (Outs[i].Flags.isNest()) continue; 6051 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 6052 PtrByteSize, LinkageSize, ParamAreaSize, 6053 NumBytesTmp, AvailableFPRs, AvailableVRs, 6054 Subtarget.hasQPX())) 6055 HasParameterArea = true; 6056 } 6057 } 6058 6059 // When using the fast calling convention, we don't provide backing for 6060 // arguments that will be in registers. 6061 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6062 6063 // Avoid allocating parameter area for fastcc functions if all the arguments 6064 // can be passed in the registers. 6065 if (IsFastCall) 6066 HasParameterArea = false; 6067 6068 // Add up all the space actually used. 6069 for (unsigned i = 0; i != NumOps; ++i) { 6070 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6071 EVT ArgVT = Outs[i].VT; 6072 EVT OrigVT = Outs[i].ArgVT; 6073 6074 if (Flags.isNest()) 6075 continue; 6076 6077 if (IsFastCall) { 6078 if (Flags.isByVal()) { 6079 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6080 if (NumGPRsUsed > NumGPRs) 6081 HasParameterArea = true; 6082 } else { 6083 switch (ArgVT.getSimpleVT().SimpleTy) { 6084 default: llvm_unreachable("Unexpected ValueType for argument!"); 6085 case MVT::i1: 6086 case MVT::i32: 6087 case MVT::i64: 6088 if (++NumGPRsUsed <= NumGPRs) 6089 continue; 6090 break; 6091 case MVT::v4i32: 6092 case MVT::v8i16: 6093 case MVT::v16i8: 6094 case MVT::v2f64: 6095 case MVT::v2i64: 6096 case MVT::v1i128: 6097 case MVT::f128: 6098 if (++NumVRsUsed <= NumVRs) 6099 continue; 6100 break; 6101 case MVT::v4f32: 6102 // When using QPX, this is handled like a FP register, otherwise, it 6103 // is an Altivec register. 6104 if (Subtarget.hasQPX()) { 6105 if (++NumFPRsUsed <= NumFPRs) 6106 continue; 6107 } else { 6108 if (++NumVRsUsed <= NumVRs) 6109 continue; 6110 } 6111 break; 6112 case MVT::f32: 6113 case MVT::f64: 6114 case MVT::v4f64: // QPX 6115 case MVT::v4i1: // QPX 6116 if (++NumFPRsUsed <= NumFPRs) 6117 continue; 6118 break; 6119 } 6120 HasParameterArea = true; 6121 } 6122 } 6123 6124 /* Respect alignment of argument on the stack. */ 6125 auto Alignement = 6126 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6127 NumBytes = alignTo(NumBytes, Alignement); 6128 6129 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6130 if (Flags.isInConsecutiveRegsLast()) 6131 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6132 } 6133 6134 unsigned NumBytesActuallyUsed = NumBytes; 6135 6136 // In the old ELFv1 ABI, 6137 // the prolog code of the callee may store up to 8 GPR argument registers to 6138 // the stack, allowing va_start to index over them in memory if its varargs. 6139 // Because we cannot tell if this is needed on the caller side, we have to 6140 // conservatively assume that it is needed. As such, make sure we have at 6141 // least enough stack space for the caller to store the 8 GPRs. 6142 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6143 // really requires memory operands, e.g. a vararg function. 6144 if (HasParameterArea) 6145 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6146 else 6147 NumBytes = LinkageSize; 6148 6149 // Tail call needs the stack to be aligned. 6150 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6151 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6152 6153 int SPDiff = 0; 6154 6155 // Calculate by how many bytes the stack has to be adjusted in case of tail 6156 // call optimization. 6157 if (!IsSibCall) 6158 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6159 6160 // To protect arguments on the stack from being clobbered in a tail call, 6161 // force all the loads to happen before doing any other lowering. 6162 if (CFlags.IsTailCall) 6163 Chain = DAG.getStackArgumentTokenFactor(Chain); 6164 6165 // Adjust the stack pointer for the new arguments... 6166 // These operations are automatically eliminated by the prolog/epilog pass 6167 if (!IsSibCall) 6168 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6169 SDValue CallSeqStart = Chain; 6170 6171 // Load the return address and frame pointer so it can be move somewhere else 6172 // later. 6173 SDValue LROp, FPOp; 6174 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6175 6176 // Set up a copy of the stack pointer for use loading and storing any 6177 // arguments that may not fit in the registers available for argument 6178 // passing. 6179 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6180 6181 // Figure out which arguments are going to go in registers, and which in 6182 // memory. Also, if this is a vararg function, floating point operations 6183 // must be stored to our stack, and loaded into integer regs as well, if 6184 // any integer regs are available for argument passing. 6185 unsigned ArgOffset = LinkageSize; 6186 6187 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6188 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6189 6190 SmallVector<SDValue, 8> MemOpChains; 6191 for (unsigned i = 0; i != NumOps; ++i) { 6192 SDValue Arg = OutVals[i]; 6193 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6194 EVT ArgVT = Outs[i].VT; 6195 EVT OrigVT = Outs[i].ArgVT; 6196 6197 // PtrOff will be used to store the current argument to the stack if a 6198 // register cannot be found for it. 6199 SDValue PtrOff; 6200 6201 // We re-align the argument offset for each argument, except when using the 6202 // fast calling convention, when we need to make sure we do that only when 6203 // we'll actually use a stack slot. 6204 auto ComputePtrOff = [&]() { 6205 /* Respect alignment of argument on the stack. */ 6206 auto Alignment = 6207 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6208 ArgOffset = alignTo(ArgOffset, Alignment); 6209 6210 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6211 6212 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6213 }; 6214 6215 if (!IsFastCall) { 6216 ComputePtrOff(); 6217 6218 /* Compute GPR index associated with argument offset. */ 6219 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6220 GPR_idx = std::min(GPR_idx, NumGPRs); 6221 } 6222 6223 // Promote integers to 64-bit values. 6224 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6225 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6226 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6227 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6228 } 6229 6230 // FIXME memcpy is used way more than necessary. Correctness first. 6231 // Note: "by value" is code for passing a structure by value, not 6232 // basic types. 6233 if (Flags.isByVal()) { 6234 // Note: Size includes alignment padding, so 6235 // struct x { short a; char b; } 6236 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6237 // These are the proper values we need for right-justifying the 6238 // aggregate in a parameter register. 6239 unsigned Size = Flags.getByValSize(); 6240 6241 // An empty aggregate parameter takes up no storage and no 6242 // registers. 6243 if (Size == 0) 6244 continue; 6245 6246 if (IsFastCall) 6247 ComputePtrOff(); 6248 6249 // All aggregates smaller than 8 bytes must be passed right-justified. 6250 if (Size==1 || Size==2 || Size==4) { 6251 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6252 if (GPR_idx != NumGPRs) { 6253 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6254 MachinePointerInfo(), VT); 6255 MemOpChains.push_back(Load.getValue(1)); 6256 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6257 6258 ArgOffset += PtrByteSize; 6259 continue; 6260 } 6261 } 6262 6263 if (GPR_idx == NumGPRs && Size < 8) { 6264 SDValue AddPtr = PtrOff; 6265 if (!isLittleEndian) { 6266 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6267 PtrOff.getValueType()); 6268 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6269 } 6270 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6271 CallSeqStart, 6272 Flags, DAG, dl); 6273 ArgOffset += PtrByteSize; 6274 continue; 6275 } 6276 // Copy entire object into memory. There are cases where gcc-generated 6277 // code assumes it is there, even if it could be put entirely into 6278 // registers. (This is not what the doc says.) 6279 6280 // FIXME: The above statement is likely due to a misunderstanding of the 6281 // documents. All arguments must be copied into the parameter area BY 6282 // THE CALLEE in the event that the callee takes the address of any 6283 // formal argument. That has not yet been implemented. However, it is 6284 // reasonable to use the stack area as a staging area for the register 6285 // load. 6286 6287 // Skip this for small aggregates, as we will use the same slot for a 6288 // right-justified copy, below. 6289 if (Size >= 8) 6290 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6291 CallSeqStart, 6292 Flags, DAG, dl); 6293 6294 // When a register is available, pass a small aggregate right-justified. 6295 if (Size < 8 && GPR_idx != NumGPRs) { 6296 // The easiest way to get this right-justified in a register 6297 // is to copy the structure into the rightmost portion of a 6298 // local variable slot, then load the whole slot into the 6299 // register. 6300 // FIXME: The memcpy seems to produce pretty awful code for 6301 // small aggregates, particularly for packed ones. 6302 // FIXME: It would be preferable to use the slot in the 6303 // parameter save area instead of a new local variable. 6304 SDValue AddPtr = PtrOff; 6305 if (!isLittleEndian) { 6306 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6307 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6308 } 6309 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6310 CallSeqStart, 6311 Flags, DAG, dl); 6312 6313 // Load the slot into the register. 6314 SDValue Load = 6315 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6316 MemOpChains.push_back(Load.getValue(1)); 6317 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6318 6319 // Done with this argument. 6320 ArgOffset += PtrByteSize; 6321 continue; 6322 } 6323 6324 // For aggregates larger than PtrByteSize, copy the pieces of the 6325 // object that fit into registers from the parameter save area. 6326 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6327 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6328 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6329 if (GPR_idx != NumGPRs) { 6330 SDValue Load = 6331 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6332 MemOpChains.push_back(Load.getValue(1)); 6333 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6334 ArgOffset += PtrByteSize; 6335 } else { 6336 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6337 break; 6338 } 6339 } 6340 continue; 6341 } 6342 6343 switch (Arg.getSimpleValueType().SimpleTy) { 6344 default: llvm_unreachable("Unexpected ValueType for argument!"); 6345 case MVT::i1: 6346 case MVT::i32: 6347 case MVT::i64: 6348 if (Flags.isNest()) { 6349 // The 'nest' parameter, if any, is passed in R11. 6350 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6351 break; 6352 } 6353 6354 // These can be scalar arguments or elements of an integer array type 6355 // passed directly. Clang may use those instead of "byval" aggregate 6356 // types to avoid forcing arguments to memory unnecessarily. 6357 if (GPR_idx != NumGPRs) { 6358 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6359 } else { 6360 if (IsFastCall) 6361 ComputePtrOff(); 6362 6363 assert(HasParameterArea && 6364 "Parameter area must exist to pass an argument in memory."); 6365 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6366 true, CFlags.IsTailCall, false, MemOpChains, 6367 TailCallArguments, dl); 6368 if (IsFastCall) 6369 ArgOffset += PtrByteSize; 6370 } 6371 if (!IsFastCall) 6372 ArgOffset += PtrByteSize; 6373 break; 6374 case MVT::f32: 6375 case MVT::f64: { 6376 // These can be scalar arguments or elements of a float array type 6377 // passed directly. The latter are used to implement ELFv2 homogenous 6378 // float aggregates. 6379 6380 // Named arguments go into FPRs first, and once they overflow, the 6381 // remaining arguments go into GPRs and then the parameter save area. 6382 // Unnamed arguments for vararg functions always go to GPRs and 6383 // then the parameter save area. For now, put all arguments to vararg 6384 // routines always in both locations (FPR *and* GPR or stack slot). 6385 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6386 bool NeededLoad = false; 6387 6388 // First load the argument into the next available FPR. 6389 if (FPR_idx != NumFPRs) 6390 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6391 6392 // Next, load the argument into GPR or stack slot if needed. 6393 if (!NeedGPROrStack) 6394 ; 6395 else if (GPR_idx != NumGPRs && !IsFastCall) { 6396 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6397 // once we support fp <-> gpr moves. 6398 6399 // In the non-vararg case, this can only ever happen in the 6400 // presence of f32 array types, since otherwise we never run 6401 // out of FPRs before running out of GPRs. 6402 SDValue ArgVal; 6403 6404 // Double values are always passed in a single GPR. 6405 if (Arg.getValueType() != MVT::f32) { 6406 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6407 6408 // Non-array float values are extended and passed in a GPR. 6409 } else if (!Flags.isInConsecutiveRegs()) { 6410 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6411 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6412 6413 // If we have an array of floats, we collect every odd element 6414 // together with its predecessor into one GPR. 6415 } else if (ArgOffset % PtrByteSize != 0) { 6416 SDValue Lo, Hi; 6417 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6418 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6419 if (!isLittleEndian) 6420 std::swap(Lo, Hi); 6421 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6422 6423 // The final element, if even, goes into the first half of a GPR. 6424 } else if (Flags.isInConsecutiveRegsLast()) { 6425 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6426 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6427 if (!isLittleEndian) 6428 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6429 DAG.getConstant(32, dl, MVT::i32)); 6430 6431 // Non-final even elements are skipped; they will be handled 6432 // together the with subsequent argument on the next go-around. 6433 } else 6434 ArgVal = SDValue(); 6435 6436 if (ArgVal.getNode()) 6437 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6438 } else { 6439 if (IsFastCall) 6440 ComputePtrOff(); 6441 6442 // Single-precision floating-point values are mapped to the 6443 // second (rightmost) word of the stack doubleword. 6444 if (Arg.getValueType() == MVT::f32 && 6445 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6446 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6447 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6448 } 6449 6450 assert(HasParameterArea && 6451 "Parameter area must exist to pass an argument in memory."); 6452 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6453 true, CFlags.IsTailCall, false, MemOpChains, 6454 TailCallArguments, dl); 6455 6456 NeededLoad = true; 6457 } 6458 // When passing an array of floats, the array occupies consecutive 6459 // space in the argument area; only round up to the next doubleword 6460 // at the end of the array. Otherwise, each float takes 8 bytes. 6461 if (!IsFastCall || NeededLoad) { 6462 ArgOffset += (Arg.getValueType() == MVT::f32 && 6463 Flags.isInConsecutiveRegs()) ? 4 : 8; 6464 if (Flags.isInConsecutiveRegsLast()) 6465 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6466 } 6467 break; 6468 } 6469 case MVT::v4f32: 6470 case MVT::v4i32: 6471 case MVT::v8i16: 6472 case MVT::v16i8: 6473 case MVT::v2f64: 6474 case MVT::v2i64: 6475 case MVT::v1i128: 6476 case MVT::f128: 6477 if (!Subtarget.hasQPX()) { 6478 // These can be scalar arguments or elements of a vector array type 6479 // passed directly. The latter are used to implement ELFv2 homogenous 6480 // vector aggregates. 6481 6482 // For a varargs call, named arguments go into VRs or on the stack as 6483 // usual; unnamed arguments always go to the stack or the corresponding 6484 // GPRs when within range. For now, we always put the value in both 6485 // locations (or even all three). 6486 if (CFlags.IsVarArg) { 6487 assert(HasParameterArea && 6488 "Parameter area must exist if we have a varargs call."); 6489 // We could elide this store in the case where the object fits 6490 // entirely in R registers. Maybe later. 6491 SDValue Store = 6492 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6493 MemOpChains.push_back(Store); 6494 if (VR_idx != NumVRs) { 6495 SDValue Load = 6496 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6497 MemOpChains.push_back(Load.getValue(1)); 6498 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6499 } 6500 ArgOffset += 16; 6501 for (unsigned i=0; i<16; i+=PtrByteSize) { 6502 if (GPR_idx == NumGPRs) 6503 break; 6504 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6505 DAG.getConstant(i, dl, PtrVT)); 6506 SDValue Load = 6507 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6508 MemOpChains.push_back(Load.getValue(1)); 6509 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6510 } 6511 break; 6512 } 6513 6514 // Non-varargs Altivec params go into VRs or on the stack. 6515 if (VR_idx != NumVRs) { 6516 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6517 } else { 6518 if (IsFastCall) 6519 ComputePtrOff(); 6520 6521 assert(HasParameterArea && 6522 "Parameter area must exist to pass an argument in memory."); 6523 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6524 true, CFlags.IsTailCall, true, MemOpChains, 6525 TailCallArguments, dl); 6526 if (IsFastCall) 6527 ArgOffset += 16; 6528 } 6529 6530 if (!IsFastCall) 6531 ArgOffset += 16; 6532 break; 6533 } // not QPX 6534 6535 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6536 "Invalid QPX parameter type"); 6537 6538 LLVM_FALLTHROUGH; 6539 case MVT::v4f64: 6540 case MVT::v4i1: { 6541 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6542 if (CFlags.IsVarArg) { 6543 assert(HasParameterArea && 6544 "Parameter area must exist if we have a varargs call."); 6545 // We could elide this store in the case where the object fits 6546 // entirely in R registers. Maybe later. 6547 SDValue Store = 6548 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6549 MemOpChains.push_back(Store); 6550 if (QFPR_idx != NumQFPRs) { 6551 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6552 PtrOff, MachinePointerInfo()); 6553 MemOpChains.push_back(Load.getValue(1)); 6554 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6555 } 6556 ArgOffset += (IsF32 ? 16 : 32); 6557 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6558 if (GPR_idx == NumGPRs) 6559 break; 6560 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6561 DAG.getConstant(i, dl, PtrVT)); 6562 SDValue Load = 6563 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6564 MemOpChains.push_back(Load.getValue(1)); 6565 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6566 } 6567 break; 6568 } 6569 6570 // Non-varargs QPX params go into registers or on the stack. 6571 if (QFPR_idx != NumQFPRs) { 6572 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6573 } else { 6574 if (IsFastCall) 6575 ComputePtrOff(); 6576 6577 assert(HasParameterArea && 6578 "Parameter area must exist to pass an argument in memory."); 6579 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6580 true, CFlags.IsTailCall, true, MemOpChains, 6581 TailCallArguments, dl); 6582 if (IsFastCall) 6583 ArgOffset += (IsF32 ? 16 : 32); 6584 } 6585 6586 if (!IsFastCall) 6587 ArgOffset += (IsF32 ? 16 : 32); 6588 break; 6589 } 6590 } 6591 } 6592 6593 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6594 "mismatch in size of parameter area"); 6595 (void)NumBytesActuallyUsed; 6596 6597 if (!MemOpChains.empty()) 6598 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6599 6600 // Check if this is an indirect call (MTCTR/BCTRL). 6601 // See prepareDescriptorIndirectCall and buildCallOperands for more 6602 // information about calls through function pointers in the 64-bit SVR4 ABI. 6603 if (CFlags.IsIndirect) { 6604 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6605 // caller in the TOC save area. 6606 if (isTOCSaveRestoreRequired(Subtarget)) { 6607 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6608 // Load r2 into a virtual register and store it to the TOC save area. 6609 setUsesTOCBasePtr(DAG); 6610 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6611 // TOC save area offset. 6612 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6613 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6614 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6615 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6616 MachinePointerInfo::getStack( 6617 DAG.getMachineFunction(), TOCSaveOffset)); 6618 } 6619 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6620 // This does not mean the MTCTR instruction must use R12; it's easier 6621 // to model this as an extra parameter, so do that. 6622 if (isELFv2ABI && !CFlags.IsPatchPoint) 6623 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6624 } 6625 6626 // Build a sequence of copy-to-reg nodes chained together with token chain 6627 // and flag operands which copy the outgoing args into the appropriate regs. 6628 SDValue InFlag; 6629 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6630 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6631 RegsToPass[i].second, InFlag); 6632 InFlag = Chain.getValue(1); 6633 } 6634 6635 if (CFlags.IsTailCall && !IsSibCall) 6636 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6637 TailCallArguments); 6638 6639 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6640 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6641 } 6642 6643 SDValue PPCTargetLowering::LowerCall_Darwin( 6644 SDValue Chain, SDValue Callee, CallFlags CFlags, 6645 const SmallVectorImpl<ISD::OutputArg> &Outs, 6646 const SmallVectorImpl<SDValue> &OutVals, 6647 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6648 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6649 const CallBase *CB) const { 6650 unsigned NumOps = Outs.size(); 6651 6652 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6653 bool isPPC64 = PtrVT == MVT::i64; 6654 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6655 6656 MachineFunction &MF = DAG.getMachineFunction(); 6657 6658 // Mark this function as potentially containing a function that contains a 6659 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6660 // and restoring the callers stack pointer in this functions epilog. This is 6661 // done because by tail calling the called function might overwrite the value 6662 // in this function's (MF) stack pointer stack slot 0(SP). 6663 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6664 CFlags.CallConv == CallingConv::Fast) 6665 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6666 6667 // Count how many bytes are to be pushed on the stack, including the linkage 6668 // area, and parameter passing area. We start with 24/48 bytes, which is 6669 // prereserved space for [SP][CR][LR][3 x unused]. 6670 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6671 unsigned NumBytes = LinkageSize; 6672 6673 // Add up all the space actually used. 6674 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6675 // they all go in registers, but we must reserve stack space for them for 6676 // possible use by the caller. In varargs or 64-bit calls, parameters are 6677 // assigned stack space in order, with padding so Altivec parameters are 6678 // 16-byte aligned. 6679 unsigned nAltivecParamsAtEnd = 0; 6680 for (unsigned i = 0; i != NumOps; ++i) { 6681 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6682 EVT ArgVT = Outs[i].VT; 6683 // Varargs Altivec parameters are padded to a 16 byte boundary. 6684 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6685 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6686 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6687 if (!CFlags.IsVarArg && !isPPC64) { 6688 // Non-varargs Altivec parameters go after all the non-Altivec 6689 // parameters; handle those later so we know how much padding we need. 6690 nAltivecParamsAtEnd++; 6691 continue; 6692 } 6693 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6694 NumBytes = ((NumBytes+15)/16)*16; 6695 } 6696 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6697 } 6698 6699 // Allow for Altivec parameters at the end, if needed. 6700 if (nAltivecParamsAtEnd) { 6701 NumBytes = ((NumBytes+15)/16)*16; 6702 NumBytes += 16*nAltivecParamsAtEnd; 6703 } 6704 6705 // The prolog code of the callee may store up to 8 GPR argument registers to 6706 // the stack, allowing va_start to index over them in memory if its varargs. 6707 // Because we cannot tell if this is needed on the caller side, we have to 6708 // conservatively assume that it is needed. As such, make sure we have at 6709 // least enough stack space for the caller to store the 8 GPRs. 6710 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6711 6712 // Tail call needs the stack to be aligned. 6713 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6714 CFlags.CallConv == CallingConv::Fast) 6715 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6716 6717 // Calculate by how many bytes the stack has to be adjusted in case of tail 6718 // call optimization. 6719 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6720 6721 // To protect arguments on the stack from being clobbered in a tail call, 6722 // force all the loads to happen before doing any other lowering. 6723 if (CFlags.IsTailCall) 6724 Chain = DAG.getStackArgumentTokenFactor(Chain); 6725 6726 // Adjust the stack pointer for the new arguments... 6727 // These operations are automatically eliminated by the prolog/epilog pass 6728 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6729 SDValue CallSeqStart = Chain; 6730 6731 // Load the return address and frame pointer so it can be move somewhere else 6732 // later. 6733 SDValue LROp, FPOp; 6734 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6735 6736 // Set up a copy of the stack pointer for use loading and storing any 6737 // arguments that may not fit in the registers available for argument 6738 // passing. 6739 SDValue StackPtr; 6740 if (isPPC64) 6741 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6742 else 6743 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6744 6745 // Figure out which arguments are going to go in registers, and which in 6746 // memory. Also, if this is a vararg function, floating point operations 6747 // must be stored to our stack, and loaded into integer regs as well, if 6748 // any integer regs are available for argument passing. 6749 unsigned ArgOffset = LinkageSize; 6750 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6751 6752 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6753 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6754 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6755 }; 6756 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6757 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6758 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6759 }; 6760 static const MCPhysReg VR[] = { 6761 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6762 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6763 }; 6764 const unsigned NumGPRs = array_lengthof(GPR_32); 6765 const unsigned NumFPRs = 13; 6766 const unsigned NumVRs = array_lengthof(VR); 6767 6768 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6769 6770 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6771 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6772 6773 SmallVector<SDValue, 8> MemOpChains; 6774 for (unsigned i = 0; i != NumOps; ++i) { 6775 SDValue Arg = OutVals[i]; 6776 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6777 6778 // PtrOff will be used to store the current argument to the stack if a 6779 // register cannot be found for it. 6780 SDValue PtrOff; 6781 6782 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6783 6784 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6785 6786 // On PPC64, promote integers to 64-bit values. 6787 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6788 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6789 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6790 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6791 } 6792 6793 // FIXME memcpy is used way more than necessary. Correctness first. 6794 // Note: "by value" is code for passing a structure by value, not 6795 // basic types. 6796 if (Flags.isByVal()) { 6797 unsigned Size = Flags.getByValSize(); 6798 // Very small objects are passed right-justified. Everything else is 6799 // passed left-justified. 6800 if (Size==1 || Size==2) { 6801 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6802 if (GPR_idx != NumGPRs) { 6803 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6804 MachinePointerInfo(), VT); 6805 MemOpChains.push_back(Load.getValue(1)); 6806 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6807 6808 ArgOffset += PtrByteSize; 6809 } else { 6810 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6811 PtrOff.getValueType()); 6812 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6813 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6814 CallSeqStart, 6815 Flags, DAG, dl); 6816 ArgOffset += PtrByteSize; 6817 } 6818 continue; 6819 } 6820 // Copy entire object into memory. There are cases where gcc-generated 6821 // code assumes it is there, even if it could be put entirely into 6822 // registers. (This is not what the doc says.) 6823 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6824 CallSeqStart, 6825 Flags, DAG, dl); 6826 6827 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6828 // copy the pieces of the object that fit into registers from the 6829 // parameter save area. 6830 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6831 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6832 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6833 if (GPR_idx != NumGPRs) { 6834 SDValue Load = 6835 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6836 MemOpChains.push_back(Load.getValue(1)); 6837 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6838 ArgOffset += PtrByteSize; 6839 } else { 6840 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6841 break; 6842 } 6843 } 6844 continue; 6845 } 6846 6847 switch (Arg.getSimpleValueType().SimpleTy) { 6848 default: llvm_unreachable("Unexpected ValueType for argument!"); 6849 case MVT::i1: 6850 case MVT::i32: 6851 case MVT::i64: 6852 if (GPR_idx != NumGPRs) { 6853 if (Arg.getValueType() == MVT::i1) 6854 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6855 6856 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6857 } else { 6858 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6859 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6860 TailCallArguments, dl); 6861 } 6862 ArgOffset += PtrByteSize; 6863 break; 6864 case MVT::f32: 6865 case MVT::f64: 6866 if (FPR_idx != NumFPRs) { 6867 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6868 6869 if (CFlags.IsVarArg) { 6870 SDValue Store = 6871 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6872 MemOpChains.push_back(Store); 6873 6874 // Float varargs are always shadowed in available integer registers 6875 if (GPR_idx != NumGPRs) { 6876 SDValue Load = 6877 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6878 MemOpChains.push_back(Load.getValue(1)); 6879 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6880 } 6881 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6882 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6883 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6884 SDValue Load = 6885 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6886 MemOpChains.push_back(Load.getValue(1)); 6887 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6888 } 6889 } else { 6890 // If we have any FPRs remaining, we may also have GPRs remaining. 6891 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6892 // GPRs. 6893 if (GPR_idx != NumGPRs) 6894 ++GPR_idx; 6895 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6896 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6897 ++GPR_idx; 6898 } 6899 } else 6900 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6901 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6902 TailCallArguments, dl); 6903 if (isPPC64) 6904 ArgOffset += 8; 6905 else 6906 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6907 break; 6908 case MVT::v4f32: 6909 case MVT::v4i32: 6910 case MVT::v8i16: 6911 case MVT::v16i8: 6912 if (CFlags.IsVarArg) { 6913 // These go aligned on the stack, or in the corresponding R registers 6914 // when within range. The Darwin PPC ABI doc claims they also go in 6915 // V registers; in fact gcc does this only for arguments that are 6916 // prototyped, not for those that match the ... We do it for all 6917 // arguments, seems to work. 6918 while (ArgOffset % 16 !=0) { 6919 ArgOffset += PtrByteSize; 6920 if (GPR_idx != NumGPRs) 6921 GPR_idx++; 6922 } 6923 // We could elide this store in the case where the object fits 6924 // entirely in R registers. Maybe later. 6925 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6926 DAG.getConstant(ArgOffset, dl, PtrVT)); 6927 SDValue Store = 6928 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6929 MemOpChains.push_back(Store); 6930 if (VR_idx != NumVRs) { 6931 SDValue Load = 6932 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6933 MemOpChains.push_back(Load.getValue(1)); 6934 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6935 } 6936 ArgOffset += 16; 6937 for (unsigned i=0; i<16; i+=PtrByteSize) { 6938 if (GPR_idx == NumGPRs) 6939 break; 6940 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6941 DAG.getConstant(i, dl, PtrVT)); 6942 SDValue Load = 6943 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6944 MemOpChains.push_back(Load.getValue(1)); 6945 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6946 } 6947 break; 6948 } 6949 6950 // Non-varargs Altivec params generally go in registers, but have 6951 // stack space allocated at the end. 6952 if (VR_idx != NumVRs) { 6953 // Doesn't have GPR space allocated. 6954 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6955 } else if (nAltivecParamsAtEnd==0) { 6956 // We are emitting Altivec params in order. 6957 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6958 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6959 TailCallArguments, dl); 6960 ArgOffset += 16; 6961 } 6962 break; 6963 } 6964 } 6965 // If all Altivec parameters fit in registers, as they usually do, 6966 // they get stack space following the non-Altivec parameters. We 6967 // don't track this here because nobody below needs it. 6968 // If there are more Altivec parameters than fit in registers emit 6969 // the stores here. 6970 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6971 unsigned j = 0; 6972 // Offset is aligned; skip 1st 12 params which go in V registers. 6973 ArgOffset = ((ArgOffset+15)/16)*16; 6974 ArgOffset += 12*16; 6975 for (unsigned i = 0; i != NumOps; ++i) { 6976 SDValue Arg = OutVals[i]; 6977 EVT ArgType = Outs[i].VT; 6978 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6979 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6980 if (++j > NumVRs) { 6981 SDValue PtrOff; 6982 // We are emitting Altivec params in order. 6983 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6984 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6985 TailCallArguments, dl); 6986 ArgOffset += 16; 6987 } 6988 } 6989 } 6990 } 6991 6992 if (!MemOpChains.empty()) 6993 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6994 6995 // On Darwin, R12 must contain the address of an indirect callee. This does 6996 // not mean the MTCTR instruction must use R12; it's easier to model this as 6997 // an extra parameter, so do that. 6998 if (CFlags.IsIndirect) { 6999 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7000 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 7001 PPC::R12), Callee)); 7002 } 7003 7004 // Build a sequence of copy-to-reg nodes chained together with token chain 7005 // and flag operands which copy the outgoing args into the appropriate regs. 7006 SDValue InFlag; 7007 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 7008 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 7009 RegsToPass[i].second, InFlag); 7010 InFlag = Chain.getValue(1); 7011 } 7012 7013 if (CFlags.IsTailCall) 7014 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 7015 TailCallArguments); 7016 7017 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7018 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7019 } 7020 7021 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 7022 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 7023 CCState &State) { 7024 7025 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 7026 State.getMachineFunction().getSubtarget()); 7027 const bool IsPPC64 = Subtarget.isPPC64(); 7028 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 7029 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 7030 7031 assert((!ValVT.isInteger() || 7032 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 7033 "Integer argument exceeds register size: should have been legalized"); 7034 7035 if (ValVT == MVT::f128) 7036 report_fatal_error("f128 is unimplemented on AIX."); 7037 7038 if (ArgFlags.isNest()) 7039 report_fatal_error("Nest arguments are unimplemented."); 7040 7041 if (ValVT.isVector() || LocVT.isVector()) 7042 report_fatal_error("Vector arguments are unimplemented on AIX."); 7043 7044 static const MCPhysReg GPR_32[] = {// 32-bit registers. 7045 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7046 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7047 static const MCPhysReg GPR_64[] = {// 64-bit registers. 7048 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7049 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7050 7051 if (ArgFlags.isByVal()) { 7052 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 7053 report_fatal_error("Pass-by-value arguments with alignment greater than " 7054 "register width are not supported."); 7055 7056 const unsigned ByValSize = ArgFlags.getByValSize(); 7057 7058 // An empty aggregate parameter takes up no storage and no registers, 7059 // but needs a MemLoc for a stack slot for the formal arguments side. 7060 if (ByValSize == 0) { 7061 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7062 State.getNextStackOffset(), RegVT, 7063 LocInfo)); 7064 return false; 7065 } 7066 7067 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 7068 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 7069 for (const unsigned E = Offset + StackSize; Offset < E; 7070 Offset += PtrAlign.value()) { 7071 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7072 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7073 else { 7074 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 7075 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 7076 LocInfo)); 7077 break; 7078 } 7079 } 7080 return false; 7081 } 7082 7083 // Arguments always reserve parameter save area. 7084 switch (ValVT.SimpleTy) { 7085 default: 7086 report_fatal_error("Unhandled value type for argument."); 7087 case MVT::i64: 7088 // i64 arguments should have been split to i32 for PPC32. 7089 assert(IsPPC64 && "PPC32 should have split i64 values."); 7090 LLVM_FALLTHROUGH; 7091 case MVT::i1: 7092 case MVT::i32: { 7093 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 7094 // AIX integer arguments are always passed in register width. 7095 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 7096 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 7097 : CCValAssign::LocInfo::ZExt; 7098 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 7099 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7100 else 7101 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 7102 7103 return false; 7104 } 7105 case MVT::f32: 7106 case MVT::f64: { 7107 // Parameter save area (PSA) is reserved even if the float passes in fpr. 7108 const unsigned StoreSize = LocVT.getStoreSize(); 7109 // Floats are always 4-byte aligned in the PSA on AIX. 7110 // This includes f64 in 64-bit mode for ABI compatibility. 7111 const unsigned Offset = 7112 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 7113 unsigned FReg = State.AllocateReg(FPR); 7114 if (FReg) 7115 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 7116 7117 // Reserve and initialize GPRs or initialize the PSA as required. 7118 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 7119 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 7120 assert(FReg && "An FPR should be available when a GPR is reserved."); 7121 if (State.isVarArg()) { 7122 // Successfully reserved GPRs are only initialized for vararg calls. 7123 // Custom handling is required for: 7124 // f64 in PPC32 needs to be split into 2 GPRs. 7125 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 7126 State.addLoc( 7127 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 7128 } 7129 } else { 7130 // If there are insufficient GPRs, the PSA needs to be initialized. 7131 // Initialization occurs even if an FPR was initialized for 7132 // compatibility with the AIX XL compiler. The full memory for the 7133 // argument will be initialized even if a prior word is saved in GPR. 7134 // A custom memLoc is used when the argument also passes in FPR so 7135 // that the callee handling can skip over it easily. 7136 State.addLoc( 7137 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 7138 LocInfo) 7139 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 7140 break; 7141 } 7142 } 7143 7144 return false; 7145 } 7146 } 7147 return true; 7148 } 7149 7150 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 7151 bool IsPPC64) { 7152 assert((IsPPC64 || SVT != MVT::i64) && 7153 "i64 should have been split for 32-bit codegen."); 7154 7155 switch (SVT) { 7156 default: 7157 report_fatal_error("Unexpected value type for formal argument"); 7158 case MVT::i1: 7159 case MVT::i32: 7160 case MVT::i64: 7161 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7162 case MVT::f32: 7163 return &PPC::F4RCRegClass; 7164 case MVT::f64: 7165 return &PPC::F8RCRegClass; 7166 } 7167 } 7168 7169 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7170 SelectionDAG &DAG, SDValue ArgValue, 7171 MVT LocVT, const SDLoc &dl) { 7172 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7173 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7174 7175 if (Flags.isSExt()) 7176 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7177 DAG.getValueType(ValVT)); 7178 else if (Flags.isZExt()) 7179 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7180 DAG.getValueType(ValVT)); 7181 7182 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7183 } 7184 7185 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7186 const unsigned LASize = FL->getLinkageSize(); 7187 7188 if (PPC::GPRCRegClass.contains(Reg)) { 7189 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7190 "Reg must be a valid argument register!"); 7191 return LASize + 4 * (Reg - PPC::R3); 7192 } 7193 7194 if (PPC::G8RCRegClass.contains(Reg)) { 7195 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7196 "Reg must be a valid argument register!"); 7197 return LASize + 8 * (Reg - PPC::X3); 7198 } 7199 7200 llvm_unreachable("Only general purpose registers expected."); 7201 } 7202 7203 // AIX ABI Stack Frame Layout: 7204 // 7205 // Low Memory +--------------------------------------------+ 7206 // SP +---> | Back chain | ---+ 7207 // | +--------------------------------------------+ | 7208 // | | Saved Condition Register | | 7209 // | +--------------------------------------------+ | 7210 // | | Saved Linkage Register | | 7211 // | +--------------------------------------------+ | Linkage Area 7212 // | | Reserved for compilers | | 7213 // | +--------------------------------------------+ | 7214 // | | Reserved for binders | | 7215 // | +--------------------------------------------+ | 7216 // | | Saved TOC pointer | ---+ 7217 // | +--------------------------------------------+ 7218 // | | Parameter save area | 7219 // | +--------------------------------------------+ 7220 // | | Alloca space | 7221 // | +--------------------------------------------+ 7222 // | | Local variable space | 7223 // | +--------------------------------------------+ 7224 // | | Float/int conversion temporary | 7225 // | +--------------------------------------------+ 7226 // | | Save area for AltiVec registers | 7227 // | +--------------------------------------------+ 7228 // | | AltiVec alignment padding | 7229 // | +--------------------------------------------+ 7230 // | | Save area for VRSAVE register | 7231 // | +--------------------------------------------+ 7232 // | | Save area for General Purpose registers | 7233 // | +--------------------------------------------+ 7234 // | | Save area for Floating Point registers | 7235 // | +--------------------------------------------+ 7236 // +---- | Back chain | 7237 // High Memory +--------------------------------------------+ 7238 // 7239 // Specifications: 7240 // AIX 7.2 Assembler Language Reference 7241 // Subroutine linkage convention 7242 7243 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7244 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7245 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7246 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7247 7248 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7249 CallConv == CallingConv::Fast) && 7250 "Unexpected calling convention!"); 7251 7252 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7253 report_fatal_error("Tail call support is unimplemented on AIX."); 7254 7255 if (useSoftFloat()) 7256 report_fatal_error("Soft float support is unimplemented on AIX."); 7257 7258 const PPCSubtarget &Subtarget = 7259 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7260 if (Subtarget.hasQPX()) 7261 report_fatal_error("QPX support is not supported on AIX."); 7262 7263 const bool IsPPC64 = Subtarget.isPPC64(); 7264 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7265 7266 // Assign locations to all of the incoming arguments. 7267 SmallVector<CCValAssign, 16> ArgLocs; 7268 MachineFunction &MF = DAG.getMachineFunction(); 7269 MachineFrameInfo &MFI = MF.getFrameInfo(); 7270 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7271 7272 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7273 // Reserve space for the linkage area on the stack. 7274 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7275 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7276 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7277 7278 SmallVector<SDValue, 8> MemOps; 7279 7280 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7281 CCValAssign &VA = ArgLocs[I++]; 7282 MVT LocVT = VA.getLocVT(); 7283 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7284 7285 // For compatibility with the AIX XL compiler, the float args in the 7286 // parameter save area are initialized even if the argument is available 7287 // in register. The caller is required to initialize both the register 7288 // and memory, however, the callee can choose to expect it in either. 7289 // The memloc is dismissed here because the argument is retrieved from 7290 // the register. 7291 if (VA.isMemLoc() && VA.needsCustom()) 7292 continue; 7293 7294 if (Flags.isByVal() && VA.isMemLoc()) { 7295 const unsigned Size = 7296 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7297 PtrByteSize); 7298 const int FI = MF.getFrameInfo().CreateFixedObject( 7299 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7300 /* IsAliased */ true); 7301 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7302 InVals.push_back(FIN); 7303 7304 continue; 7305 } 7306 7307 if (Flags.isByVal()) { 7308 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7309 7310 const MCPhysReg ArgReg = VA.getLocReg(); 7311 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7312 7313 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7314 report_fatal_error("Over aligned byvals not supported yet."); 7315 7316 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7317 const int FI = MF.getFrameInfo().CreateFixedObject( 7318 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7319 /* IsAliased */ true); 7320 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7321 InVals.push_back(FIN); 7322 7323 // Add live ins for all the RegLocs for the same ByVal. 7324 const TargetRegisterClass *RegClass = 7325 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7326 7327 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7328 unsigned Offset) { 7329 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7330 // Since the callers side has left justified the aggregate in the 7331 // register, we can simply store the entire register into the stack 7332 // slot. 7333 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7334 // The store to the fixedstack object is needed becuase accessing a 7335 // field of the ByVal will use a gep and load. Ideally we will optimize 7336 // to extracting the value from the register directly, and elide the 7337 // stores when the arguments address is not taken, but that will need to 7338 // be future work. 7339 SDValue Store = 7340 DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom, 7341 DAG.getObjectPtrOffset(dl, FIN, Offset), 7342 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7343 7344 MemOps.push_back(Store); 7345 }; 7346 7347 unsigned Offset = 0; 7348 HandleRegLoc(VA.getLocReg(), Offset); 7349 Offset += PtrByteSize; 7350 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7351 Offset += PtrByteSize) { 7352 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7353 "RegLocs should be for ByVal argument."); 7354 7355 const CCValAssign RL = ArgLocs[I++]; 7356 HandleRegLoc(RL.getLocReg(), Offset); 7357 } 7358 7359 if (Offset != StackSize) { 7360 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7361 "Expected MemLoc for remaining bytes."); 7362 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7363 // Consume the MemLoc.The InVal has already been emitted, so nothing 7364 // more needs to be done. 7365 ++I; 7366 } 7367 7368 continue; 7369 } 7370 7371 EVT ValVT = VA.getValVT(); 7372 if (VA.isRegLoc() && !VA.needsCustom()) { 7373 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7374 unsigned VReg = 7375 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7376 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7377 if (ValVT.isScalarInteger() && 7378 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7379 ArgValue = 7380 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7381 } 7382 InVals.push_back(ArgValue); 7383 continue; 7384 } 7385 if (VA.isMemLoc()) { 7386 const unsigned LocSize = LocVT.getStoreSize(); 7387 const unsigned ValSize = ValVT.getStoreSize(); 7388 assert((ValSize <= LocSize) && 7389 "Object size is larger than size of MemLoc"); 7390 int CurArgOffset = VA.getLocMemOffset(); 7391 // Objects are right-justified because AIX is big-endian. 7392 if (LocSize > ValSize) 7393 CurArgOffset += LocSize - ValSize; 7394 // Potential tail calls could cause overwriting of argument stack slots. 7395 const bool IsImmutable = 7396 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7397 (CallConv == CallingConv::Fast)); 7398 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7399 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7400 SDValue ArgValue = 7401 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7402 InVals.push_back(ArgValue); 7403 continue; 7404 } 7405 } 7406 7407 // On AIX a minimum of 8 words is saved to the parameter save area. 7408 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7409 // Area that is at least reserved in the caller of this function. 7410 unsigned CallerReservedArea = 7411 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7412 7413 // Set the size that is at least reserved in caller of this function. Tail 7414 // call optimized function's reserved stack space needs to be aligned so 7415 // that taking the difference between two stack areas will result in an 7416 // aligned stack. 7417 CallerReservedArea = 7418 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7419 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7420 FuncInfo->setMinReservedArea(CallerReservedArea); 7421 7422 if (isVarArg) { 7423 FuncInfo->setVarArgsFrameIndex( 7424 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7425 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7426 7427 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7428 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7429 7430 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7431 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7432 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7433 7434 // The fixed integer arguments of a variadic function are stored to the 7435 // VarArgsFrameIndex on the stack so that they may be loaded by 7436 // dereferencing the result of va_next. 7437 for (unsigned GPRIndex = 7438 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7439 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7440 7441 const unsigned VReg = 7442 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7443 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7444 7445 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7446 SDValue Store = 7447 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7448 MemOps.push_back(Store); 7449 // Increment the address for the next argument to store. 7450 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7451 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7452 } 7453 } 7454 7455 if (!MemOps.empty()) 7456 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7457 7458 return Chain; 7459 } 7460 7461 SDValue PPCTargetLowering::LowerCall_AIX( 7462 SDValue Chain, SDValue Callee, CallFlags CFlags, 7463 const SmallVectorImpl<ISD::OutputArg> &Outs, 7464 const SmallVectorImpl<SDValue> &OutVals, 7465 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7466 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7467 const CallBase *CB) const { 7468 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7469 // AIX ABI stack frame layout. 7470 7471 assert((CFlags.CallConv == CallingConv::C || 7472 CFlags.CallConv == CallingConv::Cold || 7473 CFlags.CallConv == CallingConv::Fast) && 7474 "Unexpected calling convention!"); 7475 7476 if (CFlags.IsPatchPoint) 7477 report_fatal_error("This call type is unimplemented on AIX."); 7478 7479 const PPCSubtarget& Subtarget = 7480 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7481 if (Subtarget.hasQPX()) 7482 report_fatal_error("QPX is not supported on AIX."); 7483 if (Subtarget.hasAltivec()) 7484 report_fatal_error("Altivec support is unimplemented on AIX."); 7485 7486 MachineFunction &MF = DAG.getMachineFunction(); 7487 SmallVector<CCValAssign, 16> ArgLocs; 7488 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7489 *DAG.getContext()); 7490 7491 // Reserve space for the linkage save area (LSA) on the stack. 7492 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7493 // [SP][CR][LR][2 x reserved][TOC]. 7494 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7495 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7496 const bool IsPPC64 = Subtarget.isPPC64(); 7497 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7498 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7499 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7500 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7501 7502 // The prolog code of the callee may store up to 8 GPR argument registers to 7503 // the stack, allowing va_start to index over them in memory if the callee 7504 // is variadic. 7505 // Because we cannot tell if this is needed on the caller side, we have to 7506 // conservatively assume that it is needed. As such, make sure we have at 7507 // least enough stack space for the caller to store the 8 GPRs. 7508 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7509 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7510 CCInfo.getNextStackOffset()); 7511 7512 // Adjust the stack pointer for the new arguments... 7513 // These operations are automatically eliminated by the prolog/epilog pass. 7514 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7515 SDValue CallSeqStart = Chain; 7516 7517 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7518 SmallVector<SDValue, 8> MemOpChains; 7519 7520 // Set up a copy of the stack pointer for loading and storing any 7521 // arguments that may not fit in the registers available for argument 7522 // passing. 7523 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7524 : DAG.getRegister(PPC::R1, MVT::i32); 7525 7526 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7527 const unsigned ValNo = ArgLocs[I].getValNo(); 7528 SDValue Arg = OutVals[ValNo]; 7529 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7530 7531 if (Flags.isByVal()) { 7532 const unsigned ByValSize = Flags.getByValSize(); 7533 7534 // Nothing to do for zero-sized ByVals on the caller side. 7535 if (!ByValSize) { 7536 ++I; 7537 continue; 7538 } 7539 7540 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7541 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, 7542 (LoadOffset != 0) 7543 ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7544 : Arg, 7545 MachinePointerInfo(), VT); 7546 }; 7547 7548 unsigned LoadOffset = 0; 7549 7550 // Initialize registers, which are fully occupied by the by-val argument. 7551 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7552 SDValue Load = GetLoad(PtrVT, LoadOffset); 7553 MemOpChains.push_back(Load.getValue(1)); 7554 LoadOffset += PtrByteSize; 7555 const CCValAssign &ByValVA = ArgLocs[I++]; 7556 assert(ByValVA.getValNo() == ValNo && 7557 "Unexpected location for pass-by-value argument."); 7558 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7559 } 7560 7561 if (LoadOffset == ByValSize) 7562 continue; 7563 7564 // There must be one more loc to handle the remainder. 7565 assert(ArgLocs[I].getValNo() == ValNo && 7566 "Expected additional location for by-value argument."); 7567 7568 if (ArgLocs[I].isMemLoc()) { 7569 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7570 const CCValAssign &ByValVA = ArgLocs[I++]; 7571 ISD::ArgFlagsTy MemcpyFlags = Flags; 7572 // Only memcpy the bytes that don't pass in register. 7573 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7574 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7575 (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset) 7576 : Arg, 7577 DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()), 7578 CallSeqStart, MemcpyFlags, DAG, dl); 7579 continue; 7580 } 7581 7582 // Initialize the final register residue. 7583 // Any residue that occupies the final by-val arg register must be 7584 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7585 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7586 // 2 and 1 byte loads. 7587 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7588 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7589 "Unexpected register residue for by-value argument."); 7590 SDValue ResidueVal; 7591 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7592 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7593 const MVT VT = 7594 N == 1 ? MVT::i8 7595 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7596 SDValue Load = GetLoad(VT, LoadOffset); 7597 MemOpChains.push_back(Load.getValue(1)); 7598 LoadOffset += N; 7599 Bytes += N; 7600 7601 // By-val arguments are passed left-justfied in register. 7602 // Every load here needs to be shifted, otherwise a full register load 7603 // should have been used. 7604 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7605 "Unexpected load emitted during handling of pass-by-value " 7606 "argument."); 7607 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7608 EVT ShiftAmountTy = 7609 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7610 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7611 SDValue ShiftedLoad = 7612 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7613 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7614 ShiftedLoad) 7615 : ShiftedLoad; 7616 } 7617 7618 const CCValAssign &ByValVA = ArgLocs[I++]; 7619 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7620 continue; 7621 } 7622 7623 CCValAssign &VA = ArgLocs[I++]; 7624 const MVT LocVT = VA.getLocVT(); 7625 const MVT ValVT = VA.getValVT(); 7626 7627 switch (VA.getLocInfo()) { 7628 default: 7629 report_fatal_error("Unexpected argument extension type."); 7630 case CCValAssign::Full: 7631 break; 7632 case CCValAssign::ZExt: 7633 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7634 break; 7635 case CCValAssign::SExt: 7636 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7637 break; 7638 } 7639 7640 if (VA.isRegLoc() && !VA.needsCustom()) { 7641 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7642 continue; 7643 } 7644 7645 if (VA.isMemLoc()) { 7646 SDValue PtrOff = 7647 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7648 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7649 MemOpChains.push_back( 7650 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7651 7652 continue; 7653 } 7654 7655 // Custom handling is used for GPR initializations for vararg float 7656 // arguments. 7657 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7658 ValVT.isFloatingPoint() && LocVT.isInteger() && 7659 "Unexpected register handling for calling convention."); 7660 7661 SDValue ArgAsInt = 7662 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7663 7664 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7665 // f32 in 32-bit GPR 7666 // f64 in 64-bit GPR 7667 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7668 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7669 // f32 in 64-bit GPR. 7670 RegsToPass.push_back(std::make_pair( 7671 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7672 else { 7673 // f64 in two 32-bit GPRs 7674 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7675 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7676 "Unexpected custom register for argument!"); 7677 CCValAssign &GPR1 = VA; 7678 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7679 DAG.getConstant(32, dl, MVT::i8)); 7680 RegsToPass.push_back(std::make_pair( 7681 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7682 7683 if (I != E) { 7684 // If only 1 GPR was available, there will only be one custom GPR and 7685 // the argument will also pass in memory. 7686 CCValAssign &PeekArg = ArgLocs[I]; 7687 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7688 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7689 CCValAssign &GPR2 = ArgLocs[I++]; 7690 RegsToPass.push_back(std::make_pair( 7691 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7692 } 7693 } 7694 } 7695 } 7696 7697 if (!MemOpChains.empty()) 7698 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7699 7700 // For indirect calls, we need to save the TOC base to the stack for 7701 // restoration after the call. 7702 if (CFlags.IsIndirect) { 7703 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7704 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7705 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7706 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7707 const unsigned TOCSaveOffset = 7708 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7709 7710 setUsesTOCBasePtr(DAG); 7711 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7712 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7713 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7714 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7715 Chain = DAG.getStore( 7716 Val.getValue(1), dl, Val, AddPtr, 7717 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7718 } 7719 7720 // Build a sequence of copy-to-reg nodes chained together with token chain 7721 // and flag operands which copy the outgoing args into the appropriate regs. 7722 SDValue InFlag; 7723 for (auto Reg : RegsToPass) { 7724 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7725 InFlag = Chain.getValue(1); 7726 } 7727 7728 const int SPDiff = 0; 7729 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7730 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7731 } 7732 7733 bool 7734 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7735 MachineFunction &MF, bool isVarArg, 7736 const SmallVectorImpl<ISD::OutputArg> &Outs, 7737 LLVMContext &Context) const { 7738 SmallVector<CCValAssign, 16> RVLocs; 7739 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7740 return CCInfo.CheckReturn( 7741 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7742 ? RetCC_PPC_Cold 7743 : RetCC_PPC); 7744 } 7745 7746 SDValue 7747 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7748 bool isVarArg, 7749 const SmallVectorImpl<ISD::OutputArg> &Outs, 7750 const SmallVectorImpl<SDValue> &OutVals, 7751 const SDLoc &dl, SelectionDAG &DAG) const { 7752 SmallVector<CCValAssign, 16> RVLocs; 7753 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7754 *DAG.getContext()); 7755 CCInfo.AnalyzeReturn(Outs, 7756 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7757 ? RetCC_PPC_Cold 7758 : RetCC_PPC); 7759 7760 SDValue Flag; 7761 SmallVector<SDValue, 4> RetOps(1, Chain); 7762 7763 // Copy the result values into the output registers. 7764 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7765 CCValAssign &VA = RVLocs[i]; 7766 assert(VA.isRegLoc() && "Can only return in registers!"); 7767 7768 SDValue Arg = OutVals[RealResIdx]; 7769 7770 switch (VA.getLocInfo()) { 7771 default: llvm_unreachable("Unknown loc info!"); 7772 case CCValAssign::Full: break; 7773 case CCValAssign::AExt: 7774 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7775 break; 7776 case CCValAssign::ZExt: 7777 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7778 break; 7779 case CCValAssign::SExt: 7780 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7781 break; 7782 } 7783 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7784 bool isLittleEndian = Subtarget.isLittleEndian(); 7785 // Legalize ret f64 -> ret 2 x i32. 7786 SDValue SVal = 7787 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7788 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7789 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7790 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7791 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7792 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7793 Flag = Chain.getValue(1); 7794 VA = RVLocs[++i]; // skip ahead to next loc 7795 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7796 } else 7797 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7798 Flag = Chain.getValue(1); 7799 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7800 } 7801 7802 RetOps[0] = Chain; // Update chain. 7803 7804 // Add the flag if we have it. 7805 if (Flag.getNode()) 7806 RetOps.push_back(Flag); 7807 7808 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7809 } 7810 7811 SDValue 7812 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7813 SelectionDAG &DAG) const { 7814 SDLoc dl(Op); 7815 7816 // Get the correct type for integers. 7817 EVT IntVT = Op.getValueType(); 7818 7819 // Get the inputs. 7820 SDValue Chain = Op.getOperand(0); 7821 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7822 // Build a DYNAREAOFFSET node. 7823 SDValue Ops[2] = {Chain, FPSIdx}; 7824 SDVTList VTs = DAG.getVTList(IntVT); 7825 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7826 } 7827 7828 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7829 SelectionDAG &DAG) const { 7830 // When we pop the dynamic allocation we need to restore the SP link. 7831 SDLoc dl(Op); 7832 7833 // Get the correct type for pointers. 7834 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7835 7836 // Construct the stack pointer operand. 7837 bool isPPC64 = Subtarget.isPPC64(); 7838 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7839 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7840 7841 // Get the operands for the STACKRESTORE. 7842 SDValue Chain = Op.getOperand(0); 7843 SDValue SaveSP = Op.getOperand(1); 7844 7845 // Load the old link SP. 7846 SDValue LoadLinkSP = 7847 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7848 7849 // Restore the stack pointer. 7850 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7851 7852 // Store the old link SP. 7853 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7854 } 7855 7856 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7857 MachineFunction &MF = DAG.getMachineFunction(); 7858 bool isPPC64 = Subtarget.isPPC64(); 7859 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7860 7861 // Get current frame pointer save index. The users of this index will be 7862 // primarily DYNALLOC instructions. 7863 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7864 int RASI = FI->getReturnAddrSaveIndex(); 7865 7866 // If the frame pointer save index hasn't been defined yet. 7867 if (!RASI) { 7868 // Find out what the fix offset of the frame pointer save area. 7869 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7870 // Allocate the frame index for frame pointer save area. 7871 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7872 // Save the result. 7873 FI->setReturnAddrSaveIndex(RASI); 7874 } 7875 return DAG.getFrameIndex(RASI, PtrVT); 7876 } 7877 7878 SDValue 7879 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7880 MachineFunction &MF = DAG.getMachineFunction(); 7881 bool isPPC64 = Subtarget.isPPC64(); 7882 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7883 7884 // Get current frame pointer save index. The users of this index will be 7885 // primarily DYNALLOC instructions. 7886 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7887 int FPSI = FI->getFramePointerSaveIndex(); 7888 7889 // If the frame pointer save index hasn't been defined yet. 7890 if (!FPSI) { 7891 // Find out what the fix offset of the frame pointer save area. 7892 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7893 // Allocate the frame index for frame pointer save area. 7894 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7895 // Save the result. 7896 FI->setFramePointerSaveIndex(FPSI); 7897 } 7898 return DAG.getFrameIndex(FPSI, PtrVT); 7899 } 7900 7901 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7902 SelectionDAG &DAG) const { 7903 // Get the inputs. 7904 SDValue Chain = Op.getOperand(0); 7905 SDValue Size = Op.getOperand(1); 7906 SDLoc dl(Op); 7907 7908 // Get the correct type for pointers. 7909 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7910 // Negate the size. 7911 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7912 DAG.getConstant(0, dl, PtrVT), Size); 7913 // Construct a node for the frame pointer save index. 7914 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7915 // Build a DYNALLOC node. 7916 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7917 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7918 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7919 } 7920 7921 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7922 SelectionDAG &DAG) const { 7923 MachineFunction &MF = DAG.getMachineFunction(); 7924 7925 bool isPPC64 = Subtarget.isPPC64(); 7926 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7927 7928 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7929 return DAG.getFrameIndex(FI, PtrVT); 7930 } 7931 7932 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7933 SelectionDAG &DAG) const { 7934 SDLoc DL(Op); 7935 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7936 DAG.getVTList(MVT::i32, MVT::Other), 7937 Op.getOperand(0), Op.getOperand(1)); 7938 } 7939 7940 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7941 SelectionDAG &DAG) const { 7942 SDLoc DL(Op); 7943 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7944 Op.getOperand(0), Op.getOperand(1)); 7945 } 7946 7947 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7948 if (Op.getValueType().isVector()) 7949 return LowerVectorLoad(Op, DAG); 7950 7951 assert(Op.getValueType() == MVT::i1 && 7952 "Custom lowering only for i1 loads"); 7953 7954 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7955 7956 SDLoc dl(Op); 7957 LoadSDNode *LD = cast<LoadSDNode>(Op); 7958 7959 SDValue Chain = LD->getChain(); 7960 SDValue BasePtr = LD->getBasePtr(); 7961 MachineMemOperand *MMO = LD->getMemOperand(); 7962 7963 SDValue NewLD = 7964 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7965 BasePtr, MVT::i8, MMO); 7966 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7967 7968 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7969 return DAG.getMergeValues(Ops, dl); 7970 } 7971 7972 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7973 if (Op.getOperand(1).getValueType().isVector()) 7974 return LowerVectorStore(Op, DAG); 7975 7976 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7977 "Custom lowering only for i1 stores"); 7978 7979 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7980 7981 SDLoc dl(Op); 7982 StoreSDNode *ST = cast<StoreSDNode>(Op); 7983 7984 SDValue Chain = ST->getChain(); 7985 SDValue BasePtr = ST->getBasePtr(); 7986 SDValue Value = ST->getValue(); 7987 MachineMemOperand *MMO = ST->getMemOperand(); 7988 7989 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7990 Value); 7991 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7992 } 7993 7994 // FIXME: Remove this once the ANDI glue bug is fixed: 7995 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7996 assert(Op.getValueType() == MVT::i1 && 7997 "Custom lowering only for i1 results"); 7998 7999 SDLoc DL(Op); 8000 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 8001 } 8002 8003 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 8004 SelectionDAG &DAG) const { 8005 8006 // Implements a vector truncate that fits in a vector register as a shuffle. 8007 // We want to legalize vector truncates down to where the source fits in 8008 // a vector register (and target is therefore smaller than vector register 8009 // size). At that point legalization will try to custom lower the sub-legal 8010 // result and get here - where we can contain the truncate as a single target 8011 // operation. 8012 8013 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 8014 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 8015 // 8016 // We will implement it for big-endian ordering as this (where x denotes 8017 // undefined): 8018 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 8019 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 8020 // 8021 // The same operation in little-endian ordering will be: 8022 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 8023 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 8024 8025 assert(Op.getValueType().isVector() && "Vector type expected."); 8026 8027 SDLoc DL(Op); 8028 SDValue N1 = Op.getOperand(0); 8029 unsigned SrcSize = N1.getValueType().getSizeInBits(); 8030 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 8031 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 8032 8033 EVT TrgVT = Op.getValueType(); 8034 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 8035 EVT EltVT = TrgVT.getVectorElementType(); 8036 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8037 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8038 8039 // First list the elements we want to keep. 8040 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 8041 SmallVector<int, 16> ShuffV; 8042 if (Subtarget.isLittleEndian()) 8043 for (unsigned i = 0; i < TrgNumElts; ++i) 8044 ShuffV.push_back(i * SizeMult); 8045 else 8046 for (unsigned i = 1; i <= TrgNumElts; ++i) 8047 ShuffV.push_back(i * SizeMult - 1); 8048 8049 // Populate the remaining elements with undefs. 8050 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 8051 // ShuffV.push_back(i + WideNumElts); 8052 ShuffV.push_back(WideNumElts + 1); 8053 8054 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 8055 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 8056 } 8057 8058 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 8059 /// possible. 8060 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 8061 // Not FP? Not a fsel. 8062 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 8063 !Op.getOperand(2).getValueType().isFloatingPoint()) 8064 return Op; 8065 8066 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 8067 8068 EVT ResVT = Op.getValueType(); 8069 EVT CmpVT = Op.getOperand(0).getValueType(); 8070 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8071 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 8072 SDLoc dl(Op); 8073 SDNodeFlags Flags = Op.getNode()->getFlags(); 8074 8075 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 8076 // presence of infinities. 8077 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 8078 switch (CC) { 8079 default: 8080 break; 8081 case ISD::SETOGT: 8082 case ISD::SETGT: 8083 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 8084 case ISD::SETOLT: 8085 case ISD::SETLT: 8086 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 8087 } 8088 } 8089 8090 // We might be able to do better than this under some circumstances, but in 8091 // general, fsel-based lowering of select is a finite-math-only optimization. 8092 // For more information, see section F.3 of the 2.06 ISA specification. 8093 // With ISA 3.0 8094 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 8095 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 8096 return Op; 8097 8098 // If the RHS of the comparison is a 0.0, we don't need to do the 8099 // subtraction at all. 8100 SDValue Sel1; 8101 if (isFloatingPointZero(RHS)) 8102 switch (CC) { 8103 default: break; // SETUO etc aren't handled by fsel. 8104 case ISD::SETNE: 8105 std::swap(TV, FV); 8106 LLVM_FALLTHROUGH; 8107 case ISD::SETEQ: 8108 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8109 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8110 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8111 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8112 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8113 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8114 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 8115 case ISD::SETULT: 8116 case ISD::SETLT: 8117 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8118 LLVM_FALLTHROUGH; 8119 case ISD::SETOGE: 8120 case ISD::SETGE: 8121 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8122 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8123 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 8124 case ISD::SETUGT: 8125 case ISD::SETGT: 8126 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 8127 LLVM_FALLTHROUGH; 8128 case ISD::SETOLE: 8129 case ISD::SETLE: 8130 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 8131 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 8132 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8133 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8134 } 8135 8136 SDValue Cmp; 8137 switch (CC) { 8138 default: break; // SETUO etc aren't handled by fsel. 8139 case ISD::SETNE: 8140 std::swap(TV, FV); 8141 LLVM_FALLTHROUGH; 8142 case ISD::SETEQ: 8143 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8144 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8145 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8146 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8147 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8148 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8149 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8150 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8151 case ISD::SETULT: 8152 case ISD::SETLT: 8153 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8154 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8155 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8156 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8157 case ISD::SETOGE: 8158 case ISD::SETGE: 8159 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8160 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8161 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8162 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8163 case ISD::SETUGT: 8164 case ISD::SETGT: 8165 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8166 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8167 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8168 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8169 case ISD::SETOLE: 8170 case ISD::SETLE: 8171 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8172 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8173 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8174 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8175 } 8176 return Op; 8177 } 8178 8179 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8180 SelectionDAG &DAG, 8181 const SDLoc &dl) const { 8182 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8183 SDValue Src = Op.getOperand(0); 8184 if (Src.getValueType() == MVT::f32) 8185 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8186 8187 SDValue Tmp; 8188 switch (Op.getSimpleValueType().SimpleTy) { 8189 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8190 case MVT::i32: 8191 Tmp = DAG.getNode( 8192 Op.getOpcode() == ISD::FP_TO_SINT 8193 ? PPCISD::FCTIWZ 8194 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8195 dl, MVT::f64, Src); 8196 break; 8197 case MVT::i64: 8198 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8199 "i64 FP_TO_UINT is supported only with FPCVT"); 8200 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8201 PPCISD::FCTIDUZ, 8202 dl, MVT::f64, Src); 8203 break; 8204 } 8205 8206 // Convert the FP value to an int value through memory. 8207 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8208 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 8209 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8210 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8211 MachinePointerInfo MPI = 8212 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8213 8214 // Emit a store to the stack slot. 8215 SDValue Chain; 8216 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8217 if (i32Stack) { 8218 MachineFunction &MF = DAG.getMachineFunction(); 8219 Alignment = Align(4); 8220 MachineMemOperand *MMO = 8221 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8222 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 8223 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8224 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8225 } else 8226 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment); 8227 8228 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8229 // add in a bias on big endian. 8230 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8231 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8232 DAG.getConstant(4, dl, FIPtr.getValueType())); 8233 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8234 } 8235 8236 RLI.Chain = Chain; 8237 RLI.Ptr = FIPtr; 8238 RLI.MPI = MPI; 8239 RLI.Alignment = Alignment; 8240 } 8241 8242 /// Custom lowers floating point to integer conversions to use 8243 /// the direct move instructions available in ISA 2.07 to avoid the 8244 /// need for load/store combinations. 8245 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8246 SelectionDAG &DAG, 8247 const SDLoc &dl) const { 8248 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8249 SDValue Src = Op.getOperand(0); 8250 8251 if (Src.getValueType() == MVT::f32) 8252 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8253 8254 SDValue Tmp; 8255 switch (Op.getSimpleValueType().SimpleTy) { 8256 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8257 case MVT::i32: 8258 Tmp = DAG.getNode( 8259 Op.getOpcode() == ISD::FP_TO_SINT 8260 ? PPCISD::FCTIWZ 8261 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 8262 dl, MVT::f64, Src); 8263 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 8264 break; 8265 case MVT::i64: 8266 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 8267 "i64 FP_TO_UINT is supported only with FPCVT"); 8268 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 8269 PPCISD::FCTIDUZ, 8270 dl, MVT::f64, Src); 8271 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 8272 break; 8273 } 8274 return Tmp; 8275 } 8276 8277 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8278 const SDLoc &dl) const { 8279 8280 // FP to INT conversions are legal for f128. 8281 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 8282 return Op; 8283 8284 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8285 // PPC (the libcall is not available). 8286 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 8287 if (Op.getValueType() == MVT::i32) { 8288 if (Op.getOpcode() == ISD::FP_TO_SINT) { 8289 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8290 MVT::f64, Op.getOperand(0), 8291 DAG.getIntPtrConstant(0, dl)); 8292 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 8293 MVT::f64, Op.getOperand(0), 8294 DAG.getIntPtrConstant(1, dl)); 8295 8296 // Add the two halves of the long double in round-to-zero mode. 8297 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8298 8299 // Now use a smaller FP_TO_SINT. 8300 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8301 } 8302 if (Op.getOpcode() == ISD::FP_TO_UINT) { 8303 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8304 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8305 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8306 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8307 // FIXME: generated code sucks. 8308 // TODO: Are there fast-math-flags to propagate to this FSUB? 8309 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 8310 Op.getOperand(0), Tmp); 8311 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8312 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8313 DAG.getConstant(0x80000000, dl, MVT::i32)); 8314 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 8315 Op.getOperand(0)); 8316 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 8317 ISD::SETGE); 8318 } 8319 } 8320 8321 return SDValue(); 8322 } 8323 8324 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8325 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8326 8327 ReuseLoadInfo RLI; 8328 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8329 8330 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8331 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8332 } 8333 8334 // We're trying to insert a regular store, S, and then a load, L. If the 8335 // incoming value, O, is a load, we might just be able to have our load use the 8336 // address used by O. However, we don't know if anything else will store to 8337 // that address before we can load from it. To prevent this situation, we need 8338 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8339 // the same chain operand as O, we create a token factor from the chain results 8340 // of O and L, and we replace all uses of O's chain result with that token 8341 // factor (see spliceIntoChain below for this last part). 8342 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8343 ReuseLoadInfo &RLI, 8344 SelectionDAG &DAG, 8345 ISD::LoadExtType ET) const { 8346 SDLoc dl(Op); 8347 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8348 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8349 if (ET == ISD::NON_EXTLOAD && 8350 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8351 isOperationLegalOrCustom(Op.getOpcode(), 8352 Op.getOperand(0).getValueType())) { 8353 8354 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8355 return true; 8356 } 8357 8358 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8359 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8360 LD->isNonTemporal()) 8361 return false; 8362 if (LD->getMemoryVT() != MemVT) 8363 return false; 8364 8365 RLI.Ptr = LD->getBasePtr(); 8366 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8367 assert(LD->getAddressingMode() == ISD::PRE_INC && 8368 "Non-pre-inc AM on PPC?"); 8369 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8370 LD->getOffset()); 8371 } 8372 8373 RLI.Chain = LD->getChain(); 8374 RLI.MPI = LD->getPointerInfo(); 8375 RLI.IsDereferenceable = LD->isDereferenceable(); 8376 RLI.IsInvariant = LD->isInvariant(); 8377 RLI.Alignment = LD->getAlign(); 8378 RLI.AAInfo = LD->getAAInfo(); 8379 RLI.Ranges = LD->getRanges(); 8380 8381 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8382 return true; 8383 } 8384 8385 // Given the head of the old chain, ResChain, insert a token factor containing 8386 // it and NewResChain, and make users of ResChain now be users of that token 8387 // factor. 8388 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8389 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8390 SDValue NewResChain, 8391 SelectionDAG &DAG) const { 8392 if (!ResChain) 8393 return; 8394 8395 SDLoc dl(NewResChain); 8396 8397 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8398 NewResChain, DAG.getUNDEF(MVT::Other)); 8399 assert(TF.getNode() != NewResChain.getNode() && 8400 "A new TF really is required here"); 8401 8402 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8403 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8404 } 8405 8406 /// Analyze profitability of direct move 8407 /// prefer float load to int load plus direct move 8408 /// when there is no integer use of int load 8409 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8410 SDNode *Origin = Op.getOperand(0).getNode(); 8411 if (Origin->getOpcode() != ISD::LOAD) 8412 return true; 8413 8414 // If there is no LXSIBZX/LXSIHZX, like Power8, 8415 // prefer direct move if the memory size is 1 or 2 bytes. 8416 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8417 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8418 return true; 8419 8420 for (SDNode::use_iterator UI = Origin->use_begin(), 8421 UE = Origin->use_end(); 8422 UI != UE; ++UI) { 8423 8424 // Only look at the users of the loaded value. 8425 if (UI.getUse().get().getResNo() != 0) 8426 continue; 8427 8428 if (UI->getOpcode() != ISD::SINT_TO_FP && 8429 UI->getOpcode() != ISD::UINT_TO_FP) 8430 return true; 8431 } 8432 8433 return false; 8434 } 8435 8436 /// Custom lowers integer to floating point conversions to use 8437 /// the direct move instructions available in ISA 2.07 to avoid the 8438 /// need for load/store combinations. 8439 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8440 SelectionDAG &DAG, 8441 const SDLoc &dl) const { 8442 assert((Op.getValueType() == MVT::f32 || 8443 Op.getValueType() == MVT::f64) && 8444 "Invalid floating point type as target of conversion"); 8445 assert(Subtarget.hasFPCVT() && 8446 "Int to FP conversions with direct moves require FPCVT"); 8447 SDValue FP; 8448 SDValue Src = Op.getOperand(0); 8449 bool SinglePrec = Op.getValueType() == MVT::f32; 8450 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8451 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 8452 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 8453 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 8454 8455 if (WordInt) { 8456 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 8457 dl, MVT::f64, Src); 8458 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8459 } 8460 else { 8461 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 8462 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 8463 } 8464 8465 return FP; 8466 } 8467 8468 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8469 8470 EVT VecVT = Vec.getValueType(); 8471 assert(VecVT.isVector() && "Expected a vector type."); 8472 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8473 8474 EVT EltVT = VecVT.getVectorElementType(); 8475 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8476 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8477 8478 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8479 SmallVector<SDValue, 16> Ops(NumConcat); 8480 Ops[0] = Vec; 8481 SDValue UndefVec = DAG.getUNDEF(VecVT); 8482 for (unsigned i = 1; i < NumConcat; ++i) 8483 Ops[i] = UndefVec; 8484 8485 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8486 } 8487 8488 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8489 const SDLoc &dl) const { 8490 8491 unsigned Opc = Op.getOpcode(); 8492 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8493 "Unexpected conversion type"); 8494 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8495 "Supports conversions to v2f64/v4f32 only."); 8496 8497 bool SignedConv = Opc == ISD::SINT_TO_FP; 8498 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8499 8500 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8501 EVT WideVT = Wide.getValueType(); 8502 unsigned WideNumElts = WideVT.getVectorNumElements(); 8503 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8504 8505 SmallVector<int, 16> ShuffV; 8506 for (unsigned i = 0; i < WideNumElts; ++i) 8507 ShuffV.push_back(i + WideNumElts); 8508 8509 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8510 int SaveElts = FourEltRes ? 4 : 2; 8511 if (Subtarget.isLittleEndian()) 8512 for (int i = 0; i < SaveElts; i++) 8513 ShuffV[i * Stride] = i; 8514 else 8515 for (int i = 1; i <= SaveElts; i++) 8516 ShuffV[i * Stride - 1] = i - 1; 8517 8518 SDValue ShuffleSrc2 = 8519 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8520 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8521 8522 SDValue Extend; 8523 if (SignedConv) { 8524 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8525 EVT ExtVT = Op.getOperand(0).getValueType(); 8526 if (Subtarget.hasP9Altivec()) 8527 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8528 IntermediateVT.getVectorNumElements()); 8529 8530 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8531 DAG.getValueType(ExtVT)); 8532 } else 8533 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8534 8535 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8536 } 8537 8538 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8539 SelectionDAG &DAG) const { 8540 SDLoc dl(Op); 8541 8542 EVT InVT = Op.getOperand(0).getValueType(); 8543 EVT OutVT = Op.getValueType(); 8544 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8545 isOperationCustom(Op.getOpcode(), InVT)) 8546 return LowerINT_TO_FPVector(Op, DAG, dl); 8547 8548 // Conversions to f128 are legal. 8549 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 8550 return Op; 8551 8552 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8553 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8554 return SDValue(); 8555 8556 SDValue Value = Op.getOperand(0); 8557 // The values are now known to be -1 (false) or 1 (true). To convert this 8558 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8559 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8560 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8561 8562 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8563 8564 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8565 8566 if (Op.getValueType() != MVT::v4f64) 8567 Value = DAG.getNode(ISD::FP_ROUND, dl, 8568 Op.getValueType(), Value, 8569 DAG.getIntPtrConstant(1, dl)); 8570 return Value; 8571 } 8572 8573 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8574 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8575 return SDValue(); 8576 8577 if (Op.getOperand(0).getValueType() == MVT::i1) 8578 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8579 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8580 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8581 8582 // If we have direct moves, we can do all the conversion, skip the store/load 8583 // however, without FPCVT we can't do most conversions. 8584 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8585 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8586 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8587 8588 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8589 "UINT_TO_FP is supported only with FPCVT"); 8590 8591 // If we have FCFIDS, then use it when converting to single-precision. 8592 // Otherwise, convert to double-precision and then round. 8593 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8594 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8595 : PPCISD::FCFIDS) 8596 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8597 : PPCISD::FCFID); 8598 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8599 ? MVT::f32 8600 : MVT::f64; 8601 8602 if (Op.getOperand(0).getValueType() == MVT::i64) { 8603 SDValue SINT = Op.getOperand(0); 8604 // When converting to single-precision, we actually need to convert 8605 // to double-precision first and then round to single-precision. 8606 // To avoid double-rounding effects during that operation, we have 8607 // to prepare the input operand. Bits that might be truncated when 8608 // converting to double-precision are replaced by a bit that won't 8609 // be lost at this stage, but is below the single-precision rounding 8610 // position. 8611 // 8612 // However, if -enable-unsafe-fp-math is in effect, accept double 8613 // rounding to avoid the extra overhead. 8614 if (Op.getValueType() == MVT::f32 && 8615 !Subtarget.hasFPCVT() && 8616 !DAG.getTarget().Options.UnsafeFPMath) { 8617 8618 // Twiddle input to make sure the low 11 bits are zero. (If this 8619 // is the case, we are guaranteed the value will fit into the 53 bit 8620 // mantissa of an IEEE double-precision value without rounding.) 8621 // If any of those low 11 bits were not zero originally, make sure 8622 // bit 12 (value 2048) is set instead, so that the final rounding 8623 // to single-precision gets the correct result. 8624 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8625 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8626 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8627 Round, DAG.getConstant(2047, dl, MVT::i64)); 8628 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8629 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8630 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8631 8632 // However, we cannot use that value unconditionally: if the magnitude 8633 // of the input value is small, the bit-twiddling we did above might 8634 // end up visibly changing the output. Fortunately, in that case, we 8635 // don't need to twiddle bits since the original input will convert 8636 // exactly to double-precision floating-point already. Therefore, 8637 // construct a conditional to use the original value if the top 11 8638 // bits are all sign-bit copies, and use the rounded value computed 8639 // above otherwise. 8640 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8641 SINT, DAG.getConstant(53, dl, MVT::i32)); 8642 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8643 Cond, DAG.getConstant(1, dl, MVT::i64)); 8644 Cond = DAG.getSetCC( 8645 dl, 8646 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8647 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8648 8649 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8650 } 8651 8652 ReuseLoadInfo RLI; 8653 SDValue Bits; 8654 8655 MachineFunction &MF = DAG.getMachineFunction(); 8656 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8657 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8658 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8659 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8660 } else if (Subtarget.hasLFIWAX() && 8661 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8662 MachineMemOperand *MMO = 8663 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8664 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8665 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8666 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8667 DAG.getVTList(MVT::f64, MVT::Other), 8668 Ops, MVT::i32, MMO); 8669 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8670 } else if (Subtarget.hasFPCVT() && 8671 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8672 MachineMemOperand *MMO = 8673 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8674 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8675 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8676 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8677 DAG.getVTList(MVT::f64, MVT::Other), 8678 Ops, MVT::i32, MMO); 8679 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8680 } else if (((Subtarget.hasLFIWAX() && 8681 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8682 (Subtarget.hasFPCVT() && 8683 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8684 SINT.getOperand(0).getValueType() == MVT::i32) { 8685 MachineFrameInfo &MFI = MF.getFrameInfo(); 8686 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8687 8688 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8689 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8690 8691 SDValue Store = 8692 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8693 MachinePointerInfo::getFixedStack( 8694 DAG.getMachineFunction(), FrameIdx)); 8695 8696 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8697 "Expected an i32 store"); 8698 8699 RLI.Ptr = FIdx; 8700 RLI.Chain = Store; 8701 RLI.MPI = 8702 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8703 RLI.Alignment = Align(4); 8704 8705 MachineMemOperand *MMO = 8706 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8707 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8708 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8709 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8710 PPCISD::LFIWZX : PPCISD::LFIWAX, 8711 dl, DAG.getVTList(MVT::f64, MVT::Other), 8712 Ops, MVT::i32, MMO); 8713 } else 8714 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8715 8716 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8717 8718 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8719 FP = DAG.getNode(ISD::FP_ROUND, dl, 8720 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8721 return FP; 8722 } 8723 8724 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8725 "Unhandled INT_TO_FP type in custom expander!"); 8726 // Since we only generate this in 64-bit mode, we can take advantage of 8727 // 64-bit registers. In particular, sign extend the input value into the 8728 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8729 // then lfd it and fcfid it. 8730 MachineFunction &MF = DAG.getMachineFunction(); 8731 MachineFrameInfo &MFI = MF.getFrameInfo(); 8732 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8733 8734 SDValue Ld; 8735 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8736 ReuseLoadInfo RLI; 8737 bool ReusingLoad; 8738 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8739 DAG))) { 8740 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8741 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8742 8743 SDValue Store = 8744 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8745 MachinePointerInfo::getFixedStack( 8746 DAG.getMachineFunction(), FrameIdx)); 8747 8748 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8749 "Expected an i32 store"); 8750 8751 RLI.Ptr = FIdx; 8752 RLI.Chain = Store; 8753 RLI.MPI = 8754 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8755 RLI.Alignment = Align(4); 8756 } 8757 8758 MachineMemOperand *MMO = 8759 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8760 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8761 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8762 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8763 PPCISD::LFIWZX : PPCISD::LFIWAX, 8764 dl, DAG.getVTList(MVT::f64, MVT::Other), 8765 Ops, MVT::i32, MMO); 8766 if (ReusingLoad) 8767 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8768 } else { 8769 assert(Subtarget.isPPC64() && 8770 "i32->FP without LFIWAX supported only on PPC64"); 8771 8772 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8773 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8774 8775 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8776 Op.getOperand(0)); 8777 8778 // STD the extended value into the stack slot. 8779 SDValue Store = DAG.getStore( 8780 DAG.getEntryNode(), dl, Ext64, FIdx, 8781 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8782 8783 // Load the value as a double. 8784 Ld = DAG.getLoad( 8785 MVT::f64, dl, Store, FIdx, 8786 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8787 } 8788 8789 // FCFID it and return it. 8790 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8791 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8792 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8793 DAG.getIntPtrConstant(0, dl)); 8794 return FP; 8795 } 8796 8797 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8798 SelectionDAG &DAG) const { 8799 SDLoc dl(Op); 8800 /* 8801 The rounding mode is in bits 30:31 of FPSR, and has the following 8802 settings: 8803 00 Round to nearest 8804 01 Round to 0 8805 10 Round to +inf 8806 11 Round to -inf 8807 8808 FLT_ROUNDS, on the other hand, expects the following: 8809 -1 Undefined 8810 0 Round to 0 8811 1 Round to nearest 8812 2 Round to +inf 8813 3 Round to -inf 8814 8815 To perform the conversion, we do: 8816 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8817 */ 8818 8819 MachineFunction &MF = DAG.getMachineFunction(); 8820 EVT VT = Op.getValueType(); 8821 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8822 8823 // Save FP Control Word to register 8824 SDValue Chain = Op.getOperand(0); 8825 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8826 Chain = MFFS.getValue(1); 8827 8828 // Save FP register to stack slot 8829 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8830 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8831 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8832 8833 // Load FP Control Word from low 32 bits of stack slot. 8834 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8835 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8836 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8837 Chain = CWD.getValue(1); 8838 8839 // Transform as necessary 8840 SDValue CWD1 = 8841 DAG.getNode(ISD::AND, dl, MVT::i32, 8842 CWD, DAG.getConstant(3, dl, MVT::i32)); 8843 SDValue CWD2 = 8844 DAG.getNode(ISD::SRL, dl, MVT::i32, 8845 DAG.getNode(ISD::AND, dl, MVT::i32, 8846 DAG.getNode(ISD::XOR, dl, MVT::i32, 8847 CWD, DAG.getConstant(3, dl, MVT::i32)), 8848 DAG.getConstant(3, dl, MVT::i32)), 8849 DAG.getConstant(1, dl, MVT::i32)); 8850 8851 SDValue RetVal = 8852 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8853 8854 RetVal = 8855 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8856 dl, VT, RetVal); 8857 8858 return DAG.getMergeValues({RetVal, Chain}, dl); 8859 } 8860 8861 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8862 EVT VT = Op.getValueType(); 8863 unsigned BitWidth = VT.getSizeInBits(); 8864 SDLoc dl(Op); 8865 assert(Op.getNumOperands() == 3 && 8866 VT == Op.getOperand(1).getValueType() && 8867 "Unexpected SHL!"); 8868 8869 // Expand into a bunch of logical ops. Note that these ops 8870 // depend on the PPC behavior for oversized shift amounts. 8871 SDValue Lo = Op.getOperand(0); 8872 SDValue Hi = Op.getOperand(1); 8873 SDValue Amt = Op.getOperand(2); 8874 EVT AmtVT = Amt.getValueType(); 8875 8876 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8877 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8878 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8879 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8880 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8881 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8882 DAG.getConstant(-BitWidth, dl, AmtVT)); 8883 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8884 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8885 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8886 SDValue OutOps[] = { OutLo, OutHi }; 8887 return DAG.getMergeValues(OutOps, dl); 8888 } 8889 8890 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8891 EVT VT = Op.getValueType(); 8892 SDLoc dl(Op); 8893 unsigned BitWidth = VT.getSizeInBits(); 8894 assert(Op.getNumOperands() == 3 && 8895 VT == Op.getOperand(1).getValueType() && 8896 "Unexpected SRL!"); 8897 8898 // Expand into a bunch of logical ops. Note that these ops 8899 // depend on the PPC behavior for oversized shift amounts. 8900 SDValue Lo = Op.getOperand(0); 8901 SDValue Hi = Op.getOperand(1); 8902 SDValue Amt = Op.getOperand(2); 8903 EVT AmtVT = Amt.getValueType(); 8904 8905 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8906 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8907 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8908 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8909 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8910 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8911 DAG.getConstant(-BitWidth, dl, AmtVT)); 8912 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8913 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8914 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8915 SDValue OutOps[] = { OutLo, OutHi }; 8916 return DAG.getMergeValues(OutOps, dl); 8917 } 8918 8919 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8920 SDLoc dl(Op); 8921 EVT VT = Op.getValueType(); 8922 unsigned BitWidth = VT.getSizeInBits(); 8923 assert(Op.getNumOperands() == 3 && 8924 VT == Op.getOperand(1).getValueType() && 8925 "Unexpected SRA!"); 8926 8927 // Expand into a bunch of logical ops, followed by a select_cc. 8928 SDValue Lo = Op.getOperand(0); 8929 SDValue Hi = Op.getOperand(1); 8930 SDValue Amt = Op.getOperand(2); 8931 EVT AmtVT = Amt.getValueType(); 8932 8933 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8934 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8935 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8936 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8937 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8938 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8939 DAG.getConstant(-BitWidth, dl, AmtVT)); 8940 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8941 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8942 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8943 Tmp4, Tmp6, ISD::SETLE); 8944 SDValue OutOps[] = { OutLo, OutHi }; 8945 return DAG.getMergeValues(OutOps, dl); 8946 } 8947 8948 //===----------------------------------------------------------------------===// 8949 // Vector related lowering. 8950 // 8951 8952 /// BuildSplatI - Build a canonical splati of Val with an element size of 8953 /// SplatSize. Cast the result to VT. 8954 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8955 SelectionDAG &DAG, const SDLoc &dl) { 8956 static const MVT VTys[] = { // canonical VT to use for each size. 8957 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8958 }; 8959 8960 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8961 8962 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8963 if (Val == -1) 8964 SplatSize = 1; 8965 8966 EVT CanonicalVT = VTys[SplatSize-1]; 8967 8968 // Build a canonical splat for this value. 8969 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8970 } 8971 8972 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8973 /// specified intrinsic ID. 8974 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8975 const SDLoc &dl, EVT DestVT = MVT::Other) { 8976 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8977 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8978 DAG.getConstant(IID, dl, MVT::i32), Op); 8979 } 8980 8981 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8982 /// specified intrinsic ID. 8983 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8984 SelectionDAG &DAG, const SDLoc &dl, 8985 EVT DestVT = MVT::Other) { 8986 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8987 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8988 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8989 } 8990 8991 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8992 /// specified intrinsic ID. 8993 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8994 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8995 EVT DestVT = MVT::Other) { 8996 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8997 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8998 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8999 } 9000 9001 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 9002 /// amount. The result has the specified value type. 9003 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 9004 SelectionDAG &DAG, const SDLoc &dl) { 9005 // Force LHS/RHS to be the right type. 9006 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 9007 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 9008 9009 int Ops[16]; 9010 for (unsigned i = 0; i != 16; ++i) 9011 Ops[i] = i + Amt; 9012 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 9013 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9014 } 9015 9016 /// Do we have an efficient pattern in a .td file for this node? 9017 /// 9018 /// \param V - pointer to the BuildVectorSDNode being matched 9019 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 9020 /// 9021 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 9022 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 9023 /// the opposite is true (expansion is beneficial) are: 9024 /// - The node builds a vector out of integers that are not 32 or 64-bits 9025 /// - The node builds a vector out of constants 9026 /// - The node is a "load-and-splat" 9027 /// In all other cases, we will choose to keep the BUILD_VECTOR. 9028 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 9029 bool HasDirectMove, 9030 bool HasP8Vector) { 9031 EVT VecVT = V->getValueType(0); 9032 bool RightType = VecVT == MVT::v2f64 || 9033 (HasP8Vector && VecVT == MVT::v4f32) || 9034 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 9035 if (!RightType) 9036 return false; 9037 9038 bool IsSplat = true; 9039 bool IsLoad = false; 9040 SDValue Op0 = V->getOperand(0); 9041 9042 // This function is called in a block that confirms the node is not a constant 9043 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9044 // different constants. 9045 if (V->isConstant()) 9046 return false; 9047 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9048 if (V->getOperand(i).isUndef()) 9049 return false; 9050 // We want to expand nodes that represent load-and-splat even if the 9051 // loaded value is a floating point truncation or conversion to int. 9052 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9053 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9054 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9055 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9056 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9057 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9058 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9059 IsLoad = true; 9060 // If the operands are different or the input is not a load and has more 9061 // uses than just this BV node, then it isn't a splat. 9062 if (V->getOperand(i) != Op0 || 9063 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9064 IsSplat = false; 9065 } 9066 return !(IsSplat && IsLoad); 9067 } 9068 9069 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9070 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9071 9072 SDLoc dl(Op); 9073 SDValue Op0 = Op->getOperand(0); 9074 9075 if (!EnableQuadPrecision || 9076 (Op.getValueType() != MVT::f128 ) || 9077 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9078 (Op0.getOperand(0).getValueType() != MVT::i64) || 9079 (Op0.getOperand(1).getValueType() != MVT::i64)) 9080 return SDValue(); 9081 9082 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9083 Op0.getOperand(1)); 9084 } 9085 9086 static const SDValue *getNormalLoadInput(const SDValue &Op) { 9087 const SDValue *InputLoad = &Op; 9088 if (InputLoad->getOpcode() == ISD::BITCAST) 9089 InputLoad = &InputLoad->getOperand(0); 9090 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9091 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) 9092 InputLoad = &InputLoad->getOperand(0); 9093 if (InputLoad->getOpcode() != ISD::LOAD) 9094 return nullptr; 9095 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9096 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9097 } 9098 9099 // If this is a case we can't handle, return null and let the default 9100 // expansion code take care of it. If we CAN select this case, and if it 9101 // selects to a single instruction, return Op. Otherwise, if we can codegen 9102 // this case more efficiently than a constant pool load, lower it to the 9103 // sequence of ops that should be used. 9104 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9105 SelectionDAG &DAG) const { 9106 SDLoc dl(Op); 9107 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9108 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9109 9110 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 9111 // We first build an i32 vector, load it into a QPX register, 9112 // then convert it to a floating-point vector and compare it 9113 // to a zero vector to get the boolean result. 9114 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9115 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 9116 MachinePointerInfo PtrInfo = 9117 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9118 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9119 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9120 9121 assert(BVN->getNumOperands() == 4 && 9122 "BUILD_VECTOR for v4i1 does not have 4 operands"); 9123 9124 bool IsConst = true; 9125 for (unsigned i = 0; i < 4; ++i) { 9126 if (BVN->getOperand(i).isUndef()) continue; 9127 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 9128 IsConst = false; 9129 break; 9130 } 9131 } 9132 9133 if (IsConst) { 9134 Constant *One = 9135 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 9136 Constant *NegOne = 9137 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 9138 9139 Constant *CV[4]; 9140 for (unsigned i = 0; i < 4; ++i) { 9141 if (BVN->getOperand(i).isUndef()) 9142 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 9143 else if (isNullConstant(BVN->getOperand(i))) 9144 CV[i] = NegOne; 9145 else 9146 CV[i] = One; 9147 } 9148 9149 Constant *CP = ConstantVector::get(CV); 9150 SDValue CPIdx = 9151 DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), Align(16)); 9152 9153 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 9154 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 9155 return DAG.getMemIntrinsicNode( 9156 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 9157 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 9158 } 9159 9160 SmallVector<SDValue, 4> Stores; 9161 for (unsigned i = 0; i < 4; ++i) { 9162 if (BVN->getOperand(i).isUndef()) continue; 9163 9164 unsigned Offset = 4*i; 9165 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9166 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9167 9168 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 9169 if (StoreSize > 4) { 9170 Stores.push_back( 9171 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 9172 PtrInfo.getWithOffset(Offset), MVT::i32)); 9173 } else { 9174 SDValue StoreValue = BVN->getOperand(i); 9175 if (StoreSize < 4) 9176 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 9177 9178 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 9179 PtrInfo.getWithOffset(Offset))); 9180 } 9181 } 9182 9183 SDValue StoreChain; 9184 if (!Stores.empty()) 9185 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9186 else 9187 StoreChain = DAG.getEntryNode(); 9188 9189 // Now load from v4i32 into the QPX register; this will extend it to 9190 // v4i64 but not yet convert it to a floating point. Nevertheless, this 9191 // is typed as v4f64 because the QPX register integer states are not 9192 // explicitly represented. 9193 9194 SDValue Ops[] = {StoreChain, 9195 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 9196 FIdx}; 9197 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 9198 9199 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 9200 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9201 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9202 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 9203 LoadedVect); 9204 9205 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 9206 9207 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 9208 } 9209 9210 // All other QPX vectors are handled by generic code. 9211 if (Subtarget.hasQPX()) 9212 return SDValue(); 9213 9214 // Check if this is a splat of a constant value. 9215 APInt APSplatBits, APSplatUndef; 9216 unsigned SplatBitSize; 9217 bool HasAnyUndefs; 9218 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9219 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9220 SplatBitSize > 32) { 9221 9222 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 9223 // Handle load-and-splat patterns as we have instructions that will do this 9224 // in one go. 9225 if (InputLoad && DAG.isSplatValue(Op, true)) { 9226 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9227 9228 // We have handling for 4 and 8 byte elements. 9229 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9230 9231 // Checking for a single use of this load, we have to check for vector 9232 // width (128 bits) / ElementSize uses (since each operand of the 9233 // BUILD_VECTOR is a separate use of the value. 9234 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9235 ((Subtarget.hasVSX() && ElementSize == 64) || 9236 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9237 SDValue Ops[] = { 9238 LD->getChain(), // Chain 9239 LD->getBasePtr(), // Ptr 9240 DAG.getValueType(Op.getValueType()) // VT 9241 }; 9242 return 9243 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9244 DAG.getVTList(Op.getValueType(), MVT::Other), 9245 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9246 } 9247 } 9248 9249 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9250 // lowered to VSX instructions under certain conditions. 9251 // Without VSX, there is no pattern more efficient than expanding the node. 9252 if (Subtarget.hasVSX() && 9253 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9254 Subtarget.hasP8Vector())) 9255 return Op; 9256 return SDValue(); 9257 } 9258 9259 unsigned SplatBits = APSplatBits.getZExtValue(); 9260 unsigned SplatUndef = APSplatUndef.getZExtValue(); 9261 unsigned SplatSize = SplatBitSize / 8; 9262 9263 // First, handle single instruction cases. 9264 9265 // All zeros? 9266 if (SplatBits == 0) { 9267 // Canonicalize all zero vectors to be v4i32. 9268 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9269 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9270 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9271 } 9272 return Op; 9273 } 9274 9275 // We have XXSPLTIB for constant splats one byte wide 9276 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 9277 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 9278 if (Subtarget.hasP9Vector() && SplatSize == 1) 9279 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 9280 9281 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9282 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9283 (32-SplatBitSize)); 9284 if (SextVal >= -16 && SextVal <= 15) 9285 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 9286 9287 // Two instruction sequences. 9288 9289 // If this value is in the range [-32,30] and is even, use: 9290 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9291 // If this value is in the range [17,31] and is odd, use: 9292 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9293 // If this value is in the range [-31,-17] and is odd, use: 9294 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9295 // Note the last two are three-instruction sequences. 9296 if (SextVal >= -32 && SextVal <= 31) { 9297 // To avoid having these optimizations undone by constant folding, 9298 // we convert to a pseudo that will be expanded later into one of 9299 // the above forms. 9300 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9301 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9302 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9303 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9304 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9305 if (VT == Op.getValueType()) 9306 return RetVal; 9307 else 9308 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9309 } 9310 9311 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9312 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9313 // for fneg/fabs. 9314 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9315 // Make -1 and vspltisw -1: 9316 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 9317 9318 // Make the VSLW intrinsic, computing 0x8000_0000. 9319 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9320 OnesV, DAG, dl); 9321 9322 // xor by OnesV to invert it. 9323 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9324 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9325 } 9326 9327 // Check to see if this is a wide variety of vsplti*, binop self cases. 9328 static const signed char SplatCsts[] = { 9329 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9330 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9331 }; 9332 9333 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9334 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9335 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9336 int i = SplatCsts[idx]; 9337 9338 // Figure out what shift amount will be used by altivec if shifted by i in 9339 // this splat size. 9340 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9341 9342 // vsplti + shl self. 9343 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9344 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9345 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9346 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9347 Intrinsic::ppc_altivec_vslw 9348 }; 9349 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9350 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9351 } 9352 9353 // vsplti + srl self. 9354 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9355 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9356 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9357 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9358 Intrinsic::ppc_altivec_vsrw 9359 }; 9360 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9361 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9362 } 9363 9364 // vsplti + sra self. 9365 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9366 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9367 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9368 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9369 Intrinsic::ppc_altivec_vsraw 9370 }; 9371 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9372 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9373 } 9374 9375 // vsplti + rol self. 9376 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9377 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9378 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 9379 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9380 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9381 Intrinsic::ppc_altivec_vrlw 9382 }; 9383 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9384 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9385 } 9386 9387 // t = vsplti c, result = vsldoi t, t, 1 9388 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9389 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9390 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9391 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9392 } 9393 // t = vsplti c, result = vsldoi t, t, 2 9394 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9395 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9396 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9397 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9398 } 9399 // t = vsplti c, result = vsldoi t, t, 3 9400 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9401 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 9402 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9403 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9404 } 9405 } 9406 9407 return SDValue(); 9408 } 9409 9410 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9411 /// the specified operations to build the shuffle. 9412 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9413 SDValue RHS, SelectionDAG &DAG, 9414 const SDLoc &dl) { 9415 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9416 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9417 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9418 9419 enum { 9420 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9421 OP_VMRGHW, 9422 OP_VMRGLW, 9423 OP_VSPLTISW0, 9424 OP_VSPLTISW1, 9425 OP_VSPLTISW2, 9426 OP_VSPLTISW3, 9427 OP_VSLDOI4, 9428 OP_VSLDOI8, 9429 OP_VSLDOI12 9430 }; 9431 9432 if (OpNum == OP_COPY) { 9433 if (LHSID == (1*9+2)*9+3) return LHS; 9434 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9435 return RHS; 9436 } 9437 9438 SDValue OpLHS, OpRHS; 9439 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9440 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9441 9442 int ShufIdxs[16]; 9443 switch (OpNum) { 9444 default: llvm_unreachable("Unknown i32 permute!"); 9445 case OP_VMRGHW: 9446 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9447 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9448 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9449 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9450 break; 9451 case OP_VMRGLW: 9452 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9453 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9454 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9455 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9456 break; 9457 case OP_VSPLTISW0: 9458 for (unsigned i = 0; i != 16; ++i) 9459 ShufIdxs[i] = (i&3)+0; 9460 break; 9461 case OP_VSPLTISW1: 9462 for (unsigned i = 0; i != 16; ++i) 9463 ShufIdxs[i] = (i&3)+4; 9464 break; 9465 case OP_VSPLTISW2: 9466 for (unsigned i = 0; i != 16; ++i) 9467 ShufIdxs[i] = (i&3)+8; 9468 break; 9469 case OP_VSPLTISW3: 9470 for (unsigned i = 0; i != 16; ++i) 9471 ShufIdxs[i] = (i&3)+12; 9472 break; 9473 case OP_VSLDOI4: 9474 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9475 case OP_VSLDOI8: 9476 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9477 case OP_VSLDOI12: 9478 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9479 } 9480 EVT VT = OpLHS.getValueType(); 9481 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9482 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9483 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9484 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9485 } 9486 9487 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9488 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9489 /// SDValue. 9490 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9491 SelectionDAG &DAG) const { 9492 const unsigned BytesInVector = 16; 9493 bool IsLE = Subtarget.isLittleEndian(); 9494 SDLoc dl(N); 9495 SDValue V1 = N->getOperand(0); 9496 SDValue V2 = N->getOperand(1); 9497 unsigned ShiftElts = 0, InsertAtByte = 0; 9498 bool Swap = false; 9499 9500 // Shifts required to get the byte we want at element 7. 9501 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9502 0, 15, 14, 13, 12, 11, 10, 9}; 9503 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9504 1, 2, 3, 4, 5, 6, 7, 8}; 9505 9506 ArrayRef<int> Mask = N->getMask(); 9507 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9508 9509 // For each mask element, find out if we're just inserting something 9510 // from V2 into V1 or vice versa. 9511 // Possible permutations inserting an element from V2 into V1: 9512 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9513 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9514 // ... 9515 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9516 // Inserting from V1 into V2 will be similar, except mask range will be 9517 // [16,31]. 9518 9519 bool FoundCandidate = false; 9520 // If both vector operands for the shuffle are the same vector, the mask 9521 // will contain only elements from the first one and the second one will be 9522 // undef. 9523 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9524 // Go through the mask of half-words to find an element that's being moved 9525 // from one vector to the other. 9526 for (unsigned i = 0; i < BytesInVector; ++i) { 9527 unsigned CurrentElement = Mask[i]; 9528 // If 2nd operand is undefined, we should only look for element 7 in the 9529 // Mask. 9530 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9531 continue; 9532 9533 bool OtherElementsInOrder = true; 9534 // Examine the other elements in the Mask to see if they're in original 9535 // order. 9536 for (unsigned j = 0; j < BytesInVector; ++j) { 9537 if (j == i) 9538 continue; 9539 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9540 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9541 // in which we always assume we're always picking from the 1st operand. 9542 int MaskOffset = 9543 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9544 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9545 OtherElementsInOrder = false; 9546 break; 9547 } 9548 } 9549 // If other elements are in original order, we record the number of shifts 9550 // we need to get the element we want into element 7. Also record which byte 9551 // in the vector we should insert into. 9552 if (OtherElementsInOrder) { 9553 // If 2nd operand is undefined, we assume no shifts and no swapping. 9554 if (V2.isUndef()) { 9555 ShiftElts = 0; 9556 Swap = false; 9557 } else { 9558 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9559 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9560 : BigEndianShifts[CurrentElement & 0xF]; 9561 Swap = CurrentElement < BytesInVector; 9562 } 9563 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9564 FoundCandidate = true; 9565 break; 9566 } 9567 } 9568 9569 if (!FoundCandidate) 9570 return SDValue(); 9571 9572 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9573 // optionally with VECSHL if shift is required. 9574 if (Swap) 9575 std::swap(V1, V2); 9576 if (V2.isUndef()) 9577 V2 = V1; 9578 if (ShiftElts) { 9579 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9580 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9581 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9582 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9583 } 9584 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9585 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9586 } 9587 9588 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9589 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9590 /// SDValue. 9591 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9592 SelectionDAG &DAG) const { 9593 const unsigned NumHalfWords = 8; 9594 const unsigned BytesInVector = NumHalfWords * 2; 9595 // Check that the shuffle is on half-words. 9596 if (!isNByteElemShuffleMask(N, 2, 1)) 9597 return SDValue(); 9598 9599 bool IsLE = Subtarget.isLittleEndian(); 9600 SDLoc dl(N); 9601 SDValue V1 = N->getOperand(0); 9602 SDValue V2 = N->getOperand(1); 9603 unsigned ShiftElts = 0, InsertAtByte = 0; 9604 bool Swap = false; 9605 9606 // Shifts required to get the half-word we want at element 3. 9607 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9608 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9609 9610 uint32_t Mask = 0; 9611 uint32_t OriginalOrderLow = 0x1234567; 9612 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9613 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9614 // 32-bit space, only need 4-bit nibbles per element. 9615 for (unsigned i = 0; i < NumHalfWords; ++i) { 9616 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9617 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9618 } 9619 9620 // For each mask element, find out if we're just inserting something 9621 // from V2 into V1 or vice versa. Possible permutations inserting an element 9622 // from V2 into V1: 9623 // X, 1, 2, 3, 4, 5, 6, 7 9624 // 0, X, 2, 3, 4, 5, 6, 7 9625 // 0, 1, X, 3, 4, 5, 6, 7 9626 // 0, 1, 2, X, 4, 5, 6, 7 9627 // 0, 1, 2, 3, X, 5, 6, 7 9628 // 0, 1, 2, 3, 4, X, 6, 7 9629 // 0, 1, 2, 3, 4, 5, X, 7 9630 // 0, 1, 2, 3, 4, 5, 6, X 9631 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9632 9633 bool FoundCandidate = false; 9634 // Go through the mask of half-words to find an element that's being moved 9635 // from one vector to the other. 9636 for (unsigned i = 0; i < NumHalfWords; ++i) { 9637 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9638 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9639 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9640 uint32_t TargetOrder = 0x0; 9641 9642 // If both vector operands for the shuffle are the same vector, the mask 9643 // will contain only elements from the first one and the second one will be 9644 // undef. 9645 if (V2.isUndef()) { 9646 ShiftElts = 0; 9647 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9648 TargetOrder = OriginalOrderLow; 9649 Swap = false; 9650 // Skip if not the correct element or mask of other elements don't equal 9651 // to our expected order. 9652 if (MaskOneElt == VINSERTHSrcElem && 9653 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9654 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9655 FoundCandidate = true; 9656 break; 9657 } 9658 } else { // If both operands are defined. 9659 // Target order is [8,15] if the current mask is between [0,7]. 9660 TargetOrder = 9661 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9662 // Skip if mask of other elements don't equal our expected order. 9663 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9664 // We only need the last 3 bits for the number of shifts. 9665 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9666 : BigEndianShifts[MaskOneElt & 0x7]; 9667 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9668 Swap = MaskOneElt < NumHalfWords; 9669 FoundCandidate = true; 9670 break; 9671 } 9672 } 9673 } 9674 9675 if (!FoundCandidate) 9676 return SDValue(); 9677 9678 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9679 // optionally with VECSHL if shift is required. 9680 if (Swap) 9681 std::swap(V1, V2); 9682 if (V2.isUndef()) 9683 V2 = V1; 9684 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9685 if (ShiftElts) { 9686 // Double ShiftElts because we're left shifting on v16i8 type. 9687 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9688 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9689 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9690 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9691 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9692 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9693 } 9694 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9695 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9696 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9697 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9698 } 9699 9700 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9701 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9702 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9703 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9704 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9705 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9706 assert(Op.getValueType() == MVT::v1i128 && 9707 "Only set v1i128 as custom, other type shouldn't reach here!"); 9708 SDLoc dl(Op); 9709 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9710 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9711 unsigned SHLAmt = N1.getConstantOperandVal(0); 9712 if (SHLAmt % 8 == 0) { 9713 SmallVector<int, 16> Mask(16, 0); 9714 std::iota(Mask.begin(), Mask.end(), 0); 9715 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9716 if (SDValue Shuffle = 9717 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9718 DAG.getUNDEF(MVT::v16i8), Mask)) 9719 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9720 } 9721 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9722 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9723 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9724 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9725 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9726 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9727 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9728 } 9729 9730 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9731 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9732 /// return the code it can be lowered into. Worst case, it can always be 9733 /// lowered into a vperm. 9734 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9735 SelectionDAG &DAG) const { 9736 SDLoc dl(Op); 9737 SDValue V1 = Op.getOperand(0); 9738 SDValue V2 = Op.getOperand(1); 9739 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9740 9741 // Any nodes that were combined in the target-independent combiner prior 9742 // to vector legalization will not be sent to the target combine. Try to 9743 // combine it here. 9744 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9745 DAG.ReplaceAllUsesOfValueWith(Op, NewShuffle); 9746 Op = NewShuffle; 9747 SVOp = cast<ShuffleVectorSDNode>(Op); 9748 } 9749 EVT VT = Op.getValueType(); 9750 bool isLittleEndian = Subtarget.isLittleEndian(); 9751 9752 unsigned ShiftElts, InsertAtByte; 9753 bool Swap = false; 9754 9755 // If this is a load-and-splat, we can do that with a single instruction 9756 // in some cases. However if the load has multiple uses, we don't want to 9757 // combine it because that will just produce multiple loads. 9758 const SDValue *InputLoad = getNormalLoadInput(V1); 9759 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9760 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9761 InputLoad->hasOneUse()) { 9762 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9763 int SplatIdx = 9764 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9765 9766 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9767 // For 4-byte load-and-splat, we need Power9. 9768 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9769 uint64_t Offset = 0; 9770 if (IsFourByte) 9771 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9772 else 9773 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9774 9775 // If we are loading a partial vector, it does not make sense to adjust 9776 // the base pointer. This happens with (splat (s_to_v_permuted (ld))). 9777 if (LD->getMemoryVT().getSizeInBits() == (IsFourByte ? 32 : 64)) 9778 Offset = 0; 9779 SDValue BasePtr = LD->getBasePtr(); 9780 if (Offset != 0) 9781 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9782 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9783 SDValue Ops[] = { 9784 LD->getChain(), // Chain 9785 BasePtr, // BasePtr 9786 DAG.getValueType(Op.getValueType()) // VT 9787 }; 9788 SDVTList VTL = 9789 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9790 SDValue LdSplt = 9791 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9792 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9793 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9794 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9795 return LdSplt; 9796 } 9797 } 9798 if (Subtarget.hasP9Vector() && 9799 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9800 isLittleEndian)) { 9801 if (Swap) 9802 std::swap(V1, V2); 9803 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9804 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9805 if (ShiftElts) { 9806 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9807 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9808 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9809 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9810 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9811 } 9812 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9813 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9814 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9815 } 9816 9817 if (Subtarget.hasP9Altivec()) { 9818 SDValue NewISDNode; 9819 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9820 return NewISDNode; 9821 9822 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9823 return NewISDNode; 9824 } 9825 9826 if (Subtarget.hasVSX() && 9827 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9828 if (Swap) 9829 std::swap(V1, V2); 9830 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9831 SDValue Conv2 = 9832 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9833 9834 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9835 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9836 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9837 } 9838 9839 if (Subtarget.hasVSX() && 9840 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9841 if (Swap) 9842 std::swap(V1, V2); 9843 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9844 SDValue Conv2 = 9845 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9846 9847 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9848 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9849 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9850 } 9851 9852 if (Subtarget.hasP9Vector()) { 9853 if (PPC::isXXBRHShuffleMask(SVOp)) { 9854 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9855 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9856 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9857 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9858 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9859 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9860 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9861 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9862 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9863 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9864 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9865 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9866 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9867 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9868 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9869 } 9870 } 9871 9872 if (Subtarget.hasVSX()) { 9873 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9874 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9875 9876 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9877 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9878 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9879 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9880 } 9881 9882 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9883 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9884 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9885 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9886 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9887 } 9888 } 9889 9890 if (Subtarget.hasQPX()) { 9891 if (VT.getVectorNumElements() != 4) 9892 return SDValue(); 9893 9894 if (V2.isUndef()) V2 = V1; 9895 9896 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9897 if (AlignIdx != -1) { 9898 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9899 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9900 } else if (SVOp->isSplat()) { 9901 int SplatIdx = SVOp->getSplatIndex(); 9902 if (SplatIdx >= 4) { 9903 std::swap(V1, V2); 9904 SplatIdx -= 4; 9905 } 9906 9907 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9908 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9909 } 9910 9911 // Lower this into a qvgpci/qvfperm pair. 9912 9913 // Compute the qvgpci literal 9914 unsigned idx = 0; 9915 for (unsigned i = 0; i < 4; ++i) { 9916 int m = SVOp->getMaskElt(i); 9917 unsigned mm = m >= 0 ? (unsigned) m : i; 9918 idx |= mm << (3-i)*3; 9919 } 9920 9921 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9922 DAG.getConstant(idx, dl, MVT::i32)); 9923 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9924 } 9925 9926 // Cases that are handled by instructions that take permute immediates 9927 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9928 // selected by the instruction selector. 9929 if (V2.isUndef()) { 9930 if (PPC::isSplatShuffleMask(SVOp, 1) || 9931 PPC::isSplatShuffleMask(SVOp, 2) || 9932 PPC::isSplatShuffleMask(SVOp, 4) || 9933 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9934 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9935 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9936 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9937 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9938 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9939 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9940 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9941 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9942 (Subtarget.hasP8Altivec() && ( 9943 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9944 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9945 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9946 return Op; 9947 } 9948 } 9949 9950 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9951 // and produce a fixed permutation. If any of these match, do not lower to 9952 // VPERM. 9953 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9954 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9955 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9956 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9957 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9958 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9959 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9960 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9961 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9962 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9963 (Subtarget.hasP8Altivec() && ( 9964 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9965 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9966 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9967 return Op; 9968 9969 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9970 // perfect shuffle table to emit an optimal matching sequence. 9971 ArrayRef<int> PermMask = SVOp->getMask(); 9972 9973 unsigned PFIndexes[4]; 9974 bool isFourElementShuffle = true; 9975 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9976 unsigned EltNo = 8; // Start out undef. 9977 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9978 if (PermMask[i*4+j] < 0) 9979 continue; // Undef, ignore it. 9980 9981 unsigned ByteSource = PermMask[i*4+j]; 9982 if ((ByteSource & 3) != j) { 9983 isFourElementShuffle = false; 9984 break; 9985 } 9986 9987 if (EltNo == 8) { 9988 EltNo = ByteSource/4; 9989 } else if (EltNo != ByteSource/4) { 9990 isFourElementShuffle = false; 9991 break; 9992 } 9993 } 9994 PFIndexes[i] = EltNo; 9995 } 9996 9997 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9998 // perfect shuffle vector to determine if it is cost effective to do this as 9999 // discrete instructions, or whether we should use a vperm. 10000 // For now, we skip this for little endian until such time as we have a 10001 // little-endian perfect shuffle table. 10002 if (isFourElementShuffle && !isLittleEndian) { 10003 // Compute the index in the perfect shuffle table. 10004 unsigned PFTableIndex = 10005 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 10006 10007 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10008 unsigned Cost = (PFEntry >> 30); 10009 10010 // Determining when to avoid vperm is tricky. Many things affect the cost 10011 // of vperm, particularly how many times the perm mask needs to be computed. 10012 // For example, if the perm mask can be hoisted out of a loop or is already 10013 // used (perhaps because there are multiple permutes with the same shuffle 10014 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 10015 // the loop requires an extra register. 10016 // 10017 // As a compromise, we only emit discrete instructions if the shuffle can be 10018 // generated in 3 or fewer operations. When we have loop information 10019 // available, if this block is within a loop, we should avoid using vperm 10020 // for 3-operation perms and use a constant pool load instead. 10021 if (Cost < 3) 10022 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 10023 } 10024 10025 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10026 // vector that will get spilled to the constant pool. 10027 if (V2.isUndef()) V2 = V1; 10028 10029 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10030 // that it is in input element units, not in bytes. Convert now. 10031 10032 // For little endian, the order of the input vectors is reversed, and 10033 // the permutation mask is complemented with respect to 31. This is 10034 // necessary to produce proper semantics with the big-endian-biased vperm 10035 // instruction. 10036 EVT EltVT = V1.getValueType().getVectorElementType(); 10037 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 10038 10039 SmallVector<SDValue, 16> ResultMask; 10040 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10041 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10042 10043 for (unsigned j = 0; j != BytesPerElement; ++j) 10044 if (isLittleEndian) 10045 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 10046 dl, MVT::i32)); 10047 else 10048 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 10049 MVT::i32)); 10050 } 10051 10052 ShufflesHandledWithVPERM++; 10053 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10054 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 10055 LLVM_DEBUG(SVOp->dump()); 10056 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 10057 LLVM_DEBUG(VPermMask.dump()); 10058 10059 if (isLittleEndian) 10060 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10061 V2, V1, VPermMask); 10062 else 10063 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 10064 V1, V2, VPermMask); 10065 } 10066 10067 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10068 /// vector comparison. If it is, return true and fill in Opc/isDot with 10069 /// information about the intrinsic. 10070 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10071 bool &isDot, const PPCSubtarget &Subtarget) { 10072 unsigned IntrinsicID = 10073 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10074 CompareOpc = -1; 10075 isDot = false; 10076 switch (IntrinsicID) { 10077 default: 10078 return false; 10079 // Comparison predicates. 10080 case Intrinsic::ppc_altivec_vcmpbfp_p: 10081 CompareOpc = 966; 10082 isDot = true; 10083 break; 10084 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10085 CompareOpc = 198; 10086 isDot = true; 10087 break; 10088 case Intrinsic::ppc_altivec_vcmpequb_p: 10089 CompareOpc = 6; 10090 isDot = true; 10091 break; 10092 case Intrinsic::ppc_altivec_vcmpequh_p: 10093 CompareOpc = 70; 10094 isDot = true; 10095 break; 10096 case Intrinsic::ppc_altivec_vcmpequw_p: 10097 CompareOpc = 134; 10098 isDot = true; 10099 break; 10100 case Intrinsic::ppc_altivec_vcmpequd_p: 10101 if (Subtarget.hasP8Altivec()) { 10102 CompareOpc = 199; 10103 isDot = true; 10104 } else 10105 return false; 10106 break; 10107 case Intrinsic::ppc_altivec_vcmpneb_p: 10108 case Intrinsic::ppc_altivec_vcmpneh_p: 10109 case Intrinsic::ppc_altivec_vcmpnew_p: 10110 case Intrinsic::ppc_altivec_vcmpnezb_p: 10111 case Intrinsic::ppc_altivec_vcmpnezh_p: 10112 case Intrinsic::ppc_altivec_vcmpnezw_p: 10113 if (Subtarget.hasP9Altivec()) { 10114 switch (IntrinsicID) { 10115 default: 10116 llvm_unreachable("Unknown comparison intrinsic."); 10117 case Intrinsic::ppc_altivec_vcmpneb_p: 10118 CompareOpc = 7; 10119 break; 10120 case Intrinsic::ppc_altivec_vcmpneh_p: 10121 CompareOpc = 71; 10122 break; 10123 case Intrinsic::ppc_altivec_vcmpnew_p: 10124 CompareOpc = 135; 10125 break; 10126 case Intrinsic::ppc_altivec_vcmpnezb_p: 10127 CompareOpc = 263; 10128 break; 10129 case Intrinsic::ppc_altivec_vcmpnezh_p: 10130 CompareOpc = 327; 10131 break; 10132 case Intrinsic::ppc_altivec_vcmpnezw_p: 10133 CompareOpc = 391; 10134 break; 10135 } 10136 isDot = true; 10137 } else 10138 return false; 10139 break; 10140 case Intrinsic::ppc_altivec_vcmpgefp_p: 10141 CompareOpc = 454; 10142 isDot = true; 10143 break; 10144 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10145 CompareOpc = 710; 10146 isDot = true; 10147 break; 10148 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10149 CompareOpc = 774; 10150 isDot = true; 10151 break; 10152 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10153 CompareOpc = 838; 10154 isDot = true; 10155 break; 10156 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10157 CompareOpc = 902; 10158 isDot = true; 10159 break; 10160 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10161 if (Subtarget.hasP8Altivec()) { 10162 CompareOpc = 967; 10163 isDot = true; 10164 } else 10165 return false; 10166 break; 10167 case Intrinsic::ppc_altivec_vcmpgtub_p: 10168 CompareOpc = 518; 10169 isDot = true; 10170 break; 10171 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10172 CompareOpc = 582; 10173 isDot = true; 10174 break; 10175 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10176 CompareOpc = 646; 10177 isDot = true; 10178 break; 10179 case Intrinsic::ppc_altivec_vcmpgtud_p: 10180 if (Subtarget.hasP8Altivec()) { 10181 CompareOpc = 711; 10182 isDot = true; 10183 } else 10184 return false; 10185 break; 10186 10187 // VSX predicate comparisons use the same infrastructure 10188 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10189 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10190 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10191 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10192 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10193 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10194 if (Subtarget.hasVSX()) { 10195 switch (IntrinsicID) { 10196 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10197 CompareOpc = 99; 10198 break; 10199 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10200 CompareOpc = 115; 10201 break; 10202 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10203 CompareOpc = 107; 10204 break; 10205 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10206 CompareOpc = 67; 10207 break; 10208 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10209 CompareOpc = 83; 10210 break; 10211 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10212 CompareOpc = 75; 10213 break; 10214 } 10215 isDot = true; 10216 } else 10217 return false; 10218 break; 10219 10220 // Normal Comparisons. 10221 case Intrinsic::ppc_altivec_vcmpbfp: 10222 CompareOpc = 966; 10223 break; 10224 case Intrinsic::ppc_altivec_vcmpeqfp: 10225 CompareOpc = 198; 10226 break; 10227 case Intrinsic::ppc_altivec_vcmpequb: 10228 CompareOpc = 6; 10229 break; 10230 case Intrinsic::ppc_altivec_vcmpequh: 10231 CompareOpc = 70; 10232 break; 10233 case Intrinsic::ppc_altivec_vcmpequw: 10234 CompareOpc = 134; 10235 break; 10236 case Intrinsic::ppc_altivec_vcmpequd: 10237 if (Subtarget.hasP8Altivec()) 10238 CompareOpc = 199; 10239 else 10240 return false; 10241 break; 10242 case Intrinsic::ppc_altivec_vcmpneb: 10243 case Intrinsic::ppc_altivec_vcmpneh: 10244 case Intrinsic::ppc_altivec_vcmpnew: 10245 case Intrinsic::ppc_altivec_vcmpnezb: 10246 case Intrinsic::ppc_altivec_vcmpnezh: 10247 case Intrinsic::ppc_altivec_vcmpnezw: 10248 if (Subtarget.hasP9Altivec()) 10249 switch (IntrinsicID) { 10250 default: 10251 llvm_unreachable("Unknown comparison intrinsic."); 10252 case Intrinsic::ppc_altivec_vcmpneb: 10253 CompareOpc = 7; 10254 break; 10255 case Intrinsic::ppc_altivec_vcmpneh: 10256 CompareOpc = 71; 10257 break; 10258 case Intrinsic::ppc_altivec_vcmpnew: 10259 CompareOpc = 135; 10260 break; 10261 case Intrinsic::ppc_altivec_vcmpnezb: 10262 CompareOpc = 263; 10263 break; 10264 case Intrinsic::ppc_altivec_vcmpnezh: 10265 CompareOpc = 327; 10266 break; 10267 case Intrinsic::ppc_altivec_vcmpnezw: 10268 CompareOpc = 391; 10269 break; 10270 } 10271 else 10272 return false; 10273 break; 10274 case Intrinsic::ppc_altivec_vcmpgefp: 10275 CompareOpc = 454; 10276 break; 10277 case Intrinsic::ppc_altivec_vcmpgtfp: 10278 CompareOpc = 710; 10279 break; 10280 case Intrinsic::ppc_altivec_vcmpgtsb: 10281 CompareOpc = 774; 10282 break; 10283 case Intrinsic::ppc_altivec_vcmpgtsh: 10284 CompareOpc = 838; 10285 break; 10286 case Intrinsic::ppc_altivec_vcmpgtsw: 10287 CompareOpc = 902; 10288 break; 10289 case Intrinsic::ppc_altivec_vcmpgtsd: 10290 if (Subtarget.hasP8Altivec()) 10291 CompareOpc = 967; 10292 else 10293 return false; 10294 break; 10295 case Intrinsic::ppc_altivec_vcmpgtub: 10296 CompareOpc = 518; 10297 break; 10298 case Intrinsic::ppc_altivec_vcmpgtuh: 10299 CompareOpc = 582; 10300 break; 10301 case Intrinsic::ppc_altivec_vcmpgtuw: 10302 CompareOpc = 646; 10303 break; 10304 case Intrinsic::ppc_altivec_vcmpgtud: 10305 if (Subtarget.hasP8Altivec()) 10306 CompareOpc = 711; 10307 else 10308 return false; 10309 break; 10310 } 10311 return true; 10312 } 10313 10314 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10315 /// lower, do it, otherwise return null. 10316 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10317 SelectionDAG &DAG) const { 10318 unsigned IntrinsicID = 10319 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10320 10321 SDLoc dl(Op); 10322 10323 if (IntrinsicID == Intrinsic::thread_pointer) { 10324 // Reads the thread pointer register, used for __builtin_thread_pointer. 10325 if (Subtarget.isPPC64()) 10326 return DAG.getRegister(PPC::X13, MVT::i64); 10327 return DAG.getRegister(PPC::R2, MVT::i32); 10328 } 10329 10330 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10331 // opcode number of the comparison. 10332 int CompareOpc; 10333 bool isDot; 10334 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10335 return SDValue(); // Don't custom lower most intrinsics. 10336 10337 // If this is a non-dot comparison, make the VCMP node and we are done. 10338 if (!isDot) { 10339 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10340 Op.getOperand(1), Op.getOperand(2), 10341 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10342 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10343 } 10344 10345 // Create the PPCISD altivec 'dot' comparison node. 10346 SDValue Ops[] = { 10347 Op.getOperand(2), // LHS 10348 Op.getOperand(3), // RHS 10349 DAG.getConstant(CompareOpc, dl, MVT::i32) 10350 }; 10351 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10352 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10353 10354 // Now that we have the comparison, emit a copy from the CR to a GPR. 10355 // This is flagged to the above dot comparison. 10356 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10357 DAG.getRegister(PPC::CR6, MVT::i32), 10358 CompNode.getValue(1)); 10359 10360 // Unpack the result based on how the target uses it. 10361 unsigned BitNo; // Bit # of CR6. 10362 bool InvertBit; // Invert result? 10363 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10364 default: // Can't happen, don't crash on invalid number though. 10365 case 0: // Return the value of the EQ bit of CR6. 10366 BitNo = 0; InvertBit = false; 10367 break; 10368 case 1: // Return the inverted value of the EQ bit of CR6. 10369 BitNo = 0; InvertBit = true; 10370 break; 10371 case 2: // Return the value of the LT bit of CR6. 10372 BitNo = 2; InvertBit = false; 10373 break; 10374 case 3: // Return the inverted value of the LT bit of CR6. 10375 BitNo = 2; InvertBit = true; 10376 break; 10377 } 10378 10379 // Shift the bit into the low position. 10380 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10381 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10382 // Isolate the bit. 10383 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10384 DAG.getConstant(1, dl, MVT::i32)); 10385 10386 // If we are supposed to, toggle the bit. 10387 if (InvertBit) 10388 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10389 DAG.getConstant(1, dl, MVT::i32)); 10390 return Flags; 10391 } 10392 10393 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10394 SelectionDAG &DAG) const { 10395 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10396 // the beginning of the argument list. 10397 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10398 SDLoc DL(Op); 10399 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10400 case Intrinsic::ppc_cfence: { 10401 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10402 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10403 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10404 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10405 Op.getOperand(ArgStart + 1)), 10406 Op.getOperand(0)), 10407 0); 10408 } 10409 default: 10410 break; 10411 } 10412 return SDValue(); 10413 } 10414 10415 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 10416 // Check for a DIV with the same operands as this REM. 10417 for (auto UI : Op.getOperand(1)->uses()) { 10418 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 10419 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 10420 if (UI->getOperand(0) == Op.getOperand(0) && 10421 UI->getOperand(1) == Op.getOperand(1)) 10422 return SDValue(); 10423 } 10424 return Op; 10425 } 10426 10427 // Lower scalar BSWAP64 to xxbrd. 10428 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10429 SDLoc dl(Op); 10430 // MTVSRDD 10431 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10432 Op.getOperand(0)); 10433 // XXBRD 10434 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10435 // MFVSRD 10436 int VectorIndex = 0; 10437 if (Subtarget.isLittleEndian()) 10438 VectorIndex = 1; 10439 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10440 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10441 return Op; 10442 } 10443 10444 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10445 // compared to a value that is atomically loaded (atomic loads zero-extend). 10446 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10447 SelectionDAG &DAG) const { 10448 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10449 "Expecting an atomic compare-and-swap here."); 10450 SDLoc dl(Op); 10451 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10452 EVT MemVT = AtomicNode->getMemoryVT(); 10453 if (MemVT.getSizeInBits() >= 32) 10454 return Op; 10455 10456 SDValue CmpOp = Op.getOperand(2); 10457 // If this is already correctly zero-extended, leave it alone. 10458 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10459 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10460 return Op; 10461 10462 // Clear the high bits of the compare operand. 10463 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10464 SDValue NewCmpOp = 10465 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10466 DAG.getConstant(MaskVal, dl, MVT::i32)); 10467 10468 // Replace the existing compare operand with the properly zero-extended one. 10469 SmallVector<SDValue, 4> Ops; 10470 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10471 Ops.push_back(AtomicNode->getOperand(i)); 10472 Ops[2] = NewCmpOp; 10473 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10474 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10475 auto NodeTy = 10476 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10477 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10478 } 10479 10480 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10481 SelectionDAG &DAG) const { 10482 SDLoc dl(Op); 10483 // Create a stack slot that is 16-byte aligned. 10484 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10485 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10486 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10487 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10488 10489 // Store the input value into Value#0 of the stack slot. 10490 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10491 MachinePointerInfo()); 10492 // Load it out. 10493 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10494 } 10495 10496 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10497 SelectionDAG &DAG) const { 10498 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10499 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10500 10501 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10502 // We have legal lowering for constant indices but not for variable ones. 10503 if (!C) 10504 return SDValue(); 10505 10506 EVT VT = Op.getValueType(); 10507 SDLoc dl(Op); 10508 SDValue V1 = Op.getOperand(0); 10509 SDValue V2 = Op.getOperand(1); 10510 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10511 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10512 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10513 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10514 unsigned InsertAtElement = C->getZExtValue(); 10515 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10516 if (Subtarget.isLittleEndian()) { 10517 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10518 } 10519 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10520 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10521 } 10522 return Op; 10523 } 10524 10525 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 10526 SelectionDAG &DAG) const { 10527 SDLoc dl(Op); 10528 SDNode *N = Op.getNode(); 10529 10530 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 10531 "Unknown extract_vector_elt type"); 10532 10533 SDValue Value = N->getOperand(0); 10534 10535 // The first part of this is like the store lowering except that we don't 10536 // need to track the chain. 10537 10538 // The values are now known to be -1 (false) or 1 (true). To convert this 10539 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10540 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10541 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10542 10543 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10544 // understand how to form the extending load. 10545 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10546 10547 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10548 10549 // Now convert to an integer and store. 10550 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10551 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10552 Value); 10553 10554 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10555 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10556 MachinePointerInfo PtrInfo = 10557 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10558 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10559 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10560 10561 SDValue StoreChain = DAG.getEntryNode(); 10562 SDValue Ops[] = {StoreChain, 10563 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10564 Value, FIdx}; 10565 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10566 10567 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10568 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10569 10570 // Extract the value requested. 10571 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10572 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10573 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10574 10575 SDValue IntVal = 10576 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 10577 10578 if (!Subtarget.useCRBits()) 10579 return IntVal; 10580 10581 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 10582 } 10583 10584 /// Lowering for QPX v4i1 loads 10585 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10586 SelectionDAG &DAG) const { 10587 SDLoc dl(Op); 10588 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10589 SDValue LoadChain = LN->getChain(); 10590 SDValue BasePtr = LN->getBasePtr(); 10591 10592 if (Op.getValueType() == MVT::v4f64 || 10593 Op.getValueType() == MVT::v4f32) { 10594 EVT MemVT = LN->getMemoryVT(); 10595 unsigned Alignment = LN->getAlignment(); 10596 10597 // If this load is properly aligned, then it is legal. 10598 if (Alignment >= MemVT.getStoreSize()) 10599 return Op; 10600 10601 EVT ScalarVT = Op.getValueType().getScalarType(), 10602 ScalarMemVT = MemVT.getScalarType(); 10603 unsigned Stride = ScalarMemVT.getStoreSize(); 10604 10605 SDValue Vals[4], LoadChains[4]; 10606 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10607 SDValue Load; 10608 if (ScalarVT != ScalarMemVT) 10609 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10610 BasePtr, 10611 LN->getPointerInfo().getWithOffset(Idx * Stride), 10612 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10613 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10614 else 10615 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10616 LN->getPointerInfo().getWithOffset(Idx * Stride), 10617 MinAlign(Alignment, Idx * Stride), 10618 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10619 10620 if (Idx == 0 && LN->isIndexed()) { 10621 assert(LN->getAddressingMode() == ISD::PRE_INC && 10622 "Unknown addressing mode on vector load"); 10623 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10624 LN->getAddressingMode()); 10625 } 10626 10627 Vals[Idx] = Load; 10628 LoadChains[Idx] = Load.getValue(1); 10629 10630 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10631 DAG.getConstant(Stride, dl, 10632 BasePtr.getValueType())); 10633 } 10634 10635 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10636 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10637 10638 if (LN->isIndexed()) { 10639 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10640 return DAG.getMergeValues(RetOps, dl); 10641 } 10642 10643 SDValue RetOps[] = { Value, TF }; 10644 return DAG.getMergeValues(RetOps, dl); 10645 } 10646 10647 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10648 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10649 10650 // To lower v4i1 from a byte array, we load the byte elements of the 10651 // vector and then reuse the BUILD_VECTOR logic. 10652 10653 SDValue VectElmts[4], VectElmtChains[4]; 10654 for (unsigned i = 0; i < 4; ++i) { 10655 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10656 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10657 10658 VectElmts[i] = DAG.getExtLoad( 10659 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10660 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10661 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10662 VectElmtChains[i] = VectElmts[i].getValue(1); 10663 } 10664 10665 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10666 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10667 10668 SDValue RVals[] = { Value, LoadChain }; 10669 return DAG.getMergeValues(RVals, dl); 10670 } 10671 10672 /// Lowering for QPX v4i1 stores 10673 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10674 SelectionDAG &DAG) const { 10675 SDLoc dl(Op); 10676 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10677 SDValue StoreChain = SN->getChain(); 10678 SDValue BasePtr = SN->getBasePtr(); 10679 SDValue Value = SN->getValue(); 10680 10681 if (Value.getValueType() == MVT::v4f64 || 10682 Value.getValueType() == MVT::v4f32) { 10683 EVT MemVT = SN->getMemoryVT(); 10684 unsigned Alignment = SN->getAlignment(); 10685 10686 // If this store is properly aligned, then it is legal. 10687 if (Alignment >= MemVT.getStoreSize()) 10688 return Op; 10689 10690 EVT ScalarVT = Value.getValueType().getScalarType(), 10691 ScalarMemVT = MemVT.getScalarType(); 10692 unsigned Stride = ScalarMemVT.getStoreSize(); 10693 10694 SDValue Stores[4]; 10695 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10696 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10697 DAG.getVectorIdxConstant(Idx, dl)); 10698 SDValue Store; 10699 if (ScalarVT != ScalarMemVT) 10700 Store = 10701 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10702 SN->getPointerInfo().getWithOffset(Idx * Stride), 10703 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10704 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10705 else 10706 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10707 SN->getPointerInfo().getWithOffset(Idx * Stride), 10708 MinAlign(Alignment, Idx * Stride), 10709 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10710 10711 if (Idx == 0 && SN->isIndexed()) { 10712 assert(SN->getAddressingMode() == ISD::PRE_INC && 10713 "Unknown addressing mode on vector store"); 10714 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10715 SN->getAddressingMode()); 10716 } 10717 10718 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10719 DAG.getConstant(Stride, dl, 10720 BasePtr.getValueType())); 10721 Stores[Idx] = Store; 10722 } 10723 10724 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10725 10726 if (SN->isIndexed()) { 10727 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10728 return DAG.getMergeValues(RetOps, dl); 10729 } 10730 10731 return TF; 10732 } 10733 10734 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10735 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10736 10737 // The values are now known to be -1 (false) or 1 (true). To convert this 10738 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10739 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10740 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10741 10742 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10743 // understand how to form the extending load. 10744 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10745 10746 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10747 10748 // Now convert to an integer and store. 10749 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10750 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10751 Value); 10752 10753 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10754 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10755 MachinePointerInfo PtrInfo = 10756 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10757 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10758 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10759 10760 SDValue Ops[] = {StoreChain, 10761 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10762 Value, FIdx}; 10763 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10764 10765 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10766 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10767 10768 // Move data into the byte array. 10769 SDValue Loads[4], LoadChains[4]; 10770 for (unsigned i = 0; i < 4; ++i) { 10771 unsigned Offset = 4*i; 10772 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10773 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10774 10775 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10776 PtrInfo.getWithOffset(Offset)); 10777 LoadChains[i] = Loads[i].getValue(1); 10778 } 10779 10780 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10781 10782 SDValue Stores[4]; 10783 for (unsigned i = 0; i < 4; ++i) { 10784 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10785 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10786 10787 Stores[i] = DAG.getTruncStore( 10788 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10789 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10790 SN->getAAInfo()); 10791 } 10792 10793 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10794 10795 return StoreChain; 10796 } 10797 10798 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10799 SDLoc dl(Op); 10800 if (Op.getValueType() == MVT::v4i32) { 10801 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10802 10803 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10804 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10805 10806 SDValue RHSSwap = // = vrlw RHS, 16 10807 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10808 10809 // Shrinkify inputs to v8i16. 10810 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10811 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10812 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10813 10814 // Low parts multiplied together, generating 32-bit results (we ignore the 10815 // top parts). 10816 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10817 LHS, RHS, DAG, dl, MVT::v4i32); 10818 10819 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10820 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10821 // Shift the high parts up 16 bits. 10822 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10823 Neg16, DAG, dl); 10824 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10825 } else if (Op.getValueType() == MVT::v16i8) { 10826 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10827 bool isLittleEndian = Subtarget.isLittleEndian(); 10828 10829 // Multiply the even 8-bit parts, producing 16-bit sums. 10830 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10831 LHS, RHS, DAG, dl, MVT::v8i16); 10832 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10833 10834 // Multiply the odd 8-bit parts, producing 16-bit sums. 10835 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10836 LHS, RHS, DAG, dl, MVT::v8i16); 10837 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10838 10839 // Merge the results together. Because vmuleub and vmuloub are 10840 // instructions with a big-endian bias, we must reverse the 10841 // element numbering and reverse the meaning of "odd" and "even" 10842 // when generating little endian code. 10843 int Ops[16]; 10844 for (unsigned i = 0; i != 8; ++i) { 10845 if (isLittleEndian) { 10846 Ops[i*2 ] = 2*i; 10847 Ops[i*2+1] = 2*i+16; 10848 } else { 10849 Ops[i*2 ] = 2*i+1; 10850 Ops[i*2+1] = 2*i+1+16; 10851 } 10852 } 10853 if (isLittleEndian) 10854 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10855 else 10856 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10857 } else { 10858 llvm_unreachable("Unknown mul to lower!"); 10859 } 10860 } 10861 10862 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10863 10864 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10865 10866 EVT VT = Op.getValueType(); 10867 assert(VT.isVector() && 10868 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10869 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10870 VT == MVT::v16i8) && 10871 "Unexpected vector element type!"); 10872 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10873 "Current subtarget doesn't support smax v2i64!"); 10874 10875 // For vector abs, it can be lowered to: 10876 // abs x 10877 // ==> 10878 // y = -x 10879 // smax(x, y) 10880 10881 SDLoc dl(Op); 10882 SDValue X = Op.getOperand(0); 10883 SDValue Zero = DAG.getConstant(0, dl, VT); 10884 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10885 10886 // SMAX patch https://reviews.llvm.org/D47332 10887 // hasn't landed yet, so use intrinsic first here. 10888 // TODO: Should use SMAX directly once SMAX patch landed 10889 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10890 if (VT == MVT::v2i64) 10891 BifID = Intrinsic::ppc_altivec_vmaxsd; 10892 else if (VT == MVT::v8i16) 10893 BifID = Intrinsic::ppc_altivec_vmaxsh; 10894 else if (VT == MVT::v16i8) 10895 BifID = Intrinsic::ppc_altivec_vmaxsb; 10896 10897 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10898 } 10899 10900 // Custom lowering for fpext vf32 to v2f64 10901 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10902 10903 assert(Op.getOpcode() == ISD::FP_EXTEND && 10904 "Should only be called for ISD::FP_EXTEND"); 10905 10906 // FIXME: handle extends from half precision float vectors on P9. 10907 // We only want to custom lower an extend from v2f32 to v2f64. 10908 if (Op.getValueType() != MVT::v2f64 || 10909 Op.getOperand(0).getValueType() != MVT::v2f32) 10910 return SDValue(); 10911 10912 SDLoc dl(Op); 10913 SDValue Op0 = Op.getOperand(0); 10914 10915 switch (Op0.getOpcode()) { 10916 default: 10917 return SDValue(); 10918 case ISD::EXTRACT_SUBVECTOR: { 10919 assert(Op0.getNumOperands() == 2 && 10920 isa<ConstantSDNode>(Op0->getOperand(1)) && 10921 "Node should have 2 operands with second one being a constant!"); 10922 10923 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10924 return SDValue(); 10925 10926 // Custom lower is only done for high or low doubleword. 10927 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10928 if (Idx % 2 != 0) 10929 return SDValue(); 10930 10931 // Since input is v4f32, at this point Idx is either 0 or 2. 10932 // Shift to get the doubleword position we want. 10933 int DWord = Idx >> 1; 10934 10935 // High and low word positions are different on little endian. 10936 if (Subtarget.isLittleEndian()) 10937 DWord ^= 0x1; 10938 10939 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10940 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10941 } 10942 case ISD::FADD: 10943 case ISD::FMUL: 10944 case ISD::FSUB: { 10945 SDValue NewLoad[2]; 10946 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10947 // Ensure both input are loads. 10948 SDValue LdOp = Op0.getOperand(i); 10949 if (LdOp.getOpcode() != ISD::LOAD) 10950 return SDValue(); 10951 // Generate new load node. 10952 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10953 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10954 NewLoad[i] = DAG.getMemIntrinsicNode( 10955 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10956 LD->getMemoryVT(), LD->getMemOperand()); 10957 } 10958 SDValue NewOp = 10959 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10960 NewLoad[1], Op0.getNode()->getFlags()); 10961 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10962 DAG.getConstant(0, dl, MVT::i32)); 10963 } 10964 case ISD::LOAD: { 10965 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10966 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10967 SDValue NewLd = DAG.getMemIntrinsicNode( 10968 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10969 LD->getMemoryVT(), LD->getMemOperand()); 10970 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10971 DAG.getConstant(0, dl, MVT::i32)); 10972 } 10973 } 10974 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10975 } 10976 10977 /// LowerOperation - Provide custom lowering hooks for some operations. 10978 /// 10979 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10980 switch (Op.getOpcode()) { 10981 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10982 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10983 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10984 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10985 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10986 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10987 case ISD::SETCC: return LowerSETCC(Op, DAG); 10988 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10989 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10990 10991 // Variable argument lowering. 10992 case ISD::VASTART: return LowerVASTART(Op, DAG); 10993 case ISD::VAARG: return LowerVAARG(Op, DAG); 10994 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10995 10996 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10997 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10998 case ISD::GET_DYNAMIC_AREA_OFFSET: 10999 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 11000 11001 // Exception handling lowering. 11002 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 11003 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 11004 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 11005 11006 case ISD::LOAD: return LowerLOAD(Op, DAG); 11007 case ISD::STORE: return LowerSTORE(Op, DAG); 11008 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 11009 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 11010 case ISD::FP_TO_UINT: 11011 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 11012 case ISD::UINT_TO_FP: 11013 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 11014 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 11015 11016 // Lower 64-bit shifts. 11017 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 11018 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 11019 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 11020 11021 // Vector-related lowering. 11022 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 11023 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 11024 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 11025 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 11026 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 11027 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 11028 case ISD::MUL: return LowerMUL(Op, DAG); 11029 case ISD::ABS: return LowerABS(Op, DAG); 11030 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 11031 case ISD::ROTL: return LowerROTL(Op, DAG); 11032 11033 // For counter-based loop handling. 11034 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 11035 11036 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 11037 11038 // Frame & Return address. 11039 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 11040 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 11041 11042 case ISD::INTRINSIC_VOID: 11043 return LowerINTRINSIC_VOID(Op, DAG); 11044 case ISD::SREM: 11045 case ISD::UREM: 11046 return LowerREM(Op, DAG); 11047 case ISD::BSWAP: 11048 return LowerBSWAP(Op, DAG); 11049 case ISD::ATOMIC_CMP_SWAP: 11050 return LowerATOMIC_CMP_SWAP(Op, DAG); 11051 } 11052 } 11053 11054 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 11055 SmallVectorImpl<SDValue>&Results, 11056 SelectionDAG &DAG) const { 11057 SDLoc dl(N); 11058 switch (N->getOpcode()) { 11059 default: 11060 llvm_unreachable("Do not know how to custom type legalize this operation!"); 11061 case ISD::READCYCLECOUNTER: { 11062 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 11063 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 11064 11065 Results.push_back( 11066 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 11067 Results.push_back(RTB.getValue(2)); 11068 break; 11069 } 11070 case ISD::INTRINSIC_W_CHAIN: { 11071 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 11072 Intrinsic::loop_decrement) 11073 break; 11074 11075 assert(N->getValueType(0) == MVT::i1 && 11076 "Unexpected result type for CTR decrement intrinsic"); 11077 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 11078 N->getValueType(0)); 11079 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 11080 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 11081 N->getOperand(1)); 11082 11083 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 11084 Results.push_back(NewInt.getValue(1)); 11085 break; 11086 } 11087 case ISD::VAARG: { 11088 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 11089 return; 11090 11091 EVT VT = N->getValueType(0); 11092 11093 if (VT == MVT::i64) { 11094 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 11095 11096 Results.push_back(NewNode); 11097 Results.push_back(NewNode.getValue(1)); 11098 } 11099 return; 11100 } 11101 case ISD::FP_TO_SINT: 11102 case ISD::FP_TO_UINT: 11103 // LowerFP_TO_INT() can only handle f32 and f64. 11104 if (N->getOperand(0).getValueType() == MVT::ppcf128) 11105 return; 11106 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 11107 return; 11108 case ISD::TRUNCATE: { 11109 EVT TrgVT = N->getValueType(0); 11110 EVT OpVT = N->getOperand(0).getValueType(); 11111 if (TrgVT.isVector() && 11112 isOperationCustom(N->getOpcode(), TrgVT) && 11113 OpVT.getSizeInBits() <= 128 && 11114 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 11115 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 11116 return; 11117 } 11118 case ISD::BITCAST: 11119 // Don't handle bitcast here. 11120 return; 11121 case ISD::FP_EXTEND: 11122 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 11123 if (Lowered) 11124 Results.push_back(Lowered); 11125 return; 11126 } 11127 } 11128 11129 //===----------------------------------------------------------------------===// 11130 // Other Lowering Code 11131 //===----------------------------------------------------------------------===// 11132 11133 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 11134 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11135 Function *Func = Intrinsic::getDeclaration(M, Id); 11136 return Builder.CreateCall(Func, {}); 11137 } 11138 11139 // The mappings for emitLeading/TrailingFence is taken from 11140 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11141 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 11142 Instruction *Inst, 11143 AtomicOrdering Ord) const { 11144 if (Ord == AtomicOrdering::SequentiallyConsistent) 11145 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11146 if (isReleaseOrStronger(Ord)) 11147 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11148 return nullptr; 11149 } 11150 11151 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 11152 Instruction *Inst, 11153 AtomicOrdering Ord) const { 11154 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11155 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11156 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11157 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11158 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11159 return Builder.CreateCall( 11160 Intrinsic::getDeclaration( 11161 Builder.GetInsertBlock()->getParent()->getParent(), 11162 Intrinsic::ppc_cfence, {Inst->getType()}), 11163 {Inst}); 11164 // FIXME: Can use isync for rmw operation. 11165 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11166 } 11167 return nullptr; 11168 } 11169 11170 MachineBasicBlock * 11171 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11172 unsigned AtomicSize, 11173 unsigned BinOpcode, 11174 unsigned CmpOpcode, 11175 unsigned CmpPred) const { 11176 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11177 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11178 11179 auto LoadMnemonic = PPC::LDARX; 11180 auto StoreMnemonic = PPC::STDCX; 11181 switch (AtomicSize) { 11182 default: 11183 llvm_unreachable("Unexpected size of atomic entity"); 11184 case 1: 11185 LoadMnemonic = PPC::LBARX; 11186 StoreMnemonic = PPC::STBCX; 11187 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11188 break; 11189 case 2: 11190 LoadMnemonic = PPC::LHARX; 11191 StoreMnemonic = PPC::STHCX; 11192 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11193 break; 11194 case 4: 11195 LoadMnemonic = PPC::LWARX; 11196 StoreMnemonic = PPC::STWCX; 11197 break; 11198 case 8: 11199 LoadMnemonic = PPC::LDARX; 11200 StoreMnemonic = PPC::STDCX; 11201 break; 11202 } 11203 11204 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11205 MachineFunction *F = BB->getParent(); 11206 MachineFunction::iterator It = ++BB->getIterator(); 11207 11208 Register dest = MI.getOperand(0).getReg(); 11209 Register ptrA = MI.getOperand(1).getReg(); 11210 Register ptrB = MI.getOperand(2).getReg(); 11211 Register incr = MI.getOperand(3).getReg(); 11212 DebugLoc dl = MI.getDebugLoc(); 11213 11214 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11215 MachineBasicBlock *loop2MBB = 11216 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11217 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11218 F->insert(It, loopMBB); 11219 if (CmpOpcode) 11220 F->insert(It, loop2MBB); 11221 F->insert(It, exitMBB); 11222 exitMBB->splice(exitMBB->begin(), BB, 11223 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11224 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11225 11226 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11227 Register TmpReg = (!BinOpcode) ? incr : 11228 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11229 : &PPC::GPRCRegClass); 11230 11231 // thisMBB: 11232 // ... 11233 // fallthrough --> loopMBB 11234 BB->addSuccessor(loopMBB); 11235 11236 // loopMBB: 11237 // l[wd]arx dest, ptr 11238 // add r0, dest, incr 11239 // st[wd]cx. r0, ptr 11240 // bne- loopMBB 11241 // fallthrough --> exitMBB 11242 11243 // For max/min... 11244 // loopMBB: 11245 // l[wd]arx dest, ptr 11246 // cmpl?[wd] incr, dest 11247 // bgt exitMBB 11248 // loop2MBB: 11249 // st[wd]cx. dest, ptr 11250 // bne- loopMBB 11251 // fallthrough --> exitMBB 11252 11253 BB = loopMBB; 11254 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11255 .addReg(ptrA).addReg(ptrB); 11256 if (BinOpcode) 11257 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11258 if (CmpOpcode) { 11259 // Signed comparisons of byte or halfword values must be sign-extended. 11260 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11261 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11262 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11263 ExtReg).addReg(dest); 11264 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11265 .addReg(incr).addReg(ExtReg); 11266 } else 11267 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11268 .addReg(incr).addReg(dest); 11269 11270 BuildMI(BB, dl, TII->get(PPC::BCC)) 11271 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 11272 BB->addSuccessor(loop2MBB); 11273 BB->addSuccessor(exitMBB); 11274 BB = loop2MBB; 11275 } 11276 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11277 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11278 BuildMI(BB, dl, TII->get(PPC::BCC)) 11279 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11280 BB->addSuccessor(loopMBB); 11281 BB->addSuccessor(exitMBB); 11282 11283 // exitMBB: 11284 // ... 11285 BB = exitMBB; 11286 return BB; 11287 } 11288 11289 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11290 MachineInstr &MI, MachineBasicBlock *BB, 11291 bool is8bit, // operation 11292 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11293 // If we support part-word atomic mnemonics, just use them 11294 if (Subtarget.hasPartwordAtomics()) 11295 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11296 CmpPred); 11297 11298 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11299 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11300 // In 64 bit mode we have to use 64 bits for addresses, even though the 11301 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11302 // registers without caring whether they're 32 or 64, but here we're 11303 // doing actual arithmetic on the addresses. 11304 bool is64bit = Subtarget.isPPC64(); 11305 bool isLittleEndian = Subtarget.isLittleEndian(); 11306 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11307 11308 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11309 MachineFunction *F = BB->getParent(); 11310 MachineFunction::iterator It = ++BB->getIterator(); 11311 11312 Register dest = MI.getOperand(0).getReg(); 11313 Register ptrA = MI.getOperand(1).getReg(); 11314 Register ptrB = MI.getOperand(2).getReg(); 11315 Register incr = MI.getOperand(3).getReg(); 11316 DebugLoc dl = MI.getDebugLoc(); 11317 11318 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11319 MachineBasicBlock *loop2MBB = 11320 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11321 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11322 F->insert(It, loopMBB); 11323 if (CmpOpcode) 11324 F->insert(It, loop2MBB); 11325 F->insert(It, exitMBB); 11326 exitMBB->splice(exitMBB->begin(), BB, 11327 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11328 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11329 11330 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11331 const TargetRegisterClass *RC = 11332 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11333 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11334 11335 Register PtrReg = RegInfo.createVirtualRegister(RC); 11336 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11337 Register ShiftReg = 11338 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11339 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11340 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11341 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11342 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11343 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11344 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11345 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11346 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11347 Register Ptr1Reg; 11348 Register TmpReg = 11349 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11350 11351 // thisMBB: 11352 // ... 11353 // fallthrough --> loopMBB 11354 BB->addSuccessor(loopMBB); 11355 11356 // The 4-byte load must be aligned, while a char or short may be 11357 // anywhere in the word. Hence all this nasty bookkeeping code. 11358 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11359 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11360 // xori shift, shift1, 24 [16] 11361 // rlwinm ptr, ptr1, 0, 0, 29 11362 // slw incr2, incr, shift 11363 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11364 // slw mask, mask2, shift 11365 // loopMBB: 11366 // lwarx tmpDest, ptr 11367 // add tmp, tmpDest, incr2 11368 // andc tmp2, tmpDest, mask 11369 // and tmp3, tmp, mask 11370 // or tmp4, tmp3, tmp2 11371 // stwcx. tmp4, ptr 11372 // bne- loopMBB 11373 // fallthrough --> exitMBB 11374 // srw dest, tmpDest, shift 11375 if (ptrA != ZeroReg) { 11376 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11377 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11378 .addReg(ptrA) 11379 .addReg(ptrB); 11380 } else { 11381 Ptr1Reg = ptrB; 11382 } 11383 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11384 // mode. 11385 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11386 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11387 .addImm(3) 11388 .addImm(27) 11389 .addImm(is8bit ? 28 : 27); 11390 if (!isLittleEndian) 11391 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11392 .addReg(Shift1Reg) 11393 .addImm(is8bit ? 24 : 16); 11394 if (is64bit) 11395 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11396 .addReg(Ptr1Reg) 11397 .addImm(0) 11398 .addImm(61); 11399 else 11400 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11401 .addReg(Ptr1Reg) 11402 .addImm(0) 11403 .addImm(0) 11404 .addImm(29); 11405 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11406 if (is8bit) 11407 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11408 else { 11409 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11410 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11411 .addReg(Mask3Reg) 11412 .addImm(65535); 11413 } 11414 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11415 .addReg(Mask2Reg) 11416 .addReg(ShiftReg); 11417 11418 BB = loopMBB; 11419 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11420 .addReg(ZeroReg) 11421 .addReg(PtrReg); 11422 if (BinOpcode) 11423 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11424 .addReg(Incr2Reg) 11425 .addReg(TmpDestReg); 11426 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11427 .addReg(TmpDestReg) 11428 .addReg(MaskReg); 11429 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11430 if (CmpOpcode) { 11431 // For unsigned comparisons, we can directly compare the shifted values. 11432 // For signed comparisons we shift and sign extend. 11433 Register SReg = RegInfo.createVirtualRegister(GPRC); 11434 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11435 .addReg(TmpDestReg) 11436 .addReg(MaskReg); 11437 unsigned ValueReg = SReg; 11438 unsigned CmpReg = Incr2Reg; 11439 if (CmpOpcode == PPC::CMPW) { 11440 ValueReg = RegInfo.createVirtualRegister(GPRC); 11441 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11442 .addReg(SReg) 11443 .addReg(ShiftReg); 11444 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11445 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11446 .addReg(ValueReg); 11447 ValueReg = ValueSReg; 11448 CmpReg = incr; 11449 } 11450 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11451 .addReg(CmpReg) 11452 .addReg(ValueReg); 11453 BuildMI(BB, dl, TII->get(PPC::BCC)) 11454 .addImm(CmpPred) 11455 .addReg(PPC::CR0) 11456 .addMBB(exitMBB); 11457 BB->addSuccessor(loop2MBB); 11458 BB->addSuccessor(exitMBB); 11459 BB = loop2MBB; 11460 } 11461 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11462 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11463 .addReg(Tmp4Reg) 11464 .addReg(ZeroReg) 11465 .addReg(PtrReg); 11466 BuildMI(BB, dl, TII->get(PPC::BCC)) 11467 .addImm(PPC::PRED_NE) 11468 .addReg(PPC::CR0) 11469 .addMBB(loopMBB); 11470 BB->addSuccessor(loopMBB); 11471 BB->addSuccessor(exitMBB); 11472 11473 // exitMBB: 11474 // ... 11475 BB = exitMBB; 11476 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11477 .addReg(TmpDestReg) 11478 .addReg(ShiftReg); 11479 return BB; 11480 } 11481 11482 llvm::MachineBasicBlock * 11483 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11484 MachineBasicBlock *MBB) const { 11485 DebugLoc DL = MI.getDebugLoc(); 11486 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11487 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11488 11489 MachineFunction *MF = MBB->getParent(); 11490 MachineRegisterInfo &MRI = MF->getRegInfo(); 11491 11492 const BasicBlock *BB = MBB->getBasicBlock(); 11493 MachineFunction::iterator I = ++MBB->getIterator(); 11494 11495 Register DstReg = MI.getOperand(0).getReg(); 11496 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11497 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11498 Register mainDstReg = MRI.createVirtualRegister(RC); 11499 Register restoreDstReg = MRI.createVirtualRegister(RC); 11500 11501 MVT PVT = getPointerTy(MF->getDataLayout()); 11502 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11503 "Invalid Pointer Size!"); 11504 // For v = setjmp(buf), we generate 11505 // 11506 // thisMBB: 11507 // SjLjSetup mainMBB 11508 // bl mainMBB 11509 // v_restore = 1 11510 // b sinkMBB 11511 // 11512 // mainMBB: 11513 // buf[LabelOffset] = LR 11514 // v_main = 0 11515 // 11516 // sinkMBB: 11517 // v = phi(main, restore) 11518 // 11519 11520 MachineBasicBlock *thisMBB = MBB; 11521 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11522 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11523 MF->insert(I, mainMBB); 11524 MF->insert(I, sinkMBB); 11525 11526 MachineInstrBuilder MIB; 11527 11528 // Transfer the remainder of BB and its successor edges to sinkMBB. 11529 sinkMBB->splice(sinkMBB->begin(), MBB, 11530 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11531 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11532 11533 // Note that the structure of the jmp_buf used here is not compatible 11534 // with that used by libc, and is not designed to be. Specifically, it 11535 // stores only those 'reserved' registers that LLVM does not otherwise 11536 // understand how to spill. Also, by convention, by the time this 11537 // intrinsic is called, Clang has already stored the frame address in the 11538 // first slot of the buffer and stack address in the third. Following the 11539 // X86 target code, we'll store the jump address in the second slot. We also 11540 // need to save the TOC pointer (R2) to handle jumps between shared 11541 // libraries, and that will be stored in the fourth slot. The thread 11542 // identifier (R13) is not affected. 11543 11544 // thisMBB: 11545 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11546 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11547 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11548 11549 // Prepare IP either in reg. 11550 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11551 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11552 Register BufReg = MI.getOperand(1).getReg(); 11553 11554 if (Subtarget.is64BitELFABI()) { 11555 setUsesTOCBasePtr(*MBB->getParent()); 11556 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11557 .addReg(PPC::X2) 11558 .addImm(TOCOffset) 11559 .addReg(BufReg) 11560 .cloneMemRefs(MI); 11561 } 11562 11563 // Naked functions never have a base pointer, and so we use r1. For all 11564 // other functions, this decision must be delayed until during PEI. 11565 unsigned BaseReg; 11566 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11567 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11568 else 11569 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11570 11571 MIB = BuildMI(*thisMBB, MI, DL, 11572 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11573 .addReg(BaseReg) 11574 .addImm(BPOffset) 11575 .addReg(BufReg) 11576 .cloneMemRefs(MI); 11577 11578 // Setup 11579 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11580 MIB.addRegMask(TRI->getNoPreservedMask()); 11581 11582 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11583 11584 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11585 .addMBB(mainMBB); 11586 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11587 11588 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11589 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11590 11591 // mainMBB: 11592 // mainDstReg = 0 11593 MIB = 11594 BuildMI(mainMBB, DL, 11595 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11596 11597 // Store IP 11598 if (Subtarget.isPPC64()) { 11599 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11600 .addReg(LabelReg) 11601 .addImm(LabelOffset) 11602 .addReg(BufReg); 11603 } else { 11604 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11605 .addReg(LabelReg) 11606 .addImm(LabelOffset) 11607 .addReg(BufReg); 11608 } 11609 MIB.cloneMemRefs(MI); 11610 11611 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11612 mainMBB->addSuccessor(sinkMBB); 11613 11614 // sinkMBB: 11615 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11616 TII->get(PPC::PHI), DstReg) 11617 .addReg(mainDstReg).addMBB(mainMBB) 11618 .addReg(restoreDstReg).addMBB(thisMBB); 11619 11620 MI.eraseFromParent(); 11621 return sinkMBB; 11622 } 11623 11624 MachineBasicBlock * 11625 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11626 MachineBasicBlock *MBB) const { 11627 DebugLoc DL = MI.getDebugLoc(); 11628 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11629 11630 MachineFunction *MF = MBB->getParent(); 11631 MachineRegisterInfo &MRI = MF->getRegInfo(); 11632 11633 MVT PVT = getPointerTy(MF->getDataLayout()); 11634 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11635 "Invalid Pointer Size!"); 11636 11637 const TargetRegisterClass *RC = 11638 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11639 Register Tmp = MRI.createVirtualRegister(RC); 11640 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11641 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11642 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11643 unsigned BP = 11644 (PVT == MVT::i64) 11645 ? PPC::X30 11646 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11647 : PPC::R30); 11648 11649 MachineInstrBuilder MIB; 11650 11651 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11652 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11653 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11654 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11655 11656 Register BufReg = MI.getOperand(0).getReg(); 11657 11658 // Reload FP (the jumped-to function may not have had a 11659 // frame pointer, and if so, then its r31 will be restored 11660 // as necessary). 11661 if (PVT == MVT::i64) { 11662 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11663 .addImm(0) 11664 .addReg(BufReg); 11665 } else { 11666 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11667 .addImm(0) 11668 .addReg(BufReg); 11669 } 11670 MIB.cloneMemRefs(MI); 11671 11672 // Reload IP 11673 if (PVT == MVT::i64) { 11674 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11675 .addImm(LabelOffset) 11676 .addReg(BufReg); 11677 } else { 11678 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11679 .addImm(LabelOffset) 11680 .addReg(BufReg); 11681 } 11682 MIB.cloneMemRefs(MI); 11683 11684 // Reload SP 11685 if (PVT == MVT::i64) { 11686 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11687 .addImm(SPOffset) 11688 .addReg(BufReg); 11689 } else { 11690 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11691 .addImm(SPOffset) 11692 .addReg(BufReg); 11693 } 11694 MIB.cloneMemRefs(MI); 11695 11696 // Reload BP 11697 if (PVT == MVT::i64) { 11698 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11699 .addImm(BPOffset) 11700 .addReg(BufReg); 11701 } else { 11702 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11703 .addImm(BPOffset) 11704 .addReg(BufReg); 11705 } 11706 MIB.cloneMemRefs(MI); 11707 11708 // Reload TOC 11709 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11710 setUsesTOCBasePtr(*MBB->getParent()); 11711 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11712 .addImm(TOCOffset) 11713 .addReg(BufReg) 11714 .cloneMemRefs(MI); 11715 } 11716 11717 // Jump 11718 BuildMI(*MBB, MI, DL, 11719 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11720 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11721 11722 MI.eraseFromParent(); 11723 return MBB; 11724 } 11725 11726 MachineBasicBlock * 11727 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11728 MachineBasicBlock *BB) const { 11729 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11730 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11731 if (Subtarget.is64BitELFABI() && 11732 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11733 !Subtarget.isUsingPCRelativeCalls()) { 11734 // Call lowering should have added an r2 operand to indicate a dependence 11735 // on the TOC base pointer value. It can't however, because there is no 11736 // way to mark the dependence as implicit there, and so the stackmap code 11737 // will confuse it with a regular operand. Instead, add the dependence 11738 // here. 11739 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11740 } 11741 11742 return emitPatchPoint(MI, BB); 11743 } 11744 11745 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11746 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11747 return emitEHSjLjSetJmp(MI, BB); 11748 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11749 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11750 return emitEHSjLjLongJmp(MI, BB); 11751 } 11752 11753 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11754 11755 // To "insert" these instructions we actually have to insert their 11756 // control-flow patterns. 11757 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11758 MachineFunction::iterator It = ++BB->getIterator(); 11759 11760 MachineFunction *F = BB->getParent(); 11761 11762 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11763 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11764 MI.getOpcode() == PPC::SELECT_I8) { 11765 SmallVector<MachineOperand, 2> Cond; 11766 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11767 MI.getOpcode() == PPC::SELECT_CC_I8) 11768 Cond.push_back(MI.getOperand(4)); 11769 else 11770 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11771 Cond.push_back(MI.getOperand(1)); 11772 11773 DebugLoc dl = MI.getDebugLoc(); 11774 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11775 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11776 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11777 MI.getOpcode() == PPC::SELECT_CC_F8 || 11778 MI.getOpcode() == PPC::SELECT_CC_F16 || 11779 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11780 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11781 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11782 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11783 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11784 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11785 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11786 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11787 MI.getOpcode() == PPC::SELECT_CC_SPE || 11788 MI.getOpcode() == PPC::SELECT_F4 || 11789 MI.getOpcode() == PPC::SELECT_F8 || 11790 MI.getOpcode() == PPC::SELECT_F16 || 11791 MI.getOpcode() == PPC::SELECT_QFRC || 11792 MI.getOpcode() == PPC::SELECT_QSRC || 11793 MI.getOpcode() == PPC::SELECT_QBRC || 11794 MI.getOpcode() == PPC::SELECT_SPE || 11795 MI.getOpcode() == PPC::SELECT_SPE4 || 11796 MI.getOpcode() == PPC::SELECT_VRRC || 11797 MI.getOpcode() == PPC::SELECT_VSFRC || 11798 MI.getOpcode() == PPC::SELECT_VSSRC || 11799 MI.getOpcode() == PPC::SELECT_VSRC) { 11800 // The incoming instruction knows the destination vreg to set, the 11801 // condition code register to branch on, the true/false values to 11802 // select between, and a branch opcode to use. 11803 11804 // thisMBB: 11805 // ... 11806 // TrueVal = ... 11807 // cmpTY ccX, r1, r2 11808 // bCC copy1MBB 11809 // fallthrough --> copy0MBB 11810 MachineBasicBlock *thisMBB = BB; 11811 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11812 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11813 DebugLoc dl = MI.getDebugLoc(); 11814 F->insert(It, copy0MBB); 11815 F->insert(It, sinkMBB); 11816 11817 // Transfer the remainder of BB and its successor edges to sinkMBB. 11818 sinkMBB->splice(sinkMBB->begin(), BB, 11819 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11820 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11821 11822 // Next, add the true and fallthrough blocks as its successors. 11823 BB->addSuccessor(copy0MBB); 11824 BB->addSuccessor(sinkMBB); 11825 11826 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11827 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11828 MI.getOpcode() == PPC::SELECT_F16 || 11829 MI.getOpcode() == PPC::SELECT_SPE4 || 11830 MI.getOpcode() == PPC::SELECT_SPE || 11831 MI.getOpcode() == PPC::SELECT_QFRC || 11832 MI.getOpcode() == PPC::SELECT_QSRC || 11833 MI.getOpcode() == PPC::SELECT_QBRC || 11834 MI.getOpcode() == PPC::SELECT_VRRC || 11835 MI.getOpcode() == PPC::SELECT_VSFRC || 11836 MI.getOpcode() == PPC::SELECT_VSSRC || 11837 MI.getOpcode() == PPC::SELECT_VSRC) { 11838 BuildMI(BB, dl, TII->get(PPC::BC)) 11839 .addReg(MI.getOperand(1).getReg()) 11840 .addMBB(sinkMBB); 11841 } else { 11842 unsigned SelectPred = MI.getOperand(4).getImm(); 11843 BuildMI(BB, dl, TII->get(PPC::BCC)) 11844 .addImm(SelectPred) 11845 .addReg(MI.getOperand(1).getReg()) 11846 .addMBB(sinkMBB); 11847 } 11848 11849 // copy0MBB: 11850 // %FalseValue = ... 11851 // # fallthrough to sinkMBB 11852 BB = copy0MBB; 11853 11854 // Update machine-CFG edges 11855 BB->addSuccessor(sinkMBB); 11856 11857 // sinkMBB: 11858 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11859 // ... 11860 BB = sinkMBB; 11861 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11862 .addReg(MI.getOperand(3).getReg()) 11863 .addMBB(copy0MBB) 11864 .addReg(MI.getOperand(2).getReg()) 11865 .addMBB(thisMBB); 11866 } else if (MI.getOpcode() == PPC::ReadTB) { 11867 // To read the 64-bit time-base register on a 32-bit target, we read the 11868 // two halves. Should the counter have wrapped while it was being read, we 11869 // need to try again. 11870 // ... 11871 // readLoop: 11872 // mfspr Rx,TBU # load from TBU 11873 // mfspr Ry,TB # load from TB 11874 // mfspr Rz,TBU # load from TBU 11875 // cmpw crX,Rx,Rz # check if 'old'='new' 11876 // bne readLoop # branch if they're not equal 11877 // ... 11878 11879 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11880 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11881 DebugLoc dl = MI.getDebugLoc(); 11882 F->insert(It, readMBB); 11883 F->insert(It, sinkMBB); 11884 11885 // Transfer the remainder of BB and its successor edges to sinkMBB. 11886 sinkMBB->splice(sinkMBB->begin(), BB, 11887 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11888 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11889 11890 BB->addSuccessor(readMBB); 11891 BB = readMBB; 11892 11893 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11894 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11895 Register LoReg = MI.getOperand(0).getReg(); 11896 Register HiReg = MI.getOperand(1).getReg(); 11897 11898 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11899 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11900 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11901 11902 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11903 11904 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11905 .addReg(HiReg) 11906 .addReg(ReadAgainReg); 11907 BuildMI(BB, dl, TII->get(PPC::BCC)) 11908 .addImm(PPC::PRED_NE) 11909 .addReg(CmpReg) 11910 .addMBB(readMBB); 11911 11912 BB->addSuccessor(readMBB); 11913 BB->addSuccessor(sinkMBB); 11914 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11915 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11916 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11917 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11918 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11919 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11920 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11921 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11922 11923 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11924 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11925 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11926 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11927 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11928 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11929 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11930 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11931 11932 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11933 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11934 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11935 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11936 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11937 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11938 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11939 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11940 11941 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11942 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11943 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11944 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11945 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11946 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11947 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11948 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11949 11950 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11951 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11952 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11953 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11954 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11955 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11956 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11957 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11958 11959 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11960 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11961 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11962 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11963 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11964 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11965 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11966 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11967 11968 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11969 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11970 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11971 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11972 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11973 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11974 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11975 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11976 11977 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11978 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11979 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11980 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11981 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11982 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11983 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11984 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11985 11986 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11987 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11988 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11989 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11990 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11991 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11992 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11993 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11994 11995 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11996 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11997 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11998 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11999 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 12000 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 12001 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12002 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 12003 12004 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12005 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12006 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12007 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12008 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12009 BB = EmitAtomicBinary(MI, BB, 4, 0); 12010 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12011 BB = EmitAtomicBinary(MI, BB, 8, 0); 12012 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12013 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12014 (Subtarget.hasPartwordAtomics() && 12015 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12016 (Subtarget.hasPartwordAtomics() && 12017 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12018 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12019 12020 auto LoadMnemonic = PPC::LDARX; 12021 auto StoreMnemonic = PPC::STDCX; 12022 switch (MI.getOpcode()) { 12023 default: 12024 llvm_unreachable("Compare and swap of unknown size"); 12025 case PPC::ATOMIC_CMP_SWAP_I8: 12026 LoadMnemonic = PPC::LBARX; 12027 StoreMnemonic = PPC::STBCX; 12028 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12029 break; 12030 case PPC::ATOMIC_CMP_SWAP_I16: 12031 LoadMnemonic = PPC::LHARX; 12032 StoreMnemonic = PPC::STHCX; 12033 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12034 break; 12035 case PPC::ATOMIC_CMP_SWAP_I32: 12036 LoadMnemonic = PPC::LWARX; 12037 StoreMnemonic = PPC::STWCX; 12038 break; 12039 case PPC::ATOMIC_CMP_SWAP_I64: 12040 LoadMnemonic = PPC::LDARX; 12041 StoreMnemonic = PPC::STDCX; 12042 break; 12043 } 12044 Register dest = MI.getOperand(0).getReg(); 12045 Register ptrA = MI.getOperand(1).getReg(); 12046 Register ptrB = MI.getOperand(2).getReg(); 12047 Register oldval = MI.getOperand(3).getReg(); 12048 Register newval = MI.getOperand(4).getReg(); 12049 DebugLoc dl = MI.getDebugLoc(); 12050 12051 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12052 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12053 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12054 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12055 F->insert(It, loop1MBB); 12056 F->insert(It, loop2MBB); 12057 F->insert(It, midMBB); 12058 F->insert(It, exitMBB); 12059 exitMBB->splice(exitMBB->begin(), BB, 12060 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12061 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12062 12063 // thisMBB: 12064 // ... 12065 // fallthrough --> loopMBB 12066 BB->addSuccessor(loop1MBB); 12067 12068 // loop1MBB: 12069 // l[bhwd]arx dest, ptr 12070 // cmp[wd] dest, oldval 12071 // bne- midMBB 12072 // loop2MBB: 12073 // st[bhwd]cx. newval, ptr 12074 // bne- loopMBB 12075 // b exitBB 12076 // midMBB: 12077 // st[bhwd]cx. dest, ptr 12078 // exitBB: 12079 BB = loop1MBB; 12080 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12081 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 12082 .addReg(oldval) 12083 .addReg(dest); 12084 BuildMI(BB, dl, TII->get(PPC::BCC)) 12085 .addImm(PPC::PRED_NE) 12086 .addReg(PPC::CR0) 12087 .addMBB(midMBB); 12088 BB->addSuccessor(loop2MBB); 12089 BB->addSuccessor(midMBB); 12090 12091 BB = loop2MBB; 12092 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12093 .addReg(newval) 12094 .addReg(ptrA) 12095 .addReg(ptrB); 12096 BuildMI(BB, dl, TII->get(PPC::BCC)) 12097 .addImm(PPC::PRED_NE) 12098 .addReg(PPC::CR0) 12099 .addMBB(loop1MBB); 12100 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12101 BB->addSuccessor(loop1MBB); 12102 BB->addSuccessor(exitMBB); 12103 12104 BB = midMBB; 12105 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12106 .addReg(dest) 12107 .addReg(ptrA) 12108 .addReg(ptrB); 12109 BB->addSuccessor(exitMBB); 12110 12111 // exitMBB: 12112 // ... 12113 BB = exitMBB; 12114 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12115 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12116 // We must use 64-bit registers for addresses when targeting 64-bit, 12117 // since we're actually doing arithmetic on them. Other registers 12118 // can be 32-bit. 12119 bool is64bit = Subtarget.isPPC64(); 12120 bool isLittleEndian = Subtarget.isLittleEndian(); 12121 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12122 12123 Register dest = MI.getOperand(0).getReg(); 12124 Register ptrA = MI.getOperand(1).getReg(); 12125 Register ptrB = MI.getOperand(2).getReg(); 12126 Register oldval = MI.getOperand(3).getReg(); 12127 Register newval = MI.getOperand(4).getReg(); 12128 DebugLoc dl = MI.getDebugLoc(); 12129 12130 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12131 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12132 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 12133 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12134 F->insert(It, loop1MBB); 12135 F->insert(It, loop2MBB); 12136 F->insert(It, midMBB); 12137 F->insert(It, exitMBB); 12138 exitMBB->splice(exitMBB->begin(), BB, 12139 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12140 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12141 12142 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12143 const TargetRegisterClass *RC = 12144 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12145 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12146 12147 Register PtrReg = RegInfo.createVirtualRegister(RC); 12148 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12149 Register ShiftReg = 12150 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12151 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12152 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12153 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12154 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12155 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12156 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12157 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12158 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12159 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12160 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12161 Register Ptr1Reg; 12162 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12163 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12164 // thisMBB: 12165 // ... 12166 // fallthrough --> loopMBB 12167 BB->addSuccessor(loop1MBB); 12168 12169 // The 4-byte load must be aligned, while a char or short may be 12170 // anywhere in the word. Hence all this nasty bookkeeping code. 12171 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12172 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12173 // xori shift, shift1, 24 [16] 12174 // rlwinm ptr, ptr1, 0, 0, 29 12175 // slw newval2, newval, shift 12176 // slw oldval2, oldval,shift 12177 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12178 // slw mask, mask2, shift 12179 // and newval3, newval2, mask 12180 // and oldval3, oldval2, mask 12181 // loop1MBB: 12182 // lwarx tmpDest, ptr 12183 // and tmp, tmpDest, mask 12184 // cmpw tmp, oldval3 12185 // bne- midMBB 12186 // loop2MBB: 12187 // andc tmp2, tmpDest, mask 12188 // or tmp4, tmp2, newval3 12189 // stwcx. tmp4, ptr 12190 // bne- loop1MBB 12191 // b exitBB 12192 // midMBB: 12193 // stwcx. tmpDest, ptr 12194 // exitBB: 12195 // srw dest, tmpDest, shift 12196 if (ptrA != ZeroReg) { 12197 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12198 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12199 .addReg(ptrA) 12200 .addReg(ptrB); 12201 } else { 12202 Ptr1Reg = ptrB; 12203 } 12204 12205 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12206 // mode. 12207 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12208 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12209 .addImm(3) 12210 .addImm(27) 12211 .addImm(is8bit ? 28 : 27); 12212 if (!isLittleEndian) 12213 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12214 .addReg(Shift1Reg) 12215 .addImm(is8bit ? 24 : 16); 12216 if (is64bit) 12217 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12218 .addReg(Ptr1Reg) 12219 .addImm(0) 12220 .addImm(61); 12221 else 12222 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12223 .addReg(Ptr1Reg) 12224 .addImm(0) 12225 .addImm(0) 12226 .addImm(29); 12227 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12228 .addReg(newval) 12229 .addReg(ShiftReg); 12230 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12231 .addReg(oldval) 12232 .addReg(ShiftReg); 12233 if (is8bit) 12234 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12235 else { 12236 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12237 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12238 .addReg(Mask3Reg) 12239 .addImm(65535); 12240 } 12241 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12242 .addReg(Mask2Reg) 12243 .addReg(ShiftReg); 12244 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12245 .addReg(NewVal2Reg) 12246 .addReg(MaskReg); 12247 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12248 .addReg(OldVal2Reg) 12249 .addReg(MaskReg); 12250 12251 BB = loop1MBB; 12252 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12253 .addReg(ZeroReg) 12254 .addReg(PtrReg); 12255 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12256 .addReg(TmpDestReg) 12257 .addReg(MaskReg); 12258 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12259 .addReg(TmpReg) 12260 .addReg(OldVal3Reg); 12261 BuildMI(BB, dl, TII->get(PPC::BCC)) 12262 .addImm(PPC::PRED_NE) 12263 .addReg(PPC::CR0) 12264 .addMBB(midMBB); 12265 BB->addSuccessor(loop2MBB); 12266 BB->addSuccessor(midMBB); 12267 12268 BB = loop2MBB; 12269 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12270 .addReg(TmpDestReg) 12271 .addReg(MaskReg); 12272 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12273 .addReg(Tmp2Reg) 12274 .addReg(NewVal3Reg); 12275 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12276 .addReg(Tmp4Reg) 12277 .addReg(ZeroReg) 12278 .addReg(PtrReg); 12279 BuildMI(BB, dl, TII->get(PPC::BCC)) 12280 .addImm(PPC::PRED_NE) 12281 .addReg(PPC::CR0) 12282 .addMBB(loop1MBB); 12283 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12284 BB->addSuccessor(loop1MBB); 12285 BB->addSuccessor(exitMBB); 12286 12287 BB = midMBB; 12288 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12289 .addReg(TmpDestReg) 12290 .addReg(ZeroReg) 12291 .addReg(PtrReg); 12292 BB->addSuccessor(exitMBB); 12293 12294 // exitMBB: 12295 // ... 12296 BB = exitMBB; 12297 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12298 .addReg(TmpReg) 12299 .addReg(ShiftReg); 12300 } else if (MI.getOpcode() == PPC::FADDrtz) { 12301 // This pseudo performs an FADD with rounding mode temporarily forced 12302 // to round-to-zero. We emit this via custom inserter since the FPSCR 12303 // is not modeled at the SelectionDAG level. 12304 Register Dest = MI.getOperand(0).getReg(); 12305 Register Src1 = MI.getOperand(1).getReg(); 12306 Register Src2 = MI.getOperand(2).getReg(); 12307 DebugLoc dl = MI.getDebugLoc(); 12308 12309 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12310 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12311 12312 // Save FPSCR value. 12313 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12314 12315 // Set rounding mode to round-to-zero. 12316 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 12317 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 12318 12319 // Perform addition. 12320 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 12321 12322 // Restore FPSCR value. 12323 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12324 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12325 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12326 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12327 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12328 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12329 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12330 ? PPC::ANDI8_rec 12331 : PPC::ANDI_rec; 12332 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12333 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12334 12335 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12336 Register Dest = RegInfo.createVirtualRegister( 12337 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12338 12339 DebugLoc Dl = MI.getDebugLoc(); 12340 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12341 .addReg(MI.getOperand(1).getReg()) 12342 .addImm(1); 12343 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12344 MI.getOperand(0).getReg()) 12345 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12346 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12347 DebugLoc Dl = MI.getDebugLoc(); 12348 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12349 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12350 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12351 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12352 MI.getOperand(0).getReg()) 12353 .addReg(CRReg); 12354 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12355 DebugLoc Dl = MI.getDebugLoc(); 12356 unsigned Imm = MI.getOperand(1).getImm(); 12357 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12358 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12359 MI.getOperand(0).getReg()) 12360 .addReg(PPC::CR0EQ); 12361 } else if (MI.getOpcode() == PPC::SETRNDi) { 12362 DebugLoc dl = MI.getDebugLoc(); 12363 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12364 12365 // Save FPSCR value. 12366 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12367 12368 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12369 // the following settings: 12370 // 00 Round to nearest 12371 // 01 Round to 0 12372 // 10 Round to +inf 12373 // 11 Round to -inf 12374 12375 // When the operand is immediate, using the two least significant bits of 12376 // the immediate to set the bits 62:63 of FPSCR. 12377 unsigned Mode = MI.getOperand(1).getImm(); 12378 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12379 .addImm(31); 12380 12381 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12382 .addImm(30); 12383 } else if (MI.getOpcode() == PPC::SETRND) { 12384 DebugLoc dl = MI.getDebugLoc(); 12385 12386 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12387 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12388 // If the target doesn't have DirectMove, we should use stack to do the 12389 // conversion, because the target doesn't have the instructions like mtvsrd 12390 // or mfvsrd to do this conversion directly. 12391 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12392 if (Subtarget.hasDirectMove()) { 12393 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12394 .addReg(SrcReg); 12395 } else { 12396 // Use stack to do the register copy. 12397 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12398 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12399 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12400 if (RC == &PPC::F8RCRegClass) { 12401 // Copy register from F8RCRegClass to G8RCRegclass. 12402 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12403 "Unsupported RegClass."); 12404 12405 StoreOp = PPC::STFD; 12406 LoadOp = PPC::LD; 12407 } else { 12408 // Copy register from G8RCRegClass to F8RCRegclass. 12409 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12410 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12411 "Unsupported RegClass."); 12412 } 12413 12414 MachineFrameInfo &MFI = F->getFrameInfo(); 12415 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12416 12417 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12418 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12419 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12420 MFI.getObjectAlign(FrameIdx)); 12421 12422 // Store the SrcReg into the stack. 12423 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12424 .addReg(SrcReg) 12425 .addImm(0) 12426 .addFrameIndex(FrameIdx) 12427 .addMemOperand(MMOStore); 12428 12429 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12430 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12431 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12432 MFI.getObjectAlign(FrameIdx)); 12433 12434 // Load from the stack where SrcReg is stored, and save to DestReg, 12435 // so we have done the RegClass conversion from RegClass::SrcReg to 12436 // RegClass::DestReg. 12437 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12438 .addImm(0) 12439 .addFrameIndex(FrameIdx) 12440 .addMemOperand(MMOLoad); 12441 } 12442 }; 12443 12444 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12445 12446 // Save FPSCR value. 12447 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12448 12449 // When the operand is gprc register, use two least significant bits of the 12450 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12451 // 12452 // copy OldFPSCRTmpReg, OldFPSCRReg 12453 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12454 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12455 // copy NewFPSCRReg, NewFPSCRTmpReg 12456 // mtfsf 255, NewFPSCRReg 12457 MachineOperand SrcOp = MI.getOperand(1); 12458 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12459 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12460 12461 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12462 12463 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12464 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12465 12466 // The first operand of INSERT_SUBREG should be a register which has 12467 // subregisters, we only care about its RegClass, so we should use an 12468 // IMPLICIT_DEF register. 12469 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12470 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12471 .addReg(ImDefReg) 12472 .add(SrcOp) 12473 .addImm(1); 12474 12475 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12476 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12477 .addReg(OldFPSCRTmpReg) 12478 .addReg(ExtSrcReg) 12479 .addImm(0) 12480 .addImm(62); 12481 12482 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12483 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12484 12485 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12486 // bits of FPSCR. 12487 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12488 .addImm(255) 12489 .addReg(NewFPSCRReg) 12490 .addImm(0) 12491 .addImm(0); 12492 } else { 12493 llvm_unreachable("Unexpected instr type to insert"); 12494 } 12495 12496 MI.eraseFromParent(); // The pseudo instruction is gone now. 12497 return BB; 12498 } 12499 12500 //===----------------------------------------------------------------------===// 12501 // Target Optimization Hooks 12502 //===----------------------------------------------------------------------===// 12503 12504 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12505 // For the estimates, convergence is quadratic, so we essentially double the 12506 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12507 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12508 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12509 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12510 if (VT.getScalarType() == MVT::f64) 12511 RefinementSteps++; 12512 return RefinementSteps; 12513 } 12514 12515 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12516 int Enabled, int &RefinementSteps, 12517 bool &UseOneConstNR, 12518 bool Reciprocal) const { 12519 EVT VT = Operand.getValueType(); 12520 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12521 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12522 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12523 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12524 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12525 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12526 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12527 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12528 12529 // The Newton-Raphson computation with a single constant does not provide 12530 // enough accuracy on some CPUs. 12531 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12532 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12533 } 12534 return SDValue(); 12535 } 12536 12537 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12538 int Enabled, 12539 int &RefinementSteps) const { 12540 EVT VT = Operand.getValueType(); 12541 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12542 (VT == MVT::f64 && Subtarget.hasFRE()) || 12543 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12544 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 12545 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 12546 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 12547 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12548 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12549 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12550 } 12551 return SDValue(); 12552 } 12553 12554 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12555 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12556 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12557 // enabled for division), this functionality is redundant with the default 12558 // combiner logic (once the division -> reciprocal/multiply transformation 12559 // has taken place). As a result, this matters more for older cores than for 12560 // newer ones. 12561 12562 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12563 // reciprocal if there are two or more FDIVs (for embedded cores with only 12564 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12565 switch (Subtarget.getCPUDirective()) { 12566 default: 12567 return 3; 12568 case PPC::DIR_440: 12569 case PPC::DIR_A2: 12570 case PPC::DIR_E500: 12571 case PPC::DIR_E500mc: 12572 case PPC::DIR_E5500: 12573 return 2; 12574 } 12575 } 12576 12577 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12578 // collapsed, and so we need to look through chains of them. 12579 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12580 int64_t& Offset, SelectionDAG &DAG) { 12581 if (DAG.isBaseWithConstantOffset(Loc)) { 12582 Base = Loc.getOperand(0); 12583 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12584 12585 // The base might itself be a base plus an offset, and if so, accumulate 12586 // that as well. 12587 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12588 } 12589 } 12590 12591 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12592 unsigned Bytes, int Dist, 12593 SelectionDAG &DAG) { 12594 if (VT.getSizeInBits() / 8 != Bytes) 12595 return false; 12596 12597 SDValue BaseLoc = Base->getBasePtr(); 12598 if (Loc.getOpcode() == ISD::FrameIndex) { 12599 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12600 return false; 12601 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12602 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12603 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12604 int FS = MFI.getObjectSize(FI); 12605 int BFS = MFI.getObjectSize(BFI); 12606 if (FS != BFS || FS != (int)Bytes) return false; 12607 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12608 } 12609 12610 SDValue Base1 = Loc, Base2 = BaseLoc; 12611 int64_t Offset1 = 0, Offset2 = 0; 12612 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12613 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12614 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12615 return true; 12616 12617 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12618 const GlobalValue *GV1 = nullptr; 12619 const GlobalValue *GV2 = nullptr; 12620 Offset1 = 0; 12621 Offset2 = 0; 12622 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12623 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12624 if (isGA1 && isGA2 && GV1 == GV2) 12625 return Offset1 == (Offset2 + Dist*Bytes); 12626 return false; 12627 } 12628 12629 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12630 // not enforce equality of the chain operands. 12631 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12632 unsigned Bytes, int Dist, 12633 SelectionDAG &DAG) { 12634 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12635 EVT VT = LS->getMemoryVT(); 12636 SDValue Loc = LS->getBasePtr(); 12637 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12638 } 12639 12640 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12641 EVT VT; 12642 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12643 default: return false; 12644 case Intrinsic::ppc_qpx_qvlfd: 12645 case Intrinsic::ppc_qpx_qvlfda: 12646 VT = MVT::v4f64; 12647 break; 12648 case Intrinsic::ppc_qpx_qvlfs: 12649 case Intrinsic::ppc_qpx_qvlfsa: 12650 VT = MVT::v4f32; 12651 break; 12652 case Intrinsic::ppc_qpx_qvlfcd: 12653 case Intrinsic::ppc_qpx_qvlfcda: 12654 VT = MVT::v2f64; 12655 break; 12656 case Intrinsic::ppc_qpx_qvlfcs: 12657 case Intrinsic::ppc_qpx_qvlfcsa: 12658 VT = MVT::v2f32; 12659 break; 12660 case Intrinsic::ppc_qpx_qvlfiwa: 12661 case Intrinsic::ppc_qpx_qvlfiwz: 12662 case Intrinsic::ppc_altivec_lvx: 12663 case Intrinsic::ppc_altivec_lvxl: 12664 case Intrinsic::ppc_vsx_lxvw4x: 12665 case Intrinsic::ppc_vsx_lxvw4x_be: 12666 VT = MVT::v4i32; 12667 break; 12668 case Intrinsic::ppc_vsx_lxvd2x: 12669 case Intrinsic::ppc_vsx_lxvd2x_be: 12670 VT = MVT::v2f64; 12671 break; 12672 case Intrinsic::ppc_altivec_lvebx: 12673 VT = MVT::i8; 12674 break; 12675 case Intrinsic::ppc_altivec_lvehx: 12676 VT = MVT::i16; 12677 break; 12678 case Intrinsic::ppc_altivec_lvewx: 12679 VT = MVT::i32; 12680 break; 12681 } 12682 12683 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12684 } 12685 12686 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12687 EVT VT; 12688 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12689 default: return false; 12690 case Intrinsic::ppc_qpx_qvstfd: 12691 case Intrinsic::ppc_qpx_qvstfda: 12692 VT = MVT::v4f64; 12693 break; 12694 case Intrinsic::ppc_qpx_qvstfs: 12695 case Intrinsic::ppc_qpx_qvstfsa: 12696 VT = MVT::v4f32; 12697 break; 12698 case Intrinsic::ppc_qpx_qvstfcd: 12699 case Intrinsic::ppc_qpx_qvstfcda: 12700 VT = MVT::v2f64; 12701 break; 12702 case Intrinsic::ppc_qpx_qvstfcs: 12703 case Intrinsic::ppc_qpx_qvstfcsa: 12704 VT = MVT::v2f32; 12705 break; 12706 case Intrinsic::ppc_qpx_qvstfiw: 12707 case Intrinsic::ppc_qpx_qvstfiwa: 12708 case Intrinsic::ppc_altivec_stvx: 12709 case Intrinsic::ppc_altivec_stvxl: 12710 case Intrinsic::ppc_vsx_stxvw4x: 12711 VT = MVT::v4i32; 12712 break; 12713 case Intrinsic::ppc_vsx_stxvd2x: 12714 VT = MVT::v2f64; 12715 break; 12716 case Intrinsic::ppc_vsx_stxvw4x_be: 12717 VT = MVT::v4i32; 12718 break; 12719 case Intrinsic::ppc_vsx_stxvd2x_be: 12720 VT = MVT::v2f64; 12721 break; 12722 case Intrinsic::ppc_altivec_stvebx: 12723 VT = MVT::i8; 12724 break; 12725 case Intrinsic::ppc_altivec_stvehx: 12726 VT = MVT::i16; 12727 break; 12728 case Intrinsic::ppc_altivec_stvewx: 12729 VT = MVT::i32; 12730 break; 12731 } 12732 12733 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12734 } 12735 12736 return false; 12737 } 12738 12739 // Return true is there is a nearyby consecutive load to the one provided 12740 // (regardless of alignment). We search up and down the chain, looking though 12741 // token factors and other loads (but nothing else). As a result, a true result 12742 // indicates that it is safe to create a new consecutive load adjacent to the 12743 // load provided. 12744 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12745 SDValue Chain = LD->getChain(); 12746 EVT VT = LD->getMemoryVT(); 12747 12748 SmallSet<SDNode *, 16> LoadRoots; 12749 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12750 SmallSet<SDNode *, 16> Visited; 12751 12752 // First, search up the chain, branching to follow all token-factor operands. 12753 // If we find a consecutive load, then we're done, otherwise, record all 12754 // nodes just above the top-level loads and token factors. 12755 while (!Queue.empty()) { 12756 SDNode *ChainNext = Queue.pop_back_val(); 12757 if (!Visited.insert(ChainNext).second) 12758 continue; 12759 12760 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12761 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12762 return true; 12763 12764 if (!Visited.count(ChainLD->getChain().getNode())) 12765 Queue.push_back(ChainLD->getChain().getNode()); 12766 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12767 for (const SDUse &O : ChainNext->ops()) 12768 if (!Visited.count(O.getNode())) 12769 Queue.push_back(O.getNode()); 12770 } else 12771 LoadRoots.insert(ChainNext); 12772 } 12773 12774 // Second, search down the chain, starting from the top-level nodes recorded 12775 // in the first phase. These top-level nodes are the nodes just above all 12776 // loads and token factors. Starting with their uses, recursively look though 12777 // all loads (just the chain uses) and token factors to find a consecutive 12778 // load. 12779 Visited.clear(); 12780 Queue.clear(); 12781 12782 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12783 IE = LoadRoots.end(); I != IE; ++I) { 12784 Queue.push_back(*I); 12785 12786 while (!Queue.empty()) { 12787 SDNode *LoadRoot = Queue.pop_back_val(); 12788 if (!Visited.insert(LoadRoot).second) 12789 continue; 12790 12791 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12792 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12793 return true; 12794 12795 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12796 UE = LoadRoot->use_end(); UI != UE; ++UI) 12797 if (((isa<MemSDNode>(*UI) && 12798 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12799 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12800 Queue.push_back(*UI); 12801 } 12802 } 12803 12804 return false; 12805 } 12806 12807 /// This function is called when we have proved that a SETCC node can be replaced 12808 /// by subtraction (and other supporting instructions) so that the result of 12809 /// comparison is kept in a GPR instead of CR. This function is purely for 12810 /// codegen purposes and has some flags to guide the codegen process. 12811 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12812 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12813 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12814 12815 // Zero extend the operands to the largest legal integer. Originally, they 12816 // must be of a strictly smaller size. 12817 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12818 DAG.getConstant(Size, DL, MVT::i32)); 12819 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12820 DAG.getConstant(Size, DL, MVT::i32)); 12821 12822 // Swap if needed. Depends on the condition code. 12823 if (Swap) 12824 std::swap(Op0, Op1); 12825 12826 // Subtract extended integers. 12827 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12828 12829 // Move the sign bit to the least significant position and zero out the rest. 12830 // Now the least significant bit carries the result of original comparison. 12831 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12832 DAG.getConstant(Size - 1, DL, MVT::i32)); 12833 auto Final = Shifted; 12834 12835 // Complement the result if needed. Based on the condition code. 12836 if (Complement) 12837 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12838 DAG.getConstant(1, DL, MVT::i64)); 12839 12840 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12841 } 12842 12843 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12844 DAGCombinerInfo &DCI) const { 12845 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12846 12847 SelectionDAG &DAG = DCI.DAG; 12848 SDLoc DL(N); 12849 12850 // Size of integers being compared has a critical role in the following 12851 // analysis, so we prefer to do this when all types are legal. 12852 if (!DCI.isAfterLegalizeDAG()) 12853 return SDValue(); 12854 12855 // If all users of SETCC extend its value to a legal integer type 12856 // then we replace SETCC with a subtraction 12857 for (SDNode::use_iterator UI = N->use_begin(), 12858 UE = N->use_end(); UI != UE; ++UI) { 12859 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12860 return SDValue(); 12861 } 12862 12863 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12864 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12865 12866 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12867 12868 if (OpSize < Size) { 12869 switch (CC) { 12870 default: break; 12871 case ISD::SETULT: 12872 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12873 case ISD::SETULE: 12874 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12875 case ISD::SETUGT: 12876 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12877 case ISD::SETUGE: 12878 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12879 } 12880 } 12881 12882 return SDValue(); 12883 } 12884 12885 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12886 DAGCombinerInfo &DCI) const { 12887 SelectionDAG &DAG = DCI.DAG; 12888 SDLoc dl(N); 12889 12890 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12891 // If we're tracking CR bits, we need to be careful that we don't have: 12892 // trunc(binary-ops(zext(x), zext(y))) 12893 // or 12894 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12895 // such that we're unnecessarily moving things into GPRs when it would be 12896 // better to keep them in CR bits. 12897 12898 // Note that trunc here can be an actual i1 trunc, or can be the effective 12899 // truncation that comes from a setcc or select_cc. 12900 if (N->getOpcode() == ISD::TRUNCATE && 12901 N->getValueType(0) != MVT::i1) 12902 return SDValue(); 12903 12904 if (N->getOperand(0).getValueType() != MVT::i32 && 12905 N->getOperand(0).getValueType() != MVT::i64) 12906 return SDValue(); 12907 12908 if (N->getOpcode() == ISD::SETCC || 12909 N->getOpcode() == ISD::SELECT_CC) { 12910 // If we're looking at a comparison, then we need to make sure that the 12911 // high bits (all except for the first) don't matter the result. 12912 ISD::CondCode CC = 12913 cast<CondCodeSDNode>(N->getOperand( 12914 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12915 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12916 12917 if (ISD::isSignedIntSetCC(CC)) { 12918 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12919 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12920 return SDValue(); 12921 } else if (ISD::isUnsignedIntSetCC(CC)) { 12922 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12923 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12924 !DAG.MaskedValueIsZero(N->getOperand(1), 12925 APInt::getHighBitsSet(OpBits, OpBits-1))) 12926 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12927 : SDValue()); 12928 } else { 12929 // This is neither a signed nor an unsigned comparison, just make sure 12930 // that the high bits are equal. 12931 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12932 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12933 12934 // We don't really care about what is known about the first bit (if 12935 // anything), so clear it in all masks prior to comparing them. 12936 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12937 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12938 12939 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12940 return SDValue(); 12941 } 12942 } 12943 12944 // We now know that the higher-order bits are irrelevant, we just need to 12945 // make sure that all of the intermediate operations are bit operations, and 12946 // all inputs are extensions. 12947 if (N->getOperand(0).getOpcode() != ISD::AND && 12948 N->getOperand(0).getOpcode() != ISD::OR && 12949 N->getOperand(0).getOpcode() != ISD::XOR && 12950 N->getOperand(0).getOpcode() != ISD::SELECT && 12951 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12952 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12953 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12954 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12955 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12956 return SDValue(); 12957 12958 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12959 N->getOperand(1).getOpcode() != ISD::AND && 12960 N->getOperand(1).getOpcode() != ISD::OR && 12961 N->getOperand(1).getOpcode() != ISD::XOR && 12962 N->getOperand(1).getOpcode() != ISD::SELECT && 12963 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12964 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12965 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12966 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12967 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12968 return SDValue(); 12969 12970 SmallVector<SDValue, 4> Inputs; 12971 SmallVector<SDValue, 8> BinOps, PromOps; 12972 SmallPtrSet<SDNode *, 16> Visited; 12973 12974 for (unsigned i = 0; i < 2; ++i) { 12975 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12976 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12977 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12978 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12979 isa<ConstantSDNode>(N->getOperand(i))) 12980 Inputs.push_back(N->getOperand(i)); 12981 else 12982 BinOps.push_back(N->getOperand(i)); 12983 12984 if (N->getOpcode() == ISD::TRUNCATE) 12985 break; 12986 } 12987 12988 // Visit all inputs, collect all binary operations (and, or, xor and 12989 // select) that are all fed by extensions. 12990 while (!BinOps.empty()) { 12991 SDValue BinOp = BinOps.back(); 12992 BinOps.pop_back(); 12993 12994 if (!Visited.insert(BinOp.getNode()).second) 12995 continue; 12996 12997 PromOps.push_back(BinOp); 12998 12999 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13000 // The condition of the select is not promoted. 13001 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13002 continue; 13003 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13004 continue; 13005 13006 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13007 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13008 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13009 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13010 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13011 Inputs.push_back(BinOp.getOperand(i)); 13012 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13013 BinOp.getOperand(i).getOpcode() == ISD::OR || 13014 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13015 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13016 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13017 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13018 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13019 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13020 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13021 BinOps.push_back(BinOp.getOperand(i)); 13022 } else { 13023 // We have an input that is not an extension or another binary 13024 // operation; we'll abort this transformation. 13025 return SDValue(); 13026 } 13027 } 13028 } 13029 13030 // Make sure that this is a self-contained cluster of operations (which 13031 // is not quite the same thing as saying that everything has only one 13032 // use). 13033 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13034 if (isa<ConstantSDNode>(Inputs[i])) 13035 continue; 13036 13037 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13038 UE = Inputs[i].getNode()->use_end(); 13039 UI != UE; ++UI) { 13040 SDNode *User = *UI; 13041 if (User != N && !Visited.count(User)) 13042 return SDValue(); 13043 13044 // Make sure that we're not going to promote the non-output-value 13045 // operand(s) or SELECT or SELECT_CC. 13046 // FIXME: Although we could sometimes handle this, and it does occur in 13047 // practice that one of the condition inputs to the select is also one of 13048 // the outputs, we currently can't deal with this. 13049 if (User->getOpcode() == ISD::SELECT) { 13050 if (User->getOperand(0) == Inputs[i]) 13051 return SDValue(); 13052 } else if (User->getOpcode() == ISD::SELECT_CC) { 13053 if (User->getOperand(0) == Inputs[i] || 13054 User->getOperand(1) == Inputs[i]) 13055 return SDValue(); 13056 } 13057 } 13058 } 13059 13060 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13061 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13062 UE = PromOps[i].getNode()->use_end(); 13063 UI != UE; ++UI) { 13064 SDNode *User = *UI; 13065 if (User != N && !Visited.count(User)) 13066 return SDValue(); 13067 13068 // Make sure that we're not going to promote the non-output-value 13069 // operand(s) or SELECT or SELECT_CC. 13070 // FIXME: Although we could sometimes handle this, and it does occur in 13071 // practice that one of the condition inputs to the select is also one of 13072 // the outputs, we currently can't deal with this. 13073 if (User->getOpcode() == ISD::SELECT) { 13074 if (User->getOperand(0) == PromOps[i]) 13075 return SDValue(); 13076 } else if (User->getOpcode() == ISD::SELECT_CC) { 13077 if (User->getOperand(0) == PromOps[i] || 13078 User->getOperand(1) == PromOps[i]) 13079 return SDValue(); 13080 } 13081 } 13082 } 13083 13084 // Replace all inputs with the extension operand. 13085 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13086 // Constants may have users outside the cluster of to-be-promoted nodes, 13087 // and so we need to replace those as we do the promotions. 13088 if (isa<ConstantSDNode>(Inputs[i])) 13089 continue; 13090 else 13091 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13092 } 13093 13094 std::list<HandleSDNode> PromOpHandles; 13095 for (auto &PromOp : PromOps) 13096 PromOpHandles.emplace_back(PromOp); 13097 13098 // Replace all operations (these are all the same, but have a different 13099 // (i1) return type). DAG.getNode will validate that the types of 13100 // a binary operator match, so go through the list in reverse so that 13101 // we've likely promoted both operands first. Any intermediate truncations or 13102 // extensions disappear. 13103 while (!PromOpHandles.empty()) { 13104 SDValue PromOp = PromOpHandles.back().getValue(); 13105 PromOpHandles.pop_back(); 13106 13107 if (PromOp.getOpcode() == ISD::TRUNCATE || 13108 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13109 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13110 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13111 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13112 PromOp.getOperand(0).getValueType() != MVT::i1) { 13113 // The operand is not yet ready (see comment below). 13114 PromOpHandles.emplace_front(PromOp); 13115 continue; 13116 } 13117 13118 SDValue RepValue = PromOp.getOperand(0); 13119 if (isa<ConstantSDNode>(RepValue)) 13120 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13121 13122 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13123 continue; 13124 } 13125 13126 unsigned C; 13127 switch (PromOp.getOpcode()) { 13128 default: C = 0; break; 13129 case ISD::SELECT: C = 1; break; 13130 case ISD::SELECT_CC: C = 2; break; 13131 } 13132 13133 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13134 PromOp.getOperand(C).getValueType() != MVT::i1) || 13135 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13136 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13137 // The to-be-promoted operands of this node have not yet been 13138 // promoted (this should be rare because we're going through the 13139 // list backward, but if one of the operands has several users in 13140 // this cluster of to-be-promoted nodes, it is possible). 13141 PromOpHandles.emplace_front(PromOp); 13142 continue; 13143 } 13144 13145 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13146 PromOp.getNode()->op_end()); 13147 13148 // If there are any constant inputs, make sure they're replaced now. 13149 for (unsigned i = 0; i < 2; ++i) 13150 if (isa<ConstantSDNode>(Ops[C+i])) 13151 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13152 13153 DAG.ReplaceAllUsesOfValueWith(PromOp, 13154 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13155 } 13156 13157 // Now we're left with the initial truncation itself. 13158 if (N->getOpcode() == ISD::TRUNCATE) 13159 return N->getOperand(0); 13160 13161 // Otherwise, this is a comparison. The operands to be compared have just 13162 // changed type (to i1), but everything else is the same. 13163 return SDValue(N, 0); 13164 } 13165 13166 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13167 DAGCombinerInfo &DCI) const { 13168 SelectionDAG &DAG = DCI.DAG; 13169 SDLoc dl(N); 13170 13171 // If we're tracking CR bits, we need to be careful that we don't have: 13172 // zext(binary-ops(trunc(x), trunc(y))) 13173 // or 13174 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13175 // such that we're unnecessarily moving things into CR bits that can more 13176 // efficiently stay in GPRs. Note that if we're not certain that the high 13177 // bits are set as required by the final extension, we still may need to do 13178 // some masking to get the proper behavior. 13179 13180 // This same functionality is important on PPC64 when dealing with 13181 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13182 // the return values of functions. Because it is so similar, it is handled 13183 // here as well. 13184 13185 if (N->getValueType(0) != MVT::i32 && 13186 N->getValueType(0) != MVT::i64) 13187 return SDValue(); 13188 13189 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13190 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13191 return SDValue(); 13192 13193 if (N->getOperand(0).getOpcode() != ISD::AND && 13194 N->getOperand(0).getOpcode() != ISD::OR && 13195 N->getOperand(0).getOpcode() != ISD::XOR && 13196 N->getOperand(0).getOpcode() != ISD::SELECT && 13197 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13198 return SDValue(); 13199 13200 SmallVector<SDValue, 4> Inputs; 13201 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13202 SmallPtrSet<SDNode *, 16> Visited; 13203 13204 // Visit all inputs, collect all binary operations (and, or, xor and 13205 // select) that are all fed by truncations. 13206 while (!BinOps.empty()) { 13207 SDValue BinOp = BinOps.back(); 13208 BinOps.pop_back(); 13209 13210 if (!Visited.insert(BinOp.getNode()).second) 13211 continue; 13212 13213 PromOps.push_back(BinOp); 13214 13215 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13216 // The condition of the select is not promoted. 13217 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13218 continue; 13219 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13220 continue; 13221 13222 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13223 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13224 Inputs.push_back(BinOp.getOperand(i)); 13225 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13226 BinOp.getOperand(i).getOpcode() == ISD::OR || 13227 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13228 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13229 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13230 BinOps.push_back(BinOp.getOperand(i)); 13231 } else { 13232 // We have an input that is not a truncation or another binary 13233 // operation; we'll abort this transformation. 13234 return SDValue(); 13235 } 13236 } 13237 } 13238 13239 // The operands of a select that must be truncated when the select is 13240 // promoted because the operand is actually part of the to-be-promoted set. 13241 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13242 13243 // Make sure that this is a self-contained cluster of operations (which 13244 // is not quite the same thing as saying that everything has only one 13245 // use). 13246 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13247 if (isa<ConstantSDNode>(Inputs[i])) 13248 continue; 13249 13250 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13251 UE = Inputs[i].getNode()->use_end(); 13252 UI != UE; ++UI) { 13253 SDNode *User = *UI; 13254 if (User != N && !Visited.count(User)) 13255 return SDValue(); 13256 13257 // If we're going to promote the non-output-value operand(s) or SELECT or 13258 // SELECT_CC, record them for truncation. 13259 if (User->getOpcode() == ISD::SELECT) { 13260 if (User->getOperand(0) == Inputs[i]) 13261 SelectTruncOp[0].insert(std::make_pair(User, 13262 User->getOperand(0).getValueType())); 13263 } else if (User->getOpcode() == ISD::SELECT_CC) { 13264 if (User->getOperand(0) == Inputs[i]) 13265 SelectTruncOp[0].insert(std::make_pair(User, 13266 User->getOperand(0).getValueType())); 13267 if (User->getOperand(1) == Inputs[i]) 13268 SelectTruncOp[1].insert(std::make_pair(User, 13269 User->getOperand(1).getValueType())); 13270 } 13271 } 13272 } 13273 13274 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13275 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13276 UE = PromOps[i].getNode()->use_end(); 13277 UI != UE; ++UI) { 13278 SDNode *User = *UI; 13279 if (User != N && !Visited.count(User)) 13280 return SDValue(); 13281 13282 // If we're going to promote the non-output-value operand(s) or SELECT or 13283 // SELECT_CC, record them for truncation. 13284 if (User->getOpcode() == ISD::SELECT) { 13285 if (User->getOperand(0) == PromOps[i]) 13286 SelectTruncOp[0].insert(std::make_pair(User, 13287 User->getOperand(0).getValueType())); 13288 } else if (User->getOpcode() == ISD::SELECT_CC) { 13289 if (User->getOperand(0) == PromOps[i]) 13290 SelectTruncOp[0].insert(std::make_pair(User, 13291 User->getOperand(0).getValueType())); 13292 if (User->getOperand(1) == PromOps[i]) 13293 SelectTruncOp[1].insert(std::make_pair(User, 13294 User->getOperand(1).getValueType())); 13295 } 13296 } 13297 } 13298 13299 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13300 bool ReallyNeedsExt = false; 13301 if (N->getOpcode() != ISD::ANY_EXTEND) { 13302 // If all of the inputs are not already sign/zero extended, then 13303 // we'll still need to do that at the end. 13304 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13305 if (isa<ConstantSDNode>(Inputs[i])) 13306 continue; 13307 13308 unsigned OpBits = 13309 Inputs[i].getOperand(0).getValueSizeInBits(); 13310 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13311 13312 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13313 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13314 APInt::getHighBitsSet(OpBits, 13315 OpBits-PromBits))) || 13316 (N->getOpcode() == ISD::SIGN_EXTEND && 13317 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13318 (OpBits-(PromBits-1)))) { 13319 ReallyNeedsExt = true; 13320 break; 13321 } 13322 } 13323 } 13324 13325 // Replace all inputs, either with the truncation operand, or a 13326 // truncation or extension to the final output type. 13327 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13328 // Constant inputs need to be replaced with the to-be-promoted nodes that 13329 // use them because they might have users outside of the cluster of 13330 // promoted nodes. 13331 if (isa<ConstantSDNode>(Inputs[i])) 13332 continue; 13333 13334 SDValue InSrc = Inputs[i].getOperand(0); 13335 if (Inputs[i].getValueType() == N->getValueType(0)) 13336 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13337 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13338 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13339 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13340 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13341 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13342 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13343 else 13344 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13345 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13346 } 13347 13348 std::list<HandleSDNode> PromOpHandles; 13349 for (auto &PromOp : PromOps) 13350 PromOpHandles.emplace_back(PromOp); 13351 13352 // Replace all operations (these are all the same, but have a different 13353 // (promoted) return type). DAG.getNode will validate that the types of 13354 // a binary operator match, so go through the list in reverse so that 13355 // we've likely promoted both operands first. 13356 while (!PromOpHandles.empty()) { 13357 SDValue PromOp = PromOpHandles.back().getValue(); 13358 PromOpHandles.pop_back(); 13359 13360 unsigned C; 13361 switch (PromOp.getOpcode()) { 13362 default: C = 0; break; 13363 case ISD::SELECT: C = 1; break; 13364 case ISD::SELECT_CC: C = 2; break; 13365 } 13366 13367 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13368 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13369 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13370 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13371 // The to-be-promoted operands of this node have not yet been 13372 // promoted (this should be rare because we're going through the 13373 // list backward, but if one of the operands has several users in 13374 // this cluster of to-be-promoted nodes, it is possible). 13375 PromOpHandles.emplace_front(PromOp); 13376 continue; 13377 } 13378 13379 // For SELECT and SELECT_CC nodes, we do a similar check for any 13380 // to-be-promoted comparison inputs. 13381 if (PromOp.getOpcode() == ISD::SELECT || 13382 PromOp.getOpcode() == ISD::SELECT_CC) { 13383 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13384 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13385 (SelectTruncOp[1].count(PromOp.getNode()) && 13386 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13387 PromOpHandles.emplace_front(PromOp); 13388 continue; 13389 } 13390 } 13391 13392 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13393 PromOp.getNode()->op_end()); 13394 13395 // If this node has constant inputs, then they'll need to be promoted here. 13396 for (unsigned i = 0; i < 2; ++i) { 13397 if (!isa<ConstantSDNode>(Ops[C+i])) 13398 continue; 13399 if (Ops[C+i].getValueType() == N->getValueType(0)) 13400 continue; 13401 13402 if (N->getOpcode() == ISD::SIGN_EXTEND) 13403 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13404 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13405 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13406 else 13407 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13408 } 13409 13410 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13411 // truncate them again to the original value type. 13412 if (PromOp.getOpcode() == ISD::SELECT || 13413 PromOp.getOpcode() == ISD::SELECT_CC) { 13414 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13415 if (SI0 != SelectTruncOp[0].end()) 13416 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13417 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13418 if (SI1 != SelectTruncOp[1].end()) 13419 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13420 } 13421 13422 DAG.ReplaceAllUsesOfValueWith(PromOp, 13423 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13424 } 13425 13426 // Now we're left with the initial extension itself. 13427 if (!ReallyNeedsExt) 13428 return N->getOperand(0); 13429 13430 // To zero extend, just mask off everything except for the first bit (in the 13431 // i1 case). 13432 if (N->getOpcode() == ISD::ZERO_EXTEND) 13433 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13434 DAG.getConstant(APInt::getLowBitsSet( 13435 N->getValueSizeInBits(0), PromBits), 13436 dl, N->getValueType(0))); 13437 13438 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13439 "Invalid extension type"); 13440 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13441 SDValue ShiftCst = 13442 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13443 return DAG.getNode( 13444 ISD::SRA, dl, N->getValueType(0), 13445 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13446 ShiftCst); 13447 } 13448 13449 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13450 DAGCombinerInfo &DCI) const { 13451 assert(N->getOpcode() == ISD::SETCC && 13452 "Should be called with a SETCC node"); 13453 13454 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13455 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13456 SDValue LHS = N->getOperand(0); 13457 SDValue RHS = N->getOperand(1); 13458 13459 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13460 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13461 LHS.hasOneUse()) 13462 std::swap(LHS, RHS); 13463 13464 // x == 0-y --> x+y == 0 13465 // x != 0-y --> x+y != 0 13466 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13467 RHS.hasOneUse()) { 13468 SDLoc DL(N); 13469 SelectionDAG &DAG = DCI.DAG; 13470 EVT VT = N->getValueType(0); 13471 EVT OpVT = LHS.getValueType(); 13472 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13473 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13474 } 13475 } 13476 13477 return DAGCombineTruncBoolExt(N, DCI); 13478 } 13479 13480 // Is this an extending load from an f32 to an f64? 13481 static bool isFPExtLoad(SDValue Op) { 13482 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13483 return LD->getExtensionType() == ISD::EXTLOAD && 13484 Op.getValueType() == MVT::f64; 13485 return false; 13486 } 13487 13488 /// Reduces the number of fp-to-int conversion when building a vector. 13489 /// 13490 /// If this vector is built out of floating to integer conversions, 13491 /// transform it to a vector built out of floating point values followed by a 13492 /// single floating to integer conversion of the vector. 13493 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13494 /// becomes (fptosi (build_vector ($A, $B, ...))) 13495 SDValue PPCTargetLowering:: 13496 combineElementTruncationToVectorTruncation(SDNode *N, 13497 DAGCombinerInfo &DCI) const { 13498 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13499 "Should be called with a BUILD_VECTOR node"); 13500 13501 SelectionDAG &DAG = DCI.DAG; 13502 SDLoc dl(N); 13503 13504 SDValue FirstInput = N->getOperand(0); 13505 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13506 "The input operand must be an fp-to-int conversion."); 13507 13508 // This combine happens after legalization so the fp_to_[su]i nodes are 13509 // already converted to PPCSISD nodes. 13510 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13511 if (FirstConversion == PPCISD::FCTIDZ || 13512 FirstConversion == PPCISD::FCTIDUZ || 13513 FirstConversion == PPCISD::FCTIWZ || 13514 FirstConversion == PPCISD::FCTIWUZ) { 13515 bool IsSplat = true; 13516 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13517 FirstConversion == PPCISD::FCTIWUZ; 13518 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13519 SmallVector<SDValue, 4> Ops; 13520 EVT TargetVT = N->getValueType(0); 13521 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13522 SDValue NextOp = N->getOperand(i); 13523 if (NextOp.getOpcode() != PPCISD::MFVSR) 13524 return SDValue(); 13525 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13526 if (NextConversion != FirstConversion) 13527 return SDValue(); 13528 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13529 // This is not valid if the input was originally double precision. It is 13530 // also not profitable to do unless this is an extending load in which 13531 // case doing this combine will allow us to combine consecutive loads. 13532 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13533 return SDValue(); 13534 if (N->getOperand(i) != FirstInput) 13535 IsSplat = false; 13536 } 13537 13538 // If this is a splat, we leave it as-is since there will be only a single 13539 // fp-to-int conversion followed by a splat of the integer. This is better 13540 // for 32-bit and smaller ints and neutral for 64-bit ints. 13541 if (IsSplat) 13542 return SDValue(); 13543 13544 // Now that we know we have the right type of node, get its operands 13545 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13546 SDValue In = N->getOperand(i).getOperand(0); 13547 if (Is32Bit) { 13548 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13549 // here, we know that all inputs are extending loads so this is safe). 13550 if (In.isUndef()) 13551 Ops.push_back(DAG.getUNDEF(SrcVT)); 13552 else { 13553 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13554 MVT::f32, In.getOperand(0), 13555 DAG.getIntPtrConstant(1, dl)); 13556 Ops.push_back(Trunc); 13557 } 13558 } else 13559 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13560 } 13561 13562 unsigned Opcode; 13563 if (FirstConversion == PPCISD::FCTIDZ || 13564 FirstConversion == PPCISD::FCTIWZ) 13565 Opcode = ISD::FP_TO_SINT; 13566 else 13567 Opcode = ISD::FP_TO_UINT; 13568 13569 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13570 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13571 return DAG.getNode(Opcode, dl, TargetVT, BV); 13572 } 13573 return SDValue(); 13574 } 13575 13576 /// Reduce the number of loads when building a vector. 13577 /// 13578 /// Building a vector out of multiple loads can be converted to a load 13579 /// of the vector type if the loads are consecutive. If the loads are 13580 /// consecutive but in descending order, a shuffle is added at the end 13581 /// to reorder the vector. 13582 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13583 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13584 "Should be called with a BUILD_VECTOR node"); 13585 13586 SDLoc dl(N); 13587 13588 // Return early for non byte-sized type, as they can't be consecutive. 13589 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13590 return SDValue(); 13591 13592 bool InputsAreConsecutiveLoads = true; 13593 bool InputsAreReverseConsecutive = true; 13594 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13595 SDValue FirstInput = N->getOperand(0); 13596 bool IsRoundOfExtLoad = false; 13597 13598 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13599 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13600 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13601 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13602 } 13603 // Not a build vector of (possibly fp_rounded) loads. 13604 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13605 N->getNumOperands() == 1) 13606 return SDValue(); 13607 13608 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13609 // If any inputs are fp_round(extload), they all must be. 13610 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13611 return SDValue(); 13612 13613 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13614 N->getOperand(i); 13615 if (NextInput.getOpcode() != ISD::LOAD) 13616 return SDValue(); 13617 13618 SDValue PreviousInput = 13619 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13620 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13621 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13622 13623 // If any inputs are fp_round(extload), they all must be. 13624 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13625 return SDValue(); 13626 13627 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13628 InputsAreConsecutiveLoads = false; 13629 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13630 InputsAreReverseConsecutive = false; 13631 13632 // Exit early if the loads are neither consecutive nor reverse consecutive. 13633 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13634 return SDValue(); 13635 } 13636 13637 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13638 "The loads cannot be both consecutive and reverse consecutive."); 13639 13640 SDValue FirstLoadOp = 13641 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13642 SDValue LastLoadOp = 13643 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13644 N->getOperand(N->getNumOperands()-1); 13645 13646 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13647 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13648 if (InputsAreConsecutiveLoads) { 13649 assert(LD1 && "Input needs to be a LoadSDNode."); 13650 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13651 LD1->getBasePtr(), LD1->getPointerInfo(), 13652 LD1->getAlignment()); 13653 } 13654 if (InputsAreReverseConsecutive) { 13655 assert(LDL && "Input needs to be a LoadSDNode."); 13656 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13657 LDL->getBasePtr(), LDL->getPointerInfo(), 13658 LDL->getAlignment()); 13659 SmallVector<int, 16> Ops; 13660 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13661 Ops.push_back(i); 13662 13663 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13664 DAG.getUNDEF(N->getValueType(0)), Ops); 13665 } 13666 return SDValue(); 13667 } 13668 13669 // This function adds the required vector_shuffle needed to get 13670 // the elements of the vector extract in the correct position 13671 // as specified by the CorrectElems encoding. 13672 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13673 SDValue Input, uint64_t Elems, 13674 uint64_t CorrectElems) { 13675 SDLoc dl(N); 13676 13677 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13678 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13679 13680 // Knowing the element indices being extracted from the original 13681 // vector and the order in which they're being inserted, just put 13682 // them at element indices required for the instruction. 13683 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13684 if (DAG.getDataLayout().isLittleEndian()) 13685 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13686 else 13687 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13688 CorrectElems = CorrectElems >> 8; 13689 Elems = Elems >> 8; 13690 } 13691 13692 SDValue Shuffle = 13693 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13694 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13695 13696 EVT VT = N->getValueType(0); 13697 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13698 13699 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13700 Input.getValueType().getVectorElementType(), 13701 VT.getVectorNumElements()); 13702 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13703 DAG.getValueType(ExtVT)); 13704 } 13705 13706 // Look for build vector patterns where input operands come from sign 13707 // extended vector_extract elements of specific indices. If the correct indices 13708 // aren't used, add a vector shuffle to fix up the indices and create 13709 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13710 // during instruction selection. 13711 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13712 // This array encodes the indices that the vector sign extend instructions 13713 // extract from when extending from one type to another for both BE and LE. 13714 // The right nibble of each byte corresponds to the LE incides. 13715 // and the left nibble of each byte corresponds to the BE incides. 13716 // For example: 0x3074B8FC byte->word 13717 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13718 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13719 // For example: 0x000070F8 byte->double word 13720 // For LE: the allowed indices are: 0x0,0x8 13721 // For BE: the allowed indices are: 0x7,0xF 13722 uint64_t TargetElems[] = { 13723 0x3074B8FC, // b->w 13724 0x000070F8, // b->d 13725 0x10325476, // h->w 13726 0x00003074, // h->d 13727 0x00001032, // w->d 13728 }; 13729 13730 uint64_t Elems = 0; 13731 int Index; 13732 SDValue Input; 13733 13734 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13735 if (!Op) 13736 return false; 13737 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13738 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13739 return false; 13740 13741 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13742 // of the right width. 13743 SDValue Extract = Op.getOperand(0); 13744 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13745 Extract = Extract.getOperand(0); 13746 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13747 return false; 13748 13749 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13750 if (!ExtOp) 13751 return false; 13752 13753 Index = ExtOp->getZExtValue(); 13754 if (Input && Input != Extract.getOperand(0)) 13755 return false; 13756 13757 if (!Input) 13758 Input = Extract.getOperand(0); 13759 13760 Elems = Elems << 8; 13761 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13762 Elems |= Index; 13763 13764 return true; 13765 }; 13766 13767 // If the build vector operands aren't sign extended vector extracts, 13768 // of the same input vector, then return. 13769 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13770 if (!isSExtOfVecExtract(N->getOperand(i))) { 13771 return SDValue(); 13772 } 13773 } 13774 13775 // If the vector extract indicies are not correct, add the appropriate 13776 // vector_shuffle. 13777 int TgtElemArrayIdx; 13778 int InputSize = Input.getValueType().getScalarSizeInBits(); 13779 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13780 if (InputSize + OutputSize == 40) 13781 TgtElemArrayIdx = 0; 13782 else if (InputSize + OutputSize == 72) 13783 TgtElemArrayIdx = 1; 13784 else if (InputSize + OutputSize == 48) 13785 TgtElemArrayIdx = 2; 13786 else if (InputSize + OutputSize == 80) 13787 TgtElemArrayIdx = 3; 13788 else if (InputSize + OutputSize == 96) 13789 TgtElemArrayIdx = 4; 13790 else 13791 return SDValue(); 13792 13793 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13794 CorrectElems = DAG.getDataLayout().isLittleEndian() 13795 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13796 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13797 if (Elems != CorrectElems) { 13798 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13799 } 13800 13801 // Regular lowering will catch cases where a shuffle is not needed. 13802 return SDValue(); 13803 } 13804 13805 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13806 DAGCombinerInfo &DCI) const { 13807 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13808 "Should be called with a BUILD_VECTOR node"); 13809 13810 SelectionDAG &DAG = DCI.DAG; 13811 SDLoc dl(N); 13812 13813 if (!Subtarget.hasVSX()) 13814 return SDValue(); 13815 13816 // The target independent DAG combiner will leave a build_vector of 13817 // float-to-int conversions intact. We can generate MUCH better code for 13818 // a float-to-int conversion of a vector of floats. 13819 SDValue FirstInput = N->getOperand(0); 13820 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13821 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13822 if (Reduced) 13823 return Reduced; 13824 } 13825 13826 // If we're building a vector out of consecutive loads, just load that 13827 // vector type. 13828 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13829 if (Reduced) 13830 return Reduced; 13831 13832 // If we're building a vector out of extended elements from another vector 13833 // we have P9 vector integer extend instructions. The code assumes legal 13834 // input types (i.e. it can't handle things like v4i16) so do not run before 13835 // legalization. 13836 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13837 Reduced = combineBVOfVecSExt(N, DAG); 13838 if (Reduced) 13839 return Reduced; 13840 } 13841 13842 13843 if (N->getValueType(0) != MVT::v2f64) 13844 return SDValue(); 13845 13846 // Looking for: 13847 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13848 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13849 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13850 return SDValue(); 13851 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13852 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13853 return SDValue(); 13854 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13855 return SDValue(); 13856 13857 SDValue Ext1 = FirstInput.getOperand(0); 13858 SDValue Ext2 = N->getOperand(1).getOperand(0); 13859 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13860 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13861 return SDValue(); 13862 13863 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13864 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13865 if (!Ext1Op || !Ext2Op) 13866 return SDValue(); 13867 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13868 Ext1.getOperand(0) != Ext2.getOperand(0)) 13869 return SDValue(); 13870 13871 int FirstElem = Ext1Op->getZExtValue(); 13872 int SecondElem = Ext2Op->getZExtValue(); 13873 int SubvecIdx; 13874 if (FirstElem == 0 && SecondElem == 1) 13875 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13876 else if (FirstElem == 2 && SecondElem == 3) 13877 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13878 else 13879 return SDValue(); 13880 13881 SDValue SrcVec = Ext1.getOperand(0); 13882 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13883 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13884 return DAG.getNode(NodeType, dl, MVT::v2f64, 13885 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13886 } 13887 13888 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13889 DAGCombinerInfo &DCI) const { 13890 assert((N->getOpcode() == ISD::SINT_TO_FP || 13891 N->getOpcode() == ISD::UINT_TO_FP) && 13892 "Need an int -> FP conversion node here"); 13893 13894 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13895 return SDValue(); 13896 13897 SelectionDAG &DAG = DCI.DAG; 13898 SDLoc dl(N); 13899 SDValue Op(N, 0); 13900 13901 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13902 // from the hardware. 13903 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13904 return SDValue(); 13905 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13906 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13907 return SDValue(); 13908 13909 SDValue FirstOperand(Op.getOperand(0)); 13910 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13911 (FirstOperand.getValueType() == MVT::i8 || 13912 FirstOperand.getValueType() == MVT::i16); 13913 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13914 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13915 bool DstDouble = Op.getValueType() == MVT::f64; 13916 unsigned ConvOp = Signed ? 13917 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13918 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13919 SDValue WidthConst = 13920 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13921 dl, false); 13922 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13923 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13924 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13925 DAG.getVTList(MVT::f64, MVT::Other), 13926 Ops, MVT::i8, LDN->getMemOperand()); 13927 13928 // For signed conversion, we need to sign-extend the value in the VSR 13929 if (Signed) { 13930 SDValue ExtOps[] = { Ld, WidthConst }; 13931 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13932 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13933 } else 13934 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13935 } 13936 13937 13938 // For i32 intermediate values, unfortunately, the conversion functions 13939 // leave the upper 32 bits of the value are undefined. Within the set of 13940 // scalar instructions, we have no method for zero- or sign-extending the 13941 // value. Thus, we cannot handle i32 intermediate values here. 13942 if (Op.getOperand(0).getValueType() == MVT::i32) 13943 return SDValue(); 13944 13945 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13946 "UINT_TO_FP is supported only with FPCVT"); 13947 13948 // If we have FCFIDS, then use it when converting to single-precision. 13949 // Otherwise, convert to double-precision and then round. 13950 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13951 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13952 : PPCISD::FCFIDS) 13953 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13954 : PPCISD::FCFID); 13955 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13956 ? MVT::f32 13957 : MVT::f64; 13958 13959 // If we're converting from a float, to an int, and back to a float again, 13960 // then we don't need the store/load pair at all. 13961 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13962 Subtarget.hasFPCVT()) || 13963 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13964 SDValue Src = Op.getOperand(0).getOperand(0); 13965 if (Src.getValueType() == MVT::f32) { 13966 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13967 DCI.AddToWorklist(Src.getNode()); 13968 } else if (Src.getValueType() != MVT::f64) { 13969 // Make sure that we don't pick up a ppc_fp128 source value. 13970 return SDValue(); 13971 } 13972 13973 unsigned FCTOp = 13974 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13975 PPCISD::FCTIDUZ; 13976 13977 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13978 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13979 13980 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13981 FP = DAG.getNode(ISD::FP_ROUND, dl, 13982 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13983 DCI.AddToWorklist(FP.getNode()); 13984 } 13985 13986 return FP; 13987 } 13988 13989 return SDValue(); 13990 } 13991 13992 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13993 // builtins) into loads with swaps. 13994 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13995 DAGCombinerInfo &DCI) const { 13996 SelectionDAG &DAG = DCI.DAG; 13997 SDLoc dl(N); 13998 SDValue Chain; 13999 SDValue Base; 14000 MachineMemOperand *MMO; 14001 14002 switch (N->getOpcode()) { 14003 default: 14004 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14005 case ISD::LOAD: { 14006 LoadSDNode *LD = cast<LoadSDNode>(N); 14007 Chain = LD->getChain(); 14008 Base = LD->getBasePtr(); 14009 MMO = LD->getMemOperand(); 14010 // If the MMO suggests this isn't a load of a full vector, leave 14011 // things alone. For a built-in, we have to make the change for 14012 // correctness, so if there is a size problem that will be a bug. 14013 if (MMO->getSize() < 16) 14014 return SDValue(); 14015 break; 14016 } 14017 case ISD::INTRINSIC_W_CHAIN: { 14018 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14019 Chain = Intrin->getChain(); 14020 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14021 // us what we want. Get operand 2 instead. 14022 Base = Intrin->getOperand(2); 14023 MMO = Intrin->getMemOperand(); 14024 break; 14025 } 14026 } 14027 14028 MVT VecTy = N->getValueType(0).getSimpleVT(); 14029 14030 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 14031 // aligned and the type is a vector with elements up to 4 bytes 14032 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14033 VecTy.getScalarSizeInBits() <= 32) { 14034 return SDValue(); 14035 } 14036 14037 SDValue LoadOps[] = { Chain, Base }; 14038 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14039 DAG.getVTList(MVT::v2f64, MVT::Other), 14040 LoadOps, MVT::v2f64, MMO); 14041 14042 DCI.AddToWorklist(Load.getNode()); 14043 Chain = Load.getValue(1); 14044 SDValue Swap = DAG.getNode( 14045 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14046 DCI.AddToWorklist(Swap.getNode()); 14047 14048 // Add a bitcast if the resulting load type doesn't match v2f64. 14049 if (VecTy != MVT::v2f64) { 14050 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14051 DCI.AddToWorklist(N.getNode()); 14052 // Package {bitcast value, swap's chain} to match Load's shape. 14053 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14054 N, Swap.getValue(1)); 14055 } 14056 14057 return Swap; 14058 } 14059 14060 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14061 // builtins) into stores with swaps. 14062 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14063 DAGCombinerInfo &DCI) const { 14064 SelectionDAG &DAG = DCI.DAG; 14065 SDLoc dl(N); 14066 SDValue Chain; 14067 SDValue Base; 14068 unsigned SrcOpnd; 14069 MachineMemOperand *MMO; 14070 14071 switch (N->getOpcode()) { 14072 default: 14073 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14074 case ISD::STORE: { 14075 StoreSDNode *ST = cast<StoreSDNode>(N); 14076 Chain = ST->getChain(); 14077 Base = ST->getBasePtr(); 14078 MMO = ST->getMemOperand(); 14079 SrcOpnd = 1; 14080 // If the MMO suggests this isn't a store of a full vector, leave 14081 // things alone. For a built-in, we have to make the change for 14082 // correctness, so if there is a size problem that will be a bug. 14083 if (MMO->getSize() < 16) 14084 return SDValue(); 14085 break; 14086 } 14087 case ISD::INTRINSIC_VOID: { 14088 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14089 Chain = Intrin->getChain(); 14090 // Intrin->getBasePtr() oddly does not get what we want. 14091 Base = Intrin->getOperand(3); 14092 MMO = Intrin->getMemOperand(); 14093 SrcOpnd = 2; 14094 break; 14095 } 14096 } 14097 14098 SDValue Src = N->getOperand(SrcOpnd); 14099 MVT VecTy = Src.getValueType().getSimpleVT(); 14100 14101 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 14102 // aligned and the type is a vector with elements up to 4 bytes 14103 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 14104 VecTy.getScalarSizeInBits() <= 32) { 14105 return SDValue(); 14106 } 14107 14108 // All stores are done as v2f64 and possible bit cast. 14109 if (VecTy != MVT::v2f64) { 14110 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14111 DCI.AddToWorklist(Src.getNode()); 14112 } 14113 14114 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14115 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14116 DCI.AddToWorklist(Swap.getNode()); 14117 Chain = Swap.getValue(1); 14118 SDValue StoreOps[] = { Chain, Swap, Base }; 14119 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14120 DAG.getVTList(MVT::Other), 14121 StoreOps, VecTy, MMO); 14122 DCI.AddToWorklist(Store.getNode()); 14123 return Store; 14124 } 14125 14126 // Handle DAG combine for STORE (FP_TO_INT F). 14127 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14128 DAGCombinerInfo &DCI) const { 14129 14130 SelectionDAG &DAG = DCI.DAG; 14131 SDLoc dl(N); 14132 unsigned Opcode = N->getOperand(1).getOpcode(); 14133 14134 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14135 && "Not a FP_TO_INT Instruction!"); 14136 14137 SDValue Val = N->getOperand(1).getOperand(0); 14138 EVT Op1VT = N->getOperand(1).getValueType(); 14139 EVT ResVT = Val.getValueType(); 14140 14141 // Floating point types smaller than 32 bits are not legal on Power. 14142 if (ResVT.getScalarSizeInBits() < 32) 14143 return SDValue(); 14144 14145 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14146 bool ValidTypeForStoreFltAsInt = 14147 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14148 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14149 14150 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14151 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14152 return SDValue(); 14153 14154 // Extend f32 values to f64 14155 if (ResVT.getScalarSizeInBits() == 32) { 14156 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14157 DCI.AddToWorklist(Val.getNode()); 14158 } 14159 14160 // Set signed or unsigned conversion opcode. 14161 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14162 PPCISD::FP_TO_SINT_IN_VSR : 14163 PPCISD::FP_TO_UINT_IN_VSR; 14164 14165 Val = DAG.getNode(ConvOpcode, 14166 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14167 DCI.AddToWorklist(Val.getNode()); 14168 14169 // Set number of bytes being converted. 14170 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14171 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14172 DAG.getIntPtrConstant(ByteSize, dl, false), 14173 DAG.getValueType(Op1VT) }; 14174 14175 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14176 DAG.getVTList(MVT::Other), Ops, 14177 cast<StoreSDNode>(N)->getMemoryVT(), 14178 cast<StoreSDNode>(N)->getMemOperand()); 14179 14180 DCI.AddToWorklist(Val.getNode()); 14181 return Val; 14182 } 14183 14184 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14185 // Check that the source of the element keeps flipping 14186 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14187 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14188 for (int i = 1, e = Mask.size(); i < e; i++) { 14189 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14190 return false; 14191 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14192 return false; 14193 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14194 } 14195 return true; 14196 } 14197 14198 static bool isSplatBV(SDValue Op) { 14199 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14200 return false; 14201 SDValue FirstOp; 14202 14203 // Find first non-undef input. 14204 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14205 FirstOp = Op.getOperand(i); 14206 if (!FirstOp.isUndef()) 14207 break; 14208 } 14209 14210 // All inputs are undef or the same as the first non-undef input. 14211 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14212 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14213 return false; 14214 return true; 14215 } 14216 14217 static SDValue isScalarToVec(SDValue Op) { 14218 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14219 return Op; 14220 if (Op.getOpcode() != ISD::BITCAST) 14221 return SDValue(); 14222 Op = Op.getOperand(0); 14223 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14224 return Op; 14225 return SDValue(); 14226 } 14227 14228 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14229 int LHSMaxIdx, int RHSMinIdx, 14230 int RHSMaxIdx, int HalfVec) { 14231 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14232 int Idx = ShuffV[i]; 14233 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14234 ShuffV[i] += HalfVec; 14235 } 14236 return; 14237 } 14238 14239 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14240 // the original is: 14241 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14242 // In such a case, just change the shuffle mask to extract the element 14243 // from the permuted index. 14244 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 14245 SDLoc dl(OrigSToV); 14246 EVT VT = OrigSToV.getValueType(); 14247 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14248 "Expecting a SCALAR_TO_VECTOR here"); 14249 SDValue Input = OrigSToV.getOperand(0); 14250 14251 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14252 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14253 SDValue OrigVector = Input.getOperand(0); 14254 14255 // Can't handle non-const element indices or different vector types 14256 // for the input to the extract and the output of the scalar_to_vector. 14257 if (Idx && VT == OrigVector.getValueType()) { 14258 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 14259 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 14260 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14261 } 14262 } 14263 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14264 OrigSToV.getOperand(0)); 14265 } 14266 14267 // On little endian subtargets, combine shuffles such as: 14268 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14269 // into: 14270 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14271 // because the latter can be matched to a single instruction merge. 14272 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14273 // to put the value into element zero. Adjust the shuffle mask so that the 14274 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14275 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14276 SelectionDAG &DAG) const { 14277 SDValue LHS = SVN->getOperand(0); 14278 SDValue RHS = SVN->getOperand(1); 14279 auto Mask = SVN->getMask(); 14280 int NumElts = LHS.getValueType().getVectorNumElements(); 14281 SDValue Res(SVN, 0); 14282 SDLoc dl(SVN); 14283 14284 // None of these combines are useful on big endian systems since the ISA 14285 // already has a big endian bias. 14286 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14287 return Res; 14288 14289 // If this is not a shuffle of a shuffle and the first element comes from 14290 // the second vector, canonicalize to the commuted form. This will make it 14291 // more likely to match one of the single instruction patterns. 14292 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14293 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14294 std::swap(LHS, RHS); 14295 Res = DAG.getCommutedVectorShuffle(*SVN); 14296 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14297 } 14298 14299 // Adjust the shuffle mask if either input vector comes from a 14300 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14301 // form (to prevent the need for a swap). 14302 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14303 SDValue SToVLHS = isScalarToVec(LHS); 14304 SDValue SToVRHS = isScalarToVec(RHS); 14305 if (SToVLHS || SToVRHS) { 14306 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14307 : SToVRHS.getValueType().getVectorNumElements(); 14308 int NumEltsOut = ShuffV.size(); 14309 14310 // Initially assume that neither input is permuted. These will be adjusted 14311 // accordingly if either input is. 14312 int LHSMaxIdx = -1; 14313 int RHSMinIdx = -1; 14314 int RHSMaxIdx = -1; 14315 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14316 14317 // Get the permuted scalar to vector nodes for the source(s) that come from 14318 // ISD::SCALAR_TO_VECTOR. 14319 if (SToVLHS) { 14320 // Set up the values for the shuffle vector fixup. 14321 LHSMaxIdx = NumEltsOut / NumEltsIn; 14322 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14323 if (SToVLHS.getValueType() != LHS.getValueType()) 14324 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14325 LHS = SToVLHS; 14326 } 14327 if (SToVRHS) { 14328 RHSMinIdx = NumEltsOut; 14329 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14330 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14331 if (SToVRHS.getValueType() != RHS.getValueType()) 14332 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14333 RHS = SToVRHS; 14334 } 14335 14336 // Fix up the shuffle mask to reflect where the desired element actually is. 14337 // The minimum and maximum indices that correspond to element zero for both 14338 // the LHS and RHS are computed and will control which shuffle mask entries 14339 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14340 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14341 // HalfVec to refer to the corresponding element in the permuted vector. 14342 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14343 HalfVec); 14344 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14345 14346 // We may have simplified away the shuffle. We won't be able to do anything 14347 // further with it here. 14348 if (!isa<ShuffleVectorSDNode>(Res)) 14349 return Res; 14350 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14351 } 14352 14353 // The common case after we commuted the shuffle is that the RHS is a splat 14354 // and we have elements coming in from the splat at indices that are not 14355 // conducive to using a merge. 14356 // Example: 14357 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14358 if (!isSplatBV(RHS)) 14359 return Res; 14360 14361 // We are looking for a mask such that all even elements are from 14362 // one vector and all odd elements from the other. 14363 if (!isAlternatingShuffMask(Mask, NumElts)) 14364 return Res; 14365 14366 // Adjust the mask so we are pulling in the same index from the splat 14367 // as the index from the interesting vector in consecutive elements. 14368 // Example (even elements from first vector): 14369 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14370 if (Mask[0] < NumElts) 14371 for (int i = 1, e = Mask.size(); i < e; i += 2) 14372 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14373 // Example (odd elements from first vector): 14374 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14375 else 14376 for (int i = 0, e = Mask.size(); i < e; i += 2) 14377 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14378 14379 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14380 return Res; 14381 } 14382 14383 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14384 LSBaseSDNode *LSBase, 14385 DAGCombinerInfo &DCI) const { 14386 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14387 "Not a reverse memop pattern!"); 14388 14389 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14390 auto Mask = SVN->getMask(); 14391 int i = 0; 14392 auto I = Mask.rbegin(); 14393 auto E = Mask.rend(); 14394 14395 for (; I != E; ++I) { 14396 if (*I != i) 14397 return false; 14398 i++; 14399 } 14400 return true; 14401 }; 14402 14403 SelectionDAG &DAG = DCI.DAG; 14404 EVT VT = SVN->getValueType(0); 14405 14406 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14407 return SDValue(); 14408 14409 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14410 // See comment in PPCVSXSwapRemoval.cpp. 14411 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14412 if (!Subtarget.hasP9Vector()) 14413 return SDValue(); 14414 14415 if(!IsElementReverse(SVN)) 14416 return SDValue(); 14417 14418 if (LSBase->getOpcode() == ISD::LOAD) { 14419 SDLoc dl(SVN); 14420 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14421 return DAG.getMemIntrinsicNode( 14422 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14423 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14424 } 14425 14426 if (LSBase->getOpcode() == ISD::STORE) { 14427 SDLoc dl(LSBase); 14428 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14429 LSBase->getBasePtr()}; 14430 return DAG.getMemIntrinsicNode( 14431 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14432 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14433 } 14434 14435 llvm_unreachable("Expected a load or store node here"); 14436 } 14437 14438 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14439 DAGCombinerInfo &DCI) const { 14440 SelectionDAG &DAG = DCI.DAG; 14441 SDLoc dl(N); 14442 switch (N->getOpcode()) { 14443 default: break; 14444 case ISD::ADD: 14445 return combineADD(N, DCI); 14446 case ISD::SHL: 14447 return combineSHL(N, DCI); 14448 case ISD::SRA: 14449 return combineSRA(N, DCI); 14450 case ISD::SRL: 14451 return combineSRL(N, DCI); 14452 case ISD::MUL: 14453 return combineMUL(N, DCI); 14454 case ISD::FMA: 14455 case PPCISD::FNMSUB: 14456 return combineFMALike(N, DCI); 14457 case PPCISD::SHL: 14458 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14459 return N->getOperand(0); 14460 break; 14461 case PPCISD::SRL: 14462 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14463 return N->getOperand(0); 14464 break; 14465 case PPCISD::SRA: 14466 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14467 if (C->isNullValue() || // 0 >>s V -> 0. 14468 C->isAllOnesValue()) // -1 >>s V -> -1. 14469 return N->getOperand(0); 14470 } 14471 break; 14472 case ISD::SIGN_EXTEND: 14473 case ISD::ZERO_EXTEND: 14474 case ISD::ANY_EXTEND: 14475 return DAGCombineExtBoolTrunc(N, DCI); 14476 case ISD::TRUNCATE: 14477 return combineTRUNCATE(N, DCI); 14478 case ISD::SETCC: 14479 if (SDValue CSCC = combineSetCC(N, DCI)) 14480 return CSCC; 14481 LLVM_FALLTHROUGH; 14482 case ISD::SELECT_CC: 14483 return DAGCombineTruncBoolExt(N, DCI); 14484 case ISD::SINT_TO_FP: 14485 case ISD::UINT_TO_FP: 14486 return combineFPToIntToFP(N, DCI); 14487 case ISD::VECTOR_SHUFFLE: 14488 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14489 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14490 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14491 } 14492 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14493 case ISD::STORE: { 14494 14495 EVT Op1VT = N->getOperand(1).getValueType(); 14496 unsigned Opcode = N->getOperand(1).getOpcode(); 14497 14498 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14499 SDValue Val= combineStoreFPToInt(N, DCI); 14500 if (Val) 14501 return Val; 14502 } 14503 14504 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14505 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14506 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14507 if (Val) 14508 return Val; 14509 } 14510 14511 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14512 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14513 N->getOperand(1).getNode()->hasOneUse() && 14514 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14515 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14516 14517 // STBRX can only handle simple types and it makes no sense to store less 14518 // two bytes in byte-reversed order. 14519 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14520 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14521 break; 14522 14523 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14524 // Do an any-extend to 32-bits if this is a half-word input. 14525 if (BSwapOp.getValueType() == MVT::i16) 14526 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14527 14528 // If the type of BSWAP operand is wider than stored memory width 14529 // it need to be shifted to the right side before STBRX. 14530 if (Op1VT.bitsGT(mVT)) { 14531 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14532 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14533 DAG.getConstant(Shift, dl, MVT::i32)); 14534 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14535 if (Op1VT == MVT::i64) 14536 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14537 } 14538 14539 SDValue Ops[] = { 14540 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14541 }; 14542 return 14543 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14544 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14545 cast<StoreSDNode>(N)->getMemOperand()); 14546 } 14547 14548 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14549 // So it can increase the chance of CSE constant construction. 14550 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14551 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14552 // Need to sign-extended to 64-bits to handle negative values. 14553 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14554 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14555 MemVT.getSizeInBits()); 14556 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14557 14558 // DAG.getTruncStore() can't be used here because it doesn't accept 14559 // the general (base + offset) addressing mode. 14560 // So we use UpdateNodeOperands and setTruncatingStore instead. 14561 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14562 N->getOperand(3)); 14563 cast<StoreSDNode>(N)->setTruncatingStore(true); 14564 return SDValue(N, 0); 14565 } 14566 14567 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14568 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14569 if (Op1VT.isSimple()) { 14570 MVT StoreVT = Op1VT.getSimpleVT(); 14571 if (Subtarget.needsSwapsForVSXMemOps() && 14572 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14573 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14574 return expandVSXStoreForLE(N, DCI); 14575 } 14576 break; 14577 } 14578 case ISD::LOAD: { 14579 LoadSDNode *LD = cast<LoadSDNode>(N); 14580 EVT VT = LD->getValueType(0); 14581 14582 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14583 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14584 if (VT.isSimple()) { 14585 MVT LoadVT = VT.getSimpleVT(); 14586 if (Subtarget.needsSwapsForVSXMemOps() && 14587 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14588 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14589 return expandVSXLoadForLE(N, DCI); 14590 } 14591 14592 // We sometimes end up with a 64-bit integer load, from which we extract 14593 // two single-precision floating-point numbers. This happens with 14594 // std::complex<float>, and other similar structures, because of the way we 14595 // canonicalize structure copies. However, if we lack direct moves, 14596 // then the final bitcasts from the extracted integer values to the 14597 // floating-point numbers turn into store/load pairs. Even with direct moves, 14598 // just loading the two floating-point numbers is likely better. 14599 auto ReplaceTwoFloatLoad = [&]() { 14600 if (VT != MVT::i64) 14601 return false; 14602 14603 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14604 LD->isVolatile()) 14605 return false; 14606 14607 // We're looking for a sequence like this: 14608 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14609 // t16: i64 = srl t13, Constant:i32<32> 14610 // t17: i32 = truncate t16 14611 // t18: f32 = bitcast t17 14612 // t19: i32 = truncate t13 14613 // t20: f32 = bitcast t19 14614 14615 if (!LD->hasNUsesOfValue(2, 0)) 14616 return false; 14617 14618 auto UI = LD->use_begin(); 14619 while (UI.getUse().getResNo() != 0) ++UI; 14620 SDNode *Trunc = *UI++; 14621 while (UI.getUse().getResNo() != 0) ++UI; 14622 SDNode *RightShift = *UI; 14623 if (Trunc->getOpcode() != ISD::TRUNCATE) 14624 std::swap(Trunc, RightShift); 14625 14626 if (Trunc->getOpcode() != ISD::TRUNCATE || 14627 Trunc->getValueType(0) != MVT::i32 || 14628 !Trunc->hasOneUse()) 14629 return false; 14630 if (RightShift->getOpcode() != ISD::SRL || 14631 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14632 RightShift->getConstantOperandVal(1) != 32 || 14633 !RightShift->hasOneUse()) 14634 return false; 14635 14636 SDNode *Trunc2 = *RightShift->use_begin(); 14637 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14638 Trunc2->getValueType(0) != MVT::i32 || 14639 !Trunc2->hasOneUse()) 14640 return false; 14641 14642 SDNode *Bitcast = *Trunc->use_begin(); 14643 SDNode *Bitcast2 = *Trunc2->use_begin(); 14644 14645 if (Bitcast->getOpcode() != ISD::BITCAST || 14646 Bitcast->getValueType(0) != MVT::f32) 14647 return false; 14648 if (Bitcast2->getOpcode() != ISD::BITCAST || 14649 Bitcast2->getValueType(0) != MVT::f32) 14650 return false; 14651 14652 if (Subtarget.isLittleEndian()) 14653 std::swap(Bitcast, Bitcast2); 14654 14655 // Bitcast has the second float (in memory-layout order) and Bitcast2 14656 // has the first one. 14657 14658 SDValue BasePtr = LD->getBasePtr(); 14659 if (LD->isIndexed()) { 14660 assert(LD->getAddressingMode() == ISD::PRE_INC && 14661 "Non-pre-inc AM on PPC?"); 14662 BasePtr = 14663 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14664 LD->getOffset()); 14665 } 14666 14667 auto MMOFlags = 14668 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14669 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14670 LD->getPointerInfo(), LD->getAlignment(), 14671 MMOFlags, LD->getAAInfo()); 14672 SDValue AddPtr = 14673 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14674 BasePtr, DAG.getIntPtrConstant(4, dl)); 14675 SDValue FloatLoad2 = DAG.getLoad( 14676 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14677 LD->getPointerInfo().getWithOffset(4), 14678 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14679 14680 if (LD->isIndexed()) { 14681 // Note that DAGCombine should re-form any pre-increment load(s) from 14682 // what is produced here if that makes sense. 14683 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14684 } 14685 14686 DCI.CombineTo(Bitcast2, FloatLoad); 14687 DCI.CombineTo(Bitcast, FloatLoad2); 14688 14689 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14690 SDValue(FloatLoad2.getNode(), 1)); 14691 return true; 14692 }; 14693 14694 if (ReplaceTwoFloatLoad()) 14695 return SDValue(N, 0); 14696 14697 EVT MemVT = LD->getMemoryVT(); 14698 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14699 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 14700 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 14701 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 14702 if (LD->isUnindexed() && VT.isVector() && 14703 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14704 // P8 and later hardware should just use LOAD. 14705 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 14706 VT == MVT::v4i32 || VT == MVT::v4f32)) || 14707 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 14708 LD->getAlignment() >= ScalarABIAlignment)) && 14709 LD->getAlignment() < ABIAlignment) { 14710 // This is a type-legal unaligned Altivec or QPX load. 14711 SDValue Chain = LD->getChain(); 14712 SDValue Ptr = LD->getBasePtr(); 14713 bool isLittleEndian = Subtarget.isLittleEndian(); 14714 14715 // This implements the loading of unaligned vectors as described in 14716 // the venerable Apple Velocity Engine overview. Specifically: 14717 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14718 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14719 // 14720 // The general idea is to expand a sequence of one or more unaligned 14721 // loads into an alignment-based permutation-control instruction (lvsl 14722 // or lvsr), a series of regular vector loads (which always truncate 14723 // their input address to an aligned address), and a series of 14724 // permutations. The results of these permutations are the requested 14725 // loaded values. The trick is that the last "extra" load is not taken 14726 // from the address you might suspect (sizeof(vector) bytes after the 14727 // last requested load), but rather sizeof(vector) - 1 bytes after the 14728 // last requested vector. The point of this is to avoid a page fault if 14729 // the base address happened to be aligned. This works because if the 14730 // base address is aligned, then adding less than a full vector length 14731 // will cause the last vector in the sequence to be (re)loaded. 14732 // Otherwise, the next vector will be fetched as you might suspect was 14733 // necessary. 14734 14735 // We might be able to reuse the permutation generation from 14736 // a different base address offset from this one by an aligned amount. 14737 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14738 // optimization later. 14739 Intrinsic::ID Intr, IntrLD, IntrPerm; 14740 MVT PermCntlTy, PermTy, LDTy; 14741 if (Subtarget.hasAltivec()) { 14742 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 14743 Intrinsic::ppc_altivec_lvsl; 14744 IntrLD = Intrinsic::ppc_altivec_lvx; 14745 IntrPerm = Intrinsic::ppc_altivec_vperm; 14746 PermCntlTy = MVT::v16i8; 14747 PermTy = MVT::v4i32; 14748 LDTy = MVT::v4i32; 14749 } else { 14750 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 14751 Intrinsic::ppc_qpx_qvlpcls; 14752 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 14753 Intrinsic::ppc_qpx_qvlfs; 14754 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 14755 PermCntlTy = MVT::v4f64; 14756 PermTy = MVT::v4f64; 14757 LDTy = MemVT.getSimpleVT(); 14758 } 14759 14760 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14761 14762 // Create the new MMO for the new base load. It is like the original MMO, 14763 // but represents an area in memory almost twice the vector size centered 14764 // on the original address. If the address is unaligned, we might start 14765 // reading up to (sizeof(vector)-1) bytes below the address of the 14766 // original unaligned load. 14767 MachineFunction &MF = DAG.getMachineFunction(); 14768 MachineMemOperand *BaseMMO = 14769 MF.getMachineMemOperand(LD->getMemOperand(), 14770 -(long)MemVT.getStoreSize()+1, 14771 2*MemVT.getStoreSize()-1); 14772 14773 // Create the new base load. 14774 SDValue LDXIntID = 14775 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14776 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14777 SDValue BaseLoad = 14778 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14779 DAG.getVTList(PermTy, MVT::Other), 14780 BaseLoadOps, LDTy, BaseMMO); 14781 14782 // Note that the value of IncOffset (which is provided to the next 14783 // load's pointer info offset value, and thus used to calculate the 14784 // alignment), and the value of IncValue (which is actually used to 14785 // increment the pointer value) are different! This is because we 14786 // require the next load to appear to be aligned, even though it 14787 // is actually offset from the base pointer by a lesser amount. 14788 int IncOffset = VT.getSizeInBits() / 8; 14789 int IncValue = IncOffset; 14790 14791 // Walk (both up and down) the chain looking for another load at the real 14792 // (aligned) offset (the alignment of the other load does not matter in 14793 // this case). If found, then do not use the offset reduction trick, as 14794 // that will prevent the loads from being later combined (as they would 14795 // otherwise be duplicates). 14796 if (!findConsecutiveLoad(LD, DAG)) 14797 --IncValue; 14798 14799 SDValue Increment = 14800 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14801 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14802 14803 MachineMemOperand *ExtraMMO = 14804 MF.getMachineMemOperand(LD->getMemOperand(), 14805 1, 2*MemVT.getStoreSize()-1); 14806 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14807 SDValue ExtraLoad = 14808 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14809 DAG.getVTList(PermTy, MVT::Other), 14810 ExtraLoadOps, LDTy, ExtraMMO); 14811 14812 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14813 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14814 14815 // Because vperm has a big-endian bias, we must reverse the order 14816 // of the input vectors and complement the permute control vector 14817 // when generating little endian code. We have already handled the 14818 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14819 // and ExtraLoad here. 14820 SDValue Perm; 14821 if (isLittleEndian) 14822 Perm = BuildIntrinsicOp(IntrPerm, 14823 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14824 else 14825 Perm = BuildIntrinsicOp(IntrPerm, 14826 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14827 14828 if (VT != PermTy) 14829 Perm = Subtarget.hasAltivec() ? 14830 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14831 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14832 DAG.getTargetConstant(1, dl, MVT::i64)); 14833 // second argument is 1 because this rounding 14834 // is always exact. 14835 14836 // The output of the permutation is our loaded result, the TokenFactor is 14837 // our new chain. 14838 DCI.CombineTo(N, Perm, TF); 14839 return SDValue(N, 0); 14840 } 14841 } 14842 break; 14843 case ISD::INTRINSIC_WO_CHAIN: { 14844 bool isLittleEndian = Subtarget.isLittleEndian(); 14845 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14846 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14847 : Intrinsic::ppc_altivec_lvsl); 14848 if ((IID == Intr || 14849 IID == Intrinsic::ppc_qpx_qvlpcld || 14850 IID == Intrinsic::ppc_qpx_qvlpcls) && 14851 N->getOperand(1)->getOpcode() == ISD::ADD) { 14852 SDValue Add = N->getOperand(1); 14853 14854 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14855 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14856 14857 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14858 APInt::getAllOnesValue(Bits /* alignment */) 14859 .zext(Add.getScalarValueSizeInBits()))) { 14860 SDNode *BasePtr = Add->getOperand(0).getNode(); 14861 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14862 UE = BasePtr->use_end(); 14863 UI != UE; ++UI) { 14864 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14865 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14866 // We've found another LVSL/LVSR, and this address is an aligned 14867 // multiple of that one. The results will be the same, so use the 14868 // one we've just found instead. 14869 14870 return SDValue(*UI, 0); 14871 } 14872 } 14873 } 14874 14875 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14876 SDNode *BasePtr = Add->getOperand(0).getNode(); 14877 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14878 UE = BasePtr->use_end(); UI != UE; ++UI) { 14879 if (UI->getOpcode() == ISD::ADD && 14880 isa<ConstantSDNode>(UI->getOperand(1)) && 14881 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14882 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14883 (1ULL << Bits) == 0) { 14884 SDNode *OtherAdd = *UI; 14885 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14886 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14887 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14888 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14889 return SDValue(*VI, 0); 14890 } 14891 } 14892 } 14893 } 14894 } 14895 } 14896 14897 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14898 // Expose the vabsduw/h/b opportunity for down stream 14899 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14900 (IID == Intrinsic::ppc_altivec_vmaxsw || 14901 IID == Intrinsic::ppc_altivec_vmaxsh || 14902 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14903 SDValue V1 = N->getOperand(1); 14904 SDValue V2 = N->getOperand(2); 14905 if ((V1.getSimpleValueType() == MVT::v4i32 || 14906 V1.getSimpleValueType() == MVT::v8i16 || 14907 V1.getSimpleValueType() == MVT::v16i8) && 14908 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14909 // (0-a, a) 14910 if (V1.getOpcode() == ISD::SUB && 14911 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14912 V1.getOperand(1) == V2) { 14913 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14914 } 14915 // (a, 0-a) 14916 if (V2.getOpcode() == ISD::SUB && 14917 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14918 V2.getOperand(1) == V1) { 14919 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14920 } 14921 // (x-y, y-x) 14922 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14923 V1.getOperand(0) == V2.getOperand(1) && 14924 V1.getOperand(1) == V2.getOperand(0)) { 14925 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14926 } 14927 } 14928 } 14929 } 14930 14931 break; 14932 case ISD::INTRINSIC_W_CHAIN: 14933 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14934 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14935 if (Subtarget.needsSwapsForVSXMemOps()) { 14936 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14937 default: 14938 break; 14939 case Intrinsic::ppc_vsx_lxvw4x: 14940 case Intrinsic::ppc_vsx_lxvd2x: 14941 return expandVSXLoadForLE(N, DCI); 14942 } 14943 } 14944 break; 14945 case ISD::INTRINSIC_VOID: 14946 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14947 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14948 if (Subtarget.needsSwapsForVSXMemOps()) { 14949 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14950 default: 14951 break; 14952 case Intrinsic::ppc_vsx_stxvw4x: 14953 case Intrinsic::ppc_vsx_stxvd2x: 14954 return expandVSXStoreForLE(N, DCI); 14955 } 14956 } 14957 break; 14958 case ISD::BSWAP: 14959 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14960 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14961 N->getOperand(0).hasOneUse() && 14962 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14963 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14964 N->getValueType(0) == MVT::i64))) { 14965 SDValue Load = N->getOperand(0); 14966 LoadSDNode *LD = cast<LoadSDNode>(Load); 14967 // Create the byte-swapping load. 14968 SDValue Ops[] = { 14969 LD->getChain(), // Chain 14970 LD->getBasePtr(), // Ptr 14971 DAG.getValueType(N->getValueType(0)) // VT 14972 }; 14973 SDValue BSLoad = 14974 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14975 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14976 MVT::i64 : MVT::i32, MVT::Other), 14977 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14978 14979 // If this is an i16 load, insert the truncate. 14980 SDValue ResVal = BSLoad; 14981 if (N->getValueType(0) == MVT::i16) 14982 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14983 14984 // First, combine the bswap away. This makes the value produced by the 14985 // load dead. 14986 DCI.CombineTo(N, ResVal); 14987 14988 // Next, combine the load away, we give it a bogus result value but a real 14989 // chain result. The result value is dead because the bswap is dead. 14990 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14991 14992 // Return N so it doesn't get rechecked! 14993 return SDValue(N, 0); 14994 } 14995 break; 14996 case PPCISD::VCMP: 14997 // If a VCMPo node already exists with exactly the same operands as this 14998 // node, use its result instead of this node (VCMPo computes both a CR6 and 14999 // a normal output). 15000 // 15001 if (!N->getOperand(0).hasOneUse() && 15002 !N->getOperand(1).hasOneUse() && 15003 !N->getOperand(2).hasOneUse()) { 15004 15005 // Scan all of the users of the LHS, looking for VCMPo's that match. 15006 SDNode *VCMPoNode = nullptr; 15007 15008 SDNode *LHSN = N->getOperand(0).getNode(); 15009 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15010 UI != E; ++UI) 15011 if (UI->getOpcode() == PPCISD::VCMPo && 15012 UI->getOperand(1) == N->getOperand(1) && 15013 UI->getOperand(2) == N->getOperand(2) && 15014 UI->getOperand(0) == N->getOperand(0)) { 15015 VCMPoNode = *UI; 15016 break; 15017 } 15018 15019 // If there is no VCMPo node, or if the flag value has a single use, don't 15020 // transform this. 15021 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 15022 break; 15023 15024 // Look at the (necessarily single) use of the flag value. If it has a 15025 // chain, this transformation is more complex. Note that multiple things 15026 // could use the value result, which we should ignore. 15027 SDNode *FlagUser = nullptr; 15028 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 15029 FlagUser == nullptr; ++UI) { 15030 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 15031 SDNode *User = *UI; 15032 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15033 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 15034 FlagUser = User; 15035 break; 15036 } 15037 } 15038 } 15039 15040 // If the user is a MFOCRF instruction, we know this is safe. 15041 // Otherwise we give up for right now. 15042 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15043 return SDValue(VCMPoNode, 0); 15044 } 15045 break; 15046 case ISD::BRCOND: { 15047 SDValue Cond = N->getOperand(1); 15048 SDValue Target = N->getOperand(2); 15049 15050 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15051 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15052 Intrinsic::loop_decrement) { 15053 15054 // We now need to make the intrinsic dead (it cannot be instruction 15055 // selected). 15056 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15057 assert(Cond.getNode()->hasOneUse() && 15058 "Counter decrement has more than one use"); 15059 15060 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15061 N->getOperand(0), Target); 15062 } 15063 } 15064 break; 15065 case ISD::BR_CC: { 15066 // If this is a branch on an altivec predicate comparison, lower this so 15067 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15068 // lowering is done pre-legalize, because the legalizer lowers the predicate 15069 // compare down to code that is difficult to reassemble. 15070 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15071 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15072 15073 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15074 // value. If so, pass-through the AND to get to the intrinsic. 15075 if (LHS.getOpcode() == ISD::AND && 15076 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15077 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15078 Intrinsic::loop_decrement && 15079 isa<ConstantSDNode>(LHS.getOperand(1)) && 15080 !isNullConstant(LHS.getOperand(1))) 15081 LHS = LHS.getOperand(0); 15082 15083 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15084 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15085 Intrinsic::loop_decrement && 15086 isa<ConstantSDNode>(RHS)) { 15087 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15088 "Counter decrement comparison is not EQ or NE"); 15089 15090 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15091 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15092 (CC == ISD::SETNE && !Val); 15093 15094 // We now need to make the intrinsic dead (it cannot be instruction 15095 // selected). 15096 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15097 assert(LHS.getNode()->hasOneUse() && 15098 "Counter decrement has more than one use"); 15099 15100 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15101 N->getOperand(0), N->getOperand(4)); 15102 } 15103 15104 int CompareOpc; 15105 bool isDot; 15106 15107 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15108 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15109 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15110 assert(isDot && "Can't compare against a vector result!"); 15111 15112 // If this is a comparison against something other than 0/1, then we know 15113 // that the condition is never/always true. 15114 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15115 if (Val != 0 && Val != 1) { 15116 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15117 return N->getOperand(0); 15118 // Always !=, turn it into an unconditional branch. 15119 return DAG.getNode(ISD::BR, dl, MVT::Other, 15120 N->getOperand(0), N->getOperand(4)); 15121 } 15122 15123 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15124 15125 // Create the PPCISD altivec 'dot' comparison node. 15126 SDValue Ops[] = { 15127 LHS.getOperand(2), // LHS of compare 15128 LHS.getOperand(3), // RHS of compare 15129 DAG.getConstant(CompareOpc, dl, MVT::i32) 15130 }; 15131 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15132 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 15133 15134 // Unpack the result based on how the target uses it. 15135 PPC::Predicate CompOpc; 15136 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15137 default: // Can't happen, don't crash on invalid number though. 15138 case 0: // Branch on the value of the EQ bit of CR6. 15139 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15140 break; 15141 case 1: // Branch on the inverted value of the EQ bit of CR6. 15142 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15143 break; 15144 case 2: // Branch on the value of the LT bit of CR6. 15145 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15146 break; 15147 case 3: // Branch on the inverted value of the LT bit of CR6. 15148 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15149 break; 15150 } 15151 15152 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15153 DAG.getConstant(CompOpc, dl, MVT::i32), 15154 DAG.getRegister(PPC::CR6, MVT::i32), 15155 N->getOperand(4), CompNode.getValue(1)); 15156 } 15157 break; 15158 } 15159 case ISD::BUILD_VECTOR: 15160 return DAGCombineBuildVector(N, DCI); 15161 case ISD::ABS: 15162 return combineABS(N, DCI); 15163 case ISD::VSELECT: 15164 return combineVSelect(N, DCI); 15165 } 15166 15167 return SDValue(); 15168 } 15169 15170 SDValue 15171 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15172 SelectionDAG &DAG, 15173 SmallVectorImpl<SDNode *> &Created) const { 15174 // fold (sdiv X, pow2) 15175 EVT VT = N->getValueType(0); 15176 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15177 return SDValue(); 15178 if ((VT != MVT::i32 && VT != MVT::i64) || 15179 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15180 return SDValue(); 15181 15182 SDLoc DL(N); 15183 SDValue N0 = N->getOperand(0); 15184 15185 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15186 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15187 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15188 15189 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15190 Created.push_back(Op.getNode()); 15191 15192 if (IsNegPow2) { 15193 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15194 Created.push_back(Op.getNode()); 15195 } 15196 15197 return Op; 15198 } 15199 15200 //===----------------------------------------------------------------------===// 15201 // Inline Assembly Support 15202 //===----------------------------------------------------------------------===// 15203 15204 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15205 KnownBits &Known, 15206 const APInt &DemandedElts, 15207 const SelectionDAG &DAG, 15208 unsigned Depth) const { 15209 Known.resetAll(); 15210 switch (Op.getOpcode()) { 15211 default: break; 15212 case PPCISD::LBRX: { 15213 // lhbrx is known to have the top bits cleared out. 15214 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15215 Known.Zero = 0xFFFF0000; 15216 break; 15217 } 15218 case ISD::INTRINSIC_WO_CHAIN: { 15219 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15220 default: break; 15221 case Intrinsic::ppc_altivec_vcmpbfp_p: 15222 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15223 case Intrinsic::ppc_altivec_vcmpequb_p: 15224 case Intrinsic::ppc_altivec_vcmpequh_p: 15225 case Intrinsic::ppc_altivec_vcmpequw_p: 15226 case Intrinsic::ppc_altivec_vcmpequd_p: 15227 case Intrinsic::ppc_altivec_vcmpgefp_p: 15228 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15229 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15230 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15231 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15232 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15233 case Intrinsic::ppc_altivec_vcmpgtub_p: 15234 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15235 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15236 case Intrinsic::ppc_altivec_vcmpgtud_p: 15237 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15238 break; 15239 } 15240 } 15241 } 15242 } 15243 15244 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15245 switch (Subtarget.getCPUDirective()) { 15246 default: break; 15247 case PPC::DIR_970: 15248 case PPC::DIR_PWR4: 15249 case PPC::DIR_PWR5: 15250 case PPC::DIR_PWR5X: 15251 case PPC::DIR_PWR6: 15252 case PPC::DIR_PWR6X: 15253 case PPC::DIR_PWR7: 15254 case PPC::DIR_PWR8: 15255 case PPC::DIR_PWR9: 15256 case PPC::DIR_PWR10: 15257 case PPC::DIR_PWR_FUTURE: { 15258 if (!ML) 15259 break; 15260 15261 if (!DisableInnermostLoopAlign32) { 15262 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15263 // so that we can decrease cache misses and branch-prediction misses. 15264 // Actual alignment of the loop will depend on the hotness check and other 15265 // logic in alignBlocks. 15266 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15267 return Align(32); 15268 } 15269 15270 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15271 15272 // For small loops (between 5 and 8 instructions), align to a 32-byte 15273 // boundary so that the entire loop fits in one instruction-cache line. 15274 uint64_t LoopSize = 0; 15275 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15276 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15277 LoopSize += TII->getInstSizeInBytes(*J); 15278 if (LoopSize > 32) 15279 break; 15280 } 15281 15282 if (LoopSize > 16 && LoopSize <= 32) 15283 return Align(32); 15284 15285 break; 15286 } 15287 } 15288 15289 return TargetLowering::getPrefLoopAlignment(ML); 15290 } 15291 15292 /// getConstraintType - Given a constraint, return the type of 15293 /// constraint it is for this target. 15294 PPCTargetLowering::ConstraintType 15295 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15296 if (Constraint.size() == 1) { 15297 switch (Constraint[0]) { 15298 default: break; 15299 case 'b': 15300 case 'r': 15301 case 'f': 15302 case 'd': 15303 case 'v': 15304 case 'y': 15305 return C_RegisterClass; 15306 case 'Z': 15307 // FIXME: While Z does indicate a memory constraint, it specifically 15308 // indicates an r+r address (used in conjunction with the 'y' modifier 15309 // in the replacement string). Currently, we're forcing the base 15310 // register to be r0 in the asm printer (which is interpreted as zero) 15311 // and forming the complete address in the second register. This is 15312 // suboptimal. 15313 return C_Memory; 15314 } 15315 } else if (Constraint == "wc") { // individual CR bits. 15316 return C_RegisterClass; 15317 } else if (Constraint == "wa" || Constraint == "wd" || 15318 Constraint == "wf" || Constraint == "ws" || 15319 Constraint == "wi" || Constraint == "ww") { 15320 return C_RegisterClass; // VSX registers. 15321 } 15322 return TargetLowering::getConstraintType(Constraint); 15323 } 15324 15325 /// Examine constraint type and operand type and determine a weight value. 15326 /// This object must already have been set up with the operand type 15327 /// and the current alternative constraint selected. 15328 TargetLowering::ConstraintWeight 15329 PPCTargetLowering::getSingleConstraintMatchWeight( 15330 AsmOperandInfo &info, const char *constraint) const { 15331 ConstraintWeight weight = CW_Invalid; 15332 Value *CallOperandVal = info.CallOperandVal; 15333 // If we don't have a value, we can't do a match, 15334 // but allow it at the lowest weight. 15335 if (!CallOperandVal) 15336 return CW_Default; 15337 Type *type = CallOperandVal->getType(); 15338 15339 // Look at the constraint type. 15340 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15341 return CW_Register; // an individual CR bit. 15342 else if ((StringRef(constraint) == "wa" || 15343 StringRef(constraint) == "wd" || 15344 StringRef(constraint) == "wf") && 15345 type->isVectorTy()) 15346 return CW_Register; 15347 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15348 return CW_Register; // just hold 64-bit integers data. 15349 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15350 return CW_Register; 15351 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15352 return CW_Register; 15353 15354 switch (*constraint) { 15355 default: 15356 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15357 break; 15358 case 'b': 15359 if (type->isIntegerTy()) 15360 weight = CW_Register; 15361 break; 15362 case 'f': 15363 if (type->isFloatTy()) 15364 weight = CW_Register; 15365 break; 15366 case 'd': 15367 if (type->isDoubleTy()) 15368 weight = CW_Register; 15369 break; 15370 case 'v': 15371 if (type->isVectorTy()) 15372 weight = CW_Register; 15373 break; 15374 case 'y': 15375 weight = CW_Register; 15376 break; 15377 case 'Z': 15378 weight = CW_Memory; 15379 break; 15380 } 15381 return weight; 15382 } 15383 15384 std::pair<unsigned, const TargetRegisterClass *> 15385 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15386 StringRef Constraint, 15387 MVT VT) const { 15388 if (Constraint.size() == 1) { 15389 // GCC RS6000 Constraint Letters 15390 switch (Constraint[0]) { 15391 case 'b': // R1-R31 15392 if (VT == MVT::i64 && Subtarget.isPPC64()) 15393 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15394 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15395 case 'r': // R0-R31 15396 if (VT == MVT::i64 && Subtarget.isPPC64()) 15397 return std::make_pair(0U, &PPC::G8RCRegClass); 15398 return std::make_pair(0U, &PPC::GPRCRegClass); 15399 // 'd' and 'f' constraints are both defined to be "the floating point 15400 // registers", where one is for 32-bit and the other for 64-bit. We don't 15401 // really care overly much here so just give them all the same reg classes. 15402 case 'd': 15403 case 'f': 15404 if (Subtarget.hasSPE()) { 15405 if (VT == MVT::f32 || VT == MVT::i32) 15406 return std::make_pair(0U, &PPC::GPRCRegClass); 15407 if (VT == MVT::f64 || VT == MVT::i64) 15408 return std::make_pair(0U, &PPC::SPERCRegClass); 15409 } else { 15410 if (VT == MVT::f32 || VT == MVT::i32) 15411 return std::make_pair(0U, &PPC::F4RCRegClass); 15412 if (VT == MVT::f64 || VT == MVT::i64) 15413 return std::make_pair(0U, &PPC::F8RCRegClass); 15414 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15415 return std::make_pair(0U, &PPC::QFRCRegClass); 15416 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15417 return std::make_pair(0U, &PPC::QSRCRegClass); 15418 } 15419 break; 15420 case 'v': 15421 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15422 return std::make_pair(0U, &PPC::QFRCRegClass); 15423 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15424 return std::make_pair(0U, &PPC::QSRCRegClass); 15425 if (Subtarget.hasAltivec()) 15426 return std::make_pair(0U, &PPC::VRRCRegClass); 15427 break; 15428 case 'y': // crrc 15429 return std::make_pair(0U, &PPC::CRRCRegClass); 15430 } 15431 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15432 // An individual CR bit. 15433 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15434 } else if ((Constraint == "wa" || Constraint == "wd" || 15435 Constraint == "wf" || Constraint == "wi") && 15436 Subtarget.hasVSX()) { 15437 return std::make_pair(0U, &PPC::VSRCRegClass); 15438 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15439 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15440 return std::make_pair(0U, &PPC::VSSRCRegClass); 15441 else 15442 return std::make_pair(0U, &PPC::VSFRCRegClass); 15443 } 15444 15445 // If we name a VSX register, we can't defer to the base class because it 15446 // will not recognize the correct register (their names will be VSL{0-31} 15447 // and V{0-31} so they won't match). So we match them here. 15448 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15449 int VSNum = atoi(Constraint.data() + 3); 15450 assert(VSNum >= 0 && VSNum <= 63 && 15451 "Attempted to access a vsr out of range"); 15452 if (VSNum < 32) 15453 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15454 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15455 } 15456 std::pair<unsigned, const TargetRegisterClass *> R = 15457 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15458 15459 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15460 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15461 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15462 // register. 15463 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15464 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15465 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15466 PPC::GPRCRegClass.contains(R.first)) 15467 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15468 PPC::sub_32, &PPC::G8RCRegClass), 15469 &PPC::G8RCRegClass); 15470 15471 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15472 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15473 R.first = PPC::CR0; 15474 R.second = &PPC::CRRCRegClass; 15475 } 15476 15477 return R; 15478 } 15479 15480 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15481 /// vector. If it is invalid, don't add anything to Ops. 15482 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15483 std::string &Constraint, 15484 std::vector<SDValue>&Ops, 15485 SelectionDAG &DAG) const { 15486 SDValue Result; 15487 15488 // Only support length 1 constraints. 15489 if (Constraint.length() > 1) return; 15490 15491 char Letter = Constraint[0]; 15492 switch (Letter) { 15493 default: break; 15494 case 'I': 15495 case 'J': 15496 case 'K': 15497 case 'L': 15498 case 'M': 15499 case 'N': 15500 case 'O': 15501 case 'P': { 15502 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15503 if (!CST) return; // Must be an immediate to match. 15504 SDLoc dl(Op); 15505 int64_t Value = CST->getSExtValue(); 15506 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15507 // numbers are printed as such. 15508 switch (Letter) { 15509 default: llvm_unreachable("Unknown constraint letter!"); 15510 case 'I': // "I" is a signed 16-bit constant. 15511 if (isInt<16>(Value)) 15512 Result = DAG.getTargetConstant(Value, dl, TCVT); 15513 break; 15514 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15515 if (isShiftedUInt<16, 16>(Value)) 15516 Result = DAG.getTargetConstant(Value, dl, TCVT); 15517 break; 15518 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15519 if (isShiftedInt<16, 16>(Value)) 15520 Result = DAG.getTargetConstant(Value, dl, TCVT); 15521 break; 15522 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15523 if (isUInt<16>(Value)) 15524 Result = DAG.getTargetConstant(Value, dl, TCVT); 15525 break; 15526 case 'M': // "M" is a constant that is greater than 31. 15527 if (Value > 31) 15528 Result = DAG.getTargetConstant(Value, dl, TCVT); 15529 break; 15530 case 'N': // "N" is a positive constant that is an exact power of two. 15531 if (Value > 0 && isPowerOf2_64(Value)) 15532 Result = DAG.getTargetConstant(Value, dl, TCVT); 15533 break; 15534 case 'O': // "O" is the constant zero. 15535 if (Value == 0) 15536 Result = DAG.getTargetConstant(Value, dl, TCVT); 15537 break; 15538 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15539 if (isInt<16>(-Value)) 15540 Result = DAG.getTargetConstant(Value, dl, TCVT); 15541 break; 15542 } 15543 break; 15544 } 15545 } 15546 15547 if (Result.getNode()) { 15548 Ops.push_back(Result); 15549 return; 15550 } 15551 15552 // Handle standard constraint letters. 15553 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15554 } 15555 15556 // isLegalAddressingMode - Return true if the addressing mode represented 15557 // by AM is legal for this target, for a load/store of the specified type. 15558 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15559 const AddrMode &AM, Type *Ty, 15560 unsigned AS, Instruction *I) const { 15561 // PPC does not allow r+i addressing modes for vectors! 15562 if (Ty->isVectorTy() && AM.BaseOffs != 0) 15563 return false; 15564 15565 // PPC allows a sign-extended 16-bit immediate field. 15566 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15567 return false; 15568 15569 // No global is ever allowed as a base. 15570 if (AM.BaseGV) 15571 return false; 15572 15573 // PPC only support r+r, 15574 switch (AM.Scale) { 15575 case 0: // "r+i" or just "i", depending on HasBaseReg. 15576 break; 15577 case 1: 15578 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15579 return false; 15580 // Otherwise we have r+r or r+i. 15581 break; 15582 case 2: 15583 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15584 return false; 15585 // Allow 2*r as r+r. 15586 break; 15587 default: 15588 // No other scales are supported. 15589 return false; 15590 } 15591 15592 return true; 15593 } 15594 15595 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15596 SelectionDAG &DAG) const { 15597 MachineFunction &MF = DAG.getMachineFunction(); 15598 MachineFrameInfo &MFI = MF.getFrameInfo(); 15599 MFI.setReturnAddressIsTaken(true); 15600 15601 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15602 return SDValue(); 15603 15604 SDLoc dl(Op); 15605 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15606 15607 // Make sure the function does not optimize away the store of the RA to 15608 // the stack. 15609 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15610 FuncInfo->setLRStoreRequired(); 15611 bool isPPC64 = Subtarget.isPPC64(); 15612 auto PtrVT = getPointerTy(MF.getDataLayout()); 15613 15614 if (Depth > 0) { 15615 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15616 SDValue Offset = 15617 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15618 isPPC64 ? MVT::i64 : MVT::i32); 15619 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15620 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15621 MachinePointerInfo()); 15622 } 15623 15624 // Just load the return address off the stack. 15625 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15626 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15627 MachinePointerInfo()); 15628 } 15629 15630 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15631 SelectionDAG &DAG) const { 15632 SDLoc dl(Op); 15633 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15634 15635 MachineFunction &MF = DAG.getMachineFunction(); 15636 MachineFrameInfo &MFI = MF.getFrameInfo(); 15637 MFI.setFrameAddressIsTaken(true); 15638 15639 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15640 bool isPPC64 = PtrVT == MVT::i64; 15641 15642 // Naked functions never have a frame pointer, and so we use r1. For all 15643 // other functions, this decision must be delayed until during PEI. 15644 unsigned FrameReg; 15645 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15646 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15647 else 15648 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15649 15650 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15651 PtrVT); 15652 while (Depth--) 15653 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15654 FrameAddr, MachinePointerInfo()); 15655 return FrameAddr; 15656 } 15657 15658 // FIXME? Maybe this could be a TableGen attribute on some registers and 15659 // this table could be generated automatically from RegInfo. 15660 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15661 const MachineFunction &MF) const { 15662 bool isPPC64 = Subtarget.isPPC64(); 15663 15664 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15665 if (!is64Bit && VT != LLT::scalar(32)) 15666 report_fatal_error("Invalid register global variable type"); 15667 15668 Register Reg = StringSwitch<Register>(RegName) 15669 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15670 .Case("r2", isPPC64 ? Register() : PPC::R2) 15671 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15672 .Default(Register()); 15673 15674 if (Reg) 15675 return Reg; 15676 report_fatal_error("Invalid register name global variable"); 15677 } 15678 15679 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15680 // 32-bit SVR4 ABI access everything as got-indirect. 15681 if (Subtarget.is32BitELFABI()) 15682 return true; 15683 15684 // AIX accesses everything indirectly through the TOC, which is similar to 15685 // the GOT. 15686 if (Subtarget.isAIXABI()) 15687 return true; 15688 15689 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15690 // If it is small or large code model, module locals are accessed 15691 // indirectly by loading their address from .toc/.got. 15692 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15693 return true; 15694 15695 // JumpTable and BlockAddress are accessed as got-indirect. 15696 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15697 return true; 15698 15699 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15700 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15701 15702 return false; 15703 } 15704 15705 bool 15706 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15707 // The PowerPC target isn't yet aware of offsets. 15708 return false; 15709 } 15710 15711 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15712 const CallInst &I, 15713 MachineFunction &MF, 15714 unsigned Intrinsic) const { 15715 switch (Intrinsic) { 15716 case Intrinsic::ppc_qpx_qvlfd: 15717 case Intrinsic::ppc_qpx_qvlfs: 15718 case Intrinsic::ppc_qpx_qvlfcd: 15719 case Intrinsic::ppc_qpx_qvlfcs: 15720 case Intrinsic::ppc_qpx_qvlfiwa: 15721 case Intrinsic::ppc_qpx_qvlfiwz: 15722 case Intrinsic::ppc_altivec_lvx: 15723 case Intrinsic::ppc_altivec_lvxl: 15724 case Intrinsic::ppc_altivec_lvebx: 15725 case Intrinsic::ppc_altivec_lvehx: 15726 case Intrinsic::ppc_altivec_lvewx: 15727 case Intrinsic::ppc_vsx_lxvd2x: 15728 case Intrinsic::ppc_vsx_lxvw4x: { 15729 EVT VT; 15730 switch (Intrinsic) { 15731 case Intrinsic::ppc_altivec_lvebx: 15732 VT = MVT::i8; 15733 break; 15734 case Intrinsic::ppc_altivec_lvehx: 15735 VT = MVT::i16; 15736 break; 15737 case Intrinsic::ppc_altivec_lvewx: 15738 VT = MVT::i32; 15739 break; 15740 case Intrinsic::ppc_vsx_lxvd2x: 15741 VT = MVT::v2f64; 15742 break; 15743 case Intrinsic::ppc_qpx_qvlfd: 15744 VT = MVT::v4f64; 15745 break; 15746 case Intrinsic::ppc_qpx_qvlfs: 15747 VT = MVT::v4f32; 15748 break; 15749 case Intrinsic::ppc_qpx_qvlfcd: 15750 VT = MVT::v2f64; 15751 break; 15752 case Intrinsic::ppc_qpx_qvlfcs: 15753 VT = MVT::v2f32; 15754 break; 15755 default: 15756 VT = MVT::v4i32; 15757 break; 15758 } 15759 15760 Info.opc = ISD::INTRINSIC_W_CHAIN; 15761 Info.memVT = VT; 15762 Info.ptrVal = I.getArgOperand(0); 15763 Info.offset = -VT.getStoreSize()+1; 15764 Info.size = 2*VT.getStoreSize()-1; 15765 Info.align = Align(1); 15766 Info.flags = MachineMemOperand::MOLoad; 15767 return true; 15768 } 15769 case Intrinsic::ppc_qpx_qvlfda: 15770 case Intrinsic::ppc_qpx_qvlfsa: 15771 case Intrinsic::ppc_qpx_qvlfcda: 15772 case Intrinsic::ppc_qpx_qvlfcsa: 15773 case Intrinsic::ppc_qpx_qvlfiwaa: 15774 case Intrinsic::ppc_qpx_qvlfiwza: { 15775 EVT VT; 15776 switch (Intrinsic) { 15777 case Intrinsic::ppc_qpx_qvlfda: 15778 VT = MVT::v4f64; 15779 break; 15780 case Intrinsic::ppc_qpx_qvlfsa: 15781 VT = MVT::v4f32; 15782 break; 15783 case Intrinsic::ppc_qpx_qvlfcda: 15784 VT = MVT::v2f64; 15785 break; 15786 case Intrinsic::ppc_qpx_qvlfcsa: 15787 VT = MVT::v2f32; 15788 break; 15789 default: 15790 VT = MVT::v4i32; 15791 break; 15792 } 15793 15794 Info.opc = ISD::INTRINSIC_W_CHAIN; 15795 Info.memVT = VT; 15796 Info.ptrVal = I.getArgOperand(0); 15797 Info.offset = 0; 15798 Info.size = VT.getStoreSize(); 15799 Info.align = Align(1); 15800 Info.flags = MachineMemOperand::MOLoad; 15801 return true; 15802 } 15803 case Intrinsic::ppc_qpx_qvstfd: 15804 case Intrinsic::ppc_qpx_qvstfs: 15805 case Intrinsic::ppc_qpx_qvstfcd: 15806 case Intrinsic::ppc_qpx_qvstfcs: 15807 case Intrinsic::ppc_qpx_qvstfiw: 15808 case Intrinsic::ppc_altivec_stvx: 15809 case Intrinsic::ppc_altivec_stvxl: 15810 case Intrinsic::ppc_altivec_stvebx: 15811 case Intrinsic::ppc_altivec_stvehx: 15812 case Intrinsic::ppc_altivec_stvewx: 15813 case Intrinsic::ppc_vsx_stxvd2x: 15814 case Intrinsic::ppc_vsx_stxvw4x: { 15815 EVT VT; 15816 switch (Intrinsic) { 15817 case Intrinsic::ppc_altivec_stvebx: 15818 VT = MVT::i8; 15819 break; 15820 case Intrinsic::ppc_altivec_stvehx: 15821 VT = MVT::i16; 15822 break; 15823 case Intrinsic::ppc_altivec_stvewx: 15824 VT = MVT::i32; 15825 break; 15826 case Intrinsic::ppc_vsx_stxvd2x: 15827 VT = MVT::v2f64; 15828 break; 15829 case Intrinsic::ppc_qpx_qvstfd: 15830 VT = MVT::v4f64; 15831 break; 15832 case Intrinsic::ppc_qpx_qvstfs: 15833 VT = MVT::v4f32; 15834 break; 15835 case Intrinsic::ppc_qpx_qvstfcd: 15836 VT = MVT::v2f64; 15837 break; 15838 case Intrinsic::ppc_qpx_qvstfcs: 15839 VT = MVT::v2f32; 15840 break; 15841 default: 15842 VT = MVT::v4i32; 15843 break; 15844 } 15845 15846 Info.opc = ISD::INTRINSIC_VOID; 15847 Info.memVT = VT; 15848 Info.ptrVal = I.getArgOperand(1); 15849 Info.offset = -VT.getStoreSize()+1; 15850 Info.size = 2*VT.getStoreSize()-1; 15851 Info.align = Align(1); 15852 Info.flags = MachineMemOperand::MOStore; 15853 return true; 15854 } 15855 case Intrinsic::ppc_qpx_qvstfda: 15856 case Intrinsic::ppc_qpx_qvstfsa: 15857 case Intrinsic::ppc_qpx_qvstfcda: 15858 case Intrinsic::ppc_qpx_qvstfcsa: 15859 case Intrinsic::ppc_qpx_qvstfiwa: { 15860 EVT VT; 15861 switch (Intrinsic) { 15862 case Intrinsic::ppc_qpx_qvstfda: 15863 VT = MVT::v4f64; 15864 break; 15865 case Intrinsic::ppc_qpx_qvstfsa: 15866 VT = MVT::v4f32; 15867 break; 15868 case Intrinsic::ppc_qpx_qvstfcda: 15869 VT = MVT::v2f64; 15870 break; 15871 case Intrinsic::ppc_qpx_qvstfcsa: 15872 VT = MVT::v2f32; 15873 break; 15874 default: 15875 VT = MVT::v4i32; 15876 break; 15877 } 15878 15879 Info.opc = ISD::INTRINSIC_VOID; 15880 Info.memVT = VT; 15881 Info.ptrVal = I.getArgOperand(1); 15882 Info.offset = 0; 15883 Info.size = VT.getStoreSize(); 15884 Info.align = Align(1); 15885 Info.flags = MachineMemOperand::MOStore; 15886 return true; 15887 } 15888 default: 15889 break; 15890 } 15891 15892 return false; 15893 } 15894 15895 /// It returns EVT::Other if the type should be determined using generic 15896 /// target-independent logic. 15897 EVT PPCTargetLowering::getOptimalMemOpType( 15898 const MemOp &Op, const AttributeList &FuncAttributes) const { 15899 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15900 // When expanding a memset, require at least two QPX instructions to cover 15901 // the cost of loading the value to be stored from the constant pool. 15902 if (Subtarget.hasQPX() && Op.size() >= 32 && 15903 (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) && 15904 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15905 return MVT::v4f64; 15906 } 15907 15908 // We should use Altivec/VSX loads and stores when available. For unaligned 15909 // addresses, unaligned VSX loads are only fast starting with the P8. 15910 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15911 (Op.isAligned(Align(16)) || 15912 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15913 return MVT::v4i32; 15914 } 15915 15916 if (Subtarget.isPPC64()) { 15917 return MVT::i64; 15918 } 15919 15920 return MVT::i32; 15921 } 15922 15923 /// Returns true if it is beneficial to convert a load of a constant 15924 /// to just the constant itself. 15925 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15926 Type *Ty) const { 15927 assert(Ty->isIntegerTy()); 15928 15929 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15930 return !(BitSize == 0 || BitSize > 64); 15931 } 15932 15933 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15934 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15935 return false; 15936 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15937 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15938 return NumBits1 == 64 && NumBits2 == 32; 15939 } 15940 15941 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15942 if (!VT1.isInteger() || !VT2.isInteger()) 15943 return false; 15944 unsigned NumBits1 = VT1.getSizeInBits(); 15945 unsigned NumBits2 = VT2.getSizeInBits(); 15946 return NumBits1 == 64 && NumBits2 == 32; 15947 } 15948 15949 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15950 // Generally speaking, zexts are not free, but they are free when they can be 15951 // folded with other operations. 15952 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15953 EVT MemVT = LD->getMemoryVT(); 15954 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15955 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15956 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15957 LD->getExtensionType() == ISD::ZEXTLOAD)) 15958 return true; 15959 } 15960 15961 // FIXME: Add other cases... 15962 // - 32-bit shifts with a zext to i64 15963 // - zext after ctlz, bswap, etc. 15964 // - zext after and by a constant mask 15965 15966 return TargetLowering::isZExtFree(Val, VT2); 15967 } 15968 15969 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15970 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15971 "invalid fpext types"); 15972 // Extending to float128 is not free. 15973 if (DestVT == MVT::f128) 15974 return false; 15975 return true; 15976 } 15977 15978 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15979 return isInt<16>(Imm) || isUInt<16>(Imm); 15980 } 15981 15982 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15983 return isInt<16>(Imm) || isUInt<16>(Imm); 15984 } 15985 15986 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15987 unsigned, 15988 unsigned, 15989 MachineMemOperand::Flags, 15990 bool *Fast) const { 15991 if (DisablePPCUnaligned) 15992 return false; 15993 15994 // PowerPC supports unaligned memory access for simple non-vector types. 15995 // Although accessing unaligned addresses is not as efficient as accessing 15996 // aligned addresses, it is generally more efficient than manual expansion, 15997 // and generally only traps for software emulation when crossing page 15998 // boundaries. 15999 16000 if (!VT.isSimple()) 16001 return false; 16002 16003 if (VT.isFloatingPoint() && !VT.isVector() && 16004 !Subtarget.allowsUnalignedFPAccess()) 16005 return false; 16006 16007 if (VT.getSimpleVT().isVector()) { 16008 if (Subtarget.hasVSX()) { 16009 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16010 VT != MVT::v4f32 && VT != MVT::v4i32) 16011 return false; 16012 } else { 16013 return false; 16014 } 16015 } 16016 16017 if (VT == MVT::ppcf128) 16018 return false; 16019 16020 if (Fast) 16021 *Fast = true; 16022 16023 return true; 16024 } 16025 16026 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16027 EVT VT) const { 16028 return isFMAFasterThanFMulAndFAdd( 16029 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16030 } 16031 16032 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16033 Type *Ty) const { 16034 switch (Ty->getScalarType()->getTypeID()) { 16035 case Type::FloatTyID: 16036 case Type::DoubleTyID: 16037 return true; 16038 case Type::FP128TyID: 16039 return EnableQuadPrecision && Subtarget.hasP9Vector(); 16040 default: 16041 return false; 16042 } 16043 } 16044 16045 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist. 16046 // FIXME: add more patterns which are profitable to hoist. 16047 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16048 if (I->getOpcode() != Instruction::FMul) 16049 return true; 16050 16051 if (!I->hasOneUse()) 16052 return true; 16053 16054 Instruction *User = I->user_back(); 16055 assert(User && "A single use instruction with no uses."); 16056 16057 if (User->getOpcode() != Instruction::FSub && 16058 User->getOpcode() != Instruction::FAdd) 16059 return true; 16060 16061 const TargetOptions &Options = getTargetMachine().Options; 16062 const Function *F = I->getFunction(); 16063 const DataLayout &DL = F->getParent()->getDataLayout(); 16064 Type *Ty = User->getOperand(0)->getType(); 16065 16066 return !( 16067 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16068 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16069 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16070 } 16071 16072 const MCPhysReg * 16073 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16074 // LR is a callee-save register, but we must treat it as clobbered by any call 16075 // site. Hence we include LR in the scratch registers, which are in turn added 16076 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16077 // to CTR, which is used by any indirect call. 16078 static const MCPhysReg ScratchRegs[] = { 16079 PPC::X12, PPC::LR8, PPC::CTR8, 0 16080 }; 16081 16082 return ScratchRegs; 16083 } 16084 16085 Register PPCTargetLowering::getExceptionPointerRegister( 16086 const Constant *PersonalityFn) const { 16087 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16088 } 16089 16090 Register PPCTargetLowering::getExceptionSelectorRegister( 16091 const Constant *PersonalityFn) const { 16092 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16093 } 16094 16095 bool 16096 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16097 EVT VT , unsigned DefinedValues) const { 16098 if (VT == MVT::v2i64) 16099 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16100 16101 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 16102 return true; 16103 16104 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16105 } 16106 16107 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16108 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16109 return TargetLowering::getSchedulingPreference(N); 16110 16111 return Sched::ILP; 16112 } 16113 16114 // Create a fast isel object. 16115 FastISel * 16116 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16117 const TargetLibraryInfo *LibInfo) const { 16118 return PPC::createFastISel(FuncInfo, LibInfo); 16119 } 16120 16121 // 'Inverted' means the FMA opcode after negating one multiplicand. 16122 // For example, (fma -a b c) = (fnmsub a b c) 16123 static unsigned invertFMAOpcode(unsigned Opc) { 16124 switch (Opc) { 16125 default: 16126 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16127 case ISD::FMA: 16128 return PPCISD::FNMSUB; 16129 case PPCISD::FNMSUB: 16130 return ISD::FMA; 16131 } 16132 } 16133 16134 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16135 bool LegalOps, bool OptForSize, 16136 NegatibleCost &Cost, 16137 unsigned Depth) const { 16138 if (Depth > SelectionDAG::MaxRecursionDepth) 16139 return SDValue(); 16140 16141 unsigned Opc = Op.getOpcode(); 16142 EVT VT = Op.getValueType(); 16143 SDNodeFlags Flags = Op.getNode()->getFlags(); 16144 16145 switch (Opc) { 16146 case PPCISD::FNMSUB: 16147 // TODO: QPX subtarget is deprecated. No transformation here. 16148 if (!Op.hasOneUse() || !isTypeLegal(VT) || Subtarget.hasQPX()) 16149 break; 16150 16151 const TargetOptions &Options = getTargetMachine().Options; 16152 SDValue N0 = Op.getOperand(0); 16153 SDValue N1 = Op.getOperand(1); 16154 SDValue N2 = Op.getOperand(2); 16155 SDLoc Loc(Op); 16156 16157 NegatibleCost N2Cost = NegatibleCost::Expensive; 16158 SDValue NegN2 = 16159 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16160 16161 if (!NegN2) 16162 return SDValue(); 16163 16164 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16165 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16166 // These transformations may change sign of zeroes. For example, 16167 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16168 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16169 // Try and choose the cheaper one to negate. 16170 NegatibleCost N0Cost = NegatibleCost::Expensive; 16171 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16172 N0Cost, Depth + 1); 16173 16174 NegatibleCost N1Cost = NegatibleCost::Expensive; 16175 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16176 N1Cost, Depth + 1); 16177 16178 if (NegN0 && N0Cost <= N1Cost) { 16179 Cost = std::min(N0Cost, N2Cost); 16180 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16181 } else if (NegN1) { 16182 Cost = std::min(N1Cost, N2Cost); 16183 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16184 } 16185 } 16186 16187 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16188 if (isOperationLegal(ISD::FMA, VT)) { 16189 Cost = N2Cost; 16190 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16191 } 16192 16193 break; 16194 } 16195 16196 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16197 Cost, Depth); 16198 } 16199 16200 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16201 bool PPCTargetLowering::useLoadStackGuardNode() const { 16202 if (!Subtarget.isTargetLinux()) 16203 return TargetLowering::useLoadStackGuardNode(); 16204 return true; 16205 } 16206 16207 // Override to disable global variable loading on Linux. 16208 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16209 if (!Subtarget.isTargetLinux()) 16210 return TargetLowering::insertSSPDeclarations(M); 16211 } 16212 16213 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16214 bool ForCodeSize) const { 16215 if (!VT.isSimple() || !Subtarget.hasVSX()) 16216 return false; 16217 16218 switch(VT.getSimpleVT().SimpleTy) { 16219 default: 16220 // For FP types that are currently not supported by PPC backend, return 16221 // false. Examples: f16, f80. 16222 return false; 16223 case MVT::f32: 16224 case MVT::f64: 16225 case MVT::ppcf128: 16226 return Imm.isPosZero(); 16227 } 16228 } 16229 16230 // For vector shift operation op, fold 16231 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16232 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16233 SelectionDAG &DAG) { 16234 SDValue N0 = N->getOperand(0); 16235 SDValue N1 = N->getOperand(1); 16236 EVT VT = N0.getValueType(); 16237 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16238 unsigned Opcode = N->getOpcode(); 16239 unsigned TargetOpcode; 16240 16241 switch (Opcode) { 16242 default: 16243 llvm_unreachable("Unexpected shift operation"); 16244 case ISD::SHL: 16245 TargetOpcode = PPCISD::SHL; 16246 break; 16247 case ISD::SRL: 16248 TargetOpcode = PPCISD::SRL; 16249 break; 16250 case ISD::SRA: 16251 TargetOpcode = PPCISD::SRA; 16252 break; 16253 } 16254 16255 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16256 N1->getOpcode() == ISD::AND) 16257 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16258 if (Mask->getZExtValue() == OpSizeInBits - 1) 16259 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16260 16261 return SDValue(); 16262 } 16263 16264 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16265 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16266 return Value; 16267 16268 SDValue N0 = N->getOperand(0); 16269 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16270 if (!Subtarget.isISA3_0() || 16271 N0.getOpcode() != ISD::SIGN_EXTEND || 16272 N0.getOperand(0).getValueType() != MVT::i32 || 16273 CN1 == nullptr || N->getValueType(0) != MVT::i64) 16274 return SDValue(); 16275 16276 // We can't save an operation here if the value is already extended, and 16277 // the existing shift is easier to combine. 16278 SDValue ExtsSrc = N0.getOperand(0); 16279 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16280 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16281 return SDValue(); 16282 16283 SDLoc DL(N0); 16284 SDValue ShiftBy = SDValue(CN1, 0); 16285 // We want the shift amount to be i32 on the extswli, but the shift could 16286 // have an i64. 16287 if (ShiftBy.getValueType() == MVT::i64) 16288 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16289 16290 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16291 ShiftBy); 16292 } 16293 16294 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16295 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16296 return Value; 16297 16298 return SDValue(); 16299 } 16300 16301 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16302 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16303 return Value; 16304 16305 return SDValue(); 16306 } 16307 16308 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16309 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16310 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16311 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16312 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16313 const PPCSubtarget &Subtarget) { 16314 if (!Subtarget.isPPC64()) 16315 return SDValue(); 16316 16317 SDValue LHS = N->getOperand(0); 16318 SDValue RHS = N->getOperand(1); 16319 16320 auto isZextOfCompareWithConstant = [](SDValue Op) { 16321 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16322 Op.getValueType() != MVT::i64) 16323 return false; 16324 16325 SDValue Cmp = Op.getOperand(0); 16326 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16327 Cmp.getOperand(0).getValueType() != MVT::i64) 16328 return false; 16329 16330 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16331 int64_t NegConstant = 0 - Constant->getSExtValue(); 16332 // Due to the limitations of the addi instruction, 16333 // -C is required to be [-32768, 32767]. 16334 return isInt<16>(NegConstant); 16335 } 16336 16337 return false; 16338 }; 16339 16340 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16341 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16342 16343 // If there is a pattern, canonicalize a zext operand to the RHS. 16344 if (LHSHasPattern && !RHSHasPattern) 16345 std::swap(LHS, RHS); 16346 else if (!LHSHasPattern && !RHSHasPattern) 16347 return SDValue(); 16348 16349 SDLoc DL(N); 16350 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16351 SDValue Cmp = RHS.getOperand(0); 16352 SDValue Z = Cmp.getOperand(0); 16353 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16354 16355 assert(Constant && "Constant Should not be a null pointer."); 16356 int64_t NegConstant = 0 - Constant->getSExtValue(); 16357 16358 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16359 default: break; 16360 case ISD::SETNE: { 16361 // when C == 0 16362 // --> addze X, (addic Z, -1).carry 16363 // / 16364 // add X, (zext(setne Z, C))-- 16365 // \ when -32768 <= -C <= 32767 && C != 0 16366 // --> addze X, (addic (addi Z, -C), -1).carry 16367 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16368 DAG.getConstant(NegConstant, DL, MVT::i64)); 16369 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16370 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16371 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16372 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16373 SDValue(Addc.getNode(), 1)); 16374 } 16375 case ISD::SETEQ: { 16376 // when C == 0 16377 // --> addze X, (subfic Z, 0).carry 16378 // / 16379 // add X, (zext(sete Z, C))-- 16380 // \ when -32768 <= -C <= 32767 && C != 0 16381 // --> addze X, (subfic (addi Z, -C), 0).carry 16382 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16383 DAG.getConstant(NegConstant, DL, MVT::i64)); 16384 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16385 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16386 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16387 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16388 SDValue(Subc.getNode(), 1)); 16389 } 16390 } 16391 16392 return SDValue(); 16393 } 16394 16395 // Transform 16396 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16397 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16398 // In this case both C1 and C2 must be known constants. 16399 // C1+C2 must fit into a 34 bit signed integer. 16400 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16401 const PPCSubtarget &Subtarget) { 16402 if (!Subtarget.isUsingPCRelativeCalls()) 16403 return SDValue(); 16404 16405 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16406 // If we find that node try to cast the Global Address and the Constant. 16407 SDValue LHS = N->getOperand(0); 16408 SDValue RHS = N->getOperand(1); 16409 16410 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16411 std::swap(LHS, RHS); 16412 16413 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16414 return SDValue(); 16415 16416 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16417 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16418 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16419 16420 // Check that both casts succeeded. 16421 if (!GSDN || !ConstNode) 16422 return SDValue(); 16423 16424 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16425 SDLoc DL(GSDN); 16426 16427 // The signed int offset needs to fit in 34 bits. 16428 if (!isInt<34>(NewOffset)) 16429 return SDValue(); 16430 16431 // The new global address is a copy of the old global address except 16432 // that it has the updated Offset. 16433 SDValue GA = 16434 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16435 NewOffset, GSDN->getTargetFlags()); 16436 SDValue MatPCRel = 16437 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16438 return MatPCRel; 16439 } 16440 16441 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16442 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16443 return Value; 16444 16445 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16446 return Value; 16447 16448 return SDValue(); 16449 } 16450 16451 // Detect TRUNCATE operations on bitcasts of float128 values. 16452 // What we are looking for here is the situtation where we extract a subset 16453 // of bits from a 128 bit float. 16454 // This can be of two forms: 16455 // 1) BITCAST of f128 feeding TRUNCATE 16456 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16457 // The reason this is required is because we do not have a legal i128 type 16458 // and so we want to prevent having to store the f128 and then reload part 16459 // of it. 16460 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16461 DAGCombinerInfo &DCI) const { 16462 // If we are using CRBits then try that first. 16463 if (Subtarget.useCRBits()) { 16464 // Check if CRBits did anything and return that if it did. 16465 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16466 return CRTruncValue; 16467 } 16468 16469 SDLoc dl(N); 16470 SDValue Op0 = N->getOperand(0); 16471 16472 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16473 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16474 EVT VT = N->getValueType(0); 16475 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16476 return SDValue(); 16477 SDValue Sub = Op0.getOperand(0); 16478 if (Sub.getOpcode() == ISD::SUB) { 16479 SDValue SubOp0 = Sub.getOperand(0); 16480 SDValue SubOp1 = Sub.getOperand(1); 16481 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16482 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16483 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16484 SubOp1.getOperand(0), 16485 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16486 } 16487 } 16488 } 16489 16490 // Looking for a truncate of i128 to i64. 16491 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16492 return SDValue(); 16493 16494 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16495 16496 // SRL feeding TRUNCATE. 16497 if (Op0.getOpcode() == ISD::SRL) { 16498 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16499 // The right shift has to be by 64 bits. 16500 if (!ConstNode || ConstNode->getZExtValue() != 64) 16501 return SDValue(); 16502 16503 // Switch the element number to extract. 16504 EltToExtract = EltToExtract ? 0 : 1; 16505 // Update Op0 past the SRL. 16506 Op0 = Op0.getOperand(0); 16507 } 16508 16509 // BITCAST feeding a TRUNCATE possibly via SRL. 16510 if (Op0.getOpcode() == ISD::BITCAST && 16511 Op0.getValueType() == MVT::i128 && 16512 Op0.getOperand(0).getValueType() == MVT::f128) { 16513 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16514 return DCI.DAG.getNode( 16515 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16516 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16517 } 16518 return SDValue(); 16519 } 16520 16521 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16522 SelectionDAG &DAG = DCI.DAG; 16523 16524 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16525 if (!ConstOpOrElement) 16526 return SDValue(); 16527 16528 // An imul is usually smaller than the alternative sequence for legal type. 16529 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16530 isOperationLegal(ISD::MUL, N->getValueType(0))) 16531 return SDValue(); 16532 16533 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16534 switch (this->Subtarget.getCPUDirective()) { 16535 default: 16536 // TODO: enhance the condition for subtarget before pwr8 16537 return false; 16538 case PPC::DIR_PWR8: 16539 // type mul add shl 16540 // scalar 4 1 1 16541 // vector 7 2 2 16542 return true; 16543 case PPC::DIR_PWR9: 16544 case PPC::DIR_PWR10: 16545 case PPC::DIR_PWR_FUTURE: 16546 // type mul add shl 16547 // scalar 5 2 2 16548 // vector 7 2 2 16549 16550 // The cycle RATIO of related operations are showed as a table above. 16551 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16552 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16553 // are 4, it is always profitable; but for 3 instrs patterns 16554 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16555 // So we should only do it for vector type. 16556 return IsAddOne && IsNeg ? VT.isVector() : true; 16557 } 16558 }; 16559 16560 EVT VT = N->getValueType(0); 16561 SDLoc DL(N); 16562 16563 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16564 bool IsNeg = MulAmt.isNegative(); 16565 APInt MulAmtAbs = MulAmt.abs(); 16566 16567 if ((MulAmtAbs - 1).isPowerOf2()) { 16568 // (mul x, 2^N + 1) => (add (shl x, N), x) 16569 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16570 16571 if (!IsProfitable(IsNeg, true, VT)) 16572 return SDValue(); 16573 16574 SDValue Op0 = N->getOperand(0); 16575 SDValue Op1 = 16576 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16577 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16578 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16579 16580 if (!IsNeg) 16581 return Res; 16582 16583 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16584 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16585 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16586 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16587 16588 if (!IsProfitable(IsNeg, false, VT)) 16589 return SDValue(); 16590 16591 SDValue Op0 = N->getOperand(0); 16592 SDValue Op1 = 16593 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16594 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16595 16596 if (!IsNeg) 16597 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16598 else 16599 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16600 16601 } else { 16602 return SDValue(); 16603 } 16604 } 16605 16606 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16607 // in combiner since we need to check SD flags and other subtarget features. 16608 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16609 DAGCombinerInfo &DCI) const { 16610 SDValue N0 = N->getOperand(0); 16611 SDValue N1 = N->getOperand(1); 16612 SDValue N2 = N->getOperand(2); 16613 SDNodeFlags Flags = N->getFlags(); 16614 EVT VT = N->getValueType(0); 16615 SelectionDAG &DAG = DCI.DAG; 16616 const TargetOptions &Options = getTargetMachine().Options; 16617 unsigned Opc = N->getOpcode(); 16618 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16619 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16620 SDLoc Loc(N); 16621 16622 // TODO: QPX subtarget is deprecated. No transformation here. 16623 if (Subtarget.hasQPX() || !isOperationLegal(ISD::FMA, VT)) 16624 return SDValue(); 16625 16626 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16627 // since (fnmsub a b c)=-0 while c-ab=+0. 16628 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16629 return SDValue(); 16630 16631 // (fma (fneg a) b c) => (fnmsub a b c) 16632 // (fnmsub (fneg a) b c) => (fma a b c) 16633 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16634 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16635 16636 // (fma a (fneg b) c) => (fnmsub a b c) 16637 // (fnmsub a (fneg b) c) => (fma a b c) 16638 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16639 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16640 16641 return SDValue(); 16642 } 16643 16644 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16645 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16646 if (!Subtarget.is64BitELFABI()) 16647 return false; 16648 16649 // If not a tail call then no need to proceed. 16650 if (!CI->isTailCall()) 16651 return false; 16652 16653 // If sibling calls have been disabled and tail-calls aren't guaranteed 16654 // there is no reason to duplicate. 16655 auto &TM = getTargetMachine(); 16656 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16657 return false; 16658 16659 // Can't tail call a function called indirectly, or if it has variadic args. 16660 const Function *Callee = CI->getCalledFunction(); 16661 if (!Callee || Callee->isVarArg()) 16662 return false; 16663 16664 // Make sure the callee and caller calling conventions are eligible for tco. 16665 const Function *Caller = CI->getParent()->getParent(); 16666 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16667 CI->getCallingConv())) 16668 return false; 16669 16670 // If the function is local then we have a good chance at tail-calling it 16671 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16672 } 16673 16674 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16675 if (!Subtarget.hasVSX()) 16676 return false; 16677 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16678 return true; 16679 return VT == MVT::f32 || VT == MVT::f64 || 16680 VT == MVT::v4f32 || VT == MVT::v2f64; 16681 } 16682 16683 bool PPCTargetLowering:: 16684 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16685 const Value *Mask = AndI.getOperand(1); 16686 // If the mask is suitable for andi. or andis. we should sink the and. 16687 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16688 // Can't handle constants wider than 64-bits. 16689 if (CI->getBitWidth() > 64) 16690 return false; 16691 int64_t ConstVal = CI->getZExtValue(); 16692 return isUInt<16>(ConstVal) || 16693 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16694 } 16695 16696 // For non-constant masks, we can always use the record-form and. 16697 return true; 16698 } 16699 16700 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16701 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16702 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16703 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16704 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16705 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16706 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16707 assert(Subtarget.hasP9Altivec() && 16708 "Only combine this when P9 altivec supported!"); 16709 EVT VT = N->getValueType(0); 16710 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16711 return SDValue(); 16712 16713 SelectionDAG &DAG = DCI.DAG; 16714 SDLoc dl(N); 16715 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16716 // Even for signed integers, if it's known to be positive (as signed 16717 // integer) due to zero-extended inputs. 16718 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16719 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16720 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16721 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16722 (SubOpcd1 == ISD::ZERO_EXTEND || 16723 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16724 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16725 N->getOperand(0)->getOperand(0), 16726 N->getOperand(0)->getOperand(1), 16727 DAG.getTargetConstant(0, dl, MVT::i32)); 16728 } 16729 16730 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16731 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16732 N->getOperand(0).hasOneUse()) { 16733 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16734 N->getOperand(0)->getOperand(0), 16735 N->getOperand(0)->getOperand(1), 16736 DAG.getTargetConstant(1, dl, MVT::i32)); 16737 } 16738 } 16739 16740 return SDValue(); 16741 } 16742 16743 // For type v4i32/v8ii16/v16i8, transform 16744 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16745 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16746 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16747 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16748 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16749 DAGCombinerInfo &DCI) const { 16750 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16751 assert(Subtarget.hasP9Altivec() && 16752 "Only combine this when P9 altivec supported!"); 16753 16754 SelectionDAG &DAG = DCI.DAG; 16755 SDLoc dl(N); 16756 SDValue Cond = N->getOperand(0); 16757 SDValue TrueOpnd = N->getOperand(1); 16758 SDValue FalseOpnd = N->getOperand(2); 16759 EVT VT = N->getOperand(1).getValueType(); 16760 16761 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16762 FalseOpnd.getOpcode() != ISD::SUB) 16763 return SDValue(); 16764 16765 // ABSD only available for type v4i32/v8i16/v16i8 16766 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16767 return SDValue(); 16768 16769 // At least to save one more dependent computation 16770 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16771 return SDValue(); 16772 16773 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16774 16775 // Can only handle unsigned comparison here 16776 switch (CC) { 16777 default: 16778 return SDValue(); 16779 case ISD::SETUGT: 16780 case ISD::SETUGE: 16781 break; 16782 case ISD::SETULT: 16783 case ISD::SETULE: 16784 std::swap(TrueOpnd, FalseOpnd); 16785 break; 16786 } 16787 16788 SDValue CmpOpnd1 = Cond.getOperand(0); 16789 SDValue CmpOpnd2 = Cond.getOperand(1); 16790 16791 // SETCC CmpOpnd1 CmpOpnd2 cond 16792 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16793 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16794 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16795 TrueOpnd.getOperand(1) == CmpOpnd2 && 16796 FalseOpnd.getOperand(0) == CmpOpnd2 && 16797 FalseOpnd.getOperand(1) == CmpOpnd1) { 16798 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16799 CmpOpnd1, CmpOpnd2, 16800 DAG.getTargetConstant(0, dl, MVT::i32)); 16801 } 16802 16803 return SDValue(); 16804 } 16805