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, unsigned &MaxAlign, 1393 unsigned MaxMaxAlign) { 1394 if (MaxAlign == MaxMaxAlign) 1395 return; 1396 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1397 if (MaxMaxAlign >= 32 && 1398 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1399 MaxAlign = 32; 1400 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1401 MaxAlign < 16) 1402 MaxAlign = 16; 1403 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1404 unsigned EltAlign = 0; 1405 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1406 if (EltAlign > MaxAlign) 1407 MaxAlign = EltAlign; 1408 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1409 for (auto *EltTy : STy->elements()) { 1410 unsigned EltAlign = 0; 1411 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1412 if (EltAlign > MaxAlign) 1413 MaxAlign = EltAlign; 1414 if (MaxAlign == MaxMaxAlign) 1415 break; 1416 } 1417 } 1418 } 1419 1420 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1421 /// function arguments in the caller parameter area. 1422 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1423 const DataLayout &DL) const { 1424 // 16byte and wider vectors are passed on 16byte boundary. 1425 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1426 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1427 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1428 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1429 return Align; 1430 } 1431 1432 bool PPCTargetLowering::useSoftFloat() const { 1433 return Subtarget.useSoftFloat(); 1434 } 1435 1436 bool PPCTargetLowering::hasSPE() const { 1437 return Subtarget.hasSPE(); 1438 } 1439 1440 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1441 return VT.isScalarInteger(); 1442 } 1443 1444 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1445 /// type is cheaper than a multiply followed by a shift. 1446 /// This is true for words and doublewords on 64-bit PowerPC. 1447 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1448 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1449 isOperationLegal(ISD::MULHU, Type))) 1450 return true; 1451 return TargetLowering::isMulhCheaperThanMulShift(Type); 1452 } 1453 1454 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1455 switch ((PPCISD::NodeType)Opcode) { 1456 case PPCISD::FIRST_NUMBER: break; 1457 case PPCISD::FSEL: return "PPCISD::FSEL"; 1458 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1459 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1460 case PPCISD::FCFID: return "PPCISD::FCFID"; 1461 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1462 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1463 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1464 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1465 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1466 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1467 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1468 case PPCISD::FP_TO_UINT_IN_VSR: 1469 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1470 case PPCISD::FP_TO_SINT_IN_VSR: 1471 return "PPCISD::FP_TO_SINT_IN_VSR"; 1472 case PPCISD::FRE: return "PPCISD::FRE"; 1473 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1474 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1475 case PPCISD::VPERM: return "PPCISD::VPERM"; 1476 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1477 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1478 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1479 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1480 case PPCISD::CMPB: return "PPCISD::CMPB"; 1481 case PPCISD::Hi: return "PPCISD::Hi"; 1482 case PPCISD::Lo: return "PPCISD::Lo"; 1483 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1484 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1485 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1486 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1487 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1488 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1489 case PPCISD::SRL: return "PPCISD::SRL"; 1490 case PPCISD::SRA: return "PPCISD::SRA"; 1491 case PPCISD::SHL: return "PPCISD::SHL"; 1492 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1493 case PPCISD::CALL: return "PPCISD::CALL"; 1494 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1495 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1496 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1497 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1498 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1499 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1500 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1501 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1502 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1503 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1504 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1505 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1506 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1507 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1508 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1509 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1510 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1511 case PPCISD::ANDI_rec_1_EQ_BIT: 1512 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1513 case PPCISD::ANDI_rec_1_GT_BIT: 1514 return "PPCISD::ANDI_rec_1_GT_BIT"; 1515 case PPCISD::VCMP: return "PPCISD::VCMP"; 1516 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1517 case PPCISD::LBRX: return "PPCISD::LBRX"; 1518 case PPCISD::STBRX: return "PPCISD::STBRX"; 1519 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1520 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1521 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1522 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1523 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1524 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1525 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1526 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1527 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1528 case PPCISD::ST_VSR_SCAL_INT: 1529 return "PPCISD::ST_VSR_SCAL_INT"; 1530 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1531 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1532 case PPCISD::BDZ: return "PPCISD::BDZ"; 1533 case PPCISD::MFFS: return "PPCISD::MFFS"; 1534 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1535 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1536 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1537 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1538 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1539 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1540 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1541 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1542 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1543 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1544 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1545 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1546 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1547 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1548 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1549 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1550 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1551 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1552 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1553 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1554 case PPCISD::SC: return "PPCISD::SC"; 1555 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1556 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1557 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1558 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1559 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1560 case PPCISD::VABSD: return "PPCISD::VABSD"; 1561 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1562 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1563 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1564 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1565 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1566 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1567 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1568 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1569 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1570 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1571 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1572 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1573 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1574 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1575 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1576 } 1577 return nullptr; 1578 } 1579 1580 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1581 EVT VT) const { 1582 if (!VT.isVector()) 1583 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1584 1585 if (Subtarget.hasQPX()) 1586 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1587 1588 return VT.changeVectorElementTypeToInteger(); 1589 } 1590 1591 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1592 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1593 return true; 1594 } 1595 1596 //===----------------------------------------------------------------------===// 1597 // Node matching predicates, for use by the tblgen matching code. 1598 //===----------------------------------------------------------------------===// 1599 1600 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1601 static bool isFloatingPointZero(SDValue Op) { 1602 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1603 return CFP->getValueAPF().isZero(); 1604 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1605 // Maybe this has already been legalized into the constant pool? 1606 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1607 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1608 return CFP->getValueAPF().isZero(); 1609 } 1610 return false; 1611 } 1612 1613 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1614 /// true if Op is undef or if it matches the specified value. 1615 static bool isConstantOrUndef(int Op, int Val) { 1616 return Op < 0 || Op == Val; 1617 } 1618 1619 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1620 /// VPKUHUM instruction. 1621 /// The ShuffleKind distinguishes between big-endian operations with 1622 /// two different inputs (0), either-endian operations with two identical 1623 /// inputs (1), and little-endian operations with two different inputs (2). 1624 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1625 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1626 SelectionDAG &DAG) { 1627 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1628 if (ShuffleKind == 0) { 1629 if (IsLE) 1630 return false; 1631 for (unsigned i = 0; i != 16; ++i) 1632 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1633 return false; 1634 } else if (ShuffleKind == 2) { 1635 if (!IsLE) 1636 return false; 1637 for (unsigned i = 0; i != 16; ++i) 1638 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1639 return false; 1640 } else if (ShuffleKind == 1) { 1641 unsigned j = IsLE ? 0 : 1; 1642 for (unsigned i = 0; i != 8; ++i) 1643 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1644 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1645 return false; 1646 } 1647 return true; 1648 } 1649 1650 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1651 /// VPKUWUM instruction. 1652 /// The ShuffleKind distinguishes between big-endian operations with 1653 /// two different inputs (0), either-endian operations with two identical 1654 /// inputs (1), and little-endian operations with two different inputs (2). 1655 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1656 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1657 SelectionDAG &DAG) { 1658 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1659 if (ShuffleKind == 0) { 1660 if (IsLE) 1661 return false; 1662 for (unsigned i = 0; i != 16; i += 2) 1663 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1664 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1665 return false; 1666 } else if (ShuffleKind == 2) { 1667 if (!IsLE) 1668 return false; 1669 for (unsigned i = 0; i != 16; i += 2) 1670 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1671 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1672 return false; 1673 } else if (ShuffleKind == 1) { 1674 unsigned j = IsLE ? 0 : 2; 1675 for (unsigned i = 0; i != 8; i += 2) 1676 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1677 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1678 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1679 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1680 return false; 1681 } 1682 return true; 1683 } 1684 1685 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1686 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1687 /// current subtarget. 1688 /// 1689 /// The ShuffleKind distinguishes between big-endian operations with 1690 /// two different inputs (0), either-endian operations with two identical 1691 /// inputs (1), and little-endian operations with two different inputs (2). 1692 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1693 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1694 SelectionDAG &DAG) { 1695 const PPCSubtarget& Subtarget = 1696 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1697 if (!Subtarget.hasP8Vector()) 1698 return false; 1699 1700 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1701 if (ShuffleKind == 0) { 1702 if (IsLE) 1703 return false; 1704 for (unsigned i = 0; i != 16; i += 4) 1705 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1706 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1707 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1708 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1709 return false; 1710 } else if (ShuffleKind == 2) { 1711 if (!IsLE) 1712 return false; 1713 for (unsigned i = 0; i != 16; i += 4) 1714 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1715 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1716 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1717 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1718 return false; 1719 } else if (ShuffleKind == 1) { 1720 unsigned j = IsLE ? 0 : 4; 1721 for (unsigned i = 0; i != 8; i += 4) 1722 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1723 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1724 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1725 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1726 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1727 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1728 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1729 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1730 return false; 1731 } 1732 return true; 1733 } 1734 1735 /// isVMerge - Common function, used to match vmrg* shuffles. 1736 /// 1737 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1738 unsigned LHSStart, unsigned RHSStart) { 1739 if (N->getValueType(0) != MVT::v16i8) 1740 return false; 1741 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1742 "Unsupported merge size!"); 1743 1744 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1745 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1746 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1747 LHSStart+j+i*UnitSize) || 1748 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1749 RHSStart+j+i*UnitSize)) 1750 return false; 1751 } 1752 return true; 1753 } 1754 1755 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1756 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1757 /// The ShuffleKind distinguishes between big-endian merges with two 1758 /// different inputs (0), either-endian merges with two identical inputs (1), 1759 /// and little-endian merges with two different inputs (2). For the latter, 1760 /// the input operands are swapped (see PPCInstrAltivec.td). 1761 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1762 unsigned ShuffleKind, SelectionDAG &DAG) { 1763 if (DAG.getDataLayout().isLittleEndian()) { 1764 if (ShuffleKind == 1) // unary 1765 return isVMerge(N, UnitSize, 0, 0); 1766 else if (ShuffleKind == 2) // swapped 1767 return isVMerge(N, UnitSize, 0, 16); 1768 else 1769 return false; 1770 } else { 1771 if (ShuffleKind == 1) // unary 1772 return isVMerge(N, UnitSize, 8, 8); 1773 else if (ShuffleKind == 0) // normal 1774 return isVMerge(N, UnitSize, 8, 24); 1775 else 1776 return false; 1777 } 1778 } 1779 1780 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1781 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1782 /// The ShuffleKind distinguishes between big-endian merges with two 1783 /// different inputs (0), either-endian merges with two identical inputs (1), 1784 /// and little-endian merges with two different inputs (2). For the latter, 1785 /// the input operands are swapped (see PPCInstrAltivec.td). 1786 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1787 unsigned ShuffleKind, SelectionDAG &DAG) { 1788 if (DAG.getDataLayout().isLittleEndian()) { 1789 if (ShuffleKind == 1) // unary 1790 return isVMerge(N, UnitSize, 8, 8); 1791 else if (ShuffleKind == 2) // swapped 1792 return isVMerge(N, UnitSize, 8, 24); 1793 else 1794 return false; 1795 } else { 1796 if (ShuffleKind == 1) // unary 1797 return isVMerge(N, UnitSize, 0, 0); 1798 else if (ShuffleKind == 0) // normal 1799 return isVMerge(N, UnitSize, 0, 16); 1800 else 1801 return false; 1802 } 1803 } 1804 1805 /** 1806 * Common function used to match vmrgew and vmrgow shuffles 1807 * 1808 * The indexOffset determines whether to look for even or odd words in 1809 * the shuffle mask. This is based on the of the endianness of the target 1810 * machine. 1811 * - Little Endian: 1812 * - Use offset of 0 to check for odd elements 1813 * - Use offset of 4 to check for even elements 1814 * - Big Endian: 1815 * - Use offset of 0 to check for even elements 1816 * - Use offset of 4 to check for odd elements 1817 * A detailed description of the vector element ordering for little endian and 1818 * big endian can be found at 1819 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1820 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1821 * compiler differences mean to you 1822 * 1823 * The mask to the shuffle vector instruction specifies the indices of the 1824 * elements from the two input vectors to place in the result. The elements are 1825 * numbered in array-access order, starting with the first vector. These vectors 1826 * are always of type v16i8, thus each vector will contain 16 elements of size 1827 * 8. More info on the shuffle vector can be found in the 1828 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1829 * Language Reference. 1830 * 1831 * The RHSStartValue indicates whether the same input vectors are used (unary) 1832 * or two different input vectors are used, based on the following: 1833 * - If the instruction uses the same vector for both inputs, the range of the 1834 * indices will be 0 to 15. In this case, the RHSStart value passed should 1835 * be 0. 1836 * - If the instruction has two different vectors then the range of the 1837 * indices will be 0 to 31. In this case, the RHSStart value passed should 1838 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1839 * to 31 specify elements in the second vector). 1840 * 1841 * \param[in] N The shuffle vector SD Node to analyze 1842 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1843 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1844 * vector to the shuffle_vector instruction 1845 * \return true iff this shuffle vector represents an even or odd word merge 1846 */ 1847 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1848 unsigned RHSStartValue) { 1849 if (N->getValueType(0) != MVT::v16i8) 1850 return false; 1851 1852 for (unsigned i = 0; i < 2; ++i) 1853 for (unsigned j = 0; j < 4; ++j) 1854 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1855 i*RHSStartValue+j+IndexOffset) || 1856 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1857 i*RHSStartValue+j+IndexOffset+8)) 1858 return false; 1859 return true; 1860 } 1861 1862 /** 1863 * Determine if the specified shuffle mask is suitable for the vmrgew or 1864 * vmrgow instructions. 1865 * 1866 * \param[in] N The shuffle vector SD Node to analyze 1867 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1868 * \param[in] ShuffleKind Identify the type of merge: 1869 * - 0 = big-endian merge with two different inputs; 1870 * - 1 = either-endian merge with two identical inputs; 1871 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1872 * little-endian merges). 1873 * \param[in] DAG The current SelectionDAG 1874 * \return true iff this shuffle mask 1875 */ 1876 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1877 unsigned ShuffleKind, SelectionDAG &DAG) { 1878 if (DAG.getDataLayout().isLittleEndian()) { 1879 unsigned indexOffset = CheckEven ? 4 : 0; 1880 if (ShuffleKind == 1) // Unary 1881 return isVMerge(N, indexOffset, 0); 1882 else if (ShuffleKind == 2) // swapped 1883 return isVMerge(N, indexOffset, 16); 1884 else 1885 return false; 1886 } 1887 else { 1888 unsigned indexOffset = CheckEven ? 0 : 4; 1889 if (ShuffleKind == 1) // Unary 1890 return isVMerge(N, indexOffset, 0); 1891 else if (ShuffleKind == 0) // Normal 1892 return isVMerge(N, indexOffset, 16); 1893 else 1894 return false; 1895 } 1896 return false; 1897 } 1898 1899 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1900 /// amount, otherwise return -1. 1901 /// The ShuffleKind distinguishes between big-endian operations with two 1902 /// different inputs (0), either-endian operations with two identical inputs 1903 /// (1), and little-endian operations with two different inputs (2). For the 1904 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1905 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1906 SelectionDAG &DAG) { 1907 if (N->getValueType(0) != MVT::v16i8) 1908 return -1; 1909 1910 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1911 1912 // Find the first non-undef value in the shuffle mask. 1913 unsigned i; 1914 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1915 /*search*/; 1916 1917 if (i == 16) return -1; // all undef. 1918 1919 // Otherwise, check to see if the rest of the elements are consecutively 1920 // numbered from this value. 1921 unsigned ShiftAmt = SVOp->getMaskElt(i); 1922 if (ShiftAmt < i) return -1; 1923 1924 ShiftAmt -= i; 1925 bool isLE = DAG.getDataLayout().isLittleEndian(); 1926 1927 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1928 // Check the rest of the elements to see if they are consecutive. 1929 for (++i; i != 16; ++i) 1930 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1931 return -1; 1932 } else if (ShuffleKind == 1) { 1933 // Check the rest of the elements to see if they are consecutive. 1934 for (++i; i != 16; ++i) 1935 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1936 return -1; 1937 } else 1938 return -1; 1939 1940 if (isLE) 1941 ShiftAmt = 16 - ShiftAmt; 1942 1943 return ShiftAmt; 1944 } 1945 1946 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1947 /// specifies a splat of a single element that is suitable for input to 1948 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1949 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1950 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1951 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1952 1953 // The consecutive indices need to specify an element, not part of two 1954 // different elements. So abandon ship early if this isn't the case. 1955 if (N->getMaskElt(0) % EltSize != 0) 1956 return false; 1957 1958 // This is a splat operation if each element of the permute is the same, and 1959 // if the value doesn't reference the second vector. 1960 unsigned ElementBase = N->getMaskElt(0); 1961 1962 // FIXME: Handle UNDEF elements too! 1963 if (ElementBase >= 16) 1964 return false; 1965 1966 // Check that the indices are consecutive, in the case of a multi-byte element 1967 // splatted with a v16i8 mask. 1968 for (unsigned i = 1; i != EltSize; ++i) 1969 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1970 return false; 1971 1972 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1973 if (N->getMaskElt(i) < 0) continue; 1974 for (unsigned j = 0; j != EltSize; ++j) 1975 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1976 return false; 1977 } 1978 return true; 1979 } 1980 1981 /// Check that the mask is shuffling N byte elements. Within each N byte 1982 /// element of the mask, the indices could be either in increasing or 1983 /// decreasing order as long as they are consecutive. 1984 /// \param[in] N the shuffle vector SD Node to analyze 1985 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1986 /// Word/DoubleWord/QuadWord). 1987 /// \param[in] StepLen the delta indices number among the N byte element, if 1988 /// the mask is in increasing/decreasing order then it is 1/-1. 1989 /// \return true iff the mask is shuffling N byte elements. 1990 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1991 int StepLen) { 1992 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1993 "Unexpected element width."); 1994 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1995 1996 unsigned NumOfElem = 16 / Width; 1997 unsigned MaskVal[16]; // Width is never greater than 16 1998 for (unsigned i = 0; i < NumOfElem; ++i) { 1999 MaskVal[0] = N->getMaskElt(i * Width); 2000 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2001 return false; 2002 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2003 return false; 2004 } 2005 2006 for (unsigned int j = 1; j < Width; ++j) { 2007 MaskVal[j] = N->getMaskElt(i * Width + j); 2008 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2009 return false; 2010 } 2011 } 2012 } 2013 2014 return true; 2015 } 2016 2017 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2018 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2019 if (!isNByteElemShuffleMask(N, 4, 1)) 2020 return false; 2021 2022 // Now we look at mask elements 0,4,8,12 2023 unsigned M0 = N->getMaskElt(0) / 4; 2024 unsigned M1 = N->getMaskElt(4) / 4; 2025 unsigned M2 = N->getMaskElt(8) / 4; 2026 unsigned M3 = N->getMaskElt(12) / 4; 2027 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2028 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2029 2030 // Below, let H and L be arbitrary elements of the shuffle mask 2031 // where H is in the range [4,7] and L is in the range [0,3]. 2032 // H, 1, 2, 3 or L, 5, 6, 7 2033 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2034 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2035 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2036 InsertAtByte = IsLE ? 12 : 0; 2037 Swap = M0 < 4; 2038 return true; 2039 } 2040 // 0, H, 2, 3 or 4, L, 6, 7 2041 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2042 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2043 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2044 InsertAtByte = IsLE ? 8 : 4; 2045 Swap = M1 < 4; 2046 return true; 2047 } 2048 // 0, 1, H, 3 or 4, 5, L, 7 2049 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2050 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2051 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2052 InsertAtByte = IsLE ? 4 : 8; 2053 Swap = M2 < 4; 2054 return true; 2055 } 2056 // 0, 1, 2, H or 4, 5, 6, L 2057 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2058 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2059 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2060 InsertAtByte = IsLE ? 0 : 12; 2061 Swap = M3 < 4; 2062 return true; 2063 } 2064 2065 // If both vector operands for the shuffle are the same vector, the mask will 2066 // contain only elements from the first one and the second one will be undef. 2067 if (N->getOperand(1).isUndef()) { 2068 ShiftElts = 0; 2069 Swap = true; 2070 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2071 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2072 InsertAtByte = IsLE ? 12 : 0; 2073 return true; 2074 } 2075 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2076 InsertAtByte = IsLE ? 8 : 4; 2077 return true; 2078 } 2079 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2080 InsertAtByte = IsLE ? 4 : 8; 2081 return true; 2082 } 2083 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2084 InsertAtByte = IsLE ? 0 : 12; 2085 return true; 2086 } 2087 } 2088 2089 return false; 2090 } 2091 2092 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2093 bool &Swap, bool IsLE) { 2094 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2095 // Ensure each byte index of the word is consecutive. 2096 if (!isNByteElemShuffleMask(N, 4, 1)) 2097 return false; 2098 2099 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2100 unsigned M0 = N->getMaskElt(0) / 4; 2101 unsigned M1 = N->getMaskElt(4) / 4; 2102 unsigned M2 = N->getMaskElt(8) / 4; 2103 unsigned M3 = N->getMaskElt(12) / 4; 2104 2105 // If both vector operands for the shuffle are the same vector, the mask will 2106 // contain only elements from the first one and the second one will be undef. 2107 if (N->getOperand(1).isUndef()) { 2108 assert(M0 < 4 && "Indexing into an undef vector?"); 2109 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2110 return false; 2111 2112 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2113 Swap = false; 2114 return true; 2115 } 2116 2117 // Ensure each word index of the ShuffleVector Mask is consecutive. 2118 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2119 return false; 2120 2121 if (IsLE) { 2122 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2123 // Input vectors don't need to be swapped if the leading element 2124 // of the result is one of the 3 left elements of the second vector 2125 // (or if there is no shift to be done at all). 2126 Swap = false; 2127 ShiftElts = (8 - M0) % 8; 2128 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2129 // Input vectors need to be swapped if the leading element 2130 // of the result is one of the 3 left elements of the first vector 2131 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2132 Swap = true; 2133 ShiftElts = (4 - M0) % 4; 2134 } 2135 2136 return true; 2137 } else { // BE 2138 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2139 // Input vectors don't need to be swapped if the leading element 2140 // of the result is one of the 4 elements of the first vector. 2141 Swap = false; 2142 ShiftElts = M0; 2143 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2144 // Input vectors need to be swapped if the leading element 2145 // of the result is one of the 4 elements of the right vector. 2146 Swap = true; 2147 ShiftElts = M0 - 4; 2148 } 2149 2150 return true; 2151 } 2152 } 2153 2154 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2155 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2156 2157 if (!isNByteElemShuffleMask(N, Width, -1)) 2158 return false; 2159 2160 for (int i = 0; i < 16; i += Width) 2161 if (N->getMaskElt(i) != i + Width - 1) 2162 return false; 2163 2164 return true; 2165 } 2166 2167 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2168 return isXXBRShuffleMaskHelper(N, 2); 2169 } 2170 2171 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2172 return isXXBRShuffleMaskHelper(N, 4); 2173 } 2174 2175 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2176 return isXXBRShuffleMaskHelper(N, 8); 2177 } 2178 2179 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2180 return isXXBRShuffleMaskHelper(N, 16); 2181 } 2182 2183 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2184 /// if the inputs to the instruction should be swapped and set \p DM to the 2185 /// value for the immediate. 2186 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2187 /// AND element 0 of the result comes from the first input (LE) or second input 2188 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2189 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2190 /// mask. 2191 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2192 bool &Swap, bool IsLE) { 2193 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2194 2195 // Ensure each byte index of the double word is consecutive. 2196 if (!isNByteElemShuffleMask(N, 8, 1)) 2197 return false; 2198 2199 unsigned M0 = N->getMaskElt(0) / 8; 2200 unsigned M1 = N->getMaskElt(8) / 8; 2201 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2202 2203 // If both vector operands for the shuffle are the same vector, the mask will 2204 // contain only elements from the first one and the second one will be undef. 2205 if (N->getOperand(1).isUndef()) { 2206 if ((M0 | M1) < 2) { 2207 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2208 Swap = false; 2209 return true; 2210 } else 2211 return false; 2212 } 2213 2214 if (IsLE) { 2215 if (M0 > 1 && M1 < 2) { 2216 Swap = false; 2217 } else if (M0 < 2 && M1 > 1) { 2218 M0 = (M0 + 2) % 4; 2219 M1 = (M1 + 2) % 4; 2220 Swap = true; 2221 } else 2222 return false; 2223 2224 // Note: if control flow comes here that means Swap is already set above 2225 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2226 return true; 2227 } else { // BE 2228 if (M0 < 2 && M1 > 1) { 2229 Swap = false; 2230 } else if (M0 > 1 && M1 < 2) { 2231 M0 = (M0 + 2) % 4; 2232 M1 = (M1 + 2) % 4; 2233 Swap = true; 2234 } else 2235 return false; 2236 2237 // Note: if control flow comes here that means Swap is already set above 2238 DM = (M0 << 1) + (M1 & 1); 2239 return true; 2240 } 2241 } 2242 2243 2244 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2245 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2246 /// elements are counted from the left of the vector register). 2247 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2248 SelectionDAG &DAG) { 2249 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2250 assert(isSplatShuffleMask(SVOp, EltSize)); 2251 if (DAG.getDataLayout().isLittleEndian()) 2252 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2253 else 2254 return SVOp->getMaskElt(0) / EltSize; 2255 } 2256 2257 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2258 /// by using a vspltis[bhw] instruction of the specified element size, return 2259 /// the constant being splatted. The ByteSize field indicates the number of 2260 /// bytes of each element [124] -> [bhw]. 2261 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2262 SDValue OpVal(nullptr, 0); 2263 2264 // If ByteSize of the splat is bigger than the element size of the 2265 // build_vector, then we have a case where we are checking for a splat where 2266 // multiple elements of the buildvector are folded together into a single 2267 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2268 unsigned EltSize = 16/N->getNumOperands(); 2269 if (EltSize < ByteSize) { 2270 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2271 SDValue UniquedVals[4]; 2272 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2273 2274 // See if all of the elements in the buildvector agree across. 2275 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2276 if (N->getOperand(i).isUndef()) continue; 2277 // If the element isn't a constant, bail fully out. 2278 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2279 2280 if (!UniquedVals[i&(Multiple-1)].getNode()) 2281 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2282 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2283 return SDValue(); // no match. 2284 } 2285 2286 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2287 // either constant or undef values that are identical for each chunk. See 2288 // if these chunks can form into a larger vspltis*. 2289 2290 // Check to see if all of the leading entries are either 0 or -1. If 2291 // neither, then this won't fit into the immediate field. 2292 bool LeadingZero = true; 2293 bool LeadingOnes = true; 2294 for (unsigned i = 0; i != Multiple-1; ++i) { 2295 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2296 2297 LeadingZero &= isNullConstant(UniquedVals[i]); 2298 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2299 } 2300 // Finally, check the least significant entry. 2301 if (LeadingZero) { 2302 if (!UniquedVals[Multiple-1].getNode()) 2303 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2304 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2305 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2306 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2307 } 2308 if (LeadingOnes) { 2309 if (!UniquedVals[Multiple-1].getNode()) 2310 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2311 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2312 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2313 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2314 } 2315 2316 return SDValue(); 2317 } 2318 2319 // Check to see if this buildvec has a single non-undef value in its elements. 2320 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2321 if (N->getOperand(i).isUndef()) continue; 2322 if (!OpVal.getNode()) 2323 OpVal = N->getOperand(i); 2324 else if (OpVal != N->getOperand(i)) 2325 return SDValue(); 2326 } 2327 2328 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2329 2330 unsigned ValSizeInBytes = EltSize; 2331 uint64_t Value = 0; 2332 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2333 Value = CN->getZExtValue(); 2334 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2335 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2336 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2337 } 2338 2339 // If the splat value is larger than the element value, then we can never do 2340 // this splat. The only case that we could fit the replicated bits into our 2341 // immediate field for would be zero, and we prefer to use vxor for it. 2342 if (ValSizeInBytes < ByteSize) return SDValue(); 2343 2344 // If the element value is larger than the splat value, check if it consists 2345 // of a repeated bit pattern of size ByteSize. 2346 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2347 return SDValue(); 2348 2349 // Properly sign extend the value. 2350 int MaskVal = SignExtend32(Value, ByteSize * 8); 2351 2352 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2353 if (MaskVal == 0) return SDValue(); 2354 2355 // Finally, if this value fits in a 5 bit sext field, return it 2356 if (SignExtend32<5>(MaskVal) == MaskVal) 2357 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2358 return SDValue(); 2359 } 2360 2361 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2362 /// amount, otherwise return -1. 2363 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2364 EVT VT = N->getValueType(0); 2365 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2366 return -1; 2367 2368 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2369 2370 // Find the first non-undef value in the shuffle mask. 2371 unsigned i; 2372 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2373 /*search*/; 2374 2375 if (i == 4) return -1; // all undef. 2376 2377 // Otherwise, check to see if the rest of the elements are consecutively 2378 // numbered from this value. 2379 unsigned ShiftAmt = SVOp->getMaskElt(i); 2380 if (ShiftAmt < i) return -1; 2381 ShiftAmt -= i; 2382 2383 // Check the rest of the elements to see if they are consecutive. 2384 for (++i; i != 4; ++i) 2385 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2386 return -1; 2387 2388 return ShiftAmt; 2389 } 2390 2391 //===----------------------------------------------------------------------===// 2392 // Addressing Mode Selection 2393 //===----------------------------------------------------------------------===// 2394 2395 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2396 /// or 64-bit immediate, and if the value can be accurately represented as a 2397 /// sign extension from a 16-bit value. If so, this returns true and the 2398 /// immediate. 2399 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2400 if (!isa<ConstantSDNode>(N)) 2401 return false; 2402 2403 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2404 if (N->getValueType(0) == MVT::i32) 2405 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2406 else 2407 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2408 } 2409 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2410 return isIntS16Immediate(Op.getNode(), Imm); 2411 } 2412 2413 2414 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2415 /// be represented as an indexed [r+r] operation. 2416 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2417 SDValue &Index, 2418 SelectionDAG &DAG) const { 2419 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2420 UI != E; ++UI) { 2421 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2422 if (Memop->getMemoryVT() == MVT::f64) { 2423 Base = N.getOperand(0); 2424 Index = N.getOperand(1); 2425 return true; 2426 } 2427 } 2428 } 2429 return false; 2430 } 2431 2432 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2433 /// can be represented as an indexed [r+r] operation. Returns false if it 2434 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2435 /// non-zero and N can be represented by a base register plus a signed 16-bit 2436 /// displacement, make a more precise judgement by checking (displacement % \p 2437 /// EncodingAlignment). 2438 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2439 SDValue &Index, SelectionDAG &DAG, 2440 unsigned EncodingAlignment) const { 2441 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2442 // a [pc+imm]. 2443 if (SelectAddressPCRel(N, Base)) 2444 return false; 2445 2446 int16_t imm = 0; 2447 if (N.getOpcode() == ISD::ADD) { 2448 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2449 // SPE load/store can only handle 8-bit offsets. 2450 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2451 return true; 2452 if (isIntS16Immediate(N.getOperand(1), imm) && 2453 (!EncodingAlignment || !(imm % EncodingAlignment))) 2454 return false; // r+i 2455 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2456 return false; // r+i 2457 2458 Base = N.getOperand(0); 2459 Index = N.getOperand(1); 2460 return true; 2461 } else if (N.getOpcode() == ISD::OR) { 2462 if (isIntS16Immediate(N.getOperand(1), imm) && 2463 (!EncodingAlignment || !(imm % EncodingAlignment))) 2464 return false; // r+i can fold it if we can. 2465 2466 // If this is an or of disjoint bitfields, we can codegen this as an add 2467 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2468 // disjoint. 2469 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2470 2471 if (LHSKnown.Zero.getBoolValue()) { 2472 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2473 // If all of the bits are known zero on the LHS or RHS, the add won't 2474 // carry. 2475 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2476 Base = N.getOperand(0); 2477 Index = N.getOperand(1); 2478 return true; 2479 } 2480 } 2481 } 2482 2483 return false; 2484 } 2485 2486 // If we happen to be doing an i64 load or store into a stack slot that has 2487 // less than a 4-byte alignment, then the frame-index elimination may need to 2488 // use an indexed load or store instruction (because the offset may not be a 2489 // multiple of 4). The extra register needed to hold the offset comes from the 2490 // register scavenger, and it is possible that the scavenger will need to use 2491 // an emergency spill slot. As a result, we need to make sure that a spill slot 2492 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2493 // stack slot. 2494 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2495 // FIXME: This does not handle the LWA case. 2496 if (VT != MVT::i64) 2497 return; 2498 2499 // NOTE: We'll exclude negative FIs here, which come from argument 2500 // lowering, because there are no known test cases triggering this problem 2501 // using packed structures (or similar). We can remove this exclusion if 2502 // we find such a test case. The reason why this is so test-case driven is 2503 // because this entire 'fixup' is only to prevent crashes (from the 2504 // register scavenger) on not-really-valid inputs. For example, if we have: 2505 // %a = alloca i1 2506 // %b = bitcast i1* %a to i64* 2507 // store i64* a, i64 b 2508 // then the store should really be marked as 'align 1', but is not. If it 2509 // were marked as 'align 1' then the indexed form would have been 2510 // instruction-selected initially, and the problem this 'fixup' is preventing 2511 // won't happen regardless. 2512 if (FrameIdx < 0) 2513 return; 2514 2515 MachineFunction &MF = DAG.getMachineFunction(); 2516 MachineFrameInfo &MFI = MF.getFrameInfo(); 2517 2518 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2519 return; 2520 2521 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2522 FuncInfo->setHasNonRISpills(); 2523 } 2524 2525 /// Returns true if the address N can be represented by a base register plus 2526 /// a signed 16-bit displacement [r+imm], and if it is not better 2527 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2528 /// displacements that are multiples of that value. 2529 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2530 SDValue &Base, 2531 SelectionDAG &DAG, 2532 unsigned EncodingAlignment) const { 2533 // FIXME dl should come from parent load or store, not from address 2534 SDLoc dl(N); 2535 2536 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2537 // a [pc+imm]. 2538 if (SelectAddressPCRel(N, Base)) 2539 return false; 2540 2541 // If this can be more profitably realized as r+r, fail. 2542 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2543 return false; 2544 2545 if (N.getOpcode() == ISD::ADD) { 2546 int16_t imm = 0; 2547 if (isIntS16Immediate(N.getOperand(1), imm) && 2548 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2549 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2550 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2551 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2552 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2553 } else { 2554 Base = N.getOperand(0); 2555 } 2556 return true; // [r+i] 2557 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2558 // Match LOAD (ADD (X, Lo(G))). 2559 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2560 && "Cannot handle constant offsets yet!"); 2561 Disp = N.getOperand(1).getOperand(0); // The global address. 2562 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2563 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2564 Disp.getOpcode() == ISD::TargetConstantPool || 2565 Disp.getOpcode() == ISD::TargetJumpTable); 2566 Base = N.getOperand(0); 2567 return true; // [&g+r] 2568 } 2569 } else if (N.getOpcode() == ISD::OR) { 2570 int16_t imm = 0; 2571 if (isIntS16Immediate(N.getOperand(1), imm) && 2572 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2573 // If this is an or of disjoint bitfields, we can codegen this as an add 2574 // (for better address arithmetic) if the LHS and RHS of the OR are 2575 // provably disjoint. 2576 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2577 2578 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2579 // If all of the bits are known zero on the LHS or RHS, the add won't 2580 // carry. 2581 if (FrameIndexSDNode *FI = 2582 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2583 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2584 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2585 } else { 2586 Base = N.getOperand(0); 2587 } 2588 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2589 return true; 2590 } 2591 } 2592 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2593 // Loading from a constant address. 2594 2595 // If this address fits entirely in a 16-bit sext immediate field, codegen 2596 // this as "d, 0" 2597 int16_t Imm; 2598 if (isIntS16Immediate(CN, Imm) && 2599 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2600 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2601 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2602 CN->getValueType(0)); 2603 return true; 2604 } 2605 2606 // Handle 32-bit sext immediates with LIS + addr mode. 2607 if ((CN->getValueType(0) == MVT::i32 || 2608 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2609 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2610 int Addr = (int)CN->getZExtValue(); 2611 2612 // Otherwise, break this down into an LIS + disp. 2613 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2614 2615 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2616 MVT::i32); 2617 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2618 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2619 return true; 2620 } 2621 } 2622 2623 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2624 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2625 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2626 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2627 } else 2628 Base = N; 2629 return true; // [r+0] 2630 } 2631 2632 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2633 /// represented as an indexed [r+r] operation. 2634 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2635 SDValue &Index, 2636 SelectionDAG &DAG) const { 2637 // Check to see if we can easily represent this as an [r+r] address. This 2638 // will fail if it thinks that the address is more profitably represented as 2639 // reg+imm, e.g. where imm = 0. 2640 if (SelectAddressRegReg(N, Base, Index, DAG)) 2641 return true; 2642 2643 // If the address is the result of an add, we will utilize the fact that the 2644 // address calculation includes an implicit add. However, we can reduce 2645 // register pressure if we do not materialize a constant just for use as the 2646 // index register. We only get rid of the add if it is not an add of a 2647 // value and a 16-bit signed constant and both have a single use. 2648 int16_t imm = 0; 2649 if (N.getOpcode() == ISD::ADD && 2650 (!isIntS16Immediate(N.getOperand(1), imm) || 2651 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2652 Base = N.getOperand(0); 2653 Index = N.getOperand(1); 2654 return true; 2655 } 2656 2657 // Otherwise, do it the hard way, using R0 as the base register. 2658 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2659 N.getValueType()); 2660 Index = N; 2661 return true; 2662 } 2663 2664 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2665 Ty *PCRelCand = dyn_cast<Ty>(N); 2666 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2667 } 2668 2669 /// Returns true if this address is a PC Relative address. 2670 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2671 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2672 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2673 // This is a materialize PC Relative node. Always select this as PC Relative. 2674 Base = N; 2675 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2676 return true; 2677 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2678 isValidPCRelNode<GlobalAddressSDNode>(N) || 2679 isValidPCRelNode<JumpTableSDNode>(N) || 2680 isValidPCRelNode<BlockAddressSDNode>(N)) 2681 return true; 2682 return false; 2683 } 2684 2685 /// Returns true if we should use a direct load into vector instruction 2686 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2687 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2688 2689 // If there are any other uses other than scalar to vector, then we should 2690 // keep it as a scalar load -> direct move pattern to prevent multiple 2691 // loads. 2692 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2693 if (!LD) 2694 return false; 2695 2696 EVT MemVT = LD->getMemoryVT(); 2697 if (!MemVT.isSimple()) 2698 return false; 2699 switch(MemVT.getSimpleVT().SimpleTy) { 2700 case MVT::i64: 2701 break; 2702 case MVT::i32: 2703 if (!ST.hasP8Vector()) 2704 return false; 2705 break; 2706 case MVT::i16: 2707 case MVT::i8: 2708 if (!ST.hasP9Vector()) 2709 return false; 2710 break; 2711 default: 2712 return false; 2713 } 2714 2715 SDValue LoadedVal(N, 0); 2716 if (!LoadedVal.hasOneUse()) 2717 return false; 2718 2719 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2720 UI != UE; ++UI) 2721 if (UI.getUse().get().getResNo() == 0 && 2722 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2723 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2724 return false; 2725 2726 return true; 2727 } 2728 2729 /// getPreIndexedAddressParts - returns true by value, base pointer and 2730 /// offset pointer and addressing mode by reference if the node's address 2731 /// can be legally represented as pre-indexed load / store address. 2732 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2733 SDValue &Offset, 2734 ISD::MemIndexedMode &AM, 2735 SelectionDAG &DAG) const { 2736 if (DisablePPCPreinc) return false; 2737 2738 bool isLoad = true; 2739 SDValue Ptr; 2740 EVT VT; 2741 unsigned Alignment; 2742 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2743 Ptr = LD->getBasePtr(); 2744 VT = LD->getMemoryVT(); 2745 Alignment = LD->getAlignment(); 2746 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2747 Ptr = ST->getBasePtr(); 2748 VT = ST->getMemoryVT(); 2749 Alignment = ST->getAlignment(); 2750 isLoad = false; 2751 } else 2752 return false; 2753 2754 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2755 // instructions because we can fold these into a more efficient instruction 2756 // instead, (such as LXSD). 2757 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2758 return false; 2759 } 2760 2761 // PowerPC doesn't have preinc load/store instructions for vectors (except 2762 // for QPX, which does have preinc r+r forms). 2763 if (VT.isVector()) { 2764 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2765 return false; 2766 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2767 AM = ISD::PRE_INC; 2768 return true; 2769 } 2770 } 2771 2772 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2773 // Common code will reject creating a pre-inc form if the base pointer 2774 // is a frame index, or if N is a store and the base pointer is either 2775 // the same as or a predecessor of the value being stored. Check for 2776 // those situations here, and try with swapped Base/Offset instead. 2777 bool Swap = false; 2778 2779 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2780 Swap = true; 2781 else if (!isLoad) { 2782 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2783 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2784 Swap = true; 2785 } 2786 2787 if (Swap) 2788 std::swap(Base, Offset); 2789 2790 AM = ISD::PRE_INC; 2791 return true; 2792 } 2793 2794 // LDU/STU can only handle immediates that are a multiple of 4. 2795 if (VT != MVT::i64) { 2796 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2797 return false; 2798 } else { 2799 // LDU/STU need an address with at least 4-byte alignment. 2800 if (Alignment < 4) 2801 return false; 2802 2803 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2804 return false; 2805 } 2806 2807 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2808 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2809 // sext i32 to i64 when addr mode is r+i. 2810 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2811 LD->getExtensionType() == ISD::SEXTLOAD && 2812 isa<ConstantSDNode>(Offset)) 2813 return false; 2814 } 2815 2816 AM = ISD::PRE_INC; 2817 return true; 2818 } 2819 2820 //===----------------------------------------------------------------------===// 2821 // LowerOperation implementation 2822 //===----------------------------------------------------------------------===// 2823 2824 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2825 /// and LoOpFlags to the target MO flags. 2826 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2827 unsigned &HiOpFlags, unsigned &LoOpFlags, 2828 const GlobalValue *GV = nullptr) { 2829 HiOpFlags = PPCII::MO_HA; 2830 LoOpFlags = PPCII::MO_LO; 2831 2832 // Don't use the pic base if not in PIC relocation model. 2833 if (IsPIC) { 2834 HiOpFlags |= PPCII::MO_PIC_FLAG; 2835 LoOpFlags |= PPCII::MO_PIC_FLAG; 2836 } 2837 } 2838 2839 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2840 SelectionDAG &DAG) { 2841 SDLoc DL(HiPart); 2842 EVT PtrVT = HiPart.getValueType(); 2843 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2844 2845 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2846 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2847 2848 // With PIC, the first instruction is actually "GR+hi(&G)". 2849 if (isPIC) 2850 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2851 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2852 2853 // Generate non-pic code that has direct accesses to the constant pool. 2854 // The address of the global is just (hi(&g)+lo(&g)). 2855 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2856 } 2857 2858 static void setUsesTOCBasePtr(MachineFunction &MF) { 2859 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2860 FuncInfo->setUsesTOCBasePtr(); 2861 } 2862 2863 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2864 setUsesTOCBasePtr(DAG.getMachineFunction()); 2865 } 2866 2867 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2868 SDValue GA) const { 2869 const bool Is64Bit = Subtarget.isPPC64(); 2870 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2871 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2872 : Subtarget.isAIXABI() 2873 ? DAG.getRegister(PPC::R2, VT) 2874 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2875 SDValue Ops[] = { GA, Reg }; 2876 return DAG.getMemIntrinsicNode( 2877 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2878 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2879 MachineMemOperand::MOLoad); 2880 } 2881 2882 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2883 SelectionDAG &DAG) const { 2884 EVT PtrVT = Op.getValueType(); 2885 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2886 const Constant *C = CP->getConstVal(); 2887 2888 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2889 // The actual address of the GlobalValue is stored in the TOC. 2890 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2891 if (Subtarget.isUsingPCRelativeCalls()) { 2892 SDLoc DL(CP); 2893 EVT Ty = getPointerTy(DAG.getDataLayout()); 2894 SDValue ConstPool = DAG.getTargetConstantPool( 2895 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2896 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2897 } 2898 setUsesTOCBasePtr(DAG); 2899 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2900 return getTOCEntry(DAG, SDLoc(CP), GA); 2901 } 2902 2903 unsigned MOHiFlag, MOLoFlag; 2904 bool IsPIC = isPositionIndependent(); 2905 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2906 2907 if (IsPIC && Subtarget.isSVR4ABI()) { 2908 SDValue GA = 2909 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2910 return getTOCEntry(DAG, SDLoc(CP), GA); 2911 } 2912 2913 SDValue CPIHi = 2914 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2915 SDValue CPILo = 2916 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2917 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2918 } 2919 2920 // For 64-bit PowerPC, prefer the more compact relative encodings. 2921 // This trades 32 bits per jump table entry for one or two instructions 2922 // on the jump site. 2923 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2924 if (isJumpTableRelative()) 2925 return MachineJumpTableInfo::EK_LabelDifference32; 2926 2927 return TargetLowering::getJumpTableEncoding(); 2928 } 2929 2930 bool PPCTargetLowering::isJumpTableRelative() const { 2931 if (UseAbsoluteJumpTables) 2932 return false; 2933 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2934 return true; 2935 return TargetLowering::isJumpTableRelative(); 2936 } 2937 2938 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2939 SelectionDAG &DAG) const { 2940 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2941 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2942 2943 switch (getTargetMachine().getCodeModel()) { 2944 case CodeModel::Small: 2945 case CodeModel::Medium: 2946 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2947 default: 2948 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2949 getPointerTy(DAG.getDataLayout())); 2950 } 2951 } 2952 2953 const MCExpr * 2954 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2955 unsigned JTI, 2956 MCContext &Ctx) const { 2957 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2958 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2959 2960 switch (getTargetMachine().getCodeModel()) { 2961 case CodeModel::Small: 2962 case CodeModel::Medium: 2963 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2964 default: 2965 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2966 } 2967 } 2968 2969 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2970 EVT PtrVT = Op.getValueType(); 2971 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2972 2973 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2974 if (Subtarget.isUsingPCRelativeCalls()) { 2975 SDLoc DL(JT); 2976 EVT Ty = getPointerTy(DAG.getDataLayout()); 2977 SDValue GA = 2978 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2979 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2980 return MatAddr; 2981 } 2982 2983 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2984 // The actual address of the GlobalValue is stored in the TOC. 2985 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2986 setUsesTOCBasePtr(DAG); 2987 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2988 return getTOCEntry(DAG, SDLoc(JT), GA); 2989 } 2990 2991 unsigned MOHiFlag, MOLoFlag; 2992 bool IsPIC = isPositionIndependent(); 2993 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2994 2995 if (IsPIC && Subtarget.isSVR4ABI()) { 2996 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2997 PPCII::MO_PIC_FLAG); 2998 return getTOCEntry(DAG, SDLoc(GA), GA); 2999 } 3000 3001 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3002 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3003 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3004 } 3005 3006 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3007 SelectionDAG &DAG) const { 3008 EVT PtrVT = Op.getValueType(); 3009 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3010 const BlockAddress *BA = BASDN->getBlockAddress(); 3011 3012 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3013 if (Subtarget.isUsingPCRelativeCalls()) { 3014 SDLoc DL(BASDN); 3015 EVT Ty = getPointerTy(DAG.getDataLayout()); 3016 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3017 PPCII::MO_PCREL_FLAG); 3018 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3019 return MatAddr; 3020 } 3021 3022 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3023 // The actual BlockAddress is stored in the TOC. 3024 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3025 setUsesTOCBasePtr(DAG); 3026 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3027 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3028 } 3029 3030 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3031 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3032 return getTOCEntry( 3033 DAG, SDLoc(BASDN), 3034 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3035 3036 unsigned MOHiFlag, MOLoFlag; 3037 bool IsPIC = isPositionIndependent(); 3038 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3039 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3040 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3041 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3042 } 3043 3044 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3045 SelectionDAG &DAG) const { 3046 // FIXME: TLS addresses currently use medium model code sequences, 3047 // which is the most useful form. Eventually support for small and 3048 // large models could be added if users need it, at the cost of 3049 // additional complexity. 3050 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3051 if (DAG.getTarget().useEmulatedTLS()) 3052 return LowerToTLSEmulatedModel(GA, DAG); 3053 3054 SDLoc dl(GA); 3055 const GlobalValue *GV = GA->getGlobal(); 3056 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3057 bool is64bit = Subtarget.isPPC64(); 3058 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3059 PICLevel::Level picLevel = M->getPICLevel(); 3060 3061 const TargetMachine &TM = getTargetMachine(); 3062 TLSModel::Model Model = TM.getTLSModel(GV); 3063 3064 if (Model == TLSModel::LocalExec) { 3065 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3066 PPCII::MO_TPREL_HA); 3067 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3068 PPCII::MO_TPREL_LO); 3069 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3070 : DAG.getRegister(PPC::R2, MVT::i32); 3071 3072 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3073 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3074 } 3075 3076 if (Model == TLSModel::InitialExec) { 3077 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3078 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3079 PPCII::MO_TLS); 3080 SDValue GOTPtr; 3081 if (is64bit) { 3082 setUsesTOCBasePtr(DAG); 3083 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3084 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 3085 PtrVT, GOTReg, TGA); 3086 } else { 3087 if (!TM.isPositionIndependent()) 3088 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3089 else if (picLevel == PICLevel::SmallPIC) 3090 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3091 else 3092 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3093 } 3094 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 3095 PtrVT, TGA, GOTPtr); 3096 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3097 } 3098 3099 if (Model == TLSModel::GeneralDynamic) { 3100 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3101 SDValue GOTPtr; 3102 if (is64bit) { 3103 setUsesTOCBasePtr(DAG); 3104 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3105 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3106 GOTReg, TGA); 3107 } else { 3108 if (picLevel == PICLevel::SmallPIC) 3109 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3110 else 3111 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3112 } 3113 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3114 GOTPtr, TGA, TGA); 3115 } 3116 3117 if (Model == TLSModel::LocalDynamic) { 3118 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3119 SDValue GOTPtr; 3120 if (is64bit) { 3121 setUsesTOCBasePtr(DAG); 3122 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3123 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3124 GOTReg, TGA); 3125 } else { 3126 if (picLevel == PICLevel::SmallPIC) 3127 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3128 else 3129 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3130 } 3131 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3132 PtrVT, GOTPtr, TGA, TGA); 3133 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3134 PtrVT, TLSAddr, TGA); 3135 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3136 } 3137 3138 llvm_unreachable("Unknown TLS model!"); 3139 } 3140 3141 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3142 SelectionDAG &DAG) const { 3143 EVT PtrVT = Op.getValueType(); 3144 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3145 SDLoc DL(GSDN); 3146 const GlobalValue *GV = GSDN->getGlobal(); 3147 3148 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3149 // The actual address of the GlobalValue is stored in the TOC. 3150 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3151 if (Subtarget.isUsingPCRelativeCalls()) { 3152 EVT Ty = getPointerTy(DAG.getDataLayout()); 3153 if (isAccessedAsGotIndirect(Op)) { 3154 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3155 PPCII::MO_PCREL_FLAG | 3156 PPCII::MO_GOT_FLAG); 3157 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3158 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3159 MachinePointerInfo()); 3160 return Load; 3161 } else { 3162 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3163 PPCII::MO_PCREL_FLAG); 3164 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3165 } 3166 } 3167 setUsesTOCBasePtr(DAG); 3168 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3169 return getTOCEntry(DAG, DL, GA); 3170 } 3171 3172 unsigned MOHiFlag, MOLoFlag; 3173 bool IsPIC = isPositionIndependent(); 3174 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3175 3176 if (IsPIC && Subtarget.isSVR4ABI()) { 3177 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3178 GSDN->getOffset(), 3179 PPCII::MO_PIC_FLAG); 3180 return getTOCEntry(DAG, DL, GA); 3181 } 3182 3183 SDValue GAHi = 3184 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3185 SDValue GALo = 3186 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3187 3188 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3189 } 3190 3191 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3192 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3193 SDLoc dl(Op); 3194 3195 if (Op.getValueType() == MVT::v2i64) { 3196 // When the operands themselves are v2i64 values, we need to do something 3197 // special because VSX has no underlying comparison operations for these. 3198 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3199 // Equality can be handled by casting to the legal type for Altivec 3200 // comparisons, everything else needs to be expanded. 3201 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3202 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3203 DAG.getSetCC(dl, MVT::v4i32, 3204 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3205 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3206 CC)); 3207 } 3208 3209 return SDValue(); 3210 } 3211 3212 // We handle most of these in the usual way. 3213 return Op; 3214 } 3215 3216 // If we're comparing for equality to zero, expose the fact that this is 3217 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3218 // fold the new nodes. 3219 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3220 return V; 3221 3222 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3223 // Leave comparisons against 0 and -1 alone for now, since they're usually 3224 // optimized. FIXME: revisit this when we can custom lower all setcc 3225 // optimizations. 3226 if (C->isAllOnesValue() || C->isNullValue()) 3227 return SDValue(); 3228 } 3229 3230 // If we have an integer seteq/setne, turn it into a compare against zero 3231 // by xor'ing the rhs with the lhs, which is faster than setting a 3232 // condition register, reading it back out, and masking the correct bit. The 3233 // normal approach here uses sub to do this instead of xor. Using xor exposes 3234 // the result to other bit-twiddling opportunities. 3235 EVT LHSVT = Op.getOperand(0).getValueType(); 3236 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3237 EVT VT = Op.getValueType(); 3238 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3239 Op.getOperand(1)); 3240 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3241 } 3242 return SDValue(); 3243 } 3244 3245 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3246 SDNode *Node = Op.getNode(); 3247 EVT VT = Node->getValueType(0); 3248 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3249 SDValue InChain = Node->getOperand(0); 3250 SDValue VAListPtr = Node->getOperand(1); 3251 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3252 SDLoc dl(Node); 3253 3254 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3255 3256 // gpr_index 3257 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3258 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3259 InChain = GprIndex.getValue(1); 3260 3261 if (VT == MVT::i64) { 3262 // Check if GprIndex is even 3263 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3264 DAG.getConstant(1, dl, MVT::i32)); 3265 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3266 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3267 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3268 DAG.getConstant(1, dl, MVT::i32)); 3269 // Align GprIndex to be even if it isn't 3270 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3271 GprIndex); 3272 } 3273 3274 // fpr index is 1 byte after gpr 3275 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3276 DAG.getConstant(1, dl, MVT::i32)); 3277 3278 // fpr 3279 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3280 FprPtr, MachinePointerInfo(SV), MVT::i8); 3281 InChain = FprIndex.getValue(1); 3282 3283 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3284 DAG.getConstant(8, dl, MVT::i32)); 3285 3286 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3287 DAG.getConstant(4, dl, MVT::i32)); 3288 3289 // areas 3290 SDValue OverflowArea = 3291 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3292 InChain = OverflowArea.getValue(1); 3293 3294 SDValue RegSaveArea = 3295 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3296 InChain = RegSaveArea.getValue(1); 3297 3298 // select overflow_area if index > 8 3299 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3300 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3301 3302 // adjustment constant gpr_index * 4/8 3303 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3304 VT.isInteger() ? GprIndex : FprIndex, 3305 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3306 MVT::i32)); 3307 3308 // OurReg = RegSaveArea + RegConstant 3309 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3310 RegConstant); 3311 3312 // Floating types are 32 bytes into RegSaveArea 3313 if (VT.isFloatingPoint()) 3314 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3315 DAG.getConstant(32, dl, MVT::i32)); 3316 3317 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3318 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3319 VT.isInteger() ? GprIndex : FprIndex, 3320 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3321 MVT::i32)); 3322 3323 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3324 VT.isInteger() ? VAListPtr : FprPtr, 3325 MachinePointerInfo(SV), MVT::i8); 3326 3327 // determine if we should load from reg_save_area or overflow_area 3328 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3329 3330 // increase overflow_area by 4/8 if gpr/fpr > 8 3331 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3332 DAG.getConstant(VT.isInteger() ? 4 : 8, 3333 dl, MVT::i32)); 3334 3335 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3336 OverflowAreaPlusN); 3337 3338 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3339 MachinePointerInfo(), MVT::i32); 3340 3341 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3342 } 3343 3344 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3345 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3346 3347 // We have to copy the entire va_list struct: 3348 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3349 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3350 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3351 false, true, false, MachinePointerInfo(), 3352 MachinePointerInfo()); 3353 } 3354 3355 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3356 SelectionDAG &DAG) const { 3357 if (Subtarget.isAIXABI()) 3358 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3359 3360 return Op.getOperand(0); 3361 } 3362 3363 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3364 SelectionDAG &DAG) const { 3365 if (Subtarget.isAIXABI()) 3366 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3367 3368 SDValue Chain = Op.getOperand(0); 3369 SDValue Trmp = Op.getOperand(1); // trampoline 3370 SDValue FPtr = Op.getOperand(2); // nested function 3371 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3372 SDLoc dl(Op); 3373 3374 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3375 bool isPPC64 = (PtrVT == MVT::i64); 3376 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3377 3378 TargetLowering::ArgListTy Args; 3379 TargetLowering::ArgListEntry Entry; 3380 3381 Entry.Ty = IntPtrTy; 3382 Entry.Node = Trmp; Args.push_back(Entry); 3383 3384 // TrampSize == (isPPC64 ? 48 : 40); 3385 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3386 isPPC64 ? MVT::i64 : MVT::i32); 3387 Args.push_back(Entry); 3388 3389 Entry.Node = FPtr; Args.push_back(Entry); 3390 Entry.Node = Nest; Args.push_back(Entry); 3391 3392 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3393 TargetLowering::CallLoweringInfo CLI(DAG); 3394 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3395 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3396 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3397 3398 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3399 return CallResult.second; 3400 } 3401 3402 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3403 MachineFunction &MF = DAG.getMachineFunction(); 3404 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3405 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3406 3407 SDLoc dl(Op); 3408 3409 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3410 // vastart just stores the address of the VarArgsFrameIndex slot into the 3411 // memory location argument. 3412 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3413 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3414 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3415 MachinePointerInfo(SV)); 3416 } 3417 3418 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3419 // We suppose the given va_list is already allocated. 3420 // 3421 // typedef struct { 3422 // char gpr; /* index into the array of 8 GPRs 3423 // * stored in the register save area 3424 // * gpr=0 corresponds to r3, 3425 // * gpr=1 to r4, etc. 3426 // */ 3427 // char fpr; /* index into the array of 8 FPRs 3428 // * stored in the register save area 3429 // * fpr=0 corresponds to f1, 3430 // * fpr=1 to f2, etc. 3431 // */ 3432 // char *overflow_arg_area; 3433 // /* location on stack that holds 3434 // * the next overflow argument 3435 // */ 3436 // char *reg_save_area; 3437 // /* where r3:r10 and f1:f8 (if saved) 3438 // * are stored 3439 // */ 3440 // } va_list[1]; 3441 3442 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3443 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3444 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3445 PtrVT); 3446 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3447 PtrVT); 3448 3449 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3450 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3451 3452 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3453 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3454 3455 uint64_t FPROffset = 1; 3456 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3457 3458 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3459 3460 // Store first byte : number of int regs 3461 SDValue firstStore = 3462 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3463 MachinePointerInfo(SV), MVT::i8); 3464 uint64_t nextOffset = FPROffset; 3465 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3466 ConstFPROffset); 3467 3468 // Store second byte : number of float regs 3469 SDValue secondStore = 3470 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3471 MachinePointerInfo(SV, nextOffset), MVT::i8); 3472 nextOffset += StackOffset; 3473 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3474 3475 // Store second word : arguments given on stack 3476 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3477 MachinePointerInfo(SV, nextOffset)); 3478 nextOffset += FrameOffset; 3479 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3480 3481 // Store third word : arguments given in registers 3482 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3483 MachinePointerInfo(SV, nextOffset)); 3484 } 3485 3486 /// FPR - The set of FP registers that should be allocated for arguments 3487 /// on Darwin and AIX. 3488 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3489 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3490 PPC::F11, PPC::F12, PPC::F13}; 3491 3492 /// QFPR - The set of QPX registers that should be allocated for arguments. 3493 static const MCPhysReg QFPR[] = { 3494 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3495 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3496 3497 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3498 /// the stack. 3499 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3500 unsigned PtrByteSize) { 3501 unsigned ArgSize = ArgVT.getStoreSize(); 3502 if (Flags.isByVal()) 3503 ArgSize = Flags.getByValSize(); 3504 3505 // Round up to multiples of the pointer size, except for array members, 3506 // which are always packed. 3507 if (!Flags.isInConsecutiveRegs()) 3508 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3509 3510 return ArgSize; 3511 } 3512 3513 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3514 /// on the stack. 3515 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3516 ISD::ArgFlagsTy Flags, 3517 unsigned PtrByteSize) { 3518 Align Alignment(PtrByteSize); 3519 3520 // Altivec parameters are padded to a 16 byte boundary. 3521 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3522 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3523 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3524 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3525 Alignment = Align(16); 3526 // QPX vector types stored in double-precision are padded to a 32 byte 3527 // boundary. 3528 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3529 Alignment = Align(32); 3530 3531 // ByVal parameters are aligned as requested. 3532 if (Flags.isByVal()) { 3533 auto BVAlign = Flags.getNonZeroByValAlign(); 3534 if (BVAlign > PtrByteSize) { 3535 if (BVAlign.value() % PtrByteSize != 0) 3536 llvm_unreachable( 3537 "ByVal alignment is not a multiple of the pointer size"); 3538 3539 Alignment = BVAlign; 3540 } 3541 } 3542 3543 // Array members are always packed to their original alignment. 3544 if (Flags.isInConsecutiveRegs()) { 3545 // If the array member was split into multiple registers, the first 3546 // needs to be aligned to the size of the full type. (Except for 3547 // ppcf128, which is only aligned as its f64 components.) 3548 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3549 Alignment = Align(OrigVT.getStoreSize()); 3550 else 3551 Alignment = Align(ArgVT.getStoreSize()); 3552 } 3553 3554 return Alignment; 3555 } 3556 3557 /// CalculateStackSlotUsed - Return whether this argument will use its 3558 /// stack slot (instead of being passed in registers). ArgOffset, 3559 /// AvailableFPRs, and AvailableVRs must hold the current argument 3560 /// position, and will be updated to account for this argument. 3561 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3562 ISD::ArgFlagsTy Flags, 3563 unsigned PtrByteSize, 3564 unsigned LinkageSize, 3565 unsigned ParamAreaSize, 3566 unsigned &ArgOffset, 3567 unsigned &AvailableFPRs, 3568 unsigned &AvailableVRs, bool HasQPX) { 3569 bool UseMemory = false; 3570 3571 // Respect alignment of argument on the stack. 3572 Align Alignment = 3573 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3574 ArgOffset = alignTo(ArgOffset, Alignment); 3575 // If there's no space left in the argument save area, we must 3576 // use memory (this check also catches zero-sized arguments). 3577 if (ArgOffset >= LinkageSize + ParamAreaSize) 3578 UseMemory = true; 3579 3580 // Allocate argument on the stack. 3581 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3582 if (Flags.isInConsecutiveRegsLast()) 3583 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3584 // If we overran the argument save area, we must use memory 3585 // (this check catches arguments passed partially in memory) 3586 if (ArgOffset > LinkageSize + ParamAreaSize) 3587 UseMemory = true; 3588 3589 // However, if the argument is actually passed in an FPR or a VR, 3590 // we don't use memory after all. 3591 if (!Flags.isByVal()) { 3592 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3593 // QPX registers overlap with the scalar FP registers. 3594 (HasQPX && (ArgVT == MVT::v4f32 || 3595 ArgVT == MVT::v4f64 || 3596 ArgVT == MVT::v4i1))) 3597 if (AvailableFPRs > 0) { 3598 --AvailableFPRs; 3599 return false; 3600 } 3601 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3602 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3603 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3604 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3605 if (AvailableVRs > 0) { 3606 --AvailableVRs; 3607 return false; 3608 } 3609 } 3610 3611 return UseMemory; 3612 } 3613 3614 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3615 /// ensure minimum alignment required for target. 3616 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3617 unsigned NumBytes) { 3618 return alignTo(NumBytes, Lowering->getStackAlign()); 3619 } 3620 3621 SDValue PPCTargetLowering::LowerFormalArguments( 3622 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3623 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3624 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3625 if (Subtarget.isAIXABI()) 3626 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3627 InVals); 3628 if (Subtarget.is64BitELFABI()) 3629 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3630 InVals); 3631 if (Subtarget.is32BitELFABI()) 3632 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3633 InVals); 3634 3635 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3636 InVals); 3637 } 3638 3639 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3640 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3641 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3642 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3643 3644 // 32-bit SVR4 ABI Stack Frame Layout: 3645 // +-----------------------------------+ 3646 // +--> | Back chain | 3647 // | +-----------------------------------+ 3648 // | | Floating-point register save area | 3649 // | +-----------------------------------+ 3650 // | | General register save area | 3651 // | +-----------------------------------+ 3652 // | | CR save word | 3653 // | +-----------------------------------+ 3654 // | | VRSAVE save word | 3655 // | +-----------------------------------+ 3656 // | | Alignment padding | 3657 // | +-----------------------------------+ 3658 // | | Vector register save area | 3659 // | +-----------------------------------+ 3660 // | | Local variable space | 3661 // | +-----------------------------------+ 3662 // | | Parameter list area | 3663 // | +-----------------------------------+ 3664 // | | LR save word | 3665 // | +-----------------------------------+ 3666 // SP--> +--- | Back chain | 3667 // +-----------------------------------+ 3668 // 3669 // Specifications: 3670 // System V Application Binary Interface PowerPC Processor Supplement 3671 // AltiVec Technology Programming Interface Manual 3672 3673 MachineFunction &MF = DAG.getMachineFunction(); 3674 MachineFrameInfo &MFI = MF.getFrameInfo(); 3675 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3676 3677 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3678 // Potential tail calls could cause overwriting of argument stack slots. 3679 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3680 (CallConv == CallingConv::Fast)); 3681 const Align PtrAlign(4); 3682 3683 // Assign locations to all of the incoming arguments. 3684 SmallVector<CCValAssign, 16> ArgLocs; 3685 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3686 *DAG.getContext()); 3687 3688 // Reserve space for the linkage area on the stack. 3689 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3690 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3691 if (useSoftFloat()) 3692 CCInfo.PreAnalyzeFormalArguments(Ins); 3693 3694 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3695 CCInfo.clearWasPPCF128(); 3696 3697 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3698 CCValAssign &VA = ArgLocs[i]; 3699 3700 // Arguments stored in registers. 3701 if (VA.isRegLoc()) { 3702 const TargetRegisterClass *RC; 3703 EVT ValVT = VA.getValVT(); 3704 3705 switch (ValVT.getSimpleVT().SimpleTy) { 3706 default: 3707 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3708 case MVT::i1: 3709 case MVT::i32: 3710 RC = &PPC::GPRCRegClass; 3711 break; 3712 case MVT::f32: 3713 if (Subtarget.hasP8Vector()) 3714 RC = &PPC::VSSRCRegClass; 3715 else if (Subtarget.hasSPE()) 3716 RC = &PPC::GPRCRegClass; 3717 else 3718 RC = &PPC::F4RCRegClass; 3719 break; 3720 case MVT::f64: 3721 if (Subtarget.hasVSX()) 3722 RC = &PPC::VSFRCRegClass; 3723 else if (Subtarget.hasSPE()) 3724 // SPE passes doubles in GPR pairs. 3725 RC = &PPC::GPRCRegClass; 3726 else 3727 RC = &PPC::F8RCRegClass; 3728 break; 3729 case MVT::v16i8: 3730 case MVT::v8i16: 3731 case MVT::v4i32: 3732 RC = &PPC::VRRCRegClass; 3733 break; 3734 case MVT::v4f32: 3735 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3736 break; 3737 case MVT::v2f64: 3738 case MVT::v2i64: 3739 RC = &PPC::VRRCRegClass; 3740 break; 3741 case MVT::v4f64: 3742 RC = &PPC::QFRCRegClass; 3743 break; 3744 case MVT::v4i1: 3745 RC = &PPC::QBRCRegClass; 3746 break; 3747 } 3748 3749 SDValue ArgValue; 3750 // Transform the arguments stored in physical registers into 3751 // virtual ones. 3752 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3753 assert(i + 1 < e && "No second half of double precision argument"); 3754 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3755 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3756 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3757 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3758 if (!Subtarget.isLittleEndian()) 3759 std::swap (ArgValueLo, ArgValueHi); 3760 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3761 ArgValueHi); 3762 } else { 3763 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3764 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3765 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3766 if (ValVT == MVT::i1) 3767 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3768 } 3769 3770 InVals.push_back(ArgValue); 3771 } else { 3772 // Argument stored in memory. 3773 assert(VA.isMemLoc()); 3774 3775 // Get the extended size of the argument type in stack 3776 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3777 // Get the actual size of the argument type 3778 unsigned ObjSize = VA.getValVT().getStoreSize(); 3779 unsigned ArgOffset = VA.getLocMemOffset(); 3780 // Stack objects in PPC32 are right justified. 3781 ArgOffset += ArgSize - ObjSize; 3782 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3783 3784 // Create load nodes to retrieve arguments from the stack. 3785 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3786 InVals.push_back( 3787 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3788 } 3789 } 3790 3791 // Assign locations to all of the incoming aggregate by value arguments. 3792 // Aggregates passed by value are stored in the local variable space of the 3793 // caller's stack frame, right above the parameter list area. 3794 SmallVector<CCValAssign, 16> ByValArgLocs; 3795 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3796 ByValArgLocs, *DAG.getContext()); 3797 3798 // Reserve stack space for the allocations in CCInfo. 3799 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3800 3801 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3802 3803 // Area that is at least reserved in the caller of this function. 3804 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3805 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3806 3807 // Set the size that is at least reserved in caller of this function. Tail 3808 // call optimized function's reserved stack space needs to be aligned so that 3809 // taking the difference between two stack areas will result in an aligned 3810 // stack. 3811 MinReservedArea = 3812 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3813 FuncInfo->setMinReservedArea(MinReservedArea); 3814 3815 SmallVector<SDValue, 8> MemOps; 3816 3817 // If the function takes variable number of arguments, make a frame index for 3818 // the start of the first vararg value... for expansion of llvm.va_start. 3819 if (isVarArg) { 3820 static const MCPhysReg GPArgRegs[] = { 3821 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3822 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3823 }; 3824 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3825 3826 static const MCPhysReg FPArgRegs[] = { 3827 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3828 PPC::F8 3829 }; 3830 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3831 3832 if (useSoftFloat() || hasSPE()) 3833 NumFPArgRegs = 0; 3834 3835 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3836 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3837 3838 // Make room for NumGPArgRegs and NumFPArgRegs. 3839 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3840 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3841 3842 FuncInfo->setVarArgsStackOffset( 3843 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3844 CCInfo.getNextStackOffset(), true)); 3845 3846 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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()) 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: 14369 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14370 for (int i = 1, e = Mask.size(); i < e; i += 2) 14371 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14372 14373 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14374 return Res; 14375 } 14376 14377 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14378 LSBaseSDNode *LSBase, 14379 DAGCombinerInfo &DCI) const { 14380 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14381 "Not a reverse memop pattern!"); 14382 14383 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14384 auto Mask = SVN->getMask(); 14385 int i = 0; 14386 auto I = Mask.rbegin(); 14387 auto E = Mask.rend(); 14388 14389 for (; I != E; ++I) { 14390 if (*I != i) 14391 return false; 14392 i++; 14393 } 14394 return true; 14395 }; 14396 14397 SelectionDAG &DAG = DCI.DAG; 14398 EVT VT = SVN->getValueType(0); 14399 14400 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14401 return SDValue(); 14402 14403 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14404 // See comment in PPCVSXSwapRemoval.cpp. 14405 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14406 if (!Subtarget.hasP9Vector()) 14407 return SDValue(); 14408 14409 if(!IsElementReverse(SVN)) 14410 return SDValue(); 14411 14412 if (LSBase->getOpcode() == ISD::LOAD) { 14413 SDLoc dl(SVN); 14414 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14415 return DAG.getMemIntrinsicNode( 14416 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14417 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14418 } 14419 14420 if (LSBase->getOpcode() == ISD::STORE) { 14421 SDLoc dl(LSBase); 14422 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14423 LSBase->getBasePtr()}; 14424 return DAG.getMemIntrinsicNode( 14425 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14426 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14427 } 14428 14429 llvm_unreachable("Expected a load or store node here"); 14430 } 14431 14432 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14433 DAGCombinerInfo &DCI) const { 14434 SelectionDAG &DAG = DCI.DAG; 14435 SDLoc dl(N); 14436 switch (N->getOpcode()) { 14437 default: break; 14438 case ISD::ADD: 14439 return combineADD(N, DCI); 14440 case ISD::SHL: 14441 return combineSHL(N, DCI); 14442 case ISD::SRA: 14443 return combineSRA(N, DCI); 14444 case ISD::SRL: 14445 return combineSRL(N, DCI); 14446 case ISD::MUL: 14447 return combineMUL(N, DCI); 14448 case ISD::FMA: 14449 case PPCISD::FNMSUB: 14450 return combineFMALike(N, DCI); 14451 case PPCISD::SHL: 14452 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14453 return N->getOperand(0); 14454 break; 14455 case PPCISD::SRL: 14456 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14457 return N->getOperand(0); 14458 break; 14459 case PPCISD::SRA: 14460 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14461 if (C->isNullValue() || // 0 >>s V -> 0. 14462 C->isAllOnesValue()) // -1 >>s V -> -1. 14463 return N->getOperand(0); 14464 } 14465 break; 14466 case ISD::SIGN_EXTEND: 14467 case ISD::ZERO_EXTEND: 14468 case ISD::ANY_EXTEND: 14469 return DAGCombineExtBoolTrunc(N, DCI); 14470 case ISD::TRUNCATE: 14471 return combineTRUNCATE(N, DCI); 14472 case ISD::SETCC: 14473 if (SDValue CSCC = combineSetCC(N, DCI)) 14474 return CSCC; 14475 LLVM_FALLTHROUGH; 14476 case ISD::SELECT_CC: 14477 return DAGCombineTruncBoolExt(N, DCI); 14478 case ISD::SINT_TO_FP: 14479 case ISD::UINT_TO_FP: 14480 return combineFPToIntToFP(N, DCI); 14481 case ISD::VECTOR_SHUFFLE: 14482 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14483 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14484 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14485 } 14486 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14487 case ISD::STORE: { 14488 14489 EVT Op1VT = N->getOperand(1).getValueType(); 14490 unsigned Opcode = N->getOperand(1).getOpcode(); 14491 14492 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14493 SDValue Val= combineStoreFPToInt(N, DCI); 14494 if (Val) 14495 return Val; 14496 } 14497 14498 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14499 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14500 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14501 if (Val) 14502 return Val; 14503 } 14504 14505 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14506 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14507 N->getOperand(1).getNode()->hasOneUse() && 14508 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14509 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14510 14511 // STBRX can only handle simple types and it makes no sense to store less 14512 // two bytes in byte-reversed order. 14513 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14514 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14515 break; 14516 14517 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14518 // Do an any-extend to 32-bits if this is a half-word input. 14519 if (BSwapOp.getValueType() == MVT::i16) 14520 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14521 14522 // If the type of BSWAP operand is wider than stored memory width 14523 // it need to be shifted to the right side before STBRX. 14524 if (Op1VT.bitsGT(mVT)) { 14525 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14526 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14527 DAG.getConstant(Shift, dl, MVT::i32)); 14528 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14529 if (Op1VT == MVT::i64) 14530 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14531 } 14532 14533 SDValue Ops[] = { 14534 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14535 }; 14536 return 14537 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14538 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14539 cast<StoreSDNode>(N)->getMemOperand()); 14540 } 14541 14542 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14543 // So it can increase the chance of CSE constant construction. 14544 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14545 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14546 // Need to sign-extended to 64-bits to handle negative values. 14547 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14548 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14549 MemVT.getSizeInBits()); 14550 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14551 14552 // DAG.getTruncStore() can't be used here because it doesn't accept 14553 // the general (base + offset) addressing mode. 14554 // So we use UpdateNodeOperands and setTruncatingStore instead. 14555 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14556 N->getOperand(3)); 14557 cast<StoreSDNode>(N)->setTruncatingStore(true); 14558 return SDValue(N, 0); 14559 } 14560 14561 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14562 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14563 if (Op1VT.isSimple()) { 14564 MVT StoreVT = Op1VT.getSimpleVT(); 14565 if (Subtarget.needsSwapsForVSXMemOps() && 14566 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14567 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14568 return expandVSXStoreForLE(N, DCI); 14569 } 14570 break; 14571 } 14572 case ISD::LOAD: { 14573 LoadSDNode *LD = cast<LoadSDNode>(N); 14574 EVT VT = LD->getValueType(0); 14575 14576 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14577 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14578 if (VT.isSimple()) { 14579 MVT LoadVT = VT.getSimpleVT(); 14580 if (Subtarget.needsSwapsForVSXMemOps() && 14581 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14582 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14583 return expandVSXLoadForLE(N, DCI); 14584 } 14585 14586 // We sometimes end up with a 64-bit integer load, from which we extract 14587 // two single-precision floating-point numbers. This happens with 14588 // std::complex<float>, and other similar structures, because of the way we 14589 // canonicalize structure copies. However, if we lack direct moves, 14590 // then the final bitcasts from the extracted integer values to the 14591 // floating-point numbers turn into store/load pairs. Even with direct moves, 14592 // just loading the two floating-point numbers is likely better. 14593 auto ReplaceTwoFloatLoad = [&]() { 14594 if (VT != MVT::i64) 14595 return false; 14596 14597 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14598 LD->isVolatile()) 14599 return false; 14600 14601 // We're looking for a sequence like this: 14602 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14603 // t16: i64 = srl t13, Constant:i32<32> 14604 // t17: i32 = truncate t16 14605 // t18: f32 = bitcast t17 14606 // t19: i32 = truncate t13 14607 // t20: f32 = bitcast t19 14608 14609 if (!LD->hasNUsesOfValue(2, 0)) 14610 return false; 14611 14612 auto UI = LD->use_begin(); 14613 while (UI.getUse().getResNo() != 0) ++UI; 14614 SDNode *Trunc = *UI++; 14615 while (UI.getUse().getResNo() != 0) ++UI; 14616 SDNode *RightShift = *UI; 14617 if (Trunc->getOpcode() != ISD::TRUNCATE) 14618 std::swap(Trunc, RightShift); 14619 14620 if (Trunc->getOpcode() != ISD::TRUNCATE || 14621 Trunc->getValueType(0) != MVT::i32 || 14622 !Trunc->hasOneUse()) 14623 return false; 14624 if (RightShift->getOpcode() != ISD::SRL || 14625 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14626 RightShift->getConstantOperandVal(1) != 32 || 14627 !RightShift->hasOneUse()) 14628 return false; 14629 14630 SDNode *Trunc2 = *RightShift->use_begin(); 14631 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14632 Trunc2->getValueType(0) != MVT::i32 || 14633 !Trunc2->hasOneUse()) 14634 return false; 14635 14636 SDNode *Bitcast = *Trunc->use_begin(); 14637 SDNode *Bitcast2 = *Trunc2->use_begin(); 14638 14639 if (Bitcast->getOpcode() != ISD::BITCAST || 14640 Bitcast->getValueType(0) != MVT::f32) 14641 return false; 14642 if (Bitcast2->getOpcode() != ISD::BITCAST || 14643 Bitcast2->getValueType(0) != MVT::f32) 14644 return false; 14645 14646 if (Subtarget.isLittleEndian()) 14647 std::swap(Bitcast, Bitcast2); 14648 14649 // Bitcast has the second float (in memory-layout order) and Bitcast2 14650 // has the first one. 14651 14652 SDValue BasePtr = LD->getBasePtr(); 14653 if (LD->isIndexed()) { 14654 assert(LD->getAddressingMode() == ISD::PRE_INC && 14655 "Non-pre-inc AM on PPC?"); 14656 BasePtr = 14657 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14658 LD->getOffset()); 14659 } 14660 14661 auto MMOFlags = 14662 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14663 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14664 LD->getPointerInfo(), LD->getAlignment(), 14665 MMOFlags, LD->getAAInfo()); 14666 SDValue AddPtr = 14667 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14668 BasePtr, DAG.getIntPtrConstant(4, dl)); 14669 SDValue FloatLoad2 = DAG.getLoad( 14670 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14671 LD->getPointerInfo().getWithOffset(4), 14672 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14673 14674 if (LD->isIndexed()) { 14675 // Note that DAGCombine should re-form any pre-increment load(s) from 14676 // what is produced here if that makes sense. 14677 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14678 } 14679 14680 DCI.CombineTo(Bitcast2, FloatLoad); 14681 DCI.CombineTo(Bitcast, FloatLoad2); 14682 14683 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14684 SDValue(FloatLoad2.getNode(), 1)); 14685 return true; 14686 }; 14687 14688 if (ReplaceTwoFloatLoad()) 14689 return SDValue(N, 0); 14690 14691 EVT MemVT = LD->getMemoryVT(); 14692 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14693 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 14694 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 14695 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 14696 if (LD->isUnindexed() && VT.isVector() && 14697 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14698 // P8 and later hardware should just use LOAD. 14699 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 14700 VT == MVT::v4i32 || VT == MVT::v4f32)) || 14701 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 14702 LD->getAlignment() >= ScalarABIAlignment)) && 14703 LD->getAlignment() < ABIAlignment) { 14704 // This is a type-legal unaligned Altivec or QPX load. 14705 SDValue Chain = LD->getChain(); 14706 SDValue Ptr = LD->getBasePtr(); 14707 bool isLittleEndian = Subtarget.isLittleEndian(); 14708 14709 // This implements the loading of unaligned vectors as described in 14710 // the venerable Apple Velocity Engine overview. Specifically: 14711 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14712 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14713 // 14714 // The general idea is to expand a sequence of one or more unaligned 14715 // loads into an alignment-based permutation-control instruction (lvsl 14716 // or lvsr), a series of regular vector loads (which always truncate 14717 // their input address to an aligned address), and a series of 14718 // permutations. The results of these permutations are the requested 14719 // loaded values. The trick is that the last "extra" load is not taken 14720 // from the address you might suspect (sizeof(vector) bytes after the 14721 // last requested load), but rather sizeof(vector) - 1 bytes after the 14722 // last requested vector. The point of this is to avoid a page fault if 14723 // the base address happened to be aligned. This works because if the 14724 // base address is aligned, then adding less than a full vector length 14725 // will cause the last vector in the sequence to be (re)loaded. 14726 // Otherwise, the next vector will be fetched as you might suspect was 14727 // necessary. 14728 14729 // We might be able to reuse the permutation generation from 14730 // a different base address offset from this one by an aligned amount. 14731 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14732 // optimization later. 14733 Intrinsic::ID Intr, IntrLD, IntrPerm; 14734 MVT PermCntlTy, PermTy, LDTy; 14735 if (Subtarget.hasAltivec()) { 14736 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 14737 Intrinsic::ppc_altivec_lvsl; 14738 IntrLD = Intrinsic::ppc_altivec_lvx; 14739 IntrPerm = Intrinsic::ppc_altivec_vperm; 14740 PermCntlTy = MVT::v16i8; 14741 PermTy = MVT::v4i32; 14742 LDTy = MVT::v4i32; 14743 } else { 14744 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 14745 Intrinsic::ppc_qpx_qvlpcls; 14746 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 14747 Intrinsic::ppc_qpx_qvlfs; 14748 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 14749 PermCntlTy = MVT::v4f64; 14750 PermTy = MVT::v4f64; 14751 LDTy = MemVT.getSimpleVT(); 14752 } 14753 14754 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14755 14756 // Create the new MMO for the new base load. It is like the original MMO, 14757 // but represents an area in memory almost twice the vector size centered 14758 // on the original address. If the address is unaligned, we might start 14759 // reading up to (sizeof(vector)-1) bytes below the address of the 14760 // original unaligned load. 14761 MachineFunction &MF = DAG.getMachineFunction(); 14762 MachineMemOperand *BaseMMO = 14763 MF.getMachineMemOperand(LD->getMemOperand(), 14764 -(long)MemVT.getStoreSize()+1, 14765 2*MemVT.getStoreSize()-1); 14766 14767 // Create the new base load. 14768 SDValue LDXIntID = 14769 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14770 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14771 SDValue BaseLoad = 14772 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14773 DAG.getVTList(PermTy, MVT::Other), 14774 BaseLoadOps, LDTy, BaseMMO); 14775 14776 // Note that the value of IncOffset (which is provided to the next 14777 // load's pointer info offset value, and thus used to calculate the 14778 // alignment), and the value of IncValue (which is actually used to 14779 // increment the pointer value) are different! This is because we 14780 // require the next load to appear to be aligned, even though it 14781 // is actually offset from the base pointer by a lesser amount. 14782 int IncOffset = VT.getSizeInBits() / 8; 14783 int IncValue = IncOffset; 14784 14785 // Walk (both up and down) the chain looking for another load at the real 14786 // (aligned) offset (the alignment of the other load does not matter in 14787 // this case). If found, then do not use the offset reduction trick, as 14788 // that will prevent the loads from being later combined (as they would 14789 // otherwise be duplicates). 14790 if (!findConsecutiveLoad(LD, DAG)) 14791 --IncValue; 14792 14793 SDValue Increment = 14794 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14795 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14796 14797 MachineMemOperand *ExtraMMO = 14798 MF.getMachineMemOperand(LD->getMemOperand(), 14799 1, 2*MemVT.getStoreSize()-1); 14800 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14801 SDValue ExtraLoad = 14802 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14803 DAG.getVTList(PermTy, MVT::Other), 14804 ExtraLoadOps, LDTy, ExtraMMO); 14805 14806 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14807 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14808 14809 // Because vperm has a big-endian bias, we must reverse the order 14810 // of the input vectors and complement the permute control vector 14811 // when generating little endian code. We have already handled the 14812 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14813 // and ExtraLoad here. 14814 SDValue Perm; 14815 if (isLittleEndian) 14816 Perm = BuildIntrinsicOp(IntrPerm, 14817 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14818 else 14819 Perm = BuildIntrinsicOp(IntrPerm, 14820 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14821 14822 if (VT != PermTy) 14823 Perm = Subtarget.hasAltivec() ? 14824 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14825 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14826 DAG.getTargetConstant(1, dl, MVT::i64)); 14827 // second argument is 1 because this rounding 14828 // is always exact. 14829 14830 // The output of the permutation is our loaded result, the TokenFactor is 14831 // our new chain. 14832 DCI.CombineTo(N, Perm, TF); 14833 return SDValue(N, 0); 14834 } 14835 } 14836 break; 14837 case ISD::INTRINSIC_WO_CHAIN: { 14838 bool isLittleEndian = Subtarget.isLittleEndian(); 14839 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14840 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14841 : Intrinsic::ppc_altivec_lvsl); 14842 if ((IID == Intr || 14843 IID == Intrinsic::ppc_qpx_qvlpcld || 14844 IID == Intrinsic::ppc_qpx_qvlpcls) && 14845 N->getOperand(1)->getOpcode() == ISD::ADD) { 14846 SDValue Add = N->getOperand(1); 14847 14848 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14849 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14850 14851 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14852 APInt::getAllOnesValue(Bits /* alignment */) 14853 .zext(Add.getScalarValueSizeInBits()))) { 14854 SDNode *BasePtr = Add->getOperand(0).getNode(); 14855 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14856 UE = BasePtr->use_end(); 14857 UI != UE; ++UI) { 14858 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14859 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14860 // We've found another LVSL/LVSR, and this address is an aligned 14861 // multiple of that one. The results will be the same, so use the 14862 // one we've just found instead. 14863 14864 return SDValue(*UI, 0); 14865 } 14866 } 14867 } 14868 14869 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14870 SDNode *BasePtr = Add->getOperand(0).getNode(); 14871 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14872 UE = BasePtr->use_end(); UI != UE; ++UI) { 14873 if (UI->getOpcode() == ISD::ADD && 14874 isa<ConstantSDNode>(UI->getOperand(1)) && 14875 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14876 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14877 (1ULL << Bits) == 0) { 14878 SDNode *OtherAdd = *UI; 14879 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14880 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14881 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14882 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14883 return SDValue(*VI, 0); 14884 } 14885 } 14886 } 14887 } 14888 } 14889 } 14890 14891 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14892 // Expose the vabsduw/h/b opportunity for down stream 14893 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14894 (IID == Intrinsic::ppc_altivec_vmaxsw || 14895 IID == Intrinsic::ppc_altivec_vmaxsh || 14896 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14897 SDValue V1 = N->getOperand(1); 14898 SDValue V2 = N->getOperand(2); 14899 if ((V1.getSimpleValueType() == MVT::v4i32 || 14900 V1.getSimpleValueType() == MVT::v8i16 || 14901 V1.getSimpleValueType() == MVT::v16i8) && 14902 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14903 // (0-a, a) 14904 if (V1.getOpcode() == ISD::SUB && 14905 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14906 V1.getOperand(1) == V2) { 14907 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14908 } 14909 // (a, 0-a) 14910 if (V2.getOpcode() == ISD::SUB && 14911 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14912 V2.getOperand(1) == V1) { 14913 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14914 } 14915 // (x-y, y-x) 14916 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14917 V1.getOperand(0) == V2.getOperand(1) && 14918 V1.getOperand(1) == V2.getOperand(0)) { 14919 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14920 } 14921 } 14922 } 14923 } 14924 14925 break; 14926 case ISD::INTRINSIC_W_CHAIN: 14927 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14928 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14929 if (Subtarget.needsSwapsForVSXMemOps()) { 14930 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14931 default: 14932 break; 14933 case Intrinsic::ppc_vsx_lxvw4x: 14934 case Intrinsic::ppc_vsx_lxvd2x: 14935 return expandVSXLoadForLE(N, DCI); 14936 } 14937 } 14938 break; 14939 case ISD::INTRINSIC_VOID: 14940 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14941 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14942 if (Subtarget.needsSwapsForVSXMemOps()) { 14943 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14944 default: 14945 break; 14946 case Intrinsic::ppc_vsx_stxvw4x: 14947 case Intrinsic::ppc_vsx_stxvd2x: 14948 return expandVSXStoreForLE(N, DCI); 14949 } 14950 } 14951 break; 14952 case ISD::BSWAP: 14953 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14954 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14955 N->getOperand(0).hasOneUse() && 14956 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14957 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14958 N->getValueType(0) == MVT::i64))) { 14959 SDValue Load = N->getOperand(0); 14960 LoadSDNode *LD = cast<LoadSDNode>(Load); 14961 // Create the byte-swapping load. 14962 SDValue Ops[] = { 14963 LD->getChain(), // Chain 14964 LD->getBasePtr(), // Ptr 14965 DAG.getValueType(N->getValueType(0)) // VT 14966 }; 14967 SDValue BSLoad = 14968 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14969 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14970 MVT::i64 : MVT::i32, MVT::Other), 14971 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14972 14973 // If this is an i16 load, insert the truncate. 14974 SDValue ResVal = BSLoad; 14975 if (N->getValueType(0) == MVT::i16) 14976 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14977 14978 // First, combine the bswap away. This makes the value produced by the 14979 // load dead. 14980 DCI.CombineTo(N, ResVal); 14981 14982 // Next, combine the load away, we give it a bogus result value but a real 14983 // chain result. The result value is dead because the bswap is dead. 14984 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14985 14986 // Return N so it doesn't get rechecked! 14987 return SDValue(N, 0); 14988 } 14989 break; 14990 case PPCISD::VCMP: 14991 // If a VCMPo node already exists with exactly the same operands as this 14992 // node, use its result instead of this node (VCMPo computes both a CR6 and 14993 // a normal output). 14994 // 14995 if (!N->getOperand(0).hasOneUse() && 14996 !N->getOperand(1).hasOneUse() && 14997 !N->getOperand(2).hasOneUse()) { 14998 14999 // Scan all of the users of the LHS, looking for VCMPo's that match. 15000 SDNode *VCMPoNode = nullptr; 15001 15002 SDNode *LHSN = N->getOperand(0).getNode(); 15003 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15004 UI != E; ++UI) 15005 if (UI->getOpcode() == PPCISD::VCMPo && 15006 UI->getOperand(1) == N->getOperand(1) && 15007 UI->getOperand(2) == N->getOperand(2) && 15008 UI->getOperand(0) == N->getOperand(0)) { 15009 VCMPoNode = *UI; 15010 break; 15011 } 15012 15013 // If there is no VCMPo node, or if the flag value has a single use, don't 15014 // transform this. 15015 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 15016 break; 15017 15018 // Look at the (necessarily single) use of the flag value. If it has a 15019 // chain, this transformation is more complex. Note that multiple things 15020 // could use the value result, which we should ignore. 15021 SDNode *FlagUser = nullptr; 15022 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 15023 FlagUser == nullptr; ++UI) { 15024 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 15025 SDNode *User = *UI; 15026 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15027 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 15028 FlagUser = User; 15029 break; 15030 } 15031 } 15032 } 15033 15034 // If the user is a MFOCRF instruction, we know this is safe. 15035 // Otherwise we give up for right now. 15036 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15037 return SDValue(VCMPoNode, 0); 15038 } 15039 break; 15040 case ISD::BRCOND: { 15041 SDValue Cond = N->getOperand(1); 15042 SDValue Target = N->getOperand(2); 15043 15044 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15045 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 15046 Intrinsic::loop_decrement) { 15047 15048 // We now need to make the intrinsic dead (it cannot be instruction 15049 // selected). 15050 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 15051 assert(Cond.getNode()->hasOneUse() && 15052 "Counter decrement has more than one use"); 15053 15054 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 15055 N->getOperand(0), Target); 15056 } 15057 } 15058 break; 15059 case ISD::BR_CC: { 15060 // If this is a branch on an altivec predicate comparison, lower this so 15061 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15062 // lowering is done pre-legalize, because the legalizer lowers the predicate 15063 // compare down to code that is difficult to reassemble. 15064 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15065 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15066 15067 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 15068 // value. If so, pass-through the AND to get to the intrinsic. 15069 if (LHS.getOpcode() == ISD::AND && 15070 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 15071 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 15072 Intrinsic::loop_decrement && 15073 isa<ConstantSDNode>(LHS.getOperand(1)) && 15074 !isNullConstant(LHS.getOperand(1))) 15075 LHS = LHS.getOperand(0); 15076 15077 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15078 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 15079 Intrinsic::loop_decrement && 15080 isa<ConstantSDNode>(RHS)) { 15081 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 15082 "Counter decrement comparison is not EQ or NE"); 15083 15084 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15085 bool isBDNZ = (CC == ISD::SETEQ && Val) || 15086 (CC == ISD::SETNE && !Val); 15087 15088 // We now need to make the intrinsic dead (it cannot be instruction 15089 // selected). 15090 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 15091 assert(LHS.getNode()->hasOneUse() && 15092 "Counter decrement has more than one use"); 15093 15094 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 15095 N->getOperand(0), N->getOperand(4)); 15096 } 15097 15098 int CompareOpc; 15099 bool isDot; 15100 15101 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15102 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 15103 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15104 assert(isDot && "Can't compare against a vector result!"); 15105 15106 // If this is a comparison against something other than 0/1, then we know 15107 // that the condition is never/always true. 15108 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 15109 if (Val != 0 && Val != 1) { 15110 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15111 return N->getOperand(0); 15112 // Always !=, turn it into an unconditional branch. 15113 return DAG.getNode(ISD::BR, dl, MVT::Other, 15114 N->getOperand(0), N->getOperand(4)); 15115 } 15116 15117 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15118 15119 // Create the PPCISD altivec 'dot' comparison node. 15120 SDValue Ops[] = { 15121 LHS.getOperand(2), // LHS of compare 15122 LHS.getOperand(3), // RHS of compare 15123 DAG.getConstant(CompareOpc, dl, MVT::i32) 15124 }; 15125 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15126 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 15127 15128 // Unpack the result based on how the target uses it. 15129 PPC::Predicate CompOpc; 15130 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15131 default: // Can't happen, don't crash on invalid number though. 15132 case 0: // Branch on the value of the EQ bit of CR6. 15133 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15134 break; 15135 case 1: // Branch on the inverted value of the EQ bit of CR6. 15136 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15137 break; 15138 case 2: // Branch on the value of the LT bit of CR6. 15139 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 15140 break; 15141 case 3: // Branch on the inverted value of the LT bit of CR6. 15142 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 15143 break; 15144 } 15145 15146 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 15147 DAG.getConstant(CompOpc, dl, MVT::i32), 15148 DAG.getRegister(PPC::CR6, MVT::i32), 15149 N->getOperand(4), CompNode.getValue(1)); 15150 } 15151 break; 15152 } 15153 case ISD::BUILD_VECTOR: 15154 return DAGCombineBuildVector(N, DCI); 15155 case ISD::ABS: 15156 return combineABS(N, DCI); 15157 case ISD::VSELECT: 15158 return combineVSelect(N, DCI); 15159 } 15160 15161 return SDValue(); 15162 } 15163 15164 SDValue 15165 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 15166 SelectionDAG &DAG, 15167 SmallVectorImpl<SDNode *> &Created) const { 15168 // fold (sdiv X, pow2) 15169 EVT VT = N->getValueType(0); 15170 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15171 return SDValue(); 15172 if ((VT != MVT::i32 && VT != MVT::i64) || 15173 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15174 return SDValue(); 15175 15176 SDLoc DL(N); 15177 SDValue N0 = N->getOperand(0); 15178 15179 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15180 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15181 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15182 15183 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15184 Created.push_back(Op.getNode()); 15185 15186 if (IsNegPow2) { 15187 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15188 Created.push_back(Op.getNode()); 15189 } 15190 15191 return Op; 15192 } 15193 15194 //===----------------------------------------------------------------------===// 15195 // Inline Assembly Support 15196 //===----------------------------------------------------------------------===// 15197 15198 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15199 KnownBits &Known, 15200 const APInt &DemandedElts, 15201 const SelectionDAG &DAG, 15202 unsigned Depth) const { 15203 Known.resetAll(); 15204 switch (Op.getOpcode()) { 15205 default: break; 15206 case PPCISD::LBRX: { 15207 // lhbrx is known to have the top bits cleared out. 15208 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15209 Known.Zero = 0xFFFF0000; 15210 break; 15211 } 15212 case ISD::INTRINSIC_WO_CHAIN: { 15213 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15214 default: break; 15215 case Intrinsic::ppc_altivec_vcmpbfp_p: 15216 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15217 case Intrinsic::ppc_altivec_vcmpequb_p: 15218 case Intrinsic::ppc_altivec_vcmpequh_p: 15219 case Intrinsic::ppc_altivec_vcmpequw_p: 15220 case Intrinsic::ppc_altivec_vcmpequd_p: 15221 case Intrinsic::ppc_altivec_vcmpgefp_p: 15222 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15223 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15224 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15225 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15226 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15227 case Intrinsic::ppc_altivec_vcmpgtub_p: 15228 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15229 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15230 case Intrinsic::ppc_altivec_vcmpgtud_p: 15231 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15232 break; 15233 } 15234 } 15235 } 15236 } 15237 15238 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15239 switch (Subtarget.getCPUDirective()) { 15240 default: break; 15241 case PPC::DIR_970: 15242 case PPC::DIR_PWR4: 15243 case PPC::DIR_PWR5: 15244 case PPC::DIR_PWR5X: 15245 case PPC::DIR_PWR6: 15246 case PPC::DIR_PWR6X: 15247 case PPC::DIR_PWR7: 15248 case PPC::DIR_PWR8: 15249 case PPC::DIR_PWR9: 15250 case PPC::DIR_PWR10: 15251 case PPC::DIR_PWR_FUTURE: { 15252 if (!ML) 15253 break; 15254 15255 if (!DisableInnermostLoopAlign32) { 15256 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15257 // so that we can decrease cache misses and branch-prediction misses. 15258 // Actual alignment of the loop will depend on the hotness check and other 15259 // logic in alignBlocks. 15260 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15261 return Align(32); 15262 } 15263 15264 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15265 15266 // For small loops (between 5 and 8 instructions), align to a 32-byte 15267 // boundary so that the entire loop fits in one instruction-cache line. 15268 uint64_t LoopSize = 0; 15269 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15270 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15271 LoopSize += TII->getInstSizeInBytes(*J); 15272 if (LoopSize > 32) 15273 break; 15274 } 15275 15276 if (LoopSize > 16 && LoopSize <= 32) 15277 return Align(32); 15278 15279 break; 15280 } 15281 } 15282 15283 return TargetLowering::getPrefLoopAlignment(ML); 15284 } 15285 15286 /// getConstraintType - Given a constraint, return the type of 15287 /// constraint it is for this target. 15288 PPCTargetLowering::ConstraintType 15289 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15290 if (Constraint.size() == 1) { 15291 switch (Constraint[0]) { 15292 default: break; 15293 case 'b': 15294 case 'r': 15295 case 'f': 15296 case 'd': 15297 case 'v': 15298 case 'y': 15299 return C_RegisterClass; 15300 case 'Z': 15301 // FIXME: While Z does indicate a memory constraint, it specifically 15302 // indicates an r+r address (used in conjunction with the 'y' modifier 15303 // in the replacement string). Currently, we're forcing the base 15304 // register to be r0 in the asm printer (which is interpreted as zero) 15305 // and forming the complete address in the second register. This is 15306 // suboptimal. 15307 return C_Memory; 15308 } 15309 } else if (Constraint == "wc") { // individual CR bits. 15310 return C_RegisterClass; 15311 } else if (Constraint == "wa" || Constraint == "wd" || 15312 Constraint == "wf" || Constraint == "ws" || 15313 Constraint == "wi" || Constraint == "ww") { 15314 return C_RegisterClass; // VSX registers. 15315 } 15316 return TargetLowering::getConstraintType(Constraint); 15317 } 15318 15319 /// Examine constraint type and operand type and determine a weight value. 15320 /// This object must already have been set up with the operand type 15321 /// and the current alternative constraint selected. 15322 TargetLowering::ConstraintWeight 15323 PPCTargetLowering::getSingleConstraintMatchWeight( 15324 AsmOperandInfo &info, const char *constraint) const { 15325 ConstraintWeight weight = CW_Invalid; 15326 Value *CallOperandVal = info.CallOperandVal; 15327 // If we don't have a value, we can't do a match, 15328 // but allow it at the lowest weight. 15329 if (!CallOperandVal) 15330 return CW_Default; 15331 Type *type = CallOperandVal->getType(); 15332 15333 // Look at the constraint type. 15334 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15335 return CW_Register; // an individual CR bit. 15336 else if ((StringRef(constraint) == "wa" || 15337 StringRef(constraint) == "wd" || 15338 StringRef(constraint) == "wf") && 15339 type->isVectorTy()) 15340 return CW_Register; 15341 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15342 return CW_Register; // just hold 64-bit integers data. 15343 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15344 return CW_Register; 15345 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15346 return CW_Register; 15347 15348 switch (*constraint) { 15349 default: 15350 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15351 break; 15352 case 'b': 15353 if (type->isIntegerTy()) 15354 weight = CW_Register; 15355 break; 15356 case 'f': 15357 if (type->isFloatTy()) 15358 weight = CW_Register; 15359 break; 15360 case 'd': 15361 if (type->isDoubleTy()) 15362 weight = CW_Register; 15363 break; 15364 case 'v': 15365 if (type->isVectorTy()) 15366 weight = CW_Register; 15367 break; 15368 case 'y': 15369 weight = CW_Register; 15370 break; 15371 case 'Z': 15372 weight = CW_Memory; 15373 break; 15374 } 15375 return weight; 15376 } 15377 15378 std::pair<unsigned, const TargetRegisterClass *> 15379 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15380 StringRef Constraint, 15381 MVT VT) const { 15382 if (Constraint.size() == 1) { 15383 // GCC RS6000 Constraint Letters 15384 switch (Constraint[0]) { 15385 case 'b': // R1-R31 15386 if (VT == MVT::i64 && Subtarget.isPPC64()) 15387 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15388 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15389 case 'r': // R0-R31 15390 if (VT == MVT::i64 && Subtarget.isPPC64()) 15391 return std::make_pair(0U, &PPC::G8RCRegClass); 15392 return std::make_pair(0U, &PPC::GPRCRegClass); 15393 // 'd' and 'f' constraints are both defined to be "the floating point 15394 // registers", where one is for 32-bit and the other for 64-bit. We don't 15395 // really care overly much here so just give them all the same reg classes. 15396 case 'd': 15397 case 'f': 15398 if (Subtarget.hasSPE()) { 15399 if (VT == MVT::f32 || VT == MVT::i32) 15400 return std::make_pair(0U, &PPC::GPRCRegClass); 15401 if (VT == MVT::f64 || VT == MVT::i64) 15402 return std::make_pair(0U, &PPC::SPERCRegClass); 15403 } else { 15404 if (VT == MVT::f32 || VT == MVT::i32) 15405 return std::make_pair(0U, &PPC::F4RCRegClass); 15406 if (VT == MVT::f64 || VT == MVT::i64) 15407 return std::make_pair(0U, &PPC::F8RCRegClass); 15408 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15409 return std::make_pair(0U, &PPC::QFRCRegClass); 15410 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15411 return std::make_pair(0U, &PPC::QSRCRegClass); 15412 } 15413 break; 15414 case 'v': 15415 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 15416 return std::make_pair(0U, &PPC::QFRCRegClass); 15417 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 15418 return std::make_pair(0U, &PPC::QSRCRegClass); 15419 if (Subtarget.hasAltivec()) 15420 return std::make_pair(0U, &PPC::VRRCRegClass); 15421 break; 15422 case 'y': // crrc 15423 return std::make_pair(0U, &PPC::CRRCRegClass); 15424 } 15425 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15426 // An individual CR bit. 15427 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15428 } else if ((Constraint == "wa" || Constraint == "wd" || 15429 Constraint == "wf" || Constraint == "wi") && 15430 Subtarget.hasVSX()) { 15431 return std::make_pair(0U, &PPC::VSRCRegClass); 15432 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15433 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15434 return std::make_pair(0U, &PPC::VSSRCRegClass); 15435 else 15436 return std::make_pair(0U, &PPC::VSFRCRegClass); 15437 } 15438 15439 // If we name a VSX register, we can't defer to the base class because it 15440 // will not recognize the correct register (their names will be VSL{0-31} 15441 // and V{0-31} so they won't match). So we match them here. 15442 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15443 int VSNum = atoi(Constraint.data() + 3); 15444 assert(VSNum >= 0 && VSNum <= 63 && 15445 "Attempted to access a vsr out of range"); 15446 if (VSNum < 32) 15447 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15448 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15449 } 15450 std::pair<unsigned, const TargetRegisterClass *> R = 15451 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15452 15453 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15454 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15455 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15456 // register. 15457 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15458 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15459 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15460 PPC::GPRCRegClass.contains(R.first)) 15461 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15462 PPC::sub_32, &PPC::G8RCRegClass), 15463 &PPC::G8RCRegClass); 15464 15465 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15466 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15467 R.first = PPC::CR0; 15468 R.second = &PPC::CRRCRegClass; 15469 } 15470 15471 return R; 15472 } 15473 15474 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15475 /// vector. If it is invalid, don't add anything to Ops. 15476 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15477 std::string &Constraint, 15478 std::vector<SDValue>&Ops, 15479 SelectionDAG &DAG) const { 15480 SDValue Result; 15481 15482 // Only support length 1 constraints. 15483 if (Constraint.length() > 1) return; 15484 15485 char Letter = Constraint[0]; 15486 switch (Letter) { 15487 default: break; 15488 case 'I': 15489 case 'J': 15490 case 'K': 15491 case 'L': 15492 case 'M': 15493 case 'N': 15494 case 'O': 15495 case 'P': { 15496 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15497 if (!CST) return; // Must be an immediate to match. 15498 SDLoc dl(Op); 15499 int64_t Value = CST->getSExtValue(); 15500 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15501 // numbers are printed as such. 15502 switch (Letter) { 15503 default: llvm_unreachable("Unknown constraint letter!"); 15504 case 'I': // "I" is a signed 16-bit constant. 15505 if (isInt<16>(Value)) 15506 Result = DAG.getTargetConstant(Value, dl, TCVT); 15507 break; 15508 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15509 if (isShiftedUInt<16, 16>(Value)) 15510 Result = DAG.getTargetConstant(Value, dl, TCVT); 15511 break; 15512 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15513 if (isShiftedInt<16, 16>(Value)) 15514 Result = DAG.getTargetConstant(Value, dl, TCVT); 15515 break; 15516 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15517 if (isUInt<16>(Value)) 15518 Result = DAG.getTargetConstant(Value, dl, TCVT); 15519 break; 15520 case 'M': // "M" is a constant that is greater than 31. 15521 if (Value > 31) 15522 Result = DAG.getTargetConstant(Value, dl, TCVT); 15523 break; 15524 case 'N': // "N" is a positive constant that is an exact power of two. 15525 if (Value > 0 && isPowerOf2_64(Value)) 15526 Result = DAG.getTargetConstant(Value, dl, TCVT); 15527 break; 15528 case 'O': // "O" is the constant zero. 15529 if (Value == 0) 15530 Result = DAG.getTargetConstant(Value, dl, TCVT); 15531 break; 15532 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15533 if (isInt<16>(-Value)) 15534 Result = DAG.getTargetConstant(Value, dl, TCVT); 15535 break; 15536 } 15537 break; 15538 } 15539 } 15540 15541 if (Result.getNode()) { 15542 Ops.push_back(Result); 15543 return; 15544 } 15545 15546 // Handle standard constraint letters. 15547 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15548 } 15549 15550 // isLegalAddressingMode - Return true if the addressing mode represented 15551 // by AM is legal for this target, for a load/store of the specified type. 15552 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15553 const AddrMode &AM, Type *Ty, 15554 unsigned AS, Instruction *I) const { 15555 // PPC does not allow r+i addressing modes for vectors! 15556 if (Ty->isVectorTy() && AM.BaseOffs != 0) 15557 return false; 15558 15559 // PPC allows a sign-extended 16-bit immediate field. 15560 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15561 return false; 15562 15563 // No global is ever allowed as a base. 15564 if (AM.BaseGV) 15565 return false; 15566 15567 // PPC only support r+r, 15568 switch (AM.Scale) { 15569 case 0: // "r+i" or just "i", depending on HasBaseReg. 15570 break; 15571 case 1: 15572 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15573 return false; 15574 // Otherwise we have r+r or r+i. 15575 break; 15576 case 2: 15577 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15578 return false; 15579 // Allow 2*r as r+r. 15580 break; 15581 default: 15582 // No other scales are supported. 15583 return false; 15584 } 15585 15586 return true; 15587 } 15588 15589 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15590 SelectionDAG &DAG) const { 15591 MachineFunction &MF = DAG.getMachineFunction(); 15592 MachineFrameInfo &MFI = MF.getFrameInfo(); 15593 MFI.setReturnAddressIsTaken(true); 15594 15595 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15596 return SDValue(); 15597 15598 SDLoc dl(Op); 15599 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15600 15601 // Make sure the function does not optimize away the store of the RA to 15602 // the stack. 15603 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15604 FuncInfo->setLRStoreRequired(); 15605 bool isPPC64 = Subtarget.isPPC64(); 15606 auto PtrVT = getPointerTy(MF.getDataLayout()); 15607 15608 if (Depth > 0) { 15609 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15610 SDValue Offset = 15611 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15612 isPPC64 ? MVT::i64 : MVT::i32); 15613 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15614 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15615 MachinePointerInfo()); 15616 } 15617 15618 // Just load the return address off the stack. 15619 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15620 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15621 MachinePointerInfo()); 15622 } 15623 15624 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15625 SelectionDAG &DAG) const { 15626 SDLoc dl(Op); 15627 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15628 15629 MachineFunction &MF = DAG.getMachineFunction(); 15630 MachineFrameInfo &MFI = MF.getFrameInfo(); 15631 MFI.setFrameAddressIsTaken(true); 15632 15633 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15634 bool isPPC64 = PtrVT == MVT::i64; 15635 15636 // Naked functions never have a frame pointer, and so we use r1. For all 15637 // other functions, this decision must be delayed until during PEI. 15638 unsigned FrameReg; 15639 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15640 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15641 else 15642 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15643 15644 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15645 PtrVT); 15646 while (Depth--) 15647 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15648 FrameAddr, MachinePointerInfo()); 15649 return FrameAddr; 15650 } 15651 15652 // FIXME? Maybe this could be a TableGen attribute on some registers and 15653 // this table could be generated automatically from RegInfo. 15654 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15655 const MachineFunction &MF) const { 15656 bool isPPC64 = Subtarget.isPPC64(); 15657 15658 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15659 if (!is64Bit && VT != LLT::scalar(32)) 15660 report_fatal_error("Invalid register global variable type"); 15661 15662 Register Reg = StringSwitch<Register>(RegName) 15663 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15664 .Case("r2", isPPC64 ? Register() : PPC::R2) 15665 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15666 .Default(Register()); 15667 15668 if (Reg) 15669 return Reg; 15670 report_fatal_error("Invalid register name global variable"); 15671 } 15672 15673 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15674 // 32-bit SVR4 ABI access everything as got-indirect. 15675 if (Subtarget.is32BitELFABI()) 15676 return true; 15677 15678 // AIX accesses everything indirectly through the TOC, which is similar to 15679 // the GOT. 15680 if (Subtarget.isAIXABI()) 15681 return true; 15682 15683 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15684 // If it is small or large code model, module locals are accessed 15685 // indirectly by loading their address from .toc/.got. 15686 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15687 return true; 15688 15689 // JumpTable and BlockAddress are accessed as got-indirect. 15690 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15691 return true; 15692 15693 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15694 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15695 15696 return false; 15697 } 15698 15699 bool 15700 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15701 // The PowerPC target isn't yet aware of offsets. 15702 return false; 15703 } 15704 15705 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15706 const CallInst &I, 15707 MachineFunction &MF, 15708 unsigned Intrinsic) const { 15709 switch (Intrinsic) { 15710 case Intrinsic::ppc_qpx_qvlfd: 15711 case Intrinsic::ppc_qpx_qvlfs: 15712 case Intrinsic::ppc_qpx_qvlfcd: 15713 case Intrinsic::ppc_qpx_qvlfcs: 15714 case Intrinsic::ppc_qpx_qvlfiwa: 15715 case Intrinsic::ppc_qpx_qvlfiwz: 15716 case Intrinsic::ppc_altivec_lvx: 15717 case Intrinsic::ppc_altivec_lvxl: 15718 case Intrinsic::ppc_altivec_lvebx: 15719 case Intrinsic::ppc_altivec_lvehx: 15720 case Intrinsic::ppc_altivec_lvewx: 15721 case Intrinsic::ppc_vsx_lxvd2x: 15722 case Intrinsic::ppc_vsx_lxvw4x: { 15723 EVT VT; 15724 switch (Intrinsic) { 15725 case Intrinsic::ppc_altivec_lvebx: 15726 VT = MVT::i8; 15727 break; 15728 case Intrinsic::ppc_altivec_lvehx: 15729 VT = MVT::i16; 15730 break; 15731 case Intrinsic::ppc_altivec_lvewx: 15732 VT = MVT::i32; 15733 break; 15734 case Intrinsic::ppc_vsx_lxvd2x: 15735 VT = MVT::v2f64; 15736 break; 15737 case Intrinsic::ppc_qpx_qvlfd: 15738 VT = MVT::v4f64; 15739 break; 15740 case Intrinsic::ppc_qpx_qvlfs: 15741 VT = MVT::v4f32; 15742 break; 15743 case Intrinsic::ppc_qpx_qvlfcd: 15744 VT = MVT::v2f64; 15745 break; 15746 case Intrinsic::ppc_qpx_qvlfcs: 15747 VT = MVT::v2f32; 15748 break; 15749 default: 15750 VT = MVT::v4i32; 15751 break; 15752 } 15753 15754 Info.opc = ISD::INTRINSIC_W_CHAIN; 15755 Info.memVT = VT; 15756 Info.ptrVal = I.getArgOperand(0); 15757 Info.offset = -VT.getStoreSize()+1; 15758 Info.size = 2*VT.getStoreSize()-1; 15759 Info.align = Align(1); 15760 Info.flags = MachineMemOperand::MOLoad; 15761 return true; 15762 } 15763 case Intrinsic::ppc_qpx_qvlfda: 15764 case Intrinsic::ppc_qpx_qvlfsa: 15765 case Intrinsic::ppc_qpx_qvlfcda: 15766 case Intrinsic::ppc_qpx_qvlfcsa: 15767 case Intrinsic::ppc_qpx_qvlfiwaa: 15768 case Intrinsic::ppc_qpx_qvlfiwza: { 15769 EVT VT; 15770 switch (Intrinsic) { 15771 case Intrinsic::ppc_qpx_qvlfda: 15772 VT = MVT::v4f64; 15773 break; 15774 case Intrinsic::ppc_qpx_qvlfsa: 15775 VT = MVT::v4f32; 15776 break; 15777 case Intrinsic::ppc_qpx_qvlfcda: 15778 VT = MVT::v2f64; 15779 break; 15780 case Intrinsic::ppc_qpx_qvlfcsa: 15781 VT = MVT::v2f32; 15782 break; 15783 default: 15784 VT = MVT::v4i32; 15785 break; 15786 } 15787 15788 Info.opc = ISD::INTRINSIC_W_CHAIN; 15789 Info.memVT = VT; 15790 Info.ptrVal = I.getArgOperand(0); 15791 Info.offset = 0; 15792 Info.size = VT.getStoreSize(); 15793 Info.align = Align(1); 15794 Info.flags = MachineMemOperand::MOLoad; 15795 return true; 15796 } 15797 case Intrinsic::ppc_qpx_qvstfd: 15798 case Intrinsic::ppc_qpx_qvstfs: 15799 case Intrinsic::ppc_qpx_qvstfcd: 15800 case Intrinsic::ppc_qpx_qvstfcs: 15801 case Intrinsic::ppc_qpx_qvstfiw: 15802 case Intrinsic::ppc_altivec_stvx: 15803 case Intrinsic::ppc_altivec_stvxl: 15804 case Intrinsic::ppc_altivec_stvebx: 15805 case Intrinsic::ppc_altivec_stvehx: 15806 case Intrinsic::ppc_altivec_stvewx: 15807 case Intrinsic::ppc_vsx_stxvd2x: 15808 case Intrinsic::ppc_vsx_stxvw4x: { 15809 EVT VT; 15810 switch (Intrinsic) { 15811 case Intrinsic::ppc_altivec_stvebx: 15812 VT = MVT::i8; 15813 break; 15814 case Intrinsic::ppc_altivec_stvehx: 15815 VT = MVT::i16; 15816 break; 15817 case Intrinsic::ppc_altivec_stvewx: 15818 VT = MVT::i32; 15819 break; 15820 case Intrinsic::ppc_vsx_stxvd2x: 15821 VT = MVT::v2f64; 15822 break; 15823 case Intrinsic::ppc_qpx_qvstfd: 15824 VT = MVT::v4f64; 15825 break; 15826 case Intrinsic::ppc_qpx_qvstfs: 15827 VT = MVT::v4f32; 15828 break; 15829 case Intrinsic::ppc_qpx_qvstfcd: 15830 VT = MVT::v2f64; 15831 break; 15832 case Intrinsic::ppc_qpx_qvstfcs: 15833 VT = MVT::v2f32; 15834 break; 15835 default: 15836 VT = MVT::v4i32; 15837 break; 15838 } 15839 15840 Info.opc = ISD::INTRINSIC_VOID; 15841 Info.memVT = VT; 15842 Info.ptrVal = I.getArgOperand(1); 15843 Info.offset = -VT.getStoreSize()+1; 15844 Info.size = 2*VT.getStoreSize()-1; 15845 Info.align = Align(1); 15846 Info.flags = MachineMemOperand::MOStore; 15847 return true; 15848 } 15849 case Intrinsic::ppc_qpx_qvstfda: 15850 case Intrinsic::ppc_qpx_qvstfsa: 15851 case Intrinsic::ppc_qpx_qvstfcda: 15852 case Intrinsic::ppc_qpx_qvstfcsa: 15853 case Intrinsic::ppc_qpx_qvstfiwa: { 15854 EVT VT; 15855 switch (Intrinsic) { 15856 case Intrinsic::ppc_qpx_qvstfda: 15857 VT = MVT::v4f64; 15858 break; 15859 case Intrinsic::ppc_qpx_qvstfsa: 15860 VT = MVT::v4f32; 15861 break; 15862 case Intrinsic::ppc_qpx_qvstfcda: 15863 VT = MVT::v2f64; 15864 break; 15865 case Intrinsic::ppc_qpx_qvstfcsa: 15866 VT = MVT::v2f32; 15867 break; 15868 default: 15869 VT = MVT::v4i32; 15870 break; 15871 } 15872 15873 Info.opc = ISD::INTRINSIC_VOID; 15874 Info.memVT = VT; 15875 Info.ptrVal = I.getArgOperand(1); 15876 Info.offset = 0; 15877 Info.size = VT.getStoreSize(); 15878 Info.align = Align(1); 15879 Info.flags = MachineMemOperand::MOStore; 15880 return true; 15881 } 15882 default: 15883 break; 15884 } 15885 15886 return false; 15887 } 15888 15889 /// It returns EVT::Other if the type should be determined using generic 15890 /// target-independent logic. 15891 EVT PPCTargetLowering::getOptimalMemOpType( 15892 const MemOp &Op, const AttributeList &FuncAttributes) const { 15893 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15894 // When expanding a memset, require at least two QPX instructions to cover 15895 // the cost of loading the value to be stored from the constant pool. 15896 if (Subtarget.hasQPX() && Op.size() >= 32 && 15897 (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) && 15898 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15899 return MVT::v4f64; 15900 } 15901 15902 // We should use Altivec/VSX loads and stores when available. For unaligned 15903 // addresses, unaligned VSX loads are only fast starting with the P8. 15904 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15905 (Op.isAligned(Align(16)) || 15906 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15907 return MVT::v4i32; 15908 } 15909 15910 if (Subtarget.isPPC64()) { 15911 return MVT::i64; 15912 } 15913 15914 return MVT::i32; 15915 } 15916 15917 /// Returns true if it is beneficial to convert a load of a constant 15918 /// to just the constant itself. 15919 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15920 Type *Ty) const { 15921 assert(Ty->isIntegerTy()); 15922 15923 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15924 return !(BitSize == 0 || BitSize > 64); 15925 } 15926 15927 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15928 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15929 return false; 15930 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15931 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15932 return NumBits1 == 64 && NumBits2 == 32; 15933 } 15934 15935 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15936 if (!VT1.isInteger() || !VT2.isInteger()) 15937 return false; 15938 unsigned NumBits1 = VT1.getSizeInBits(); 15939 unsigned NumBits2 = VT2.getSizeInBits(); 15940 return NumBits1 == 64 && NumBits2 == 32; 15941 } 15942 15943 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15944 // Generally speaking, zexts are not free, but they are free when they can be 15945 // folded with other operations. 15946 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15947 EVT MemVT = LD->getMemoryVT(); 15948 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15949 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15950 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15951 LD->getExtensionType() == ISD::ZEXTLOAD)) 15952 return true; 15953 } 15954 15955 // FIXME: Add other cases... 15956 // - 32-bit shifts with a zext to i64 15957 // - zext after ctlz, bswap, etc. 15958 // - zext after and by a constant mask 15959 15960 return TargetLowering::isZExtFree(Val, VT2); 15961 } 15962 15963 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15964 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15965 "invalid fpext types"); 15966 // Extending to float128 is not free. 15967 if (DestVT == MVT::f128) 15968 return false; 15969 return true; 15970 } 15971 15972 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15973 return isInt<16>(Imm) || isUInt<16>(Imm); 15974 } 15975 15976 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15977 return isInt<16>(Imm) || isUInt<16>(Imm); 15978 } 15979 15980 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15981 unsigned, 15982 unsigned, 15983 MachineMemOperand::Flags, 15984 bool *Fast) const { 15985 if (DisablePPCUnaligned) 15986 return false; 15987 15988 // PowerPC supports unaligned memory access for simple non-vector types. 15989 // Although accessing unaligned addresses is not as efficient as accessing 15990 // aligned addresses, it is generally more efficient than manual expansion, 15991 // and generally only traps for software emulation when crossing page 15992 // boundaries. 15993 15994 if (!VT.isSimple()) 15995 return false; 15996 15997 if (VT.isFloatingPoint() && !VT.isVector() && 15998 !Subtarget.allowsUnalignedFPAccess()) 15999 return false; 16000 16001 if (VT.getSimpleVT().isVector()) { 16002 if (Subtarget.hasVSX()) { 16003 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16004 VT != MVT::v4f32 && VT != MVT::v4i32) 16005 return false; 16006 } else { 16007 return false; 16008 } 16009 } 16010 16011 if (VT == MVT::ppcf128) 16012 return false; 16013 16014 if (Fast) 16015 *Fast = true; 16016 16017 return true; 16018 } 16019 16020 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16021 EVT VT) const { 16022 return isFMAFasterThanFMulAndFAdd( 16023 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16024 } 16025 16026 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16027 Type *Ty) const { 16028 switch (Ty->getScalarType()->getTypeID()) { 16029 case Type::FloatTyID: 16030 case Type::DoubleTyID: 16031 return true; 16032 case Type::FP128TyID: 16033 return EnableQuadPrecision && Subtarget.hasP9Vector(); 16034 default: 16035 return false; 16036 } 16037 } 16038 16039 // Currently this is a copy from AArch64TargetLowering::isProfitableToHoist. 16040 // FIXME: add more patterns which are profitable to hoist. 16041 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16042 if (I->getOpcode() != Instruction::FMul) 16043 return true; 16044 16045 if (!I->hasOneUse()) 16046 return true; 16047 16048 Instruction *User = I->user_back(); 16049 assert(User && "A single use instruction with no uses."); 16050 16051 if (User->getOpcode() != Instruction::FSub && 16052 User->getOpcode() != Instruction::FAdd) 16053 return true; 16054 16055 const TargetOptions &Options = getTargetMachine().Options; 16056 const Function *F = I->getFunction(); 16057 const DataLayout &DL = F->getParent()->getDataLayout(); 16058 Type *Ty = User->getOperand(0)->getType(); 16059 16060 return !( 16061 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16062 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16063 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16064 } 16065 16066 const MCPhysReg * 16067 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 16068 // LR is a callee-save register, but we must treat it as clobbered by any call 16069 // site. Hence we include LR in the scratch registers, which are in turn added 16070 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 16071 // to CTR, which is used by any indirect call. 16072 static const MCPhysReg ScratchRegs[] = { 16073 PPC::X12, PPC::LR8, PPC::CTR8, 0 16074 }; 16075 16076 return ScratchRegs; 16077 } 16078 16079 Register PPCTargetLowering::getExceptionPointerRegister( 16080 const Constant *PersonalityFn) const { 16081 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 16082 } 16083 16084 Register PPCTargetLowering::getExceptionSelectorRegister( 16085 const Constant *PersonalityFn) const { 16086 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 16087 } 16088 16089 bool 16090 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 16091 EVT VT , unsigned DefinedValues) const { 16092 if (VT == MVT::v2i64) 16093 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 16094 16095 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 16096 return true; 16097 16098 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 16099 } 16100 16101 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 16102 if (DisableILPPref || Subtarget.enableMachineScheduler()) 16103 return TargetLowering::getSchedulingPreference(N); 16104 16105 return Sched::ILP; 16106 } 16107 16108 // Create a fast isel object. 16109 FastISel * 16110 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 16111 const TargetLibraryInfo *LibInfo) const { 16112 return PPC::createFastISel(FuncInfo, LibInfo); 16113 } 16114 16115 // 'Inverted' means the FMA opcode after negating one multiplicand. 16116 // For example, (fma -a b c) = (fnmsub a b c) 16117 static unsigned invertFMAOpcode(unsigned Opc) { 16118 switch (Opc) { 16119 default: 16120 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 16121 case ISD::FMA: 16122 return PPCISD::FNMSUB; 16123 case PPCISD::FNMSUB: 16124 return ISD::FMA; 16125 } 16126 } 16127 16128 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 16129 bool LegalOps, bool OptForSize, 16130 NegatibleCost &Cost, 16131 unsigned Depth) const { 16132 if (Depth > SelectionDAG::MaxRecursionDepth) 16133 return SDValue(); 16134 16135 unsigned Opc = Op.getOpcode(); 16136 EVT VT = Op.getValueType(); 16137 SDNodeFlags Flags = Op.getNode()->getFlags(); 16138 16139 switch (Opc) { 16140 case PPCISD::FNMSUB: 16141 // TODO: QPX subtarget is deprecated. No transformation here. 16142 if (!Op.hasOneUse() || !isTypeLegal(VT) || Subtarget.hasQPX()) 16143 break; 16144 16145 const TargetOptions &Options = getTargetMachine().Options; 16146 SDValue N0 = Op.getOperand(0); 16147 SDValue N1 = Op.getOperand(1); 16148 SDValue N2 = Op.getOperand(2); 16149 SDLoc Loc(Op); 16150 16151 NegatibleCost N2Cost = NegatibleCost::Expensive; 16152 SDValue NegN2 = 16153 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 16154 16155 if (!NegN2) 16156 return SDValue(); 16157 16158 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 16159 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 16160 // These transformations may change sign of zeroes. For example, 16161 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 16162 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 16163 // Try and choose the cheaper one to negate. 16164 NegatibleCost N0Cost = NegatibleCost::Expensive; 16165 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 16166 N0Cost, Depth + 1); 16167 16168 NegatibleCost N1Cost = NegatibleCost::Expensive; 16169 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 16170 N1Cost, Depth + 1); 16171 16172 if (NegN0 && N0Cost <= N1Cost) { 16173 Cost = std::min(N0Cost, N2Cost); 16174 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 16175 } else if (NegN1) { 16176 Cost = std::min(N1Cost, N2Cost); 16177 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 16178 } 16179 } 16180 16181 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 16182 if (isOperationLegal(ISD::FMA, VT)) { 16183 Cost = N2Cost; 16184 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 16185 } 16186 16187 break; 16188 } 16189 16190 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 16191 Cost, Depth); 16192 } 16193 16194 // Override to enable LOAD_STACK_GUARD lowering on Linux. 16195 bool PPCTargetLowering::useLoadStackGuardNode() const { 16196 if (!Subtarget.isTargetLinux()) 16197 return TargetLowering::useLoadStackGuardNode(); 16198 return true; 16199 } 16200 16201 // Override to disable global variable loading on Linux. 16202 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 16203 if (!Subtarget.isTargetLinux()) 16204 return TargetLowering::insertSSPDeclarations(M); 16205 } 16206 16207 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 16208 bool ForCodeSize) const { 16209 if (!VT.isSimple() || !Subtarget.hasVSX()) 16210 return false; 16211 16212 switch(VT.getSimpleVT().SimpleTy) { 16213 default: 16214 // For FP types that are currently not supported by PPC backend, return 16215 // false. Examples: f16, f80. 16216 return false; 16217 case MVT::f32: 16218 case MVT::f64: 16219 case MVT::ppcf128: 16220 return Imm.isPosZero(); 16221 } 16222 } 16223 16224 // For vector shift operation op, fold 16225 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 16226 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 16227 SelectionDAG &DAG) { 16228 SDValue N0 = N->getOperand(0); 16229 SDValue N1 = N->getOperand(1); 16230 EVT VT = N0.getValueType(); 16231 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 16232 unsigned Opcode = N->getOpcode(); 16233 unsigned TargetOpcode; 16234 16235 switch (Opcode) { 16236 default: 16237 llvm_unreachable("Unexpected shift operation"); 16238 case ISD::SHL: 16239 TargetOpcode = PPCISD::SHL; 16240 break; 16241 case ISD::SRL: 16242 TargetOpcode = PPCISD::SRL; 16243 break; 16244 case ISD::SRA: 16245 TargetOpcode = PPCISD::SRA; 16246 break; 16247 } 16248 16249 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16250 N1->getOpcode() == ISD::AND) 16251 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16252 if (Mask->getZExtValue() == OpSizeInBits - 1) 16253 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16254 16255 return SDValue(); 16256 } 16257 16258 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16259 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16260 return Value; 16261 16262 SDValue N0 = N->getOperand(0); 16263 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16264 if (!Subtarget.isISA3_0() || 16265 N0.getOpcode() != ISD::SIGN_EXTEND || 16266 N0.getOperand(0).getValueType() != MVT::i32 || 16267 CN1 == nullptr || N->getValueType(0) != MVT::i64) 16268 return SDValue(); 16269 16270 // We can't save an operation here if the value is already extended, and 16271 // the existing shift is easier to combine. 16272 SDValue ExtsSrc = N0.getOperand(0); 16273 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16274 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16275 return SDValue(); 16276 16277 SDLoc DL(N0); 16278 SDValue ShiftBy = SDValue(CN1, 0); 16279 // We want the shift amount to be i32 on the extswli, but the shift could 16280 // have an i64. 16281 if (ShiftBy.getValueType() == MVT::i64) 16282 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16283 16284 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16285 ShiftBy); 16286 } 16287 16288 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16289 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16290 return Value; 16291 16292 return SDValue(); 16293 } 16294 16295 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16296 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16297 return Value; 16298 16299 return SDValue(); 16300 } 16301 16302 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16303 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16304 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16305 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16306 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16307 const PPCSubtarget &Subtarget) { 16308 if (!Subtarget.isPPC64()) 16309 return SDValue(); 16310 16311 SDValue LHS = N->getOperand(0); 16312 SDValue RHS = N->getOperand(1); 16313 16314 auto isZextOfCompareWithConstant = [](SDValue Op) { 16315 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16316 Op.getValueType() != MVT::i64) 16317 return false; 16318 16319 SDValue Cmp = Op.getOperand(0); 16320 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16321 Cmp.getOperand(0).getValueType() != MVT::i64) 16322 return false; 16323 16324 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16325 int64_t NegConstant = 0 - Constant->getSExtValue(); 16326 // Due to the limitations of the addi instruction, 16327 // -C is required to be [-32768, 32767]. 16328 return isInt<16>(NegConstant); 16329 } 16330 16331 return false; 16332 }; 16333 16334 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16335 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16336 16337 // If there is a pattern, canonicalize a zext operand to the RHS. 16338 if (LHSHasPattern && !RHSHasPattern) 16339 std::swap(LHS, RHS); 16340 else if (!LHSHasPattern && !RHSHasPattern) 16341 return SDValue(); 16342 16343 SDLoc DL(N); 16344 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16345 SDValue Cmp = RHS.getOperand(0); 16346 SDValue Z = Cmp.getOperand(0); 16347 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16348 16349 assert(Constant && "Constant Should not be a null pointer."); 16350 int64_t NegConstant = 0 - Constant->getSExtValue(); 16351 16352 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16353 default: break; 16354 case ISD::SETNE: { 16355 // when C == 0 16356 // --> addze X, (addic Z, -1).carry 16357 // / 16358 // add X, (zext(setne Z, C))-- 16359 // \ when -32768 <= -C <= 32767 && C != 0 16360 // --> addze X, (addic (addi Z, -C), -1).carry 16361 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16362 DAG.getConstant(NegConstant, DL, MVT::i64)); 16363 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16364 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16365 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16366 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16367 SDValue(Addc.getNode(), 1)); 16368 } 16369 case ISD::SETEQ: { 16370 // when C == 0 16371 // --> addze X, (subfic Z, 0).carry 16372 // / 16373 // add X, (zext(sete Z, C))-- 16374 // \ when -32768 <= -C <= 32767 && C != 0 16375 // --> addze X, (subfic (addi Z, -C), 0).carry 16376 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16377 DAG.getConstant(NegConstant, DL, MVT::i64)); 16378 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16379 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16380 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16381 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16382 SDValue(Subc.getNode(), 1)); 16383 } 16384 } 16385 16386 return SDValue(); 16387 } 16388 16389 // Transform 16390 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16391 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16392 // In this case both C1 and C2 must be known constants. 16393 // C1+C2 must fit into a 34 bit signed integer. 16394 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16395 const PPCSubtarget &Subtarget) { 16396 if (!Subtarget.isUsingPCRelativeCalls()) 16397 return SDValue(); 16398 16399 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16400 // If we find that node try to cast the Global Address and the Constant. 16401 SDValue LHS = N->getOperand(0); 16402 SDValue RHS = N->getOperand(1); 16403 16404 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16405 std::swap(LHS, RHS); 16406 16407 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16408 return SDValue(); 16409 16410 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16411 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16412 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16413 16414 // Check that both casts succeeded. 16415 if (!GSDN || !ConstNode) 16416 return SDValue(); 16417 16418 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16419 SDLoc DL(GSDN); 16420 16421 // The signed int offset needs to fit in 34 bits. 16422 if (!isInt<34>(NewOffset)) 16423 return SDValue(); 16424 16425 // The new global address is a copy of the old global address except 16426 // that it has the updated Offset. 16427 SDValue GA = 16428 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16429 NewOffset, GSDN->getTargetFlags()); 16430 SDValue MatPCRel = 16431 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16432 return MatPCRel; 16433 } 16434 16435 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16436 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16437 return Value; 16438 16439 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16440 return Value; 16441 16442 return SDValue(); 16443 } 16444 16445 // Detect TRUNCATE operations on bitcasts of float128 values. 16446 // What we are looking for here is the situtation where we extract a subset 16447 // of bits from a 128 bit float. 16448 // This can be of two forms: 16449 // 1) BITCAST of f128 feeding TRUNCATE 16450 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16451 // The reason this is required is because we do not have a legal i128 type 16452 // and so we want to prevent having to store the f128 and then reload part 16453 // of it. 16454 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16455 DAGCombinerInfo &DCI) const { 16456 // If we are using CRBits then try that first. 16457 if (Subtarget.useCRBits()) { 16458 // Check if CRBits did anything and return that if it did. 16459 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16460 return CRTruncValue; 16461 } 16462 16463 SDLoc dl(N); 16464 SDValue Op0 = N->getOperand(0); 16465 16466 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16467 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16468 EVT VT = N->getValueType(0); 16469 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16470 return SDValue(); 16471 SDValue Sub = Op0.getOperand(0); 16472 if (Sub.getOpcode() == ISD::SUB) { 16473 SDValue SubOp0 = Sub.getOperand(0); 16474 SDValue SubOp1 = Sub.getOperand(1); 16475 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16476 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16477 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16478 SubOp1.getOperand(0), 16479 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16480 } 16481 } 16482 } 16483 16484 // Looking for a truncate of i128 to i64. 16485 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16486 return SDValue(); 16487 16488 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16489 16490 // SRL feeding TRUNCATE. 16491 if (Op0.getOpcode() == ISD::SRL) { 16492 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16493 // The right shift has to be by 64 bits. 16494 if (!ConstNode || ConstNode->getZExtValue() != 64) 16495 return SDValue(); 16496 16497 // Switch the element number to extract. 16498 EltToExtract = EltToExtract ? 0 : 1; 16499 // Update Op0 past the SRL. 16500 Op0 = Op0.getOperand(0); 16501 } 16502 16503 // BITCAST feeding a TRUNCATE possibly via SRL. 16504 if (Op0.getOpcode() == ISD::BITCAST && 16505 Op0.getValueType() == MVT::i128 && 16506 Op0.getOperand(0).getValueType() == MVT::f128) { 16507 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16508 return DCI.DAG.getNode( 16509 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16510 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16511 } 16512 return SDValue(); 16513 } 16514 16515 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16516 SelectionDAG &DAG = DCI.DAG; 16517 16518 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16519 if (!ConstOpOrElement) 16520 return SDValue(); 16521 16522 // An imul is usually smaller than the alternative sequence for legal type. 16523 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16524 isOperationLegal(ISD::MUL, N->getValueType(0))) 16525 return SDValue(); 16526 16527 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16528 switch (this->Subtarget.getCPUDirective()) { 16529 default: 16530 // TODO: enhance the condition for subtarget before pwr8 16531 return false; 16532 case PPC::DIR_PWR8: 16533 // type mul add shl 16534 // scalar 4 1 1 16535 // vector 7 2 2 16536 return true; 16537 case PPC::DIR_PWR9: 16538 case PPC::DIR_PWR10: 16539 case PPC::DIR_PWR_FUTURE: 16540 // type mul add shl 16541 // scalar 5 2 2 16542 // vector 7 2 2 16543 16544 // The cycle RATIO of related operations are showed as a table above. 16545 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16546 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16547 // are 4, it is always profitable; but for 3 instrs patterns 16548 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16549 // So we should only do it for vector type. 16550 return IsAddOne && IsNeg ? VT.isVector() : true; 16551 } 16552 }; 16553 16554 EVT VT = N->getValueType(0); 16555 SDLoc DL(N); 16556 16557 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16558 bool IsNeg = MulAmt.isNegative(); 16559 APInt MulAmtAbs = MulAmt.abs(); 16560 16561 if ((MulAmtAbs - 1).isPowerOf2()) { 16562 // (mul x, 2^N + 1) => (add (shl x, N), x) 16563 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16564 16565 if (!IsProfitable(IsNeg, true, VT)) 16566 return SDValue(); 16567 16568 SDValue Op0 = N->getOperand(0); 16569 SDValue Op1 = 16570 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16571 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16572 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16573 16574 if (!IsNeg) 16575 return Res; 16576 16577 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16578 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16579 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16580 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16581 16582 if (!IsProfitable(IsNeg, false, VT)) 16583 return SDValue(); 16584 16585 SDValue Op0 = N->getOperand(0); 16586 SDValue Op1 = 16587 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16588 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16589 16590 if (!IsNeg) 16591 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16592 else 16593 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16594 16595 } else { 16596 return SDValue(); 16597 } 16598 } 16599 16600 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16601 // in combiner since we need to check SD flags and other subtarget features. 16602 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16603 DAGCombinerInfo &DCI) const { 16604 SDValue N0 = N->getOperand(0); 16605 SDValue N1 = N->getOperand(1); 16606 SDValue N2 = N->getOperand(2); 16607 SDNodeFlags Flags = N->getFlags(); 16608 EVT VT = N->getValueType(0); 16609 SelectionDAG &DAG = DCI.DAG; 16610 const TargetOptions &Options = getTargetMachine().Options; 16611 unsigned Opc = N->getOpcode(); 16612 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16613 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16614 SDLoc Loc(N); 16615 16616 // TODO: QPX subtarget is deprecated. No transformation here. 16617 if (Subtarget.hasQPX() || !isOperationLegal(ISD::FMA, VT)) 16618 return SDValue(); 16619 16620 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16621 // since (fnmsub a b c)=-0 while c-ab=+0. 16622 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16623 return SDValue(); 16624 16625 // (fma (fneg a) b c) => (fnmsub a b c) 16626 // (fnmsub (fneg a) b c) => (fma a b c) 16627 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16628 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16629 16630 // (fma a (fneg b) c) => (fnmsub a b c) 16631 // (fnmsub a (fneg b) c) => (fma a b c) 16632 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16633 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16634 16635 return SDValue(); 16636 } 16637 16638 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16639 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16640 if (!Subtarget.is64BitELFABI()) 16641 return false; 16642 16643 // If not a tail call then no need to proceed. 16644 if (!CI->isTailCall()) 16645 return false; 16646 16647 // If sibling calls have been disabled and tail-calls aren't guaranteed 16648 // there is no reason to duplicate. 16649 auto &TM = getTargetMachine(); 16650 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16651 return false; 16652 16653 // Can't tail call a function called indirectly, or if it has variadic args. 16654 const Function *Callee = CI->getCalledFunction(); 16655 if (!Callee || Callee->isVarArg()) 16656 return false; 16657 16658 // Make sure the callee and caller calling conventions are eligible for tco. 16659 const Function *Caller = CI->getParent()->getParent(); 16660 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16661 CI->getCallingConv())) 16662 return false; 16663 16664 // If the function is local then we have a good chance at tail-calling it 16665 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16666 } 16667 16668 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16669 if (!Subtarget.hasVSX()) 16670 return false; 16671 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16672 return true; 16673 return VT == MVT::f32 || VT == MVT::f64 || 16674 VT == MVT::v4f32 || VT == MVT::v2f64; 16675 } 16676 16677 bool PPCTargetLowering:: 16678 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16679 const Value *Mask = AndI.getOperand(1); 16680 // If the mask is suitable for andi. or andis. we should sink the and. 16681 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16682 // Can't handle constants wider than 64-bits. 16683 if (CI->getBitWidth() > 64) 16684 return false; 16685 int64_t ConstVal = CI->getZExtValue(); 16686 return isUInt<16>(ConstVal) || 16687 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16688 } 16689 16690 // For non-constant masks, we can always use the record-form and. 16691 return true; 16692 } 16693 16694 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16695 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16696 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16697 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16698 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16699 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16700 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16701 assert(Subtarget.hasP9Altivec() && 16702 "Only combine this when P9 altivec supported!"); 16703 EVT VT = N->getValueType(0); 16704 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16705 return SDValue(); 16706 16707 SelectionDAG &DAG = DCI.DAG; 16708 SDLoc dl(N); 16709 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16710 // Even for signed integers, if it's known to be positive (as signed 16711 // integer) due to zero-extended inputs. 16712 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16713 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16714 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16715 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16716 (SubOpcd1 == ISD::ZERO_EXTEND || 16717 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16718 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16719 N->getOperand(0)->getOperand(0), 16720 N->getOperand(0)->getOperand(1), 16721 DAG.getTargetConstant(0, dl, MVT::i32)); 16722 } 16723 16724 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16725 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16726 N->getOperand(0).hasOneUse()) { 16727 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16728 N->getOperand(0)->getOperand(0), 16729 N->getOperand(0)->getOperand(1), 16730 DAG.getTargetConstant(1, dl, MVT::i32)); 16731 } 16732 } 16733 16734 return SDValue(); 16735 } 16736 16737 // For type v4i32/v8ii16/v16i8, transform 16738 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16739 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16740 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16741 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16742 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16743 DAGCombinerInfo &DCI) const { 16744 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16745 assert(Subtarget.hasP9Altivec() && 16746 "Only combine this when P9 altivec supported!"); 16747 16748 SelectionDAG &DAG = DCI.DAG; 16749 SDLoc dl(N); 16750 SDValue Cond = N->getOperand(0); 16751 SDValue TrueOpnd = N->getOperand(1); 16752 SDValue FalseOpnd = N->getOperand(2); 16753 EVT VT = N->getOperand(1).getValueType(); 16754 16755 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16756 FalseOpnd.getOpcode() != ISD::SUB) 16757 return SDValue(); 16758 16759 // ABSD only available for type v4i32/v8i16/v16i8 16760 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16761 return SDValue(); 16762 16763 // At least to save one more dependent computation 16764 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16765 return SDValue(); 16766 16767 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16768 16769 // Can only handle unsigned comparison here 16770 switch (CC) { 16771 default: 16772 return SDValue(); 16773 case ISD::SETUGT: 16774 case ISD::SETUGE: 16775 break; 16776 case ISD::SETULT: 16777 case ISD::SETULE: 16778 std::swap(TrueOpnd, FalseOpnd); 16779 break; 16780 } 16781 16782 SDValue CmpOpnd1 = Cond.getOperand(0); 16783 SDValue CmpOpnd2 = Cond.getOperand(1); 16784 16785 // SETCC CmpOpnd1 CmpOpnd2 cond 16786 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16787 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16788 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16789 TrueOpnd.getOperand(1) == CmpOpnd2 && 16790 FalseOpnd.getOperand(0) == CmpOpnd2 && 16791 FalseOpnd.getOperand(1) == CmpOpnd1) { 16792 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16793 CmpOpnd1, CmpOpnd2, 16794 DAG.getTargetConstant(0, dl, MVT::i32)); 16795 } 16796 16797 return SDValue(); 16798 } 16799